<template>
  <el-dialog v-dialogDrag :title="title" :visible.sync="dialogVisible" width="60%" :before-close="handleClose" center :close-on-click-modal="false">
    <data-form ref="datatop" :form="formTop" :form-model="formModel" :rules="topRules" />
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>输入配置:</span>
          </div>
          <div style="margin-top: 20px">
            <data-form ref="dataleft" :form="formLeft" :form-model="formModel" :rules="leftRules" />
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>输出配置:</span>
          </div>
          <div style="margin-top: 20px">
            <data-form ref="dataright" :form="formRight" :form-model="formModel" :rules="rightRules" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doSave">{{ $t('global.confirm') }}</el-button>
      <el-button @click="handleClose">{{ $t('global.cancel') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getDeviceDetail, setPsdConfig, setSignalConfig, setSwitchConfig } from '@/api/project';

export default {
    name: 'EditConfig',
    props: {
        // type: {
        //     type: String,
        //     required: true
        // }
    },
    data() {
        return {
            dialogVisible: false,
            formModel: {},
            formLeft: {},
            formRight: {},
            leftRules: {},
            rightRules: {},
            gatewayList: [],
            setDeviceConfigFunction: null,
            data: null,
            psdLeftValue: [
                {label: '输入-是否关门位', value: 'i_c'},
                {label: '输入-PSL关门按钮位', value: 'i_dc_b'},
                {label: '输入-PSL开门按钮位', value: 'i_do_b'},
                {label: '输入-互锁解除钥匙开关位', value: 'i_ir'},
                {label: '输入-是否锁闭位', value: 'i_l'},
                {label: '输入-PSL允许钥匙开关位', value: 'i_psl'},
                {label: '输入-PSL试灯按钮位', value: 'i_ts_b'}
            ],
            psdRightValue: [
                {label: '输出-关门位', value: 'o_c'},
                {label: '输出-关门信号灯控制位', value: 'o_dc_s'},
                {label: '输出-关门且锁闭信号灯控制位', value: 'o_dcl_s'},
                {label: '输出-开门信号灯控制位', value: 'o_do_s'},
                {label: '输出-互锁解除信号灯控制位', value: 'o_ir_s'},
                {label: '输出-锁闭位', value: 'o_l'},
                {label: '输出-开门位', value: 'o_o'},
                {label: '输出-PSL信号灯控制位', value: 'o_psl_s'}
            ],
            switchLeftValue: [
                {label: '输入-故障挤岔表示位', value: 'i_f'},
                {label: '输入-定位表示位', value: 'i_n'},
                {label: '输入-反位表示位', value: 'i_r'}
            ],
            switchRightValue: [
                {label: '输出-设置故障控制位', value: 'o_f'},
                {label: '输出-定操控制位', value: 'o_n'},
                {label: '输出-反操控制位', value: 'o_r'}
            ],
            signalLeftValue: [
                {label: '输入-故障表示位', value: 'i_f'},
                {label: '输入-绿灯表示位', value: 'i_g'},
                {label: '输入-黄灯表示位', value: 'i_y'},
                {label: '输入-黄红灯表示位', value: 'i_yr'}
            ],
            signalRightValue: [
                {label: '输出-故障控制位', value: 'o_f'},
                {label: '输出-绿灯控制位', value: 'o_g'},
                {label: '输出-红灯控制位', value: 'o_r'},
                {label: '输出-黄灯控制位', value: 'o_y'},
                {label: '输出-黄红灯控制位', value: 'o_yr'}
            ]
        };
    },
    computed: {
        formTop() {
            return {
                labelWidth: '220px',
                items: [
                    { prop: 'gatewayCode', label: '网关编码:', type: 'select', required: true, options: this.gatewayList, placeholder: '请选择网关编码' }
                ]
            };
        },
        topRules() {
            return {
                gatewayCode: [
                    { required: true, message: '请输入网关编码', trigger: 'change' }
                ]
            };
        },
        title() {
            return '编辑设备配置';
        }
    },
    methods: {
        initForm(row) {
            var validateDevice = (rule, value, callback) => {
                const list = [];
                rule.list.forEach(item=> {
                    if (item.value !== rule.field && this.formModel[item.value] === value) {
                        list.push(item.label);
                    } else if (item.value === rule.field) {
                        list.push(item.label);
                    }
                });
                let flag = false;
                if (value && value.length) {
                    for (var i = 0; i < value.length; i++) {
                        const ascallCode = value.charCodeAt(i);
                        if (ascallCode > 70 || ascallCode < 48 || (ascallCode > 57 && ascallCode < 65)) {
                            flag = true;
                        }
                    }

                }
                if (!value) {
                    callback(new Error(rule.messageEmpty));
                } else if (flag) {
                    callback(new Error('输入的每一位应为十六进制0-F,请修改'));
                } else if (list.length > 1) {
                    let repeatedValue = '';
                    list.forEach((item, index) => {
                        repeatedValue += item;
                        if (index !== list.length - 1) {
                            repeatedValue += '与';
                        }
                    });
                    callback(new Error(repeatedValue + '位置重复，请调整！'));
                } else {
                    callback();
                }
            };
            var validateAddr = (rule, value, callback) => {
                if (!value && value !== 0) {
                    callback(new Error(rule.messageEmpty));
                } else if (this.formModel.i_addr === this.formModel.o_addr) {
                    callback(new Error('输入网关字地址与输出网关字地址不能相同！'));
                } else {
                    callback();
                }
            };
            switch (row.type) {
            case 'PSD': {
                this.setDeviceConfigFunction = setPsdConfig;
                this.formLeft = {
                    labelWidth: '220px',
                    items: [
                        { prop:'i_addr', label:'输入网关字地址:', type: 'number', min: 0, max: 20000, step: 1, precisionFlag: true, precision: 0},
                        { prop: 'i_c', label: '输入-是否关门位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'i_dc_b', label: '输入-PSL关门按钮位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'i_do_b', label: '输入-PSL开门按钮位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'i_ir', label: '输入-互锁解除钥匙开关位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'i_l', label: '输入-是否锁闭位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'i_psl', label: '输入-PSL允许钥匙开关位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'i_ts_b', label: '输入-PSL试灯按钮位:', type: 'text', rightWidth: '100px', maxlength: 4}
                    ]
                };
                this.leftRules = {
                    i_addr: [
                        { validator: validateAddr, messageEmpty: '请填写输入网关字地址', trigger: 'blur' }
                    ],
                    i_c: [
                        { validator: validateDevice, messageEmpty: '请填写输入-是否关门位', list: this.psdLeftValue, trigger: 'blur' }
                    ],
                    i_dc_b: [
                        {validator: validateDevice, messageEmpty: '请填写输入-PSL关门按钮位', list: this.psdLeftValue, trigger: 'blur' }
                    ],
                    i_do_b: [
                        { validator: validateDevice, messageEmpty: '请填写输入-PSL开门按钮位', list: this.psdLeftValue, trigger: 'blur' }
                    ],
                    i_ir: [
                        { validator: validateDevice, messageEmpty: '请填写输入-互锁解除钥匙开关位', list: this.psdLeftValue, trigger: 'blur' }
                    ],
                    i_l: [
                        { validator: validateDevice, messageEmpty: '请填写输入-是否锁闭位', list: this.psdLeftValue, trigger: 'blur' }
                    ],
                    i_psl: [
                        { validator: validateDevice, messageEmpty: '请填写输入-PSL允许钥匙开关位', list: this.psdLeftValue, trigger: 'blur' }
                    ],
                    i_ts_b: [
                        { validator: validateDevice, messageEmpty: '请填写输入-PSL试灯按钮位', list: this.psdLeftValue, trigger: 'blur' }
                    ]
                };
                this.formRight = {
                    labelWidth: '220px',
                    items: [
                        { prop: 'o_addr', label: '输出网关字地址:', type: 'number', min: 0, max: 20000, step: 1, precisionFlag: true, precision: 0},
                        { prop: 'o_c', label: '输出-关门位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_dc_s', label: '输出-关门信号灯控制位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_dcl_s', label: '输出-关门且锁闭信号灯控制位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_do_s', label: '输出-开门信号灯控制位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_ir_s', label: '输出-互锁解除信号灯控制位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_l', label: '输出-锁闭位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_o', label: '输出-开门位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_psl_s', label: '输出-PSL信号灯控制位:', type: 'text', rightWidth: '100px', maxlength: 4}
                    ]
                };
                this.rightRules = {
                    o_addr: [
                        { validator: validateAddr, messageEmpty: '请填写输出网关字地址', trigger: 'blur' }
                    ],
                    o_c: [
                        { validator: validateDevice, messageEmpty: '请填写输出-关门位', list: this.psdRightValue, trigger: 'blur' }
                    ],
                    o_dc_s: [
                        { validator: validateDevice, messageEmpty: '请填写输出-关门信号灯控制位', list: this.psdRightValue, trigger: 'blur' }
                    ],
                    o_dcl_s: [
                        { validator: validateDevice, messageEmpty: '请填写输出-关门且锁闭信号灯控制位', list: this.psdRightValue, trigger: 'blur' }
                    ],
                    o_do_s: [
                        { validator: validateDevice, messageEmpty: '请填写输出-开门信号灯控制位', list: this.psdRightValue, trigger: 'blur' }
                    ],
                    o_ir_s: [
                        { validator: validateDevice, messageEmpty: '请填写输出-互锁解除信号灯控制位', list: this.psdRightValue, trigger: 'blur' }
                    ],
                    o_l: [
                        { validator: validateDevice, messageEmpty: '请填写输出-锁闭位', list: this.psdRightValue, trigger: 'blur' }
                    ],
                    o_o: [
                        { validator: validateDevice, messageEmpty: '请填写输出-开门位', list: this.psdRightValue, trigger: 'blur' }
                    ],
                    o_psl_s: [
                        { validator: validateDevice, messageEmpty: '请填写输出-PSL信号灯控制位', list: this.psdRightValue, trigger: 'blur' }
                    ]
                };
                break;
            }
            case 'SIGNAL': {
                this.setDeviceConfigFunction = setSignalConfig;
                this.formTop.labelWidth = '150px';
                this.formLeft = {
                    labelWidth: '150px',
                    items: [
                        { prop:'i_addr', label:'输入网关字地址:', type: 'number', min: 0, max: 20000, step: 1, precisionFlag: true, precision: 0},
                        { prop: 'i_f', label: '输入-故障表示位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'i_g', label: '输入-绿灯表示位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'i_y', label: '输入-黄灯表示位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'i_yr', label: '输入-黄红灯表示位:', type: 'text', rightWidth: '100px', maxlength: 4}
                    ]
                };
                this.leftRules = {
                    i_addr: [
                        { validator: validateAddr, messageEmpty: '请填写输入网关字地址', trigger: 'blur' }
                    ],
                    i_f: [
                        { validator: validateDevice, messageEmpty: '请填写输入-故障表示位', list: this.signalLeftValue, trigger: 'blur' }
                    ],
                    i_g: [
                        { validator: validateDevice, messageEmpty: '请填写输入-绿灯表示位', list: this.signalLeftValue, trigger: 'blur' }
                    ],
                    i_y: [
                        { validator: validateDevice, messageEmpty: '请填写输入-黄灯表示位', list: this.signalLeftValue, trigger: 'blur' }
                    ],
                    i_yr: [
                        { validator: validateDevice, messageEmpty: '请填写输入-黄红灯表示位', list: this.signalLeftValue, trigger: 'blur'}
                    ]
                };
                this.formRight = {
                    labelWidth: '150px',
                    size: 'mini',
                    items: [
                        { prop: 'o_addr', label: '输出网关字地址:', type: 'number', min: 0, max: 20000, step: 1, precisionFlag: true, precision: 0},
                        { prop: 'o_f', label: '输出-故障控制位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_g', label: '输出-绿灯控制位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_r', label: '输出-红灯控制位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_y', label: '输出-黄灯控制位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_yr', label: '输出-黄红灯控制位', type: 'text', rightWidth: '100px', maxlength: 4}
                    ]
                };
                this.rightRules = {
                    o_addr: [
                        { validator: validateAddr, messageEmpty: '请填写输出网关字地址', trigger: 'blur' }
                    ],
                    o_f: [
                        { validator: validateDevice, messageEmpty: '请填写输出-故障控制位', list: this.signalRightValue, trigger: 'blur' }
                    ],
                    o_g: [
                        { validator: validateDevice, messageEmpty: '请填写输出-绿灯控制位', list: this.signalRightValue, trigger: 'blur' }
                    ],
                    o_r: [
                        { validator: validateDevice, messageEmpty: '请填写输出-红灯控制位', list: this.signalRightValue, trigger: 'blur' }
                    ],
                    o_y: [
                        { validator: validateDevice, messageEmpty: '请填写输出-黄灯控制位', list: this.signalRightValue, trigger: 'blur' }
                    ],
                    o_yr: [
                        { validator: validateDevice, messageEmpty: '请填写输出-黄红灯控制位', list: this.signalRightValue, trigger: 'blur'}
                    ]
                };
                break;
            }
            case 'SWITCH': {
                this.setDeviceConfigFunction = setSwitchConfig;
                this.formTop.labelWidth = '160px';
                this.formLeft = {
                    labelWidth: '160px',
                    items: [
                        { prop:'i_addr', label:'输入网关字地址:', type: 'number', min: 0, max: 20000, step: 1, precisionFlag: true, precision: 0},
                        { prop: 'i_f', label: '输入-故障挤岔表示位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'i_n', label: '输入-定位表示位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'i_r', label: '输入-反位表示位:', type: 'text', rightWidth: '100px', maxlength: 4}
                    ]
                };
                this.leftRules = {
                    i_addr: [
                        { validator: validateAddr, messageEmpty: '请填写输入网关字地址', trigger: 'blur' }
                    ],
                    i_f: [
                        { validator: validateDevice, messageEmpty: '请填写输入-故障挤岔表示位', list: this.switchLeftValue, trigger: 'blur' }
                    ],
                    i_n: [
                        { validator: validateDevice, messageEmpty: '请填写输入-定位表示位', list: this.switchLeftValue, trigger: 'blur' }
                    ],
                    i_r: [
                        { validator: validateDevice, messageEmpty: '请填写输入-反位表示位', list: this.switchLeftValue, trigger: 'blur' }
                    ]
                };
                this.formRight = {
                    labelWidth: '160px',
                    items: [
                        { prop: 'o_addr', label: '输出网关字地址:', type: 'number', min: 0, max: 20000, step: 1, precisionFlag: true, precision: 0},
                        { prop: 'o_f', label: '输出-故障挤岔控制位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_n', label: '输出-定操控制位:', type: 'text', rightWidth: '100px', maxlength: 4},
                        { prop: 'o_r', label: '输出-反操控制位:', type: 'text', rightWidth: '100px', maxlength: 4 }
                    ]
                };
                this.rightRules = {
                    o_addr: [
                        { validator: validateAddr, messageEmpty: '请填写输出网关字地址', trigger: 'blur' }
                    ],
                    o_f: [
                        { validator: validateDevice, messageEmpty: '请填写输出-故障挤岔控制位', list: this.switchRightValue, trigger: 'blur' }
                    ],
                    o_n: [
                        { validator: validateDevice, messageEmpty: '请填写输出-定操控制位', list: this.switchRightValue, trigger: 'blur' }
                    ],
                    o_r: [
                        { validator: validateDevice, messageEmpty: '请填写输出-反操控制位', list: this.switchRightValue, trigger: 'blur' }
                    ]
                };
                break;
            }
            }
        },
        initData(row) {
            getDeviceDetail(row.id).then(resp => {
                if (resp.data.config) {
                    this.formModel = resp.data.config;
                }
            }).catch(()=> {
                this.$message.error('获取项目设备详情失败！');
            });
            if (row.projectCode === 'XTY') {
                this.gatewayList = [{lable:'XTY', value: 'XTY'}];
            } else if (row.projectCode === 'GZB') {
                this.gatewayList = [{label: 'GZB_1', value: 'GZB_1'}];
            }
        },
        doShow(row) {
            this.initData(row);
            this.initForm(row);
            this.dialogVisible = true;
            this.data = row;
        },
        doSave() {
            const self = this;
            this.$refs.datatop.validateForm(() => {
                self.$refs.dataleft.validateForm(()=> {
                    self.$refs.dataright.validateForm(()=> {
                        this.setDeviceConfigFunction(this.data.id, this.formModel).then(response => {
                            self.$message.success('设置设备网关映射配置成功');
                            self.handleClose();
                            self.$emit('reloadTable');
                        }).catch(error => {
                            self.$message.error(this.$t('tip.modifyTheFailure') + error.message);
                        });
                    });
                });
            });
        },
        handleClose(done) {
            this.formModel = {};
            this.formLeft = {};
            this.formRight = {};
            this.leftRules = {};
            this.rightRules = {};
            this.gatewayList = [];
            this.dialogVisible = false;
            this.$refs.datatop.resetForm();
            this.$refs.dataleft.resetForm();
            this.$refs.dataright.resetForm();
        }
    }
};
</script>
