<template>
  <div class="binary-left" style="width:48%">
    <div class="row auto">
      <div class="col-sm-4">
        <label class="font_normal_body" style="text-align:left">参数类型</label>
      </div>
      <div class="col-sm-4">
        <v-select
          placeholder="请选择参数组别"
          :value.sync="paramGroup"
          style="width:40%"
          width="80%"
          :search="false"
          :value-single="true"
          @change="paramGroupChange"
          v-model="paramGroup"
          :options='paramGroups'
          close-on-select
        ></v-select>
      </div>
      <div class="col-sm-4" v-show="['读取','设置'].includes(paramGroup)">
        <v-select
          placeholder="请选择参数类型"
          :value.sync="paramtype"
          style="width:40%"
          width="80%"
          :search="false"
          :value-single="true"
          v-model="paramtype"
          :options='paramtypes'
          close-on-select
        ></v-select>
      </div>
      <div v-for="(_,data) in newmeterinfo" style="height: auto">
        <div class="col-sm-12" style="height: auto" v-if="data.name===paramtype"
             v-show="(['设置特殊故障是否关阀','设置表功能开关'].includes(paramtype)&&!param.name.startsWith('设置'))||!['设置特殊故障是否关阀','设置表功能开关'].includes(paramtype)"
             v-for="(_,param) in data.params">
          <div class="col-sm-4">
            <label class="font_normal_body" style="text-align:left">{{ param.name }}：</label>
            <p class="glyphicon glyphicon-info-sign" style="margin-top:5%;color:#4a7cae"
               :title="param.remark + '，当前系统设置默认值为：'+param.default_value"></p>
          </div>
          <div class="col-sm-8" v-if="['设置特殊故障是否关阀','设置表功能开关'].includes(paramtype)">
            <radio-btn @toggle="radioBtnToggle" :title="param.title" v-model="row[param.title]" :value.sync="row[param.title]"></radio-btn>
          </div>
          <template v-if="!['设置特殊故障是否关阀','设置表功能开关'].includes(paramtype)">
            <div class="col-sm-8" v-if="param.type!=='option'">
              <input :type="param.type" v-model="row[param.title]"
                     style="width:70%" :value.sync="row[param.title]"
                     placeholder="" class="input_search">
            </div>
            <div class="col-sm-8" v-if="param.type==='option'">
              <v-select
                :placeholder='param.name'
                :value.sync="row[param.title]"
                style="width:70%"
                width="70%"
                :value-single="true"
                v-model="row[param.title]"
                :options='param.params'
                close-on-select
              >
              </v-select>
            </div>
          </template>
        </div>
      </div>
      <div class="form-group col-sm-4" style="float:right;white-space: nowrap;width: auto">
        <button class="button_search" @click="setParam()" v-if="paramtype && user ">提交</button>
        <button class="button_search" @click="setParamDefault()" v-if="paramtype && !user">提交</button>
      </div>
    </div>
  </div>
  <div class="binary-right" style="width:48%;overflow-y: auto;max-height:1000px;" v-if="user">
    <div class="row list_area table_sy">
      <h4 style="display:inline-block;"><font style="font-weight: bold">已选中客户数:</font>{{ user.length }}</h4>
      <div v-if="condition" class="row auto">
        <h4 style="display:inline-block;"><font style="font-weight: bold">查询条件:</font>{{ condition }}</h4>
      </div>
      <table class="table table-bordered table-striped table-hover" style="margin-top: 15px" id="table1">
        <thead>
        <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>
        </thead>
        <tbody>
        <tr v-for="row in user">
          <td>
            <nobr>{{ row.f_userinfo_code }}</nobr>
          </td>
          <td>
            <nobr>{{ row.f_user_name }}</nobr>
          </td>
          <td>
            <nobr>{{ row.f_user_type }}</nobr>
          </td>
          <td>
            <nobr>{{ row.f_meter_brand }}</nobr>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
  <div class="binary-right flex-row" style="width:80%;overflow-y: auto;max-height:1000px;" v-if="!user">
    <div class="binary-left" style="width:24% ;text-align:center;align-content: center;">
      <div class="row">
        <div v-for="data in newmeterinfo" style="height: auto">
          <ul class="nav nav-tabs col-sm-12">
            <li class="active"><a>{{ data.name }}</a></li>
          </ul>
          <div class="col-sm-12" style="height: auto" v-for="p in data.params">
            {{ p.name }}：{{ param[p.title] }}
          </div>
        </div>
      </div>
    </div>
    <div class="binary-right" style="width:74%;overflow-y: auto;max-height:1000px;">
      <div class="row list_area table_sy">
        <table class="table table-bordered table-striped table-hover" id="table1">
          <thead>
          <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>-->
          </thead>
          <tbody>
          <tr v-for="row in history">
            <td>
              <nobr>{{ row.f_param_group_name }}</nobr>
            </td>
            <td>
              <nobr>{{ row.f_param_name }}</nobr>
            </td>
            <td>
              <nobr>{{ row.oldvalue }}</nobr>
            </td>
            <td>
              <nobr>{{ row.f_param_value }}</nobr>
            </td>

            <!--          <td><nobr>{{row.f_user_type}}</nobr></td>-->
            <!--          <td><nobr>{{row.f_meter_brand}}</nobr></td>-->
          </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

</template>


<script>
import {HttpResetClass} from 'vue-client'
import RadioBtn from './RadioBtn'
// const copyObject = (data) => {
//   let copyData
//   if (Array.isArray(data)) {
//     copyData = []
//     data.forEach(v => {
//       copyData.push(copyObject(v))
//     })
//   } else if (typeof data === 'object') {
//     copyData = {}
//     for (let n in data) {
//       copyData[n] = copyObject(data[n])
//     }
//   } else if ((typeof data).match(/^(string|number|boolean)$/)) {
//     return data
//   }
//   return copyData
// }
export default {
  title: '参数设置',
  props: ['user', 'checked1', 'gasbrandid', 'condition'],
  components: {RadioBtn},
  data () {
    return {
      newmeterinfo: [{}],
      row: {},
      gasbrand: null,
      paramtypes: [],
      paramtype: '',
      param: {},
      history: [],
      isenbale: false,
      paramGroups: [{label: '读取', value: '读取'}, {label: '设置', value: '设置'},
        {label: '设置表功能开关', value: '设置表功能开关'}, {
          label: '设置特殊故障是否关阀',
          value: '设置特殊故障是否关阀'
        }],
      paramGroup: ''
    }
  },
  ready () {

  },
  watch: {
    param: {
      handler: function (val) {
        console.log('--------------param变了', val)
      },
      deep: true
    },
    'gasbrandid' (val) {
      if (val[0]) {
        this.refreshParam(val[0])
      }
    },
    'paramtype' (val) {
      this.row = {}
      if (val) {
        // 循环给row赋值  row存储当前页面的值   虽然我不知道为什么这么设计  但是目前只能继续用了
        const temp = this.newmeterinfo.filter(item => item.name === val)[0]
        if (temp && temp.params.length > 0) {
          for (let i = 0; i < temp.params.length; i++) {
            if (['设置特殊故障是否关阀', '设置表功能开关'].includes(val)) {
              this.row[temp.params[i].title] = ['保持不变']
            } else {
              if (temp.params[i].default_value) {
                this.row[temp.params[i].title] = temp.params[i].default_value
              }
            }
          }
        }
        this.row = Object.assign({}, this.row)
      }
    }
  },
  methods: {
    radioBtnToggle (title, value) {
      // 设置表功能开关 ->  启用时操作 ->  设置
      // pzwbit0 -> bzwbit0
      // 设置特殊故障是否关阀 ->  启用时操作 ->  设置
      // pbit0 -> bbit0
      // 当启用 为 ['保持不变']时 设置应为 ['保持不变']
      // 当启用 为 ['启用']时 设置应为 ['启用']
      // 当启用 为 []时 设置应为 ['启用']
      // 获取到设置的title
      // 把第一个p替换成b
      if (!title.startsWith('p')) {
        return
      }
      let _title = title.replace('p', 'b')
      if (value.length === 1) {
        if (value[0] === '保持不变') {
          this.row[_title] = ['保持不变']
        } else {
          this.row[_title] = ['启用']
        }
      } else {
        this.row[_title] = ['启用']
      }
      this.row = Object.assign({}, this.row)
    },
    paramGroupChange (val) {
      const tempArr = ['设置特殊故障是否关阀', '设置表功能开关']
      if (['读取', '设置'].includes(val)) {
        this.paramtypes = this.newmeterinfo
          .filter(item => item.theType === val && !tempArr.includes(item.name))
          .map(item => {
            return {label: item.name, value: item.name}
          })
          .sort((a, b) => a.label.length - b.label.length)
        this.paramtype = undefined
        return
      }
      this.paramtype = val
    },
    close () {
      this.row = {}
      this.$dispatch('close')
    },
    async setParamDefault () {
      let params = []
      for (let i = 0; i < this.newmeterinfo.length; i++) {
        for (let j = 0; j < this.newmeterinfo[i].params.length; j++) {
          if (this.newmeterinfo[i].name === this.paramtype) {
            for (let key in this.row) {
              if (!this.row[key] && !['设置特殊故障是否关阀', '设置表功能开关'].includes(this.paramtype)) {
                this.$showAlert('每个参数需要填写完整！', 'warning', 2000)
                throw new Error('每个参数需要填写完整')
              }
              if (key === this.newmeterinfo[i].params[j].title) {
                let data = {}
                data.tag = this.newmeterinfo[i].tag
                data.param_group = this.newmeterinfo[i].name
                data.param_name = this.newmeterinfo[i].params[j].name
                data.param_value = this.row[key] ? (this.row[key].code ? this.row[key].code : this.row[key]) : null
                data.param_content = this.row[key] ? (this.row[key].content ? this.row[key].content : this.row[key]) : null
                data.param_lname = this.newmeterinfo[i].params[j].title
                if (['设置特殊故障是否关阀', '设置表功能开关'].includes(this.paramtype)) {
                  if (this.row[key].length === 1 && this.row[key][0] === '启用') {
                    data.param_value = data.param_content = '1'
                    params.push(data)
                  } else {
                    data.param_value = data.param_content = '0'
                    params.push(data)
                  }
                } else if (this.row[key]) {
                  params.push(data)
                }
              }
            }
          }
        }
      }
      let param = {
        condition: 'g.f_gasbrand_id = ' + this.gasbrandid[0],
        switchCheckAll: this.checked1,
        users: '',
        params: params,
        f_alias: this.gasbrand.f_alias,
        columnName: '',
        // inputter_name: this.$login.f.name,
        f_operator: this.$login.f.name,
        f_operatorid: this.$login.f.id,
        f_orgid: this.$login.f.orgid,
        f_orgname: this.$login.f.orgs,
        f_depid: this.$login.f.depids,
        f_depname: this.$login.f.deps,
        f_gasbrand_id: this.gasbrandid[0]
      }
      console.log(param)
      if (params.length > 0) {
        await this.$resetpost('/rs/logic/alteration_batch', {data: param}, {
          rejectMsg: '批量保存失败',
          resolveMsg: '保存成功'
        })
      }
      this.row = null
      this.$dispatch('clear')
    },
    async setParam () {
      let user = []
      let filesid = ''
      this.user.forEach((item) => {
        user.push(item.f_userfiles_id)
        filesid += item.f_userfiles_id + ','
      })
      filesid = filesid.substr(0, filesid.length - 1)
      let params = []
      for (let i = 0; i < this.newmeterinfo.length; i++) {
        for (let j = 0; j < this.newmeterinfo[i].params.length; j++) {
          console.log('this.newmeterinfo[i].name === this.paramtype', this.newmeterinfo[i].name === this.paramtype)
          console.log('this.newmeterinfo[i].name === this.paramtype', this.paramtype)
          if (this.newmeterinfo[i].name === this.paramtype) {
            for (let key in this.row) {
              if (!this.row[key] && !['设置特殊故障是否关阀', '设置表功能开关'].includes(this.paramtype)) {
                this.$showAlert('每个参数需要填写完整！', 'warning', 2000)
                throw new Error('每个参数需要填写完整')
              }
              console.log('this.newmeterinfo[i].params[j].title', this.newmeterinfo[i].params[j].title)
              if (key === this.newmeterinfo[i].params[j].title) {
                let data = {}
                data.param_group = this.newmeterinfo[i].name
                data.param_name = this.newmeterinfo[i].params[j].name
                data.tag = this.newmeterinfo[i].tag
                data.param_value = this.row[key] ? (this.row[key].code ? this.row[key].code : this.row[key]) : null
                data.param_content = this.row[key] ? (this.row[key].content ? this.row[key].content : this.row[key]) : null
                data.param_lname = this.newmeterinfo[i].params[j].title
                if (['设置特殊故障是否关阀', '设置表功能开关'].includes(this.paramtype)) {
                  if (this.row[key].length === 1 && this.row[key][0] === '启用') {
                    data.param_value = data.param_content = '1'
                    params.push(data)
                  } else {
                    data.param_value = data.param_content = '0'
                    params.push(data)
                  }
                } else if (this.row[key]) {
                  params.push(data)
                }
              }
            }
          }
        }
      }
      debugger
      let param = {
        condition: 'g.f_gasbrand_id = ' + this.gasbrandid[0] + ' and f.f_userfiles_id in (' + filesid + ')',
        switchCheckAll: this.checked1,
        users: user,
        params: params,
        f_alias: this.gasbrand.f_alias,
        columnName: 'g.f_userfiles_id',
        // inputter_name: this.$login.f.name,
        f_operator: this.$login.f.name,
        f_operatorid: this.$login.f.id,
        f_orgid: this.$login.f.orgid,
        f_orgname: this.$login.f.orgs,
        f_depid: this.$login.f.depids,
        f_depname: this.$login.f.deps,
        f_gasbrand_id: this.gasbrandid[0]
      }
      console.log(param)
      if (params.length > 0) {
        await this.$resetpost('/rs/logic/alteration_batch', {data: param}, {
          rejectMsg: '批量保存失败',
          resolveMsg: '保存成功'
        })
      }
      this.row = null
      this.$dispatch('clear')
    },
    async refreshParam (val) {
      this.paramtypes = []
      let temp = {
        tablename: 't_gasbrand',
        condition: `id=${val}`
      }
      await this.$resetpost('rs/sql/saleSingleTable', {data: temp}, {resolveMsg: null, rejectMsg: null}).then((res) => {
        this.gasbrand = res.data[0]
      })
      this.newmeterinfo = [{}]

      let res = await this.$resetpost('/webmeter/rs/logic/getParamsByGasBrand', {data: {gasBrandId: val}}, {
        resolveMsg: null,
        rejectMsg: '参数获取失败'
      })
      let allDefaultValue = await this.$resetpost('/rs/sql/getAllDefaultValues', {data: {gasBrandId: val}}, {
        resolveMsg: null,
        rejectMsg: null
      })
      this.newmeterinfo = res.data
      for (let i = 0; i < this.newmeterinfo.length; i++) {
        this.paramtypes.push({label: this.newmeterinfo[i].name, value: this.newmeterinfo[i].name})
        for (let j = 0; j < this.newmeterinfo[i].params.length; j++) {
          this.newmeterinfo[i].params[j].isenbale = []
          for (let n = 0; n < allDefaultValue.data.length; n++) {
            if (this.newmeterinfo[i].params[j].name === allDefaultValue.data[n].f_param_name && this.newmeterinfo[i].name === allDefaultValue.data[n].f_group_name && allDefaultValue.data[n].f_param_title === this.newmeterinfo[i].params[j].title) {
              this.newmeterinfo[i].params[j].default_value = allDefaultValue.data[n].f_param_value
              this.newmeterinfo[i].params[j].default_id = allDefaultValue.data[n].default_id
              break
            }
          }
          if (this.newmeterinfo[i].params[j].params instanceof Array) {
            for (let k = 0; k < this.newmeterinfo[i].params[j].params.length; k++) {
              this.newmeterinfo[i].params[j].params[k].value = {
                id: this.newmeterinfo[i].params[j].params[k].label,
                code: this.newmeterinfo[i].params[j].params[k].value,
                content: this.newmeterinfo[i].params[j].params[k].label
              }
            }
          }
        }
      }
      this.$dispatch('showparam', true)
    },
    async getBrandParamsHistory () {
      let http = new HttpResetClass()
      let res = await http.load('POST', 'rs/sql/getBrandParamHistory', {
        data: {
          condition: `ga.f_gasbrand_id= ${this.gasbrandid}`
        }
      }, {resolveMsg: null, rejectMsg: '获取参数历史信息信息失败'})
      this.history = res.data
      let rat = await http.load('POST', 'rs/sql/singleTable_OrderBy', {
        data: {
          items: '*',
          tablename: 't_gasparammanage',
          condition: `f_gasbrand_id= ${this.gasbrandid}`,
          orderitem: 'id desc'
        }
      }, {resolveMsg: null, rejectMsg: '获取参数历史信息信息失败'})
      if (rat.data.length > 0) {
        rat.data.forEach((item) => {
          if (!this.param[item.f_param_lname]) {
            console.log(item.f_param_value, item.f_param_content)
            if (item.f_param_value != item.f_param_content) {
              item.f_param_value = item.f_param_content
            }
            if (item.f_param_value === '1') {
              item.f_param_value = '开'
            }
            if (item.f_param_value === '0') {
              item.f_param_value = '关'
            }
            console.log('参数取出来了---', item.f_param_lname)
            this.$set(`param['${item.f_param_lname}']`, item.f_param_value)
          }
          // this.param[item.f_param_lname] = item.f_param_value
        })
      }
      console.log('参数取出来了', this.param)
    }
  }
}
</script>
<style>
.btn-border {
  border: none;
  border-radius: 6px;
}
</style>
