<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div style="padding-left: 30px">
    <span style="font-weight: bold">通道：</span>
    <vxe-select v-model="tunnelId" placeholder="请选择使用通道" style="width: 10%" clearable>
      <vxe-option v-for="item in tunnelList" :key="item.id" :value="item.id" :label="item.tunnelName" />
    </vxe-select>
    <span style="font-weight: bold">设备：</span>
    <vxe-select v-model="eqId" placeholder="请选择查询设备" style="width: 10%" clearable>
      <vxe-option v-for="(item,index) in eqTableData" :key="index" :value="index" :label="item.name" />
    </vxe-select>
    <div style="display: inline-block">
      <vxe-toolbar>
        <template v-slot:buttons>
          <vxe-button status="primary" @click="searchPointData()">查询</vxe-button>
          <vxe-button status="primary" icon="fa fa-plus" @click="insertEvent()">新增</vxe-button>
          <vxe-button status="primary" icon="fa fa-files-o" @click="multiAdd=true">批量新增</vxe-button>
          <vxe-button status="primary" icon="fa fa-files-o" @click="batchDeletePoint()">批量删除</vxe-button>
          <vxe-button status="primary" icon="vxe-icon--refresh roll" @click="refushAll()">刷新数据点</vxe-button>
        </template>
      </vxe-toolbar>
    </div>
    <!-- <div style="float: right;padding-top: 10px">

      &lt;!&ndash;<el-button-group>
        <el-button type="primary" size="small" @click="refushEq()">刷新设备</el-button>
        <el-button type="primary" size="small" @click="refushTunnel()">刷新通道</el-button>
      </el-button-group>&ndash;&gt;
    </div>-->

    <vxe-table
      ref="xTable"
      border
      stripe
      resizable
      show-overflow
      keep-source
      max-height="800"
      align="center"
      :cell-style="headerCellClassName"
      :loading="loading"
      :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
    >
      <vxe-table-column type="checkbox" />
      <vxe-table-column field="equipmentId" title="名称" :formatter="formateEqId" />
      <vxe-table-column field="equipmentAttribute.explanation" title="设备属性" />
      <vxe-table-column title="实时数据">
        <template #default="{ row }">
          <!--{{row.id}}-->
              {{realTimeData[row.id]}}
        </template>
      </vxe-table-column>
      <vxe-table-column
        field="dataSource"
        title="数据源"
        :filters="enums.geterDataSourceEnum"
        :formatter="formatterDataSource"
      />
      <vxe-table-column field="tunnelId" title="使用通道" :formatter="formateId" />
      <vxe-table-column field="protocolPointNo" sortable title="通道点位" />
      <vxe-table-column field="protocolPointType" title="通道数据类型" :formatter="formatterPointType" />
      <vxe-table-column field="magnification" title="倍率" />
      <vxe-table-column field="generationRegulation" title="数据生成公式" :formatter="generationRegulationFormatter"/>
      <vxe-table-column field="showOnHomePage" title="展示顺序" sortable :formatter="showOnHomePageFormatter" />
      <vxe-table-column field="needAudit" title="是否考核" :filters="needAuditList" :formatter="formatterNeedAudit">
        <template #header>
          <i :class="columnShow ?'vxe-icon--remove' : 'vxe-icon--circle-plus'"  @click="columnButClick"></i>
          <span>是否考核</span>
        </template>
      </vxe-table-column>
      <vxe-table-column field="maxChangeValue" title="最大变化值" :visible="false" />
      <vxe-table-column field="maxValue" title="最大值" :visible="false" />
      <vxe-table-column field="minValue" title="最小值" :visible="false" />
      <vxe-table-column field="maxDuration" title="最长持续时间(min)" :visible="false"/>
      <vxe-table-column field="id" title="Id" />
      <vxe-table-column title="操作" width="150">
        <template v-slot="{ row }">
          <template>
            <vxe-button status="primary" size="mini" @click="editRowEvent(row)">编辑</vxe-button>
            <vxe-button status="danger" size="mini" @click="removeEvent(row)">删除</vxe-button>
          </template>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      perfect
      :current-page.sync="currentPage"
      :page-size.sync="pageSize"
      :total="totalResult"
      :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
    />

    <vxe-modal
      ref="xModal"
      v-model="showEdit"
      :title="selectRow ? '编辑&保存' : '新增&保存'"
      width="800"
      resize
      destroy-on-close
    >
      <vxe-form
        ref="form"
        :data="formData"
        :rules="formRules"
        title-align="center"
        title-width="100"
        @submit="submitEvent"
      >
        <vxe-form-item title="设备类型" field="eqType" span="12">
          <vxe-select v-model="formData.eqType" placeholder="请选择设备类型" size="medium" @change="changeEqA">
            <vxe-option
              v-for="item in enums.equipmentTypeEnum"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </vxe-select>
        </vxe-form-item>
        <vxe-form-item title="设备名" field="equipmentId" span="12">
          <vxe-select v-model="formData.equipmentId" placeholder="请选择设备名" size="medium">
            <vxe-option v-for="(item,index) in eqData" :key="index" :value="item.id" :label="item.name" />
          </vxe-select>
        </vxe-form-item>
        <vxe-form-item title="设备属性" field="equipmentAttribute" span="12">
          <vxe-select v-model="formData.equipmentAttribute.id" placeholder="请选择设备属性" size="medium" @change="attribute">
            <vxe-option v-for="item in eqaTableData" :key="item.id" :value="item.id" :label="item.explanation" />
          </vxe-select>
        </vxe-form-item>
        <vxe-form-item
          title="倍率"
          field="magnification"
          span="12"
          :item-render="{name: 'input', attrs: {type: 'float'}}"
        />
        <vxe-form-item title="数据源" field="dataSource" span="12" title-width="100px">
          <vxe-select v-model="formData.dataSource" placeholder="请选择点位生成规则" size="medium" @change="datasChange">
            <vxe-option
              v-for="item in enums.geterDataSourceEnum"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </vxe-select>
        </vxe-form-item>
        <!--外部接入-->
        <vxe-form-item title="使用通道" field="tunnelId" span="12" v-show="!gatherDisable">
          <vxe-select
            v-model="formData.tunnelId"
            placeholder="请选择使用通道"
            size="medium"
            :disabled="gatherDisable"
            @change="getByTunnel"
          >
            <vxe-option v-for="item in tunnelList" :key="item.id" :value="item.id" :label="item.tunnelName" />
          </vxe-select>
        </vxe-form-item>
        <vxe-form-item title="通道点位" field="protocolPointNo" span="12" v-show="!gatherDisable">
          <vxe-input
            v-model="formData.protocolPointNo"
            placeholder="请输入通道点位"
            clearable
            type="number"
            :disabled="gatherDisable"
            @change="checkprotocolPointNo"
          />
        </vxe-form-item>
        <vxe-form-item title="通道数据类型" field="protocolPointType" span="12" title-width="120px">
          <vxe-select v-model="formData.protocolPointType" placeholder="请选择通道数据类型" size="medium">
            <vxe-option
              v-for="item in protocolDataType"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </vxe-select>
        </vxe-form-item>
        <!--公式生成-->
          <vxe-form-item title="数据生成公式" field="generationRegulation" title-width="120px" span="24" v-show="generateShow">
            <vxe-input
              class="regulate"
              v-model="formData.generationRegulation"
              placeholder="请输入属性规则"
              type="textarea"
              clearable
              :disabled="generateDisable"
            >
              <template #suffix>
                <vxe-button icon="el-icon-key"
                v-show="regButShow"
                @click="regButClick"
                @dblclick.native="generateDisable = false"
                >系统自动计算</vxe-button>
              </template>
            </vxe-input>
            <span v-show="regTextShow">{{generationRegulationText}}</span>
          </vxe-form-item>


        <vxe-form-item title="首页展示顺序" title-width="120px" field="showOnHomePage" span="12">
          <vxe-input
            v-model="formData.showOnHomePage"
            placeholder="0为不展示"
            type="integer"
            clearable
            :disabled="formData.eqType!='WINDTOWER' && formData.eqType!='WEATHERSTATION'"
          />
        </vxe-form-item>
        <vxe-form-item title="是否考核" field="needAudit" span="12">
          <vxe-select v-model="formData.needAudit" placeholder="请选择是否考核" size="medium" @change="needChange">
            <vxe-option v-for="item in needAuditList" :key="item.value" :value="item.value" :label="item.label" />
          </vxe-select>
        </vxe-form-item>
        <vxe-form-item title="最大变化值" field="maxChangeValue" span="12" v-show="needShow">
          <vxe-input
            v-model="formData.maxChangeValue"
            placeholder="请输入变化值"
            type="number"
            clearable
            :disabled="needdisable"
          />
        </vxe-form-item>
        <vxe-form-item title="最大值" field="maxValue" span="12" v-show="needShow">
          <vxe-input
            v-model="formData.maxValue"
            placeholder="请输入最大值"
            type="number"
            clearable
            :disabled="needdisable"
          />
        </vxe-form-item>
        <vxe-form-item title="最小值" field="minValue" span="12" v-show="needShow">
          <vxe-input
            v-model="formData.minValue"
            placeholder="请输入最小值"
            type="number"
            clearable
            :disabled="needdisable"
          />
        </vxe-form-item>
        <vxe-form-item title="最长持续时间" field="maxDuration" span="12" title-width="120px" v-show="needShow">
          <vxe-input
            v-model="formData.maxDuration"
            placeholder="请输入最长持续时间"
            type="number"
            clearable
            :disabled="needdisable"
          />
        </vxe-form-item>
        <vxe-form-item align="center" span="24">
          <vxe-button status="primary" :disabled="buttonShow" type="submit">保存</vxe-button>
          <vxe-button v-show="resetShow" @click="resetForm">重置</vxe-button>
          <vxe-button @click="$refs.xModal.close()">取消</vxe-button>
        </vxe-form-item>
      </vxe-form>
    </vxe-modal>
    <MultiAdd :show="multiAdd" @close="changeMultiAdd" />
  </div>
</template>

<script>
import enumerations from '../../enumeration'
import MultiAdd from './multiAdd'

export default {

  components: {
    MultiAdd
  },
  data() {
    const checkMaxDuration = ({ cellValue, rule, row, column }) => {
      var reg = /^[1-9]\d*$/
      if (!reg.test(this.formData.maxDuration)) {
        // 如果校验失败，则返回
        return Promise.reject(new Error('请填写正整数'))
      }
    }
    // 验证展示顺序  同设备上不允许有相同的顺序
    const checkDisplayOrder = async({ cellValue, rule, row, column }) => {
      if (this.formData.showOnHomePage == 0) {
      }
      if (this.formData.equipmentId === '' || this.formData.equipmentId === null) {
        return Promise.reject(new Error('请先选择设备！'))
      }
      if (this.formData.equipmentId === this.stationCode) {
        this.formData.equipmentId = 0
      }
      const param = {
        params: {
          equipmentId: this.formData.equipmentId,
          equipmentType: this.formData.eqType,
          showOnHomePage: this.formData.showOnHomePage
        }
      }
      const data = await this.getDataPoint(param)
      if (data != null && data.length >= 1) {
        if (data[0].equipmentAttribute.id !== this.formData.equipmentAttribute.id) { return Promise.reject(new Error('同一设备的点位顺序不能相同')) }
      }
    }
    const generationRegulationValidate = async({ cellValue, rule, row, column }) => {
      const formData = this.formData
      if(formData.generationRegulation === '系统自动计算'){
        formData.generationRegulation = '1'
      }
      if (cellValue !== null) {
        const flag = await this.$axios.get('/dataExchange/protocolDataPoint/checkFormula', { params: { formula: formData.generationRegulation }}).then(re => {
          return re.code == 0
        }).catch(e => {
          return false
        }
        )
        if (!flag) {
          return Promise.reject(new Error('非法计算公式！'))
        } else {
          return Promise.resolve()
        }
      }
    }

    return {
      loading: false,
      buttonShow: false,
      resetShow: true,
      // 后台传输数据
      tableData: [],
      elTableData: [],
      elId: '',
      stationCode: '',
      eqTableData: [],
      eqId: '',
      eqData: [],
      tempId: '',
      eqaTableData: [],
      tunnelId: '',
      tunnelTable: [],
      // 批量添加的模态框是否展示
      multiAdd: false,
      // 编辑&添加 模态框是否显示
      showEdit: false,
      selectRow: null,
      // 用于区分是保存处理还是编辑处理
      saveFlag: 1,
      // 编辑弹出框内修改的点表id
      modelId: '',
      // 分页
      currentPage: 1,
      pageSize: 10,
      totalResult: 0,
      // 判断表示
      gatherDisable: false,
      generateDisable: true,
      generateShow: false,
      needdisable: true,
      input1: true,
      input2: false,
      needShow: false,//设备属性为实际功率不展示
      regTextShow: false,//公式规则提示文本显示
      regButShow: false,//系统自动计算按钮
      columnShow: false,
      pointNo: '',
      equipmentList: [],
      generationRegulationText: '',//公式规则提示文本
      generationRegulationValidate: generationRegulationValidate,
      formData: {
        equipmentId: '',
        equipmentAttribute: { 'id': '' },
        eqType: '',
        dataSource: 'GATHER',
        tunnelId: '',
        protocolPointNo: '',
        protocolPointType: 'ABCD',
        magnification: 1,
        needAudit: false,
        showOnHomePage: 0,
        maxChangeValue: '',
        maxValue: '',
        minValue: '',
        maxDuration: '',
        generationRegulation: ''
      },
      // 数据类型
      code: '',
      message: '',
      mtunnelId: '',
      gatherRules: {
        dataSource: [{ required: true, message: '请选择数据来源' }],
        equipmentId: [{ required: true, message: '请选择设备' }],
        equipmentAttribute: [{ required: true, message: '请选择设备类型' }],
        eqType: [{ required: true, message: '请选择设备属性' }],
        magnification: [{ required: true, message: '请输入倍率' }],
        tunnelId: [{ required: true, message: '请选择通道' }],
        protocolPointNo: [{ required: true, message: '请选择通道点位' }],
        showOnHomePage: [{ required: true, message: '请输入页面展示顺序', validator: checkDisplayOrder }],
        protocolPointType: [{ required: true, message: '请选择通道数据类型' }]
      },
      geterteRules: {
        dataSource: [{ required: true, message: '请选择数据来源' }],
        equipmentId: [{ required: true, message: '请选择设备' }],
        equipmentAttribute: [{ required: true, message: '请选择设备类型' }],
        eqType: [{ required: true, message: '请选择设备属性' }],
        magnification: [{ required: true, message: '请输入倍率' }],
        showOnHomePage: [{ required: true, message: '请输入页面展示顺序', validator: checkDisplayOrder }],
        generationRegulation: [{ required: true, message: '请填写属性规则', validator: generationRegulationValidate }]
      },
      needAuditRules: {
        maxChangeValue: [{ required: true, message: '请输入变化最大值' }],
        maxValue: [{ required: true, message: '请输入最大值' }],
        minValue: [{ required: true, message: '请输入最小值' }],
        maxDuration: [{ required: true, message: '请输入时长允许变化的值', validator: checkMaxDuration }]
      },
      formRules: {},
      enums: enumerations,
      needAuditList: [{ label: '是', value: true }, { label: '否', value: false }],
      tunnelList: [],
      protocolDataType: enumerations.ProtocolDataType,
      timer: '',
      realTimeData: {}
      /* ProtocolDataType: [{ label: '遥信开关量', value: 0 },
        { label: '+AB', value: 1 },
        { label: '±AB', value: 2 },
        { label: '+BA', value: 3 },
        { label: '±BA', value: 4 },
        { label: '+AABB', value: 5 },
        { label: '±AABB', value: 6 },
        { label: '+BBAA', value: 7 },
        { label: '±BBAA', value: 8 },
        { label: 'ABCD', value: 9 },
        { label: 'CDAB', value: 10 },
        { label: 'DCBA', value: 11 },
        { label: 'BADC', value: 13 }
      ]*/
    }
  },
  created() {
    this.getAll()
    /* this.$nextTick(function() {
                      this.getDataPoint()
                    })*/
    this.formRules = Object.assign(this.formRules, this.gatherRules)
    // this.formRules = Object.assign(this.formRules, this.needAuditRules)
  },
  destroyed(){
    clearInterval(this.timer)
  },
  methods: {

    columnButClick () {
      const fields = ["maxChangeValue","maxValue","minValue","maxDuration"]
      this.columnShow = !this.columnShow
      const xTable = this.$refs.xTable
      fields.forEach(field => {
        const column = xTable.getColumnByField(field)
        column.visible = this.columnShow
      })
      xTable.refreshColumn()
    },
    refushAll() {
      this.$axios.get('/refreshContainer/allDataPoint').then(res => {
        // console.log(res)
        this.$message.success('刷新成功')
      })
    },
    refushEq() {
      this.$axios.get('/refreshContainer/allPackerDataPoint').then(res => {
        // console.log(res)
        this.$message.success('刷新设备成功')
      })
    },
    refushTunnel() {
      this.$axios.get('/refreshContainer/allGatherTunnelDataPoint').then(res => {
        // console.log(res)
        this.$message.success('刷新通道成功')
      })
    },
    getAll() {
      // this.flushRealTimeData()
      Promise.all([this.getEq(), this.getTunnel(), this.getEl()]).then((res) => {
        this.eqTableData = res[0]
        this.tunnelList = res[1]
        this.stationCode = res[2].stationCode
        this.elTableData.push(res[2])
        this.flushRealTimeData()
        this.$nextTick(function () {
          this.getAllDataPoint()
        })

        let _this=this
        this.timer = setInterval(function () {
          _this.flushRealTimeData()
        }, 5000)
      })
    },
    // 场站
    getEl() {
      const axios = this.$axios
      return new Promise(function(resolve, reject) {
        axios.get('/electricField/').then(res => {
          resolve(res.data)
        })
      })
    },
    // 场站设备
    getEq() {
      const axios = this.$axios
      return new Promise(function(resolve, reject) {
        axios.get('/dataExchange/equipmentInfo/').then(res => {
          resolve(res.data)
        })
      })
    },
    // 场站设备
    getAllDataPoint() {
      this.loading = true
      this.$axios.get('/dataExchange/protocolDataPoint/gatherDataPoint/').then(res => {
          this.tableData = res.data
          console.log(this.tableData)
          this.totalResult = this.tableData.length
          this.currentPage = 1
          // console.log(this.tableData)
          this.loading = false
      })
    },
    //实时数据
    flushRealTimeData(){
      this.$axios.get('/protocolDataContainer/').then(res => {
        this.realTimeData = res.data
        // console.log(res.data)
      })
    },

    getDataPoint(param) {
      // eslint-disable-next-line prefer-const
      return this.$axios.get('/dataExchange/protocolDataPoint/gatherDataPoint/', param)
    },
    // 获取通道
    getTunnel() {
      const axios = this.$axios
      return new Promise(function(resolve, reject) {
        axios.get('/TunnelInfo/getTunnel/Master').then(res => {
          resolve(res.data)
        })
      })
    },
    // 设备属性
    getEquipmentA() {
      this.$axios.get('/dataExchange/getByEquipmentType/' + this.code).then(res => {
        this.eqaTableData = res.data
      })
    },
    // 修改是否展示批量添加的模态框显隐的控制值
    changeMultiAdd() {
      this.multiAdd = false
    },
    // 查询点表
    searchPointData() {
      if ((this.tunnelId === '' || this.tunnelId === null) && (this.eqId === '' || this.eqId === null)) {
        this.getAllDataPoint()
      } else {
        this.loading = true
        var tunnelId = ''
        var equipmentId = ''
        var equipmentType = ''
        if (this.tunnelId === '' || this.tunnelId === undefined || this.tunnelId === null) {
          tunnelId = 'ALL'
        } else tunnelId = this.tunnelId

        if (this.eqTableData[this.eqId] === [] || this.eqTableData[this.eqId] === undefined) {
          equipmentId = 'ALL'
          equipmentType = 0
        } else {
          equipmentId = this.eqTableData[this.eqId].id
          if (equipmentId === this.elTableData[0].stationCode) {
            equipmentId = 0
            equipmentType = this.eqTableData[this.eqId].code
          } else {
            equipmentType = this.eqTableData[this.eqId].equipmentType.code
          }
        }
        this.$axios.get('/dataExchange/protocolDataPoint/getBytunnelAndEquipment/' + tunnelId + '/' + equipmentId + '/' + equipmentType).then(res => {
          this.tableData = res.data
          this.totalResult = this.tableData.length
          this.currentPage = 1
          this.loading = false
        })
      }
    },
    // 设备名改变设备属性下拉框改变
    changeEqA() {
      if (this.formateEqType(this.formData.eqType)) {
        this.code = this.tempId
        if (this.tempId === 0 || this.tempId === 21) {
          this.$axios.get('/electricField/').then(res => {
            // console.log(res.data)
            this.eqData = []
            // eslint-disable-next-line eqeqeq
            if (res.code == 0) {
              this.eqData.push({ id: res.data.stationCode, name: res.data.name })
              this.formData.equipmentId = res.data.stationCode
            }
          })
        } else {
          this.$axios.get('/dataExchange/equipmentInfo/' + this.tempId).then(res => {
            this.eqData = res.data
          })
        }
        this.getEquipmentA()
      }
    },
    getByTunnel() {
      this.$axios.get('/dataExchange/protocolDataPoint/getByTunnelId/' + this.formData.tunnelId).then(res => {
        this.tunnelTable = res.data
        // console.log(this.tunnelTable)
        this.tunnelChange()
      })
    },
    // 保存
    submitEvent(formName) {
      this.formData.stationCode = this.elTableData[0].stationCode
      this.formatecode(this.formData.protocolPointType)
      if (this.formData.eqType === 'POWERSTATION') {
        this.formData.equipmentId = 0
      }
      if (this.formData.eqType === 'POWERSTATION2') {
        this.formData.equipmentId = 21
      }
      this.$delete(this.formData, 'eqType')
      if(this.formData.dataSource ==='GENERATE' && this.formData.generationRegulation === '系统自动计算'){
        this.formData.generationRegulation = '1'
      }
      if (this.saveFlag === 1) {
        this.$axios.post('/dataExchange/protocolDataPoint/saveDataPoint/', this.formData).then(res => {
          this.searchPointData()
        }).catch((res) => {
          this.$message.error(`${res}`)
        })
      } else {
        this.formData.equipmentAttribute = {
          'id': this.formData.equipmentAttribute.id
        }
        this.formData.id = this.modelId
        // console.log(this.formData)
        if (this.formData.dataSource === 'GENERATE') {
          this.formData.protocolPointType = 'ABCD'
        }
        this.$axios.put('/dataExchange/protocolDataPoint/updateDataPoint/', this.formData).then(res => {
          this.searchPointData()
        }).catch((res) => {
          this.$message.error(`${res}`)
        })
      }
      this.resetForm()
      this.formRules = {}
      this.$refs.xModal.close()
    },
    // 删除点表
    removeEvent(row) {
      this.$XModal.confirm('您确定要删除该采集点表及与其相关的转发点表?').then(type => {
        if (type === 'confirm') {
          this.$axios.delete('/dataExchange/protocolDataPoint/deleteById/' + row.id).then(res => {
            if (res.data === 1) {
              this.$message.success('删除点表成功')
            } else {
              this.$message.error('删除点表失败')
            }
            this.getAllDataPoint()
          })
        }
      })
    },
    // 编辑
    editRowEvent(row) {
      // console.log(row)
      this.needShow = true
      this.saveFlag = 2
      this.resetShow = false
      this.modelId = row.id
      if((row.equipmentAttribute.id === 100 && row.equipmentAttribute.equipmentType.code === 0) || (row.equipmentAttribute.id === 7003 && row.equipmentAttribute.equipmentType.code === 0)){
        this.needShow = false
      }
      this.formData = {
        equipmentId: row.equipmentId,
        equipmentAttribute: row.equipmentAttribute,
        protocolPointType: row.protocolPointType,
        tunnelId: row.tunnelId,
        dataSource: row.dataSource,
        protocolPointNo: row.protocolPointNo,
        magnification: row.magnification,
        needAudit: row.needAudit,
        showOnHomePage: row.showOnHomePage,
        maxChangeValue: row.maxChangeValue,
        maxValue: row.maxValue,
        minValue: row.minValue,
        maxDuration: row.maxDuration,
        generationRegulation: row.generationRegulation
      }
      if (this.formData.equipmentId === 0) {
        this.formData.equipmentId = this.elTableData[0].stationCode
      }
      this.mtunnelId = this.formData.tunnelId
      this.$nextTick(function() {
        if (row.dataSource === 'GATHER') {
          this.getByTunnel()
        }
      })
      if (this.formateEq(row.equipmentAttribute.equipmentType.code)) {
        // console.log(this.formData.eqType)
        this.pointNo = this.formData.protocolPointNo
        // 获取设备类型
        this.changeEqA()
        this.needChange()
        this.datasChange()
        this.selectRow = row
        this.showEdit = true
      }
      if(row.dataSource === 'GENERATE' && row.generationRegulation === '1'){
        this.formData.generationRegulation = '系统自动计算'
        this.generateDisable = true
        this.generateShow = true
      }else{
        this.formData.generationRegulation = row.generationRegulation
      }
    },
    // 添加
    insertEvent(row) {
      this.needShow = false
      this.saveFlag = 1
      this.resetForm()
      this.selectRow = null
      this.eqData = []
      if (this.eqId === '' || this.eqId === null) {
        this.formData.equipmentId = ''
      } else if (this.eqTableData[this.eqId].id === this.elTableData[0].stationCode) {
        this.formData.eqType = 'POWERSTATION'
        this.changeEqA()
      } else {
        var row1 = this.eqTableData[this.eqId]
        var cellValue = row1.equipmentType.message
        const item = this.enums.equipmentTypeEnum.find(item => item.label === cellValue)
        this.formData.eqType = item ? item.value : ''
        this.changeEqA()
        this.formData.equipmentId = row1.id
      }
      if (this.tunnelId !== '' && this.tunnelId !== undefined) {
        this.formData.tunnelId = this.tunnelId
      }
      this.protocolDataType = this.enums.ProtocolDataType
      this.showEdit = true
      this.resetShow = true
    },
    batchDeletePoint() {
      var selectRecords = this.$refs.xTable.getCheckboxRecords()
      if (selectRecords.length == 0) {
        this.$message.error('请选择要删除数据')
      } else {
        this.$XModal.confirm('您确定要批量删除采集点表及与其相关的转发点表?').then(type => {
          if (type === 'confirm') {
            var ids = []
            for (var i = 0; i < selectRecords.length; i++) {
              ids.push(selectRecords[i].id)
            }
            this.$axios.delete('/dataExchange/protocolDataPoint/batchDeleteGatherDataPoint/' + ids).then(res => {
              if (res.data === 1) {
                this.$message.success('删除批量点表成功')
              } else {
                this.$message.error('删除批量点表失败')
              }
              this.getAllDataPoint()
            })
          }
        })
      }
    },
    // 判断点表生成规则
    datasChange() {
      if (this.formData.dataSource === 'GATHER') {
        this.generateDisable = true
        this.generateShow = false
        this.gatherDisable = false
        this.regButShow = false
        this.regTextShow = false
      } else {
        this.generateShow = true
        this.gatherDisable = true
        this.generateDisable = false
        this.regBut()
      }
      this.checkValidate()
    },
    //公式生成按钮显示规则
    /*发电站
    * 97 => 系统限电， 101=>可用， 102=>理论， 108=>样板机理论， 112=>样板机可用， 113=>测风/光可用， 109=>测风/光理论
    * 测风塔
    * 4236=>可用
    * */
    regBut(){
      this.generateShow = true
      this.generateDisable = false
      this.formData.generationRegulation = ''
      var eqAttId = this.formData.equipmentAttribute.id
      if(eqAttId === 97 || eqAttId === 101 || eqAttId === 102 || eqAttId === 108 || eqAttId === 112 || eqAttId === 113){
        this.regButShow = true
        this.regTextShow = false
      }else if(eqAttId === 109 || eqAttId === 4236){
        this.formData.generationRegulation = ''
        this.generationRegulationText = ''
        this.regButShow = false
        this.regTextShow = true
        if(eqAttId === 109){
          this.generationRegulationText = '光伏组件效率*(1-0.003*(光伏组件温度-25))*math.pow(0.992,3)*总辐射*光伏组件总面积/1000000*0.79'
        }else{
          this.generationRegulationText = '1.293*(273/(273+温度摄氏度))*气压百帕/1013'
        }
      }else{
        this.regButShow = false
        this.regTextShow = false
      }
    },
    //公式按钮点击事件
    regButClick(){
      this.generateDisable = !this.generateDisable
      if(this.generateDisable){
        this.formData.generationRegulation = '系统自动计算'
      }else{
        this.formData.generationRegulation = ''
      }
    },
    attribute() {
      if(this.formData.dataSource === 'GENERATE'){
        this.regBut()
      }
      if (this.saveFlag === 1) {
        // console.log(this.formData.equipmentId)
        if (this.formData.equipmentId === '' || this.formData.equipmentId === null) {
          this.$message.error('请选择设备')
        } else {
          this.needShow = false
          var equipmentId = ''
          equipmentId = this.formData.equipmentId
          if (this.formData.eqType === 'POWERSTATION') {
            equipmentId = 0
            //设备属性为实际功率不展示考核的四项
            if(this.formData.equipmentAttribute.id === 100){
              this.needShow = false
            }
          }
          if (this.formData.eqType === 'POWERSTATION2') {
            equipmentId = 21
            //设备属性为实际功率不展示考核的四项
            if(this.formData.equipmentAttribute.id === 7003){
              this.needShow = false
            }
          }
          this.$axios.get('/dataExchange/protocolDataPoint/getProtocolGatherDataPoint/' + equipmentId + '/' + this.formData.equipmentAttribute.id).then((res) => {
            if (res.data.length === 0) {
              this.buttonShow = false
            } else {
              this.buttonShow = true
              // console.log(res.data)
              this.$message.error(`此设备的${res.data[0].equipmentAttribute.explanation}属性已经有采集点位`)
            }
          }).catch((res) => {
            this.$message.error(`${res}`)
          })
        }
      }
    },
    tunnelChange() {
      this.protocolDataType = []
      if (this.mtunnelId !== this.formData.tunnelId) {
        this.formData.protocolPointType = ''
      }
      for (let i = 0; i < this.tunnelList.length; i++) {
        if (this.formData.tunnelId === this.tunnelList[i].id) {
          if (this.tunnelList[i].tunnelType.substring(0, 3) === 'IEC' || this.tunnelList[i].tunnelType.substring(0, 3) === 'FIL') {
            this.protocolDataType = [{ label: '遥信开关量', value: 'A', key: 0 }, { label: 'ABCD', value: 'ABCD', key: 9 }]
          } else if (this.tunnelList[i].tunnelType.substring(0, 3) === 'CDT') {
            this.protocolDataType = [{ label: '遥信开关量', value: 'A', key: 0 }, { label: '+AB', value: 'P_AB', key: 1 }]
          } else {
            this.protocolDataType = this.enums.ProtocolDataType
          }
        }
      }
    },
    needChange() {
      this.formRules = {}
      this.checkValidate()
      if (this.formData.needAudit === false) {
        this.needdisable = true
        this.needShow = false
      } else {
        this.needdisable = false
        this.needShow = true
      }
    },
    checkValidate() {
      this.formRules = {}
      if (this.formData.dataSource === 'GATHER') {
        if (this.formData.needAudit) {
          this.formRules = Object.assign(this.formRules, this.gatherRules)
          this.formRules = Object.assign(this.formRules, this.needAuditRules)
        } else {
          this.formRules = this.gatherRules
        }
      } else {
        if (this.formData.needAudit) {
          this.formRules = Object.assign(this.formRules, this.geterteRules)
          this.formRules = Object.assign(this.formRules, this.needAuditRules)
        } else {
          this.formRules = this.geterteRules
        }
      }
    },
    // 重置
    resetForm() {
      // alert()
      this.formRules = {}
      this.formData = {
        equipmentId: '',
        equipmentAttribute: { 'id': '' },
        eqType: '',
        dataSource: 'GATHER',
        tunnelId: '',
        protocolPointNo: '',
        protocolPointType: 'ABCD',
        magnification: 1,
        needAudit: false,
        showOnHomePage: 0,
        maxChangeValue: '',
        maxValue: '',
        minValue: '',
        maxDuration: '',
        generationRegulation: ''
      }
      this.formRules = Object.assign(this.formRules, this.gatherRules)
      this.protocolDataType = this.enums.ProtocolDataType
      // this.formRules = Object.assign(this.formRules, this.needAuditRules)
      this.gatherDisable = false
      this.generateDisable = true
      this.generateShow = false
      this.columnShow = false
      this.needdisable = true
      this.buttonShow = false
    },
    // 转换类型
    formateEq(code) {
      let returnValue = ''
      if (code === 0) returnValue = 'POWERSTATION'
      if (code === 21) returnValue = 'POWERSTATION2'
      if (code === 1) returnValue = 'WEATHERSTATION'
      if (code === 2) returnValue = 'INVERTER'
      if (code === 3) returnValue = 'WINDTOWER'
      if (code === 4) returnValue = 'WINDTURBINE'
      if (code === 6) returnValue = 'BOOSTERSTATION'
      if (code === 7) returnValue = 'AGC_AVC'
      if (code === 8) returnValue = 'BWD'
      if (code === 9) returnValue = 'CYB'
      if (code === 10) returnValue = 'JDX'
      if (code === 11) returnValue = 'SYZMX'
      if (code === 12) returnValue = 'WGBC'
      if (code === 13) returnValue = 'DLQ'
      if (code === 14) returnValue = 'DZ'
      if (code === 15) returnValue = 'JDDZ'
      if (code === 16) returnValue = 'DXFDJ'
      if (code === 17) returnValue = 'QBB'
      if (code === 18) returnValue = 'LLB'
      if (code === 19) returnValue = 'FZ'
      if (code === 20) returnValue = 'XB'
      this.formData.eqType = returnValue
      return true
    },
    // 转换类型
    formateEqType(eqType) {
      this.tempId = ''
      let returnValue = ''
      if (eqType === 'POWERSTATION') returnValue = 0
      if (eqType === 'POWERSTATION2') returnValue = 21
      if (eqType === 'WEATHERSTATION') returnValue = 1
      if (eqType === 'INVERTER') returnValue = 2
      if (eqType === 'WINDTOWER') returnValue = 3
      if (eqType === 'WINDTURBINE') returnValue = 4
      if (eqType === 'BOOSTERSTATION') returnValue = 6
      if (eqType === 'AGC_AVC') returnValue = 7
      if (eqType === 'BWD') returnValue = 8
      if (eqType === 'CYB') returnValue = 9
      if (eqType === 'JDX') returnValue = 10
      if (eqType === 'SYZMX') returnValue = 11
      if (eqType === 'WGBC') returnValue = 12
      if (eqType === 'DLQ') returnValue = 13
      if (eqType === 'DZ') returnValue = 14
      if (eqType === 'JDDZ') returnValue = 15
      if (eqType === 'DXFDJ') returnValue = 16
      if (eqType === 'QBB') returnValue = 17
      if (eqType === 'LLB') returnValue = 18
      if (eqType === 'FZ') returnValue = 19
      if (eqType === 'XB') returnValue = 20

      this.tempId = returnValue
      return true
    },
    formatecode(protocolPointType) {
      let returnValue = ''
      if (protocolPointType === 'A') returnValue = 0
      if (protocolPointType === 'P_AB') returnValue = 1
      if (protocolPointType === 'PM_AB') returnValue = 2
      if (protocolPointType === 'P_BA') returnValue = 3
      if (protocolPointType === 'PM_BA') returnValue = 4
      if (protocolPointType === 'P_AABB') returnValue = 5
      if (protocolPointType === 'PM_AABB') returnValue = 6
      if (protocolPointType === 'P_BBAA') returnValue = 7
      if (protocolPointType === 'PM_BBAA') returnValue = 8
      if (protocolPointType === 'ABCD') returnValue = 9
      if (protocolPointType === 'CDAB') returnValue = 10
      if (protocolPointType === 'DCBA') returnValue = 11
      if (protocolPointType === 'BADC') returnValue = 13
      if (protocolPointType === '' || protocolPointType === null) returnValue = 'null'
      this.formData.protocolPointType = returnValue
    },
    // 转换是否考核
    formatterNeedAudit({ cellValue }) {
      const item = this.needAuditList.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    // 转换通道类型
    formatterPointType({ cellValue }) {
      const item = this.enums.ProtocolDataType.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    // 展示首页的顺序
    showOnHomePageFormatter({ cellValue }) {
      return cellValue == 0 ? '不展示' : cellValue
    },
    generationRegulationFormatter({ cellValue }){
      return cellValue === '1' ? '系统自动计算' : cellValue
    },
    formatterDataSource({ cellValue }) {
      const item = this.enums.geterDataSourceEnum.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    // 通道id转名称
    formateId(row, column) {
      // console.log(row)
      let belongTo = '未知通道名称'
      if (row.row.tunnelId === '') {
        belongTo = ''
      } else {
        for (let i = 0; i < this.tunnelList.length; i++) {
          if (row.row.tunnelId === this.tunnelList[i].id) {
            belongTo = this.tunnelList[i].tunnelName
          }
        }
      }
      return belongTo
    },
    // 设备id转名称
    formateEqId(row, column) {
      let belongTo = '未知设备名称'
      if (row.row.equipmentAttribute.equipmentType.code === 0 || row.row.equipmentAttribute.equipmentType.code === 21) {
        belongTo = this.elTableData[0].name
      } else {
        for (let i = 0; i < this.eqTableData.length; i++) {
          if (row.row.equipmentId === this.eqTableData[i].id && row.row.equipmentAttribute.equipmentType.code === this.eqTableData[i].equipmentType.code) {
            belongTo = this.eqTableData[i].name
          }
        }
      }
      return belongTo
    },
    checkprotocolPointNo() {
      this.buttonShow = false
      if (this.formData.tunnelId === '' || this.formData.tunnelId === null) {
        this.$message.error('请先选择通道')
        this.formData.protocolPointNo = ''
        this.buttonShow = true
      } else {
        if (this.formData.protocolPointNo < 0) {
          this.formData.protocolPointNo = 0
          this.$message.error('通道点位不能小于0')
        }
        var v6 = this.tunnelTable
        var num = this.formData.protocolPointNo
        for (let i = 0; i < v6.length; i++) {
          if (this.modelId === '') {
            // 新增
            if (parseInt(num) === v6[i].protocolPointNo) {
              this.$message.error('通道点位不能重复')
              this.buttonShow = true
            }
          } else {
            // 修改
            if (parseInt(this.pointNo) !== parseInt(num)) {
              if (parseInt(num) === v6[i].protocolPointNo) {
                this.$message.error('通道号不能重复')
                this.buttonShow = true
              }
            }
          }
        }
      }
    },
    headerCellClassName ({ column, columnIndex }) {
      if (column.title === '实时数据') {
        return {
          background: 'rgba(247,172,188,0.3)'
        }
      }
    },
  }
}

</script>

<style scoped>
  .vxe-modal--box .vxe-modal--box{
    top:10vh !important;
  }
  /deep/.regulate.vxe-input .vxe-input--extra-suffix, /deep/.regulate.vxe-input .vxe-input--suffix{
    width: 117px;
  }
</style>
