<template>
  <vxe-modal
    ref="multiAdd"
    v-model="show"
    :title="'批量添加'"
    width="900"
    height="auto"
    resize
    destroy-on-close
    @close="cancelButtonClick"
  >
    <vxe-form
      ref="form"
      :data="formData"
      :rules="formRules"
      title-align="center"
      title-width="100"
    >
      <vxe-form-item title="设备类型" field="eqType" span="8">
        <vxe-select v-model="formData.eqType" placeholder="请选择设备类型" size="medium" @change="flushEqsOfSelectEqType">
          <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" @change="buildAttrPnoMagData">
          <vxe-option v-for="(item,index) in eqsOfSelectEqType" :key="index" :value="item.id" :label="item.name"/>
        </vxe-select>
      </vxe-form-item>

      <vxe-form-item title="使用通道" field="tunnelId" span="8">
        <vxe-select
          v-model="formData.tunnelId"
          placeholder="请选择使用通道"
          size="medium"
          @change="tunnelChange"
        >
          <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="protocolPointType" span="9" title-width="150px">
        <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="protocolPointNo" span="12" title-width="150px">
        <vxe-button @click="openTheEditModal">批量编辑点位</vxe-button>
        <vxe-modal v-model="editModalShow" width="800" :title="'点位对应关系表'" :position="{top: 600 }" show-footer>
          <template>
            <vxe-table
              ref="xTable"
              highlight-hover-row
              size="mini"
              auto-resize
              show-overflow
              :edit-rules="tableFormRules"
              keep-source
              max-width="800"
              height="600"
              :data="attr_pno_mag"
              :edit-config="{trigger: 'dblclick', mode: 'row',activeMethod: activeRowMethod}"
              @cell-click="cancelRowEvent"
              @edit-closed="editClosedEvent"
            >
              <vxe-table-column field="explanation" title="属性名"/>
              <vxe-table-column
                field="pno"
                title="点位"
                sortable
                :edit-render="{name: 'input', attrs: {type: 'number',min:1}}"
              />
              <vxe-table-column
                field="mag"
                title="倍率"
                :edit-render="{name: 'input', attrs: {type: 'float'}, defaultValue:'1.0'}"
              />
              <vxe-table-column
                field="showNo"
                title="页面展示顺序"
                :edit-render="{name: 'input', attrs: {type: 'number',disabled: formData.eqType!='WEATHERSTATION'&&formData.eqType!='WINDTOWER'}, defaultValue:'0'}"
              />
            </vxe-table>
          </template>
        </vxe-modal>
      </vxe-form-item>

      <!--占地方用的-->
      <div style="height: 350px"/>

    </vxe-form>
  </vxe-modal>
</template>

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

    export default {
        name: 'MultiAddVue',
        props: {
            show: {
                type: Boolean,
                default: false
            }
        },
        data() {
            /**
             * 检查所选点位是否为合理点位
             * @param rule
             * @param value
             * @param callback
             */
            const checkProtocolPointNo = (row, cellValue, callback) => {
                if (cellValue === null || cellValue === '' || cellValue === undefined) {
                    callback()
                } else {
                    if (cellValue < 0) {
                        callback(new Error('点位从0开始'))
                    } else {
                        const param = {
                            params: {
                                tunnelId: this.formData.tunnelId,
                                protocolPointNo: cellValue
                            }
                        }
                        this.resultHandler(this.getDataPoint(param)).then(res => {
                            if (res.length > 0) {
                                if (res[0].id !== this.activeTableRow.gDataPointId) {
                                    callback(new Error('该通道的该点位已被占用'))
                                } else {
                                    callback()
                                }
                            } else {
                                callback()
                            }
                        })
                    }
                }
            }

            // 验证展示顺序  同设备上不允许有相同的顺序
            const checkDisplayOrder = (rule, value, callback) => {
                if (value == 0 || value === undefined) {
                    callback()
                    return
                }
                const data = this.attr_pno_mag
                for (const i in data) {
                    if (data[i].showNo == value && data[i].pno !== this.activeTableRow.pno) {
                        callback(new Error('同一设备不允许有相同的展示顺序'))
                        return
                    }
                }
                callback()
            }
            return {
                tunnelList: [],
                // 设备属性下拉狂对应的属性
                attr_pno_mag: [],
                eqsOfSelectEqType: [],
                showEdit: true,
                editModalShow: false,
                activeTableRow: {},
                formData: {
                    equipmentId: '',
                    equipmentAttribute: {'id': ''},
                    eqType: '',
                    tunnelId: '',
                    protocolPointNo: '',
                    protocolPointType: ''
                },
                formRules: {
                    eqType: [{required: true, message: '请选择设备类型', trigger: 'change'}],
                    equipmentId: [{required: true, message: '请选择设备', trigger: 'change'}],
                    tunnelId: [{required: true, message: '请选择通道', trigger: 'change'}],
                    protocolPointType: [{required: true, message: '请选择数据类型', trigger: 'change'}]
                },
                tableFormRules: {
                    pno: [{validator: checkProtocolPointNo}],
                    showNo: [{validator: checkDisplayOrder}]
                },
                enums: enumerations,
                protocolDataType: enumerations.ProtocolDataType
            }
        },
        mounted() {
            this.buildTunnelSelectData()
        },
        methods: {

            /**
             * 点击取消或关闭按钮时通知父组件修改值
             */
            cancelButtonClick() {
                this.resetForm()
                this.$emit('close')
            },

            /**
             * 当所选设备类型发生改变时 刷新设备属性下拉框对应的设备名下拉
             */
            flushEqsOfSelectEqType() {
                this.formData.equipmentId = null
                this.resultHandler(this.getEqsByEqTypeCode(this.formData.eqType)).then(res => {
                    if (res != null) {
                        this.eqsOfSelectEqType = res
                    }
                })
            },

            /**
             *针对于后台返回的信息进行二次处理的方法
             * @param  promise Promise
             * @returns {Promise}
             */
            resultHandler(promise) {
                const message = this.$message
                return new Promise(function (resolve, reject) {
                    promise.then(res => {
                        if (res.code == 0) {
                            resolve(res.data)
                        } else {
                            message.error(res.msg)
                            reject(new Error(res.msg))
                        }
                    }).catch(error => {
                        message.error('请求后台时发生异常')
                        reject(error)
                    })
                })
            },

            /**
             *对form表单内的数据进行重置
             */
            resetForm() {
                this.eqsOfSelectEqType = []
                this.formData = {
                    equipmentId: '',
                    equipmentAttribute: {'id': ''},
                    eqType: '',
                    tunnelId: '',
                    protocolPointNo: '',
                    protocolPointType: ''
                }
            },

            /**
             *根据设备类型获取该类型下的设备属性
             * 可以传设备类型的ID 或NAME  即 可以传1 或 POWERSTATION
             * @param code
             * @returns {*}
             */
            getEqAttrByEqTypeCode(typeCode) {
                return this.$axios.get('/dataExchange/getByEquipmentType/' + typeCode)
            },

            /**
             * 根据设备类型获取该类型下的设备属性
             * 可以传设备类型的ID 或NAME  即 可以传0 或 POWERSTATION
             * @param code
             * @returns {*}
             */
            getEqsByEqTypeCode(typeCode) {
                const axios = this.$axios
                if (typeCode === 0 || typeCode === 'POWERSTATION') {
                    // 当设备类型是电站时对数数据进行处理后返回
                    return new Promise(function (resolve, reject) {
                        axios.get('/electricField/').then(res => {
                            if (res.code == 0) {
                                const eqs = []
                                res.data.id = res.data.stationCode
                                eqs.push(res.data)
                                res.data = eqs
                            }
                            resolve(res)
                        }).catch(error => {
                            reject(error)
                        })
                    })
                } else {
                    return axios.get('/dataExchange/equipmentInfo/' + typeCode)
                }
            },
            /**
             * 查询到所有采集通道
             * @returns {*}
             */
            getAllGatherTunnel() {
                return this.$axios.get('/TunnelInfo/getTunnel/Master')
            },

            /**
             * 根据所有通道信息构建通道下拉框的 展示数据
             */
            buildTunnelSelectData() {
                this.resultHandler(this.getAllGatherTunnel()).then(res => {
                    if (res !== null) {
                        this.tunnelList = res
                    }
                })
            },

            /**
             * 由于双击触发修改后  不能点击他处取消修改状态（可能是框架问题） 增加此方法用于退出编辑状态
             */
            cancelRowEvent({row}) {
                // 当被点击的行不是激活修改的行 才能取消其他行的激活
                if (!this.$refs.xTable.isActiveByRow(row)) {
                    this.$refs.xTable.clearActived()
                }
            },

            /**
             * 构建attr_pno_mag 对应表格的数据 并展开表格
             */
            async buildAttrPnoMagData() {
                // 获取该设备类型的所有属性
                this.resultHandler(this.getEqAttrByEqTypeCode(this.formData.eqType)).then(res => {
                    if (res != null) {
                        this.attr_pno_mag = res
                    }
                })
                // 构建查询条件
                const param = {
                    params: {}
                }
                param.params.equipmentType = this.formData.eqType
                if (this.formData.eqType !== 'POWERSTATION') {
                    param.params.equipmentId = this.formData.equipmentId
                }
                // 对设备属性类型数据进行加工
                this.resultHandler(this.getDataPoint(param)).then(res => {
                    if (res != null) {
                        for (const i in res) {
                            for (const j in this.attr_pno_mag) {
                                if (this.attr_pno_mag[j].id === res[i].equipmentAttribute.id) {
                                    if (res[i].dataSource === 'GATHER') {
                                        this.attr_pno_mag[j].pno = res[i].protocolPointNo
                                        this.attr_pno_mag[j].mag = res[i].magnification
                                        this.attr_pno_mag[j].dataSource = res[i].dataSource
                                        this.attr_pno_mag[j].tunnelId = res[i].tunnelId
                                        this.attr_pno_mag[j].gDataPointId = res[i].id
                                        this.attr_pno_mag[j].showNo = res[i].showOnHomePage
                                    } else {
                                        this.attr_pno_mag[j].dataSource = res[i].dataSource
                                        this.attr_pno_mag[j].gDataPointId = res[i].id
                                        this.attr_pno_mag[j].showNo = res[i].showOnHomePage
                                    }
                                }
                            }
                        }
                    }
                })
            },

            /**
             * 根据入参条件获取点表
             * @param param
             * @returns {*}
             */
            getDataPoint(param) {
                return this.$axios.get('/dataExchange/protocolDataPoint/gatherDataPoint/', param)
            },
            /**
             * 验证该点位是否可在此表格中进行修改
             * @param row
             * @param rowIndex
             * @returns {boolean}
             */
            activeRowMethod({row, rowIndex}) {
                this.activeTableRow = row
                if (row.tunnelId !== null && row.tunnelId !== undefined && row.tunnelId != this.formData.tunnelId) {
                    this.$message.error('该点已被设置为使用其他通道点位，请选择对应通道修改')
                    return false
                }
                if (row.dataSource === 'GENERATE') {
                    this.$message.error('该点已被设置为公式生成点位，不可在此修改')
                    return false
                }
                return true
            },

            /**
             * 属性 -点位-倍率 对应表使用的编辑结束后进行校验和提交
             * @param row
             */
            editClosedEvent({row, rowIndex}) {
                const message = this.$message
                this.$refs.xTable.validate(row).then(r => {
                    if (row.pno === null || row.pno === undefined || row.pno === '') {
                        if (row.mag !== null) {
                            row.mag = null
                        }
                        return
                    }
                    const param = {
                        dataSource: 'GATHER',
                        tunnelId: this.formData.tunnelId,
                        protocolPointNo: row.pno,
                        showOnHomePage: row.showNo,
                        protocolPointType: this.formData.protocolPointType,
                        needAudit:false,
                        equipmentAttribute: {id: row.id},
                        magnification: row.mag == null ? 1 : row.mag
                    }
                    if (this.formData.eqType === 'POWERSTATION') {
                        param.equipmentId = 0
                    } else {
                        param.equipmentId = this.formData.equipmentId
                    }
                    if (row.gDataPointId !== undefined && row.gDataPointId !== null) {
                        // 更新
                        param.id = row.gDataPointId
                        this.resultHandler(this.updateGatherPoint(param)).then(res => {
                            message.success('修改点位操作成功')
                        }).catch(error => {
                            $refs.xTable.revertData(row)
                        })
                    } else {
                        this.resultHandler(this.saveGatherPoint(param)).then(res => {
                            message.success('新增点位操作成功')
                            row.dataSource = res.dataSource
                            row.tunnelId = res.tunnelId
                            row.gDataPointId = res.id
                            row.showNo = res.showOnHomePage
                            row.needAudit=false
                            row.mag = res.magnification
                        }).catch(error => {
                            $refs.xTable.revertData(row)
                        })
                    }
                })
            },

            /**
             * 开启下拉容器 属性 -点位-倍率表
             */
            openTheEditModal() {
                // 打开下拉版
                this.$refs.form.validate().then(() => {
                    const _this = this

                    this.editModalShow = true
                    setTimeout(function () {
                        _this.$refs.xTable.clearSort()
                        _this.$refs.xTable.sort('pno', 'asc')
                    }, 50)
                })
            },

            /**
             * 保存采集点位
             */
            saveGatherPoint(gatherPoint) {
                return this.$axios.post('/dataExchange/protocolDataPoint/saveDataPoint/', gatherPoint)
            },

            /**
             * 更新采集点位
             */
            updateGatherPoint(gatherPoint) {
                return this.$axios.put('/dataExchange/protocolDataPoint/updateDataPoint/', gatherPoint)
            },

            /**
             * 当通道类型修改时通道支持的数据类型也进行修改
             */
            tunnelChange() {
                this.protocolDataType = []
                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
                        }
                    }
                }
            }

        }
    }
</script>

<style scoped>

</style>
