<template>
  <!-- <el-dialog v-dialogDrag :title="title" :visible.sync="dialogShow" width="800px" :before-close="doClose" :modal="false"> -->
  <div v-show="dialogShow" id="faultChoose">
    <div class="falutChooseTitle">{{ title }}</div>
    <div class="closeFalutChoose" @click="closeFaultChoose">
      <span class="el-icon-close closeFalutChooseIn" />
    </div>
    <div class="draft">
      <el-radio-group v-model="auto">
        <el-radio :label="false" border>{{ $t('display.faultChoose.manual') }}</el-radio>
        <el-radio :label="true" border>{{ $t('display.faultChoose.automatic') }}</el-radio>
      </el-radio-group>
    </div>
    <div v-if="auto" class="card">
      <QueryListPage ref="pageRules" :pager-config="pagerConfig" :query-form="queryForm" :query-list="queryList" class="queryList" />
      <addFault v-if="isAdd" @closeAddRules="closeAddRules" @reload="reloadTable" />
    </div>
    <!-- <span slot="footer" class="dialog-footer"> -->
    <span class="faultChooseFoot">
      <el-button @click="dialogShow = false">{{ $t('global.cancel') }}</el-button>
      <el-button type="primary" :loading="loading" @click="handleConfirm">{{ $t('global.confirm') }}</el-button>
    </span>
  </div>

  <!-- </el-dialog> -->
</template>

<script>
import { getFailureRulesNew, setFailureModeNew, deleteFailureRule } from '@/api/simulation';
// getFailureGenerateRules
import ConstConfig from '@/scripts/ConstConfig';
import { FaultStatusEnum } from '@/scripts/FaultDicNew';
import ModelType from '@/jmap/constant/deviceType';
import AddFault from './addFault';
import { deviceFaultType} from '@/scripts/cmdPlugin/Config';

// 故障列表
export default {
    name: 'FaultChoose',
    components:{
        AddFault
    },
    props: {
        group: {
            type: String,
            required: true
        },
        offset: {
            type: Number,
            required: true
        }
    },
    data() {
        return {
            dialogShow: false,
            loading: false,
            isAdd:false,
            deviceMap: {},
            auto: false,
            pagerConfig: {
                pageSize: 'pageSize',
                pageIndex: 'pageNum'
            },
            queryForm: {
                reset: true,
                labelWidth: '120px',
                queryObject: {
                    deviceType:{
                        type: 'select',
                        label:'触发设备类型',
                        config: {
                            data: ConstConfig.ConstSelect.simulationDeviceList
                        }
                    }
                    // faultType:{
                    //     type:'select',
                    //     label:'故障类型',
                    //     config: {
                    //         data:
                    //         // ConstConfig.ConstSelect.simulationDeviceList
                    //     }
                    // }
                }
            },
            queryList: {
                query: this.getFailureRulesNew,
                selectCheckShow: false,
                radioShow: true,
                columns: [
                    {
                        type:'basicText',
                        title: this.$t('display.faultChoose.settingCondition'),
                        columnValue: (row) => {
                            return `${this.deviceMap[row.condition.triggerDeviceType]}${this.formatNameByCode(row.condition.triggerDeviceCode)} 状态：${FaultStatusEnum[row.condition.triggerDeviceType][row.condition.triggerDeviceStatus]}`;
                        }
                    },
                    {
                        type:'basicText',
                        title: this.$t('display.faultChoose.triggerTarget'),
                        columnValue: (row) => {
                            return `${this.deviceMap[row.targetDeviceType]}${this.formatNameByCode(row.targetDeviceCode)}`;
                        }
                    },
                    {
                        type:'basicText',
                        title:'故障类型',
                        columnValue: (row) => {
                            return this.covertFaultType(row);
                        }
                    },
                    {
                        type: 'button',
                        title: '操 作',
                        width: '100',
                        buttons: [
                            {
                                name: '删除',
                                handleClick: this.deleteFailure,
                                type: 'warning'
                            }
                        ]
                    }
                ],
                actions: [
                    { text: this.$t('global.add'), handler: this.handleAdd }
                ]
            }
        };
    },
    computed: {
        title() {
            return this.$t('display.faultChoose.selectFault');
        },
        lineCode() {
            return this.$route.query.lineCode;
        }
    },
    watch:{
        // $store.state.config.menuBarLoadedCount
        'offset': function (val) {
            this.dragEvent();
        }
    },
    mounted() {
        this.deviceMap = [];
        ConstConfig.ConstSelect.simulationDeviceList.forEach(elem => {
            this.deviceMap[elem.value] = elem.label;
        });
    },
    methods: {
        formatNameByCode(code) {
            let name = '';
            const device = this.$store.getters['map/getDeviceByCode'](code);
            if (device) {
                switch (device._type) {
                case ModelType.Signal:
                case ModelType.Switch:
                case ModelType.Station:
                case ModelType.Section: {
                    if (device.parentName) {
                        name += device.parentName + '-' + device.name;
                    } else {
                        name += device.name;
                    }

                    break;
                }
                }
                if (device.stationCode) {
                    const station = this.$store.getters['map/getDeviceByCode'](device.stationCode);
                    if (station) {
                        name += '【' + station.name + '】';
                    }
                }
            }

            return name;
        },
        covertType(type) {
            switch (type) {
            case 'SECTION':return 'Section';
            case 'SIGNAL':return 'Signal';
            case 'SWITCH':return 'Switch';
            case 'STATION':return 'Station';
            case 'STAND':return 'StationStand';
            case 'TRAIN':return 'Train';
            }
        },
        covertFaultType(row) {
            const currentList = deviceFaultType[this.covertType(row.condition.triggerDeviceType)];
            let faultType = '';
            currentList.forEach(temp=>{
                if (temp.value === row.faultType) {
                    faultType = temp.label;
                }
            });
            return faultType;
        },
        closeFaultChoose() {
            this.dialogShow = false;
            this.isAdd = false;
            this.$refs.addFault.resetForm();
        },
        closeAddRules() {
            this.isAdd = false;
        },
        getFailureRulesNew(params) {
            params['lineCode'] = this.$route.query.lineCode;
            return getFailureRulesNew(params);
        },
        doShow() {
            this.dialogShow = true;
            // this.queryList.data = [];
            // getFailureGenerateRules({ skin: this.lineCode, group: this.group }).then(response => {
            //     const data = response.data;
            //     data.forEach(elem => {
            //         this.queryList.data.push({
            //             id: elem.id,
            //             condition: `${this.deviceMap[elem.condition.triggerDeviceType]}${this.formatNameByCode(elem.condition.triggerDeviceCode)} 状态：${FaultStatusEnum[elem.condition.triggerDeviceType][elem.condition.triggerDeviceStatus]}`,
            //             target: `${this.deviceMap[elem.targetDeviceType]}${this.formatNameByCode(elem.targetDeviceCode)}`
            //         });
            //     });
            // });
        },
        doClose() {
            this.dialogShow = false;
        },
        handleAdd() {
            this.isAdd = true;
        },
        getFailureModel(auto) {
            const model = { auto };
            if (auto) {
                const choose = this.$refs.pageRules.currentChoose();
                if (choose) {
                    choose.id ? Object.assign(model, { ruleId: choose.id }) : this.$messageBox(this.$t('display.faultChoose.selectRules'));
                }
            }

            return model;
        },
        deleteFailure(index, row) {
            this.$confirm('删除故障规则，是否继续？', '提 示', {
                confirmButtonText: '确 定',
                cancelButtonText: '取 消',
                type: 'warning'
            }).then(() => {
                deleteFailureRule(row.id).then(resp => {
                    this.reloadTable();
                }).catch(error => {
                    this.$message.error(`删除故障规则失败: ${error.message}`);
                });
            }).catch( () => { });
        },
        handleConfirm() {
            this.$nextTick(() => {
                const faultModel = this.getFailureModel(this.auto);
                setFailureModeNew(faultModel, this.group).then(() => {
                    this.$message.success(this.$t('display.faultChoose.setFaultSuccess'));
                }).catch(() => {
                    this.$messageBox(this.$t('display.faultChoose.setFaultFail'));
                });

                this.doClose();
            });
        },
        reloadTable() {
            this.queryList.reload();
        },
        dragEvent() {
            const offset = this.offset;
            const dialogHeaderEl = document.querySelector('.falutChooseTitle');
            const dragDom = document.querySelector('#faultChoose');
            dialogHeaderEl.style.cursor = 'move';

            /** 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);*/
            const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null);

            dialogHeaderEl.onmousedown = (e) => {
            /**  鼠标按下，计算当前元素距离可视区的距离*/
                const disX = e.clientX - dialogHeaderEl.offsetLeft;
                const disY = e.clientY - dialogHeaderEl.offsetTop;

                /**  获取到的值带px 正则匹配替换*/
                let styL, styT;

                /**  注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px*/
                if (sty.left.includes('%')) {
                // eslint-disable-next-line no-useless-escape
                    styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100);
                    styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100);
                } else {
                // eslint-disable-next-line no-useless-escape
                    styL = +sty.left.replace(/\px/g, '');
                    // eslint-disable-next-line no-useless-escape
                    styT = +sty.top.replace(/\px/g, '');
                }

                document.onmousemove = function (e) {
                /** 通过事件委托，计算移动的距离*/
                    const l = e.clientX - disX;
                    const t = e.clientY - disY;

                    /** 移动当前元素*/
                    // dragDom.style.left = `${l + styL}px`;
                    // dragDom.style.top = `${t + styT}px`;

                    /** 移动当前元素*/
                    if (l + styL < 0) {
                        dragDom.style.left = `0px`;
                    } else if (l + styL > document.body.clientWidth - dragDom.clientWidth - 10) {
                        dragDom.style.left = `${document.body.clientWidth - dragDom.clientWidth - 10}px`;
                    } else {
                        dragDom.style.left = `${l + styL}px`;
                    }
                    if (t + styT <= offset) {
                        dragDom.style.top = offset + `px`;
                    } else if (t + styT > document.body.clientHeight - dragDom.clientHeight - 10) {
                        dragDom.style.top = `${document.body.clientHeight - dragDom.clientHeight - 10}px`;
                    } else {
                        dragDom.style.top = `${t + styT}px`;
                    }

                /** 将此时的位置传出去*/
                // binding.value({ x: e.pageX, y: e.pageY });
                };

                document.onmouseup = function () {
                    document.onmousemove = null;
                    document.onmouseup = null;
                };
            };
        }
    }
};
</script>
<style scoped rel="stylesheet/scss" lang="scss">
    .draft {
        text-align: center;
        margin-bottom: 10px;
    }
    .falutChooseTitle{
        padding: 15px;
        cursor: all-scroll;
    }
    #faultChoose{
        width: 900px;
        position: absolute;
        left: 30%;
        top: 20%;
        background: #fff;
        padding:0px 0px 15px 0px;
        // transform: translate3d(-50%,-50%,0);
        border-radius: 6px;
        z-index:999;
    }
    .faultChooseFoot{
        display: inline-block;
        float: right;
        margin-right: 20px;
        margin-top: 20px;
    }
    .closeFalutChoose{
        position: absolute;
        right: 0px;
        top: 0px;
        width: 35px;
        height: 35px;
        cursor: pointer;
    }
    .closeFalutChooseIn{
        font-size: 20px;
        margin-left: 5px;
        margin-top: 10px;
    }
</style>
