<style rel="stylesheet/scss" lang="scss">

</style>
<template>
  <div style="padding-left: 30px;margin-right: 20px">
    <!-- <vxe-form :data="templateInfo">
       <vxe-form-item title="名称" field="name">
         <vxe-input v-model="templateInfo.name" placeholder="请输入名称"/>
       </vxe-form-item>
       <vxe-form-item title="模版类型" field="type">
         <vxe-select v-model="templateInfo.type" placeholder="请选择模版类型" :options="enums.equipmentTypeEnum"
                     :optionProps="{value:'key',label:'label'}"/>
       </vxe-form-item>
       <vxe-form-item title="默认通道" field="defaultTunnel">
         <vxe-select v-model="templateInfo.defaultTunnel" placeholder="请选择采集通道" :options="getAllTunnelInfo()"/>
       </vxe-form-item>
     </vxe-form>-->
    <vxe-toolbar>
      <template v-slot:buttons>
        <vxe-button icon="fa fa-plus" @click="insertEvent(-1)">新增</vxe-button>
        <vxe-button icon="fa fa-trash" @click="deleteEvent()">删除选中</vxe-button>
      </template>
    </vxe-toolbar>
    <vxe-grid
      ref="xTable"
      border
      resizable
      keep-source
      row-key
      show-overflow
      align="center"
      :edit-rules="validRules"
      :data="templates"
      :edit-config="{trigger: 'dblclick', mode: 'cell', showStatus: true, activeMethod: activeCellMethod}"
      @edit-closed="editClosedEvent"
    >
      <vxe-table-column type="checkbox" width="40"/>
      <vxe-table-column type="expand" title="ID" width="100">
        <template v-slot:="{ row, rowIndex }">
          <span>{{ row.id }}</span>
        </template>
        <template v-slot:content="{ row, rowIndex }">
          <template>
            <vxe-table
              border
              :data="row.points"
              :sort-config="{defaultSort: {field: 'sequence', order: 'asc'}, orders: ['asc']}"
            >
              <vxe-table-column
                field="dataSource"
                title="数据来源"
                :edit-render="{name: '$select', options:enums.geterDataSourceEnum }"
              />
              <vxe-table-column field="equipmentAttribute.explanation" title="设备属性"/>
              <vxe-table-column field="sequence" title="顺序" sortable/>
              <vxe-table-column
                field="isUsing"
                title="是否使用"
                :filters="[ { label: '不使用', value: false }, { label: '使用', value: true, checked:true}] "
                :filter-multiple="false"
                :edit-render="{name: '$select', options:[ { label: '不使用', value: 0 }, { label: '使用', value: 1 }] }"
              />
              <vxe-table-column field="magnification" title="倍率"/>
              <vxe-table-column
                field="protocolPointType"
                title="数据协议类型"
                :edit-render="{name: '$select', options:enums.ProtocolDataType}"
              />
              <vxe-table-column
                field="tunnelId"
                title="使用通道"
                :edit-render="{name: '$select', options:getAllTunnelInfo()}"
              />
              <vxe-table-column field="pointRegulation" title="点位生成规则"/>
              <!-- <vxe-table-column field="generationRegulation" title="数据生成公式"/>-->
              <vxe-table-column
                field="needAudit"
                title="是否需要校验"
                :edit-render="{name: '$select', options:[ { label: '不校验', value: 0 }, { label: '校验', value: 1 }] }"
              />
              <vxe-table-column field="maxChangeValue" title="最大突变量"/>
              <vxe-table-column field="maxDuration" title="最长不变时间"/>
              <vxe-table-column field="maxValue" title="最大合理值"/>
              <vxe-table-column field="minValue" title="最小合理值"/>

            </vxe-table>
          </template>
        </template>
      </vxe-table-column>
      <vxe-table-column field="name" title="模版名称" :edit-render="{name: 'input', attrs: { type: 'text' }}"/>
      <vxe-table-column
        field="templateType.code"
        title="模版类型"
        :edit-render="{name: '$select', options:enums.equipmentTypeEnum,optionProps :{value:'key',label:'label'}} "
      />
      <vxe-table-column
        field="defaultTunnelId"
        title="默认通道名称"
        :edit-render="{name: '$select', options:getAllTunnelInfo()} "
      />
      <vxe-table-column title="模版点位操作">
        <template slot-scope="{row}">
          <vxe-button status="success" icon="vxe-icon--edit-outline" @click="showDetail(row)">修改模版点位</vxe-button>
        </template>
      </vxe-table-column>
      <vxe-table-column title="生成设备点位">
        <template slot-scope="{row}">
          <vxe-button status="success" icon="fa fa-cogs" @click="selectEquipment(row)">生成设备点位</vxe-button>
        </template>
      </vxe-table-column>

    </vxe-grid>
    <vxe-modal v-model="selectEquipmentModal.showSelectEquipment" title="选择设备" width="600" height="250" resize>
      <h4 style="color: red">*生成点位时将会删除设备原有点位，请谨慎操作！</h4>
      <h4 style="color: red">*选择多个设备时，寻址参数N为第一个设备的寻址位，其他设备按选中顺序依次+1</h4>
      <div>
        <el-select v-model="selectEquipmentModal.selectedEquipment" style="width:280px" multiple placeholder="请选择">
          <el-option
            v-for="item in selectEquipmentModal.equipmentOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <vxe-button status="primary" icon="fa el-icon-success" @click="selectAllEquipment()">全选设备</vxe-button>
        <vxe-input v-model="selectEquipmentModal.findAddressN" placeholder="请输入寻址参数N" type="number"/>
        <vxe-button status="primary" icon="fa fa-cogs" @click="generatePoint4Equipment()">生成
        </vxe-button>
      </div>
    </vxe-modal>
  </div>

</template>

<script>

import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import enumerations from '../../enumeration'

Vue.use(VXETable)

export default {

  data() {
    return {
      loading: false,
      /* tablePage: {
           total: 0,
           currentPage: 1,
           pageSize: 10,
           align: 'right',
           pageSizes: [10, 20, 30, 40],
           layouts: ['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total'],
           perfect: true
       },*/
      templateInfo: {},
      enums: enumerations,
      templates: [],
      tunnelOption: null,
      selectEquipmentModal: {
        showSelectEquipment: false,
        selectModel4Create: null,
        findAddressN: null,
        selectedEquipment: '',
        equipmentOptions: null
      },
      validRules: {
        name: [
          {required: true, message: '填写准确的描述名'}
        ]
      }
    }
  },
  created() {
    this.getTemplate()
  },

  mounted() {

  },
  methods: {
    getTemplate(template) {
      this.$axios.get('/dataExchange/equipmentDataTemplate/', template).then(res => {
        this.templates = res.data
        // this.tablePage.totalResult = res.data.count
      }).catch((error) => {
        this.$message.error('获取模版信息出错' + error)
      })
    },
    async updateOrSaveTemplate(template) {
      let templates = await this.$axios.put('/dataExchange/equipmentDataTemplate/', template).then(res => {
        if (res.code == 0) {
          return templates = res.data
        }
        return null
      }).catch((error) => {
        this.$message.error('保存模版信息失败' + error)
      })
      return templates
    },
    deleteTemplate(templateId) {
      let flag = 0
      this.$axios.delete('/dataExchange/equipmentDataTemplate?equipmentDataTemplateId=' + templateId).then(res => {
        flag = res.code
      }).catch((error) => {
        flag = 1
        this.$message.error('删除模版信息出错' + error)
      })
      return flag
    },
    getAllTunnelInfo() {
      if (this.tunnelOption == null) {
        this.tunnelOption = new Array()
        this.$axios.get('/TunnelInfo/getTunnel/Master').then(res => {
          const tunnels = res.data
          let obj = new Object()
          for (const i in tunnels) {
            obj = new Object()
            obj.label = tunnels[i].tunnelName
            obj.value = tunnels[i].id
            this.tunnelOption.push(obj)
          }
        })
      }
      return this.tunnelOption
    },
    showDetail(row) {
      this.$router.push({name: 'templatedatapoint', query: {equipmentDataTemplateId: row.id}})
    },
    async editClosedEvent({row}) {
      const xTable = this.$refs.xTable
      // 判断单元格值是否被修改
      if (row.templateType.code == null) {
        this.$refs.xTable.setActiveCell(row, 'templateType.code')
        this.$XModal.message({message: '必须初始化模版类型', status: 'error'})
        return
      }
      if (!this.checkName(row)) {
        return
      }
      if (xTable.isUpdateByRow(row) || this.$refs.xTable.isInsertByRow(row)) {
        const tem = new Object()
        tem.id = row.id
        tem.name = row.name
        tem.defaultTunnelId = row.defaultTunnelId
        tem.templateType = row.templateType.code
        const newRow = await this.updateOrSaveTemplate(tem)
        if (newRow !== null) {
          if (tem.id == null) {
            this.getTemplate()
            this.$XModal.message({
              message: `模版信息添加完成！`,
              status: 'success'
            })
          } else {
            this.$XModal.message({
              message: `模版信息修改完成！`,
              status: 'success'
            })
          }
          row.id = newRow.id
          this.$refs.xTable.reloadRow(row, null, null)
        }
      }
    },
    activeCellMethod({row, columnIndex}) {
      if (columnIndex === 3) {
        if (row.id === undefined || row.id === null) {
          return true
        }
        this.$XModal.message({message: '禁止修改模版类型', status: 'error'})
        return false
      }
      return true
    },
    async insertEvent(row) {
      const template = {
        name: '新增默认命名',
        defaultTunnelId: this.templateInfo.defaultTunnel === undefined ? null : this.templateInfo.defaultTunnel,
        templateType: this.templateInfo.type === undefined ? 0 : this.templateInfo.type
      }

      const newRow = await this.$refs.xTable.insertAt(template, row)
      this.$refs.xTable.setActiveCell(newRow.row, 'templateType.code')
    },

    async deleteEvent() {
      const selectRecords = this.$refs.xTable.getCheckboxRecords()
      this.$XModal.confirm('您确定要删除这' + selectRecords.length + '个模版吗吗？模版下的点位也会被删除，请谨慎操作。').then(type => {
        if (type === 'confirm') {
          for (const i in selectRecords) {
            if (selectRecords[i].id === undefined || selectRecords[i].id === null) {
              this.$refs.xTable.remove(selectRecords[i])
            } else {
              if (this.deleteTemplate(selectRecords[i].id) === 0) {
                this.$refs.xTable.remove(selectRecords[i])
              }
            }
          }
        }
      })
    },
    async selectEquipment(model) {
      this.selectEquipmentModal.selectModel4Create = model
      this.selectEquipmentModal.showSelectEquipment = true
      this.selectEquipmentModal.selectedEquipment = null
      this.selectEquipmentModal.findAddressN = null
      this.selectEquipmentModal.equipmentOptions = await this.getEquipmentByType(model.templateType.code)
    },
    selectAllEquipment() {
      const es = []
      this.selectEquipmentModal.equipmentOptions.forEach(function(e) {
        es.push(e.value)
      })
      this.selectEquipmentModal.selectedEquipment = es
    },
    async getEquipmentByType(type) {
      let options = null
      let url
      let req
      switch (type) {
        case 0:
          url = '/electricField/'
          break
        case 1:
          url = '/weatherStationInfo/'
          break
        case 2:
          url = '/inverterInfo/'
          break
        case 3:
          url = '/windTowerInfo/'
          break
        case 4:
          url = '/windTurbineInfo/'
          break
      }
      try {
        req = await this.$axios.get(url)
      } catch (e) {
        console.log(e)
      }
      if (req.code == 0) {
        options = new Array()
        for (const i in req.data) {
          options.push({
            value: req.data[i].id,
            label: req.data[i].name
          })
        }
        return options
      }
      return options
    },
    async generatePoint4Equipment() {
      const param = {
        equipmentDataTemplateId: this.selectEquipmentModal.selectModel4Create.id,
        equipmentIds: this.selectEquipmentModal.selectedEquipment,
        findAddressN: this.selectEquipmentModal.findAddressN
      }
      let req
      try {
        req = await this.$axios.post('/dataExchange/equipmentDataTemplate/generatePoint4Equipment', param)
      } catch (e) {
        console.log(e)
      }
      if (req.code == 0) {
        this.selectEquipmentModal.showSelectEquipment = false
        this.$XModal.message({message: '设备点位生成完毕', status: 'success'})
      }
    },
    checkName(row) {
      if (row.name === '') {
        this.$refs.xTable.setActiveCell(row, 'name')
        this.$XModal.message({message: '模版名称不能为空', status: 'error'})
        return false
      }
      for (const i in this.templates) {
        if (this.templates[i].id !== row.id && this.templates[i].name == row.name) {
          this.$refs.xTable.setActiveCell(row, 'name')
          this.$XModal.message({message: '模版名称不能重复', status: 'error'})
          return false
        }
      }
      return true
    }
  }
}

</script>

<style>
.using-row {
  background-color: #FFFFFF !important;
}

.unusing-row {
  background-color: #909399 !important;
}
</style>
