<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" />
      <div v-if="isAdd" class="addRules">
        <div class="addRulesInner">
          <div class="addRulesInnerTitle">新增故障</div>
          <div class="closeAddRulesInner" @click="isAdd = false">
            <span class="el-icon-close closeAddRulesIn" />
          </div>
          <el-form ref="form" :model="faultRule" label-width="100px" style="margin-left:15px;">
            <el-form-item label="目标设备">
              <!-- faultRule.targetDeviceCode -->
              <el-input v-model="targetDevice" disabled size="small" class="inputModelClass" />
              <el-button :type="field === 'targetActive' ? 'danger' : 'primary'" size="small" @click="hover('targetActive')">{{ $t('map.activate') }}</el-button>
            </el-form-item>
            <el-form-item label="故障类型">
              <el-input v-model="faultRule.faultType" size="small" class="inputModelClass" />
            </el-form-item>
            <el-form-item label="触发设备">
              <!-- faultRule.condition.triggerDeviceCode -->
              <el-input v-model="triggerDevice" size="small" disabled class="inputModelClass" />
              <el-button :type="field === 'triggerActive' ? 'danger' : 'primary'" size="small" @click="hover('triggerActive')">{{ $t('map.activate') }}</el-button>
            </el-form-item>
            <el-form-item label="触发后状态">
              <!-- <el-input v-model="faultRule.condition.triggerDeviceStatus" size="small" class="inputModelClass" /> -->
              <el-select v-model="faultRule.condition.triggerDeviceStatus" placeholder="请选择" class="inputModelClass">
                <el-option
                  v-for="item in triggerStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <span class="addRulesFooter">
            <el-button size="medium" type="primary" @click="addRulesCreate">{{ $t('global.confirm') }}</el-button>
            <el-button size="medium" @click="addRulesClose">{{ $t('global.cancel') }}</el-button>
          </span>
        </div>
      </div>
    </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 { getFailureGenerateRules, setFailureModeNew } from '@/api/simulation';
import { FaultStatusEnum } from '@/scripts/FaultDic';
import ModelType from '@/jmap/constant/deviceType';

// 故障列表
export default {
    name: 'FaultChoose',
    props: {
        group: {
            type: String,
            required: true
        },
        offset: {
            type: Number,
            required: true
        }
    },
    data() {
        return {
            dialogShow: false,
            loading: false,
            isAdd:false,
            deviceMap: {},
            auto: false,
            field:'',
            triggerStatusList:[],
            faultRule:{
                targetDeviceCode:'',
                targetDeviceType:'',
                lineCode:'',
                faultType:'',
                condition:{
                    triggerDeviceCode:'',
                    triggerDeviceStatus:'',
                    triggerDeviceType :'',
                    type:''
                }
            },
            targetDevice:'',
            triggerDevice:'',
            pagerConfig: {
                pageSize: 'pageSize',
                pageIndex: 'pageNum'
            },
            queryForm: {
                reset: true,
                labelWidth: '80px',
                queryObject: {
                    condition: {
                        type: 'text',
                        label: this.$t('display.faultChoose.settingCondition')
                    }
                }
            },
            queryList: {
                query: null,
                selectCheckShow: false,
                radioShow: true,
                columns: [
                    {
                        title: this.$t('display.faultChoose.settingCondition'),
                        prop: 'condition'
                    },
                    {
                        title: this.$t('display.faultChoose.triggerTarget'),
                        prop: 'target'
                    }
                ],
                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();
        },
        '$store.state.menuOperation.selectedCount':function(em) {
            const device = this.$store.state.menuOperation.selected;
            if (device.code) {
                this.deviceSelect(device);
            }
        }
    },
    mounted() {
        this.$Dictionary.physicalViewType().then(list => {
            this.deviceMap = [];
            list.forEach(elem => {
                this.deviceMap[elem.code] = elem.name;
            });
        });
    },
    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: {
                    name += device.name;
                    break;
                }
                }
                if (device.stationCode) {
                    const station = this.$store.getters['map/getDeviceByCode'](device.stationCode);
                    if (station) {
                        name += '【' + station.name + '】';
                    }
                }
            }

            return name;
        },
        closeFaultChoose() {
            this.dialogShow = false;
            this.isAdd = false;
        },
        deviceSelect(em) {
            if (this.field.toUpperCase() === 'targetActive'.toUpperCase()) {
                this.faultRule.targetDeviceType = em._type.toUpperCase();
                this.faultRule.targetDeviceCode = em.code;
                if (em._type.toUpperCase() === 'Section'.toUpperCase() && em.parentName) {
                    this.targetDevice = em._type + '-' + em.parentName + '-' + em.name;
                } else {
                    this.targetDevice = em._type + '-' + em.name;
                }
                this.field = '';
            } else if (this.field.toUpperCase() === 'triggerActive'.toUpperCase()) {
                this.faultRule.condition.triggerDeviceType = em._type.toUpperCase();
                this.faultRule.condition.triggerDeviceCode = em.code;
                if (em._type.toUpperCase() === 'Section'.toUpperCase() && em.parentName) {
                    this.triggerDevice = em._type + '-' + em.parentName + '-' + em.name;
                } else {
                    this.triggerDevice = em._type + '-' + em.name;
                }
                this.field = '';
            }
            //     faultRule:{
            //     targetDeviceCode:'',
            //     targetDeviceType:'',
            //     lineCode:'',
            //     faultType:'',
            //     condition:{
            //         triggerDeviceCode:'',
            //         triggerDeviceStatus:'',
            //         triggerDeviceType :'',
            //         type:''
            //     }
            // },
        },
        doShow() {
            this.dialogShow = true;
            this.faultRule.lineCode = this.$route.query.lineCode;
            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)}`
                    });
                });
            });
        },
        hover(field) {
            if (this.field == '') {
                // if (this.isFirstTips) {
                //     this.$message('请在右侧地图上选择操作');
                //     this.isFirstTips = false;
                // }
                this.field = field;
                // this.$store.dispatch('scriptRecord/updateIsScriptCommand', true);
            } else {
                this.field = '';
                // this.$store.dispatch('scriptRecord/updateIsScriptCommand', false);
            }
        },
        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;
        },
        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();
        },
        addRulesCreate() {

        },
        addRulesClose() {
            this.$refs.form.resetForm();
            this.targetDevice = '';
            this.triggerDevice = '';
            this.isAdd = false;
        },
        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;
    }
    .addRules{
        position: absolute;
        width: 100%;
        left: 0;
        top: 0px;
        height: 100%;
    }
    .addRulesInner{
        position: relative;
        width: 380px;
        height: 345px;
        margin-top:46px;
        background: #fff;
        border-radius: 10px;
        border: 1px #ccc solid;
        margin-left: auto;
        margin-right: auto;
        box-shadow: 3px 3px 3px #a0a0a0;
        z-index:2;
    }
    .queryList{
        height: 300px;
        overflow: auto;
    }
    .inputModelClass{
        width:150px;
    }
    .addRulesInnerTitle{
        padding: 10px;
        font-size: 14px;
    }
    .closeAddRulesInner{
        position: absolute;
        right: 10px;
        top: 9px;
        width: 19px;
        height: 19px;
        cursor: pointer;
    }
    .closeAddRulesIn{
        font-size: 19px;
    }
    .addRulesFooter{
        margin-left: 116px;
        display: inline-block;
    }
</style>
