<template>
  <div style="padding-left: 30px">
    <p>
      <vxe-button status="primary" icon="fa fa-reply" @click="backTemplateMenu" title="返回模版列表"
                  style="margin-right: 10px"/>
      <span>模版名称：</span>
      <vxe-input v-model="templateInfo.name" :disabled=true></vxe-input>
      <span style="margin-left: 10px">模版类型：</span>
      <vxe-input v-model="templateInfo.templateType.message" :disabled=true></vxe-input>
      <span style="margin-left: 10px">默认通道：</span>
      <vxe-select v-model="templateInfo.defaultTunnelId" :options=getAllTunnelInfo()></vxe-select>
    </p>
    <p style="color: red;margin: 3px">* ‘N’为风机的寻址参数，如点表里的第一台风机N=1，用于配置点位生成规则编写</p>
    <p style="color: red;margin: 3px">* 数据生成公式引入其他点位的方式为&nbsp;&nbsp;&nbsp;P_顺序_P</p>
    <p style="color: red;margin: 3px">* 点击表格的第一列的箭头进行拖动，改变点位顺序</p>
    <vxe-grid
      border
      resizable
      row-key
      ref="xTable"
      show-overflow
      :row-class-name="changeColorByIsUsing"
      :data="dataPoints"
      :edit-rules="validRules"
      :edit-config="{trigger: 'dblclick', mode: 'row'}"
      @edit-closed="editClosedEvent"
      :sort-config="{defaultSort: {field: 'sequence', order: 'asc'}, orders: ['asc']}"
      @edit-actived="editActivedEvent"
    >
      <vxe-table-column width="38"><i class="fa fa-arrows" style="color: goldenrod" aria-hidden="true"></i>
      </vxe-table-column>
      <vxe-table-column width="70" field="sequence" title="顺序" sortable></vxe-table-column>
      <vxe-table-column field="isUsing" title="是否需要"
                        :edit-render="{name: '$select',  options: [{ label: '需要', value: true }, { label: '不需要', value: false }], events: {change: editActivedEvent}}"></vxe-table-column>
      <vxe-table-column field="dataSource" title="数据源"
                        :edit-render="{name: '$select',  options: enums.geterDataSourceEnum , props: {disabled:overall},events: {change: editActivedEvent}}"></vxe-table-column>
      <vxe-table-column field="equipmentAttribute.explanation" title="属性名"></vxe-table-column>
      <vxe-table-column field="tunnelId" title="使用通道"
                        :edit-render="{name: '$select',  options: getAllTunnelInfo(),  props: {disabled:generateDataSource},events: {change: tunnelChangeEvent}}"></vxe-table-column>
      <vxe-table-column field="pointRegulation" title="点位生成规则"
                        :edit-render="{name: 'input', attrs: {type: 'text',disabled:generateDataSource}}"></vxe-table-column>
      <vxe-table-column field="protocolPointType" title="数据类型"
                        :edit-render="{name: '$select', options: protocolDataTypeEnum}"></vxe-table-column>
      <vxe-table-column field="magnification" title="倍率"
                        :edit-render="{name: 'input', attrs: {type: 'text',disabled: overall}}"></vxe-table-column>
      <vxe-table-column field="generationRegulation" title="数据生成规则"
                        :edit-render="{name: 'textarea', attrs: {type: 'text',disabled:gatherDataSource}}"></vxe-table-column>
      <vxe-table-column field="needAudit" title="需要审核"
                        :edit-render="{name: '$select',  options: [{ label: '需要', value: true }, { label: '不需要', value: false }], events: {change: editActivedEvent}}"></vxe-table-column>
      <vxe-table-column field="maxValue" title="最大值"
                        :edit-render="{name: 'input',  attrs: {type: 'number',disabled: isNeedAudit}}"></vxe-table-column>
      <vxe-table-column field="minValue" title="最小值"
                        :edit-render="{name: 'input',  attrs: {type: 'number',disabled: isNeedAudit}}"></vxe-table-column>
      <vxe-table-column field="maxChangeValue" title="最大变化值"
                        :edit-render="{name: 'input',  attrs: {type: 'number',disabled: isNeedAudit}}"></vxe-table-column>
      <vxe-table-column field="maxDuration" title="最长持续时间(min)"
                        :edit-render="{name: 'input',  attrs: {type: 'number',disabled: isNeedAudit}}"></vxe-table-column>
      <vxe-table-column field="remark" title="备注"
                        :edit-render="{name: 'input', attrs: {type: 'text',disabled: overall}}"></vxe-table-column>
    </vxe-grid>
  </div>
</template>

<script>

    import Vue from 'vue'
    import 'xe-utils'
    import VXETable from 'vxe-table'
    import 'vxe-table/lib/index.css'
    import Sortable from 'sortablejs';
    import enumerations from '../../enumeration'
    import systemRouter from "../../../router/modules/system";

    Vue.use(VXETable);

    export default {
        data() {
            //点位生成规则的 校验
            const pointRegulationValidate = (row, cellValue, callback) => {
                var pattern = /[^N+-/*///(/)/[/]\d]/;
                if (pattern.test(cellValue)) {
                    callback(new Error("不允许除数字，运算符，和‘N’之外的字符"))
                } else {
                    callback();
                }
            }
            const generationRegulationValidate = (row, cellValue, callback) => {
                if (cellValue !== null) {
                    this.$axios.get('/dataExchange/protocolDataPoint/checkFormula', {params: {formula: cellValue}}).then(re => {
                            if (re.code == 0) {
                                callback()
                            } else {
                                callback(new Error("非法计算公式"))
                            }
                        }
                    ).catch(e => {
                        callback(new Error("非法计算公式"))
                    })
                }
            }
            return {
                loading: false,
                tablePage: {
                    total: 0,
                    currentPage: 1,
                    pageSize: 10
                },
                templateInfo: {
                    id: this.$route.query.equipmentDataTemplateId,
                    templateType: {message: ''},
                    defaultTunnelId: ''
                },
                isNeedAudit: false,
                gatherDataSource: false,
                generateDataSource: false,
                pointRegulationValidate: pointRegulationValidate,
                /*generationRegulationValidate: generationRegulationValidate,*/
                validRules: {},
                overall: false,
                maxUsingSeq: 0,
                enums: enumerations,
                protocolDataTypeEnum:enumerations.ProtocolDataType,
                dataPoints: null,
                tunnelOptions: null,
            }
        },
        beforeDestroy() {
            if (this.sortable) {
                this.sortable.destroy()
            }
        },
        mounted() {
            // 阻止默认行为
            document.body.ondrop = function (event) {
                event.preventDefault();
                event.stopPropagation();
            };
            this.rowDrop()
        },
        created() {
            this.getTemplate(this.templateInfo.id);
            this.getAllTunnelInfo();
        },
        watch: {
            'templateInfo.defaultTunnelId': {//深度监听，可监听到对象、数组的变化
                handler(val, oldVal) {
                    if (this.dataPoints !== null) {
                        for (let i in this.dataPoints) {
                            if (this.dataPoints[i].tunnelId != undefined && this.dataPoints[i].tunnelId === oldVal) {
                                this.dataPoints[i].tunnelId = val
                            }
                        }
                        this.saveAllTemplatePoints()
                    }
                },
                deep: true
            }
        },
        methods: {

            /**
             *针对于后台返回的信息进行二次处理的方法
             * @param  promise Promise
             * @returns {Promise}
             */
            resultHandler(promise) {
                let 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)
                    })
                })
            },
            /**
             * 当行数据是否启动变化时 行背景颜色发生变化
             * @param row
             * @param rowIndex
             * @returns {string}
             */
            changeColorByIsUsing({row, rowIndex}) {
                if (row.isUsing) {
                    return 'using-row';
                } else {
                    return 'unusing-row';
                }
            },

            /**
             * 通道值发生改变的事件  通道值改变 可选的通道的数据类型发生变化
             */
            tunnelChangeEvent( row,rowIndex){
               let type= this.tunnelOptions.find(item => item.value === rowIndex.value)['type']
                if(type.indexOf("IEC104")>-1 ||type.indexOf("FILEPARSE")>-1){
                this.protocolDataTypeEnum=enumerations.ProtocolDataTypeOf104
                }else if(type.indexOf("CDT")>-1 ){
                    this.protocolDataTypeEnum=enumerations.ProtocolDataTypeOfCDT
                }else{
                    this.protocolDataTypeEnum=enumerations.ProtocolDataType
                }
            },

            /**
             * 拖动行动作的处理
             */
            rowDrop() {
                const tbody = document.querySelector('.body--wrapper>.vxe-table--body tbody');
                const _this = this;
                Sortable.create(tbody, {
                    handle: '.fa-arrows',
                    async onEnd({newIndex, oldIndex}) {
                        const currRow = _this.dataPoints.splice(oldIndex, 1)[0];
                        _this.dataPoints.splice(newIndex, 0, currRow);
                        _this.dataPoints.forEach((item, index, arr) => {
                            item.sequence = index + 1
                        })
                        try {
                            await _this.saveAllTemplatePoints();
                        } catch (e) {
                            console.error(e)
                        }
                    }
                })
            },

            /**
             * 获取到所有的通道信息并推入通道下拉列表数据内
             * @returns {null}
             */
            getAllTunnelInfo() {
                if (this.tunnelOptions == null) {
                    this.tunnelOptions = [];
                    this.resultHandler(this.$axios.get('/TunnelInfo/getTunnel/Master')).then(tunnels => {
                        let obj = {};
                        for (let i in tunnels) {
                            obj = {};
                            obj.label = tunnels[i].tunnelName;
                            obj.value = tunnels[i].id;
                            obj.type = tunnels[i].tunnelType;
                            this.tunnelOptions.push(obj);
                        }
                    })
                }
                return this.tunnelOptions;
            },

            /**
             * 保存模版点位数据
             * @param templatePoint
             * @returns {Promise<void>}
             */
            async saveTemplatePoint(templatePoint) {
                let tem = templatePoint;
                if (tem.equipmentAttribute.equipmentType.hasOwnProperty('code')) {
                    tem.equipmentAttribute.equipmentType = tem.equipmentAttribute.equipmentType.code;
                }
                await this.resultHandler(this.$axios.post('/dataExchange/templatePoint/', tem)).then(res => {
                    this.$XModal.message({
                        message: `模版点位修改完成！`,
                        status: 'success'
                    })
                })
            },


            /**
             * 保存页面上所有的通道点位
             */
           async saveAllTemplatePoints() {
                for (const tem of this.dataPoints) {
                    if (tem.equipmentAttribute.equipmentType.hasOwnProperty('code')) {
                        tem.equipmentAttribute.equipmentType = tem.equipmentAttribute.equipmentType.code;
                    }
                   await this.resultHandler(this.$axios.post('/dataExchange/templatePoint/', tem));
                }
                this.$XModal.message({
                    message: `模版点位修改完成！`,
                    status: 'success'
                })
            },

            /**
             *  获取到模版的信息  以及模版下的点位信息
             * @param templateId
             */
            getTemplate(templateId) {
                this.resultHandler(this.$axios.get('/dataExchange/equipmentDataTemplate/', {params: {id: templateId}})).then(res => {
                    this.templateInfo = res[0];
                    this.dataPoints = res[0].points.sort(function(a, b){return a.sequence - b.sequence});
                })
            },
            /**
             * 行内的编辑状态解除时 保存模版点位
             * @param row
             */
            editClosedEvent({row}) {
                this.$refs.xTable.validate(row).then(r => {
                    this.saveTemplatePoint(row)
                }).catch(errMap => errMap)
            },

            /**
             * 激活行的编辑状态 根据不同的选择判断  行内输入框是否可编辑
             * @param row
             * @param rowIndex
             */
            editActivedEvent({row, rowIndex}) {
                this.changeValidateRules(row)
                if (row.isUsing) {
                    this.isNeedAudit = !row.needAudit
                    this.gatherDataSource = row.dataSource == "GATHER"
                    this.generateDataSource = row.dataSource == "GENERATE"
                    this.overall = false;
                } else {
                    this.isNeedAudit = this.gatherDataSource = this.generateDataSource = this.overall = true;
                }
            },

            /**
             * 根据行内数据情况 修改校验规则
             * @param row
             */
            changeValidateRules(row) {
                this.validRules = {};
                if (row.isUsing) {
                    if (row.dataSource == "GATHER") {
                        this.validRules.tunnelId = [{required: true, message: '请选择通道'}],
                            this.validRules.pointRegulation = [{
                                required: true,
                                message: '请填写规则'
                            }, {validator: this.pointRegulationValidate}],
                            this.validRules.protocolPointType = [{required: true, message: '请选择数据类型'}]
                    } else if (row.dataSource == "GENERATE") {
                        this.validRules.generationRegulation = [{
                            required: true,
                            message: '请填写数据生成公式'
                        }, {validator: this.generationRegulationValidate, trigger: "blur"}]
                        this.validRules.protocolPointType = [{required: true, message: '请选择数据类型'}]
                    }
                }
                if (row.needAudit) {
                    this.validRules.maxValue = [{required: true, message: '请填写允许的最大值'}],
                        this.validRules.minValue = [{required: true, message: '请填写允许的最小值'}],
                        this.validRules.maxChangeValue = [{required: true, message: '请填写允许的最大变化值'}]
                    this.validRules.maxDuration = [{required: true, message: '请填写允许的最长持续时间'}]
                }


            },

            /**
             * 回到模版页
             */
            backTemplateMenu() {
                this.$router.go(-1);//返回上一层
            },
        }
    }

</script>

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

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