<template>
  <div class="flex bg-white p-10">
    <div class="span">
      <criteria-paged :model='model' v-ref:paged>
        <criteria :model='model' partial='criteria' v-ref:criteria @condition-changed='$parent.search'>
          <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
            <div class="row" width="100%">
              <div class="col-sm-3 form-group form-input-group">
                <label class="control-label">表&nbsp;钢&nbsp;号&nbsp;</label>
                <input type="text" class="form-control"
                       v-model="model.f_meternumber"
                       placeholder='表钢号'
                       condition="f_meternumber like '%{}%'"
                >
              </div>
              <div v-if="$parent.$parent.searchshow">
                <div class="col-sm-3 form-group form-input-group">
                  <label class="control-label">组织机构</label>
                  <right-tree :userid.sync='$parent.$parent.obj.userid'
                              :source.sync='$parent.$parent.obj.source'
                              :multiple="true"
                              @re-res="$parent.$parent.getRes"></right-tree>
                </div>
                <div class="col-sm-3 form-group form-input-group">
                  <label class="control-label">用&nbsp;户&nbsp;号&nbsp;</label>
                  <input type="text" class="form-control fixed-width"
                         v-model="model.f_userinfo_code"
                         placeholder='用户号'
                         condition="f_userinfo_code like '%{}%'"
                  >
                </div>
                <div class="col-sm-3 form-group form-input-group">
                  <label class="control-label">用户姓名</label>
                  <input type="text" class="form-control"
                         v-model="model.f_user_name"
                         placeholder='用户姓名'
                         condition="f_user_name like '%{}%'"
                  >
                </div>
                <div class="col-sm-3 form-group form-input-group">
                  <label class="control-label">用气地址</label>
                  <input type="text" class="form-control fixed-width"
                         v-model="model.f_address"
                         placeholder='用气地址'
                         :size="model.f_address ? model.f_address.length : 6"
                         condition="f_address like '%{}%'"
                  >
                </div>
                <div class="col-sm-3 form-group form-input-group">
                  <label class="control-label">用户类型</label>
                  <v-select
                    placeholder='用户类型'
                    value-single="true"
                    :value.sync="model.f_user_type"
                    v-model="model.f_user_type"
                    :options='$parent.$parent.Gasusertype'
                    close-on-select condition="f_user_type {}">
                  </v-select>
                </div>
                <div class="col-sm-3 form-group form-input-group">
                  <label class="control-label">用气性质</label>
                  <v-select
                    placeholder='用气性质'
                    value-single="true"
                    :value.sync="model.f_gasproperties"
                    v-model="model.f_gasproperties"
                    :options='$parent.$parent.Gasproperties'
                    close-on-select condition="f_gasproperties {}">
                  </v-select>
                </div>
                <div class="col-sm-3 form-group form-input-group">
                  <label class="control-label">气表品牌</label>
                  <v-select
                    placeholder='气表品牌'
                    :value.sync="model.f_meter_brand"
                    v-model="model.f_meter_brand"
                    :options='$parent.$parent.WarningType'
                    @change="$parent.$parent.getMeterType"
                    close-on-select
                    condition="f_meter_brand='{}'">
                  </v-select>
                </div>
                <div class="col-sm-3 form-group form-input-group">
                  <label class="control-label">气表型号</label>
                  <v-select v-if="$parent.$parent.styles"
                            placeholder='气表型号'
                            :value.sync="model.f_meter_style"
                            v-model="model.f_meter_style"
                            :options='$parent.$parent.Warningstyle'
                            close-on-select
                            condition="f_meter_style='{}'">
                  </v-select>
                  <v-select v-if="!$parent.$parent.styles"
                            placeholder='气表型号'
                            :value.sync="model.f_meter_style"
                            v-model="model.f_meter_style"
                            :options='$parent.$parent.Warningstyles'
                            close-on-select
                            condition="f_meter_style='{}'">
                  </v-select>
                </div>
                <div class="col-sm-3 form-group form-input-group">
                  <label class="control-label" style="word-break:keep-all;">安装时间</label>
                  <datepicker placeholder="起始时间"
                              :value.sync="model.f_start_date"
                              v-model="model.f_start_date"
                              :format="'yyyy-MM-dd HH:mm:ss'"
                              condition="f_gas_date > '{}'"
                  ></datepicker>
                </div>
                <div class="col-sm-3 form-group form-input-group">
                  <label class="control-label" style="word-break:keep-all;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;至&nbsp;&nbsp;&nbsp;</label>
                  <datepicker placeholder="结束时间"
                              :value.sync="model.f_end_date"
                              v-model="model.f_end_date"
                              :format="'yyyy-MM-dd HH:mm:ss'"
                              condition="f_gas_date < '{}'"
                  ></datepicker>
                </div>
                <div class="col-sm-3 form-group form-input-group">
                  <label class="control-label">阀门状态</label>
                  <v-select :value.sync="model.f_valvestate" v-model="model.f_valvestate"
                            placeholder='阀门状态'
                            :options='$parent.$parent.valvestate'
                            close-on-select
                            condition="f_valvestate = '{}'"></v-select>
                </div>
              </div>
              <div class="col-sm-3 form-group">
                <label class="control-label"></label>
                <button class="btn btn-success width-100" @click="search()" v-el:cba>查询</button>
                <label class="control-label"></label>
                <button class="btn btn-default width-100" @click="$parent.$parent.clearmsg">清空</button>
                <label class="control-label" v-if="!$parent.$parent.excelTable">超过十万条限制导出</label>
                <export-excel v-if="$parent.$parent.excelTable"
                              :data="{condition: $parent.$parent.condition}"
                              :field="$parent.$parent.getfield"
                              sqlurl="rs/logic/webmeter_exportfile" sql-name="getOpertionList"
                              template-name='WebMeterBatchOperationValve'
                              :choose-col="true"></export-excel>
              </div>
              <div class="col-sm-3 form-group">
                <label class="control-label"></label>
                <button class="btn btn-success width-100 " v-if="$parent.$parent.valveLimit"
                        @click="$parent.$parent.showModal('开阀')">批量开阀
                </button>
                <label class="control-label"></label>
                <button class="btn btn-success width-100" v-if="$parent.$parent.valveLimit"
                        @click="$parent.$parent.showModal('关阀')">批量关阀
                </button>
              </div>
              <div class="col-sm-3 form-group">
                <label class="control-label"></label>
                <button class="btn btn-success width-100 " v-if="$parent.$parent.Setarameterermissions"
                        @click="$parent.$parent.setRunParam">批量设置参数
                </button>
              </div>
              <div v-show="!$parent.$parent.searchshow" @click="$parent.$parent.clickshow"
                   style="position: relative;float: right;margin-right: 1%;">
                <img src="../../../static/webMeter/shousuo.png"><span>展开</span>
              </div>
              <div v-show="$parent.$parent.searchshow" @click="$parent.$parent.clickshow"
                   style="position: relative;float: right;margin-right: 1%;">
                <img src="../../../static/webMeter/shangsheng.png"><span>收缩</span>
              </div>
            </div>
          </div>
        </criteria>
        <data-grid :model="model" partial='list' v-ref:grid>
          <template partial='head'>
            <tr>
              <th style="text-align:center">
                <nobr>组织机构</nobr>
              </th>
              <th style="text-align:center">
                <nobr>用户号</nobr>
              </th>
              <th style="text-align:center">
                <nobr>用户类型</nobr>
              </th>
              <th style="text-align:center">
                <nobr>用气性质</nobr>
              </th>
              <th style="text-align:center">
                <nobr>用户姓名</nobr>
              </th>
              <th style="text-align:center">
                <nobr>用气地址</nobr>
              </th>
              <th style="text-align:center">
                <nobr>安装时间</nobr>
              </th>
              <th style="text-align:center;color:#3c763d">
                <nobr>表钢号</nobr>
              </th>
              <th style="text-align:center">
                <nobr>气表品牌</nobr>
              </th>
              <th style="text-align:center">
                <nobr>表编号</nobr>
              </th>
              <th style="text-align:center">
                <nobr>气表型号</nobr>
              </th>
              <th style="text-align:center">
                <nobr>阀门状态</nobr>
              </th>
              <th style="text-align:center">
                <nobr>全选</nobr>
                <input type="checkbox" v-model='checked1' checked="checked"
                       @click="$parent.$parent.$parent.checkedALL()">
              </th>
            </tr>
          </template>
          <template partial='body' v-ref:grid>
            <tr>
              <td style="text-align:center">
                <nobr>{{row.f_filiale}}</nobr>
              </td>
              <td style="text-align:center">
                <nobr>{{row.f_userinfo_code}}</nobr>
              </td>
              <td style="text-align:center">
                <nobr>{{row.f_user_type}}</nobr>
              </td>
              <td style="text-align:center">
                <nobr>{{row.f_gasproperties}}</nobr>
              </td>
              <td style="text-align:center">
                <nobr>{{row.f_user_name}}</nobr>
              </td>
              <td>
                <nobr>{{row.f_address}}</nobr>
              </td>
              <td style="text-align:center">
                <nobr>{{row.f_gas_date}}</nobr>
              </td>
              <td style="text-align:center">
                <nobr>{{row.f_meternumber}}</nobr>
              </td>
              <td style="text-align:center">
                <nobr>{{row.f_meter_brand}}</nobr>
              </td>
              <td style="text-align:center">{{row.f_user_id}}</td>
              <td style="text-align:center">
                <nobr>{{row.f_meter_style}}</nobr>
              </td>
              <td style="text-align:center">
                <nobr>{{row.f_valvestate}}</nobr>
              </td>
              <td style="text-align:center">
                <input type="checkbox" checked="checked" name="opertioninput"
                       @click="$parent.$parent.$parent.checked(row)"></td>
            </tr>
          </template>
          <template partial='foot'></template>
        </data-grid>
      </criteria-paged>
    </div>
  </div>
  <modal :show.sync="isShowUserException">
    <header slot="modal-header" class="modal-header">
      <button type="button" class="close" @click="close()"><span>&times;</span></button>
      <h4 class="modal-title" align="center">{{val1}}备注</h4>
    </header>
    <article slot="modal-body" class="modal-body">
      <div style="padding-left: 8px" v-if="val1=='设置参数'">
        <label class="control-label">参数类型</label>
        <v-select
          placeholder='参数类型'
          :value.sync="parameterType"
          v-model="parameterType"
          :options='parameterTypeList'
          close-on-select>
        </v-select>
      </div>
      <div class="form-group " style="padding-left: 8px">
        <label class="label-control">{{val1}}原因：<span style="color: red" v-if="val1 === '关阀'">*</span></label>
        <textarea class="form-control" v-model="reasonInfo" rows="3" placeholder="备注信息" :required="val1 === '关阀'"></textarea>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button type="button" class="btn btn-success btn-ln fr" @click='addApprovalValve()'>提交</button>
      <button type="button" class="btn btn-info btn-ln fr" @click='close()'>取消</button>
    </footer>
  </modal>
</template>

<script>
  import {PagedList} from "vue-client";
  import vue from 'vue';
  import * as Util from '../../Util';
  import {HttpResetClass} from 'vue-client'

  let fun = (json) => {
    let array = [];
    array.push({label: '无', value: undefined});
    for (let i = 0; i < json.length; i++) {
      if (json[i] == null) {
        continue
      }
      array.push({label: json[i], value: json[i]})
    }
    return array
  };
  export default {
    title: '批量开关阀',
    name: "WebMeterBatchOperationValve",
    data() {
      return {
        model: new PagedList("rs/sql/getOpertionList", 20),
        searchshow: false,
        condition: '',
        filialeCodeStr: '',
        isShowUserException: false,
        val1: '',
        reasonInfo: '',
        Gasproperties2: [],
        checked1: true,
        WarningType: [
          {label: '全部', value: ''}
        ],
        Warningstyle: [
          {label: '全部', value: ''}
        ],
        Warningstyles: [
          {label: '全部', value: ''}
        ],
        styles: false,
        excelTable: true,
        getfield: {
          'f_filiale': '组织机构',
          'f_userinfo_code': '用户号',
          'f_user_type': '用户类型',
          'f_gasproperties': '用气性质',
          'f_user_name': '用户姓名',
          'f_address': '用气地址',
          'f_gas_date': '安装时间',
          'f_meternumber': '表钢号',
          'f_meter_brand': '气表品牌',
          'f_user_id': '表编号',
          'f_meter_style': '气表型号',
          'f_valvestate': '阀门状态'
        },
        obj: {
          userid: this.$login.f.id,
          source: `tool.getFullTree(this.getRights().where(row.getType() == $organization$))`,
          res: this.$login.f.f_fengongsi,
          resids: this.$login.f.f_orgids
        },
        //开关阀权限
        valveLimit: false,
        //设置参数权限
        Setarameterermissions: false,
        parameterType: '',
        map: new Map()
      }
    },
    ready() {
      this.valveLimit = this.$login.r.includes('开关阀权限')
      this.Setarameterermissions = this.$login.r.includes('设置参数权限')
      this.obj.userid = vue.$login.f.id;
      this.obj.res = `${vue.$login.f.f_fengongsi}.${vue.$login.f.f_parentname}`;
      this.obj.resids = `${vue.$login.f.f_orgids}`;
      this.$refs.paged.$refs.criteria.model.f_start_date = Util.toStandardDateString() + ' 00:00:00'
      this.$refs.paged.$refs.criteria.model.f_end_date = Util.toStandardDateString() + ' 23:59:59'
      this.$refs.paged.$refs.criteria.search()
      //初始化气表品牌下拉框
      this.getMeterTypeAndBrand('f_meter_brand', '1=1')
    },
    methods: {
      search(args) {
        const filialeCondition = this.filialeCodeStr || this.getDefaultOrgCondition()
        let condition = args.condition
        if (filialeCondition) {
          condition = `${condition} and ${filialeCondition}`
        }
        args.condition = `${condition} and f_valvestate !='未上报'`
        this.model.search(args.condition, args.model)
        this.condition = args.condition
      },
      mapset(array) {
        this.map.clear();
        for (let i = 0; i < array.length; i++) {
          let userid = array[i].f_user_id;
          let alias = array[i].f_alias;
          let userinfoid = array[i].f_userinfo_id;
          let f_filiale = array[i].f_filiale;
          let f_filialeids = array[i].f_filialeids;
          let f_meternumber = array[i].f_meternumber;
          this.map.set(userid, {
            id: null,
            f_user_id: userid,
            f_alias: alias,
            f_userinfo_id: userinfoid,
            f_filiale: f_filiale,
            f_filialeids: f_filialeids,
            f_meternumber: f_meternumber
          })
        }
      },
      getMeterType() {
        this.Warningstyle = [{label: '全部', value: ''}]
        this.styles = false
        let f_meter_brand = this.$refs.paged.$refs.criteria.model.f_meter_brand
        this.getMeterTypeAndBrand('f_meter_style', `f_meter_brand='${f_meter_brand}'`)
      },
      getMeterTypeAndBrand(groupname, condition) {
        condition = `${condition} and ui.f_filialeids like '${this.obj.resids}%'`
        console.log(condition + "+getMeterTypeAndBrand")
        let self = this
        let load = new HttpResetClass()
        load.load('POST', 'rs/sql/getMeterStyleAndBrand', {
          data: {
            condition: condition,
            groupname: groupname
          }
        }, {warnMsg: null, resolveMsg: null}).then((res) => {
          let dr = {label: '', value: ''}
          let i = 0
          for (i = 0; i < res.data.length; i++) {
            dr = {label: '', value: ''}
            if (groupname == 'f_meter_brand') {
              dr.label = res.data[i].f_meter_brand
              dr.value = res.data[i].f_meter_brand
              //气表品牌
              console.log(dr.value + "dr.value")
              self.WarningType[i + 1] = dr
            } else if (groupname == 'f_meter_style') {
              dr.label = res.data[i].f_meter_style
              dr.value = res.data[i].f_meter_style
              //气表类型
              self.Warningstyle[i + 1] = dr
            }
          }
          if (self.Warningstyle.length > 1) {
            self.showMeterStyle()
          }
        })
        console.log(this.WarningType[0].label + ":label")
        console.log(this.WarningType[1] + ":this.WarningType[1]")
      },
      showMeterStyle() {
        console.log(this.Warningstyle.length + "this.Warningstyle.length" + this.WarningType.length)
        this.styles = true
      },

      uniq(array) {
        array.sort();
        let arraytype = [{label: '全部', value: ''}]
        let dr = {label: '', value: ''}
        if (array[0] == 'n') {
          dr = {label: '空值', value: 'is null'}
        } else {
          dr = {label: array[0], value: "='" + array[0] + "'"}
        }
        arraytype.push(dr)
        let temp = [array[0]];
        // console.log(array[0] + "array[0]")
        for (var i = 1; i < array.length; i++) {
          if (array[i] !== temp[temp.length - 1]) {
            if (array[i] == 'n') {
              dr = {label: '空值', value: 'is null'}
            } else {
              dr = {label: array[i], value: "='" + array[i] + "'"}
            }
            arraytype.push(dr);
            temp.push(array[i]);
          }
        }
        /*console.log(arraytype[1].label + "label")
        console.log(arraytype[1].value + "value")*/
        return arraytype;
      },
      back() {
        this.$parent.msg = ""
      },
      clearmsg() {
        this.$refs.paged.$refs.criteria.model = {}
      },
      clickshow() {
        this.searchshow = !this.searchshow
      },
      getRes(msg) {
        this.obj.res = msg.res;
        this.obj.resids = msg.resids
        const ids = (msg.resids || '').split(',').map(item => item.trim()).filter(item => item)
        if (ids.length <= 1) {
          this.filialeCodeStr = ids[0] ? `f_filialeids like '${ids[0]}%'` : ''
        } else {
          const parts = ids.map(code => `f_filialeids like '${code}%'`)
          this.filialeCodeStr = `(${parts.join(' or ')})`
        }
      },
      getDefaultOrgCondition () {
        const defaultOrg = this.$login.f.f_orgids || ''
        return defaultOrg ? `f_filialeids like '${defaultOrg}%'` : ''
      },
      checkedALL() {
        this.checked1 = !this.checked1
        let box = document.getElementsByName("opertioninput")
        for (var i = 0; i < box.length; i++) {
          box[i].checked = this.checked1;
        }
      },
      checked(val) {
        let userid = val.f_user_id;
        if (this.map.has(userid)) {
          this.map.delete(userid)
        } else {
          this.map.set(userid, {
            id: null,
            f_user_id: userid,
            f_alias: val.f_alias,
            f_userinfo_id: val.f_userinfo_id,
            f_filiale: val.f_filiale,
            f_filialeids: val.f_filialeids,
            f_meternumber: val.f_meternumber
          })
        }
      },
      showModal(val) {
        this.val1 = val;
        this.isShowUserException = true
      },
      close() {
        this.isShowUserException = false
      },
      addApprovalValve() {
        let valve = this.val1;
        console.log(valve + "this.val1")
        let array = [];
        this.map.forEach((value, key, map) => {
          array.push(map.get(key))
        });
        
        // 只在关阀时添加必填验证
        if (valve === '关阀' && (!this.reasonInfo || this.reasonInfo.trim() === '')) {
          this.$showMessage('请填写关阀原因');
          return;
        }
        
        if (valve == '设置参数') {
          if (this.parameterType == '') {
            return
          }
          this.approvalValveControl(valve, this.parameterType[0], array);
        } else {
          this.approvalValveControl('阀门控制', valve, array);
        }
        this.isShowUserException = false
      },
      setRunParam() {
        this.val1 = '设置参数';
        this.isShowUserException = true
      },

      approvalValveControl(f_apply_type, f_apply_value, array) {
        console.log("批量操作array======", array)
        console.log("批量操作 vue.$login.f.name======", vue.$login.f.name)
        let load = new HttpResetClass()
        let self = this
        load.load('POST', 'rs/logic/setParameter',
          {
            data: {
              userid: array,
              instructtype: f_apply_type,
              isOpen: f_apply_value,
              reasonInfo: this.reasonInfo,
              f_instruct_state: '待发送',
              inputtor: vue.$login.f.name
            }
          }).then((res) => {
          let count = res.data.count;
          let str = `执行完成,总共执行了${array.length}户的申请操作`;
          self.$showMessage(str)
        }).catch((res) => {
          this.$showMessage("执行失败，具体失败原因请查看后台日志文件！本次操作已被回滚！")
        })
      },
      /*operationValve(array,valve,instructtype) {
        console.log("批量操作array======", array)
        console.log("批量操作valve======", valve)
        console.log("批量操作 vue.$login.f.name======", vue.$login.f.name)
        let load = new HttpResetClass()
        load.load('POST', 'rs/logic/setParameter',
          {data:{
          userid: array,
          instructtype: instructtype,
          isOpen:valve,
          f_instruct_state:'待审核',
          inputtor: vue.$login.f.name
        }}, {rejectMsg: null, resolveMsg: null}).then((res) => {
          let count = array.length;
          console.log("批量操作 vue.$login.f.name======", vue.$login.f.name)
        }).catch((res) => {
          this.$showMessage("执行失败，具体失败原因请查看后台日志文件！本次操作已被回滚！")
        })
      }*/
    },
    computed: {
      MeterTypes() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('气表类型')]
      },
      TableStates() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('气表状态')]
      },
      parameterTypeList() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('设置参数')]
      },
      signtype1() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('标记名称')]
      },
      parameterState() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('标记状态')]
      },
      userfilesState() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('上报状态')]
      },
      valvestate() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('阀门状态')]
      },
      Gasusertype () {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('用户类型')]
      },
      Gasproperties () {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('用气性质')]
      }
    },
    watch: {
      'model.pageIndex'() {
        this.checked1 = false
        this.mapset(this.model.rows)
        this.checkedALL()
      },
      'model.rows'() {
        console.log("weeweweq")
        this.checked1 = false
        this.mapset(this.model.rows)
        this.checkedALL()
      },
      'checked1'(val) {
        if (val) {
          this.mapset(this.model.rows)
        } else {
          this.map.clear();
        }
      }
    }
  }
</script>

<style scoped>
  .PanelTR {
    width: 100%;
    height: 40px;
  }

  .PanelTD {
    width: 5%;
  }

  .btn-relative {
    position: relative;
    left: 25px;
    top: 15px;
  }
</style>
