<template>
  <div v-if="dialogShow" id="faultChoose">
    <div class="falutChooseTitle">{{ title }}</div>
    <div class="closeFalutChoose" @click="closeFaultChoose">
      <span class="el-icon-close closeFalutChooseIn" />
    </div>
    <!-- <div class="minimizeFalutChoose">
      <span class="el-icon-close closeFalutChooseIn" />
    </div> -->
    <el-card class="triggerFaultInfo">
      <el-button type="primary" size="small" style="margin-bottom:10px;" @click="isTableShow=!isTableShow">{{ isTableShow?'隐藏列表':'显示列表' }}</el-button>
      <el-table v-if="isTableShow" :data="faultList" height="300" border style="width: 100%;font-size:13px;">
        <el-table-column prop="targetDeviceCode" label="目标设备" width="220">
          <template slot-scope="scope">
            <span>{{ `${deviceMap[scope.row.targetDeviceType]}${formatNameByCode(scope.row.targetDeviceCode)}` }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="faultType" label="故障类型">
          <template slot-scope="scope">
            <span>{{ covertFaultType(scope.row) }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="condition" label="触发方式">-->
        <!--<template slot-scope="scope">-->
        <!--<span>{{ scope.row.condition.type === 'DEVICE'?'设备':'时间' }}</span>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column prop="condition" label="列车" width="100">
          <template slot-scope="scope">
            <span>{{ `${deviceMap[scope.row.condition.triggerDeviceType] || ''}${formatNameByCode(scope.row.condition.triggerDeviceCode)}` }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="condition" label="触发状态">-->
        <!--<template slot-scope="scope">-->
        <!--<span>{{ formatTriggerStatus(scope.row.condition) }}</span>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column prop="condition" label="到达区段" width="180">
          <template slot-scope="scope">
            <span>{{ `${formatNameByCode(scope.row.condition.triggerAssociatedDeviceCode)}` }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="condition.condition.triggerTime" label="触发时间" width="150" />
        <el-table-column prop="triggeringTime" label="故障状态">
          <template slot-scope="scope">
            <span>{{ scope.row.triggeringTime? '已触发': '未触发' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.triggeringTime" type="text" size="small" @click="handleDelete(scope.row)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div class="targetCard">
      <!-- <el-card class="box-card"> -->
      <div class="targetCardHead">
        <el-button style="padding:3px 0" type="text" @click="addRulesCreate">新增</el-button>
      </div>
      <div>
        <el-form ref="form" :model="faultRule" :inline="true" label-width="100px" style="margin-left:15px;">
          <el-form-item label="目标设备" class="targetFormItem">
            <!-- faultRule.targetDeviceCode -->
            <el-input v-model="targetDeviceName" disabled size="small" class="inputModelClass" style="width: 300px;" />
            <!--<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-select v-model="triggerMode" size="small" style="width: 200px;" @change="changeTriggerMode">-->
          <!--<el-option-->
          <!--v-for="item in triggerModeList"-->
          <!--:key="item.value"-->
          <!--:label="item.label"-->
          <!--:value="item.value"-->
          <!--/>-->
          <!--</el-select>-->
          <!--</el-form-item>-->
          <el-form-item label="故障类型" class="targetFormItem">
            <el-select v-model="faultRule.faultType" placeholder="请选择" class="inputModelClass" size="small" style="width: 300px;">
              <el-option
                v-for="item in faultTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="triggerMode === 'DEVICE'" label="列车" class="targetFormItem">
            <!-- faultRule.condition.triggerDeviceCode -->
            <el-input v-model="triggerDevice" size="small" disabled class="inputModelClass" style="width: 240px;" />
            <el-button :type="field === 'triggerActive' ? 'danger' : 'primary'" size="small" @click="hover('triggerActive')">{{ $t('map.activate') }}</el-button>
          </el-form-item>
          <!--<el-form-item v-if="triggerMode === 'DEVICE'" label="触发状态">-->
          <!--&lt;!&ndash; <el-input v-model="faultRule.condition.triggerDeviceStatus" size="small" class="inputModelClass" /> &ndash;&gt;-->
          <!--<el-select v-model="faultRule.condition.triggerDeviceStatus" placeholder="请选择" class="inputModelClass" size="small" style="width: 200px;">-->
          <!--<el-option-->
          <!--v-for="item in triggerStatusList"-->
          <!--:key="item.value"-->
          <!--:label="item.label"-->
          <!--:value="item.value"-->
          <!--/>-->
          <!--</el-select>-->
          <!--</el-form-item>-->
          <el-form-item v-if="triggerMode === 'DEVICE'" label="到达区段" class="targetFormItem">
            <el-input v-model="triggerAssociatedDevice" size="small" disabled class="inputModelClass" style="width: 240px;" />
            <el-button :type="field === 'triggerAssociated'? 'danger': 'primary'" size="small" @click="hover('triggerAssociated')">{{ $t('map.activate') }}</el-button>
          </el-form-item>
          <el-form-item v-if="triggerMode === 'TIME'" label="触发时间" class="targetFormItem">
            <el-date-picker
              v-model="faultRule.condition.triggerTime"
              size="small"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间"
            />
          </el-form-item>
        </el-form>
      </div>
      <!-- </el-card> -->
    </div>
  </div>
</template>

<script>
import { getSimulationFaultRules, setFailureModeNew, deleteFailureRule, cancelFailureModeNew } from '@/api/simulation';
import ConstConfig from '@/scripts/ConstConfig';
import { FaultStatusEnum } from '@/scripts/FaultDicNew';
import ModelType from '@/jmapNew/constant/deviceType';
import { deviceFaultType } from '@/scripts/cmdPlugin/Config';

// 故障列表
export default {
    name: 'FaultChoose',
    props: {
        group: {
            type: String,
            required: true
        },
        offset: {
            type: Number,
            required: true
        }
    },
    data() {
        return {
            dialogShow: false,
            loading: false,
            isAdd:false,
            isTableShow:true,
            deviceMap: {},
            simulationFault:{},
            faultList: [],
            faultRule:{
                targetDeviceCode:'',
                targetDeviceType:'',
                faultType:'',
                condition:{
                    triggerDeviceCode:'',
                    triggerDeviceStatus:'',
                    triggerDeviceType :'',
                    type:'DEVICE',
                    triggerTime: '',
                    triggerAssociatedDeviceCode: ''
                }
            },
            triggerDevice:'',
            triggerAssociatedDevice: '',
            triggerMode: 'DEVICE',
            triggerModeList: [
                {label: '设备触发', value: 'DEVICE'},
                {label: '时间触发', value: 'TIME'}
            ],
            field:'',
            triggerStatusList:[],
            faultTypeList:[],
            targetDeviceName: ''
        };
    },
    computed: {
        title() {
            return '自动故障设置';
        },
        lineCode() {
            return this.$route.query.lineCode;
        },
        targetDevice() {
            return this.$store.state.training.triggerFaultDevice;
        }
    },
    watch:{
        '$store.state.socket.autoFaultTrigger':function(val) {
            this.dialogShow && this.getSimulationFaultRules();
        },
        '$store.state.menuOperation.selectedCount':function(em) {
            const device = this.$store.state.menuOperation.selected;
            if (device && device.code) {
                this.deviceSelect(device);
            }
        },
        targetDevice: function(device) {
            this.targetDeviceName = this.targetDevice.name || this.targetDevice.code;
        }
    },
    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;
                }
                case ModelType.Train:
                    name = device.code;
                    break;
                }
                if (device.stationCode) {
                    const station = this.$store.getters['map/getDeviceByCode'](device.stationCode);
                    if (station) {
                        name += '【' + station.name + '】';
                    }
                }
            }

            return name;
        },
        // formatTriggerStatus(condition) {
        //     if (!condition.triggerDeviceType) {
        //         return '';
        //     }
        //     const faultStatus = FaultStatusEnum[condition.triggerDeviceType];
        //     return faultStatus[condition.triggerDeviceStatus];
        // },
        hover(field) {
            if (this.field == '') {
                this.field = field;
            } else {
                this.field = '';
            }
        },
        handleDelete(row) {
            cancelFailureModeNew(row.id, this.$route.query.group).then(resp => {
                this.getSimulationFaultRules();
            }).catch(() => {
                this.$message.error('取消故障失败！');
            });
        },
        covertType(type) {
            switch (type) {
            case 'SECTION':return 'Section';
            case 'SIGNAL':return 'Signal';
            case 'SWITCH':return 'Switch';
            case 'STATION':return 'Station';
            case 'ZC':return 'ZcControl';
            case 'STAND':return 'StationStand';
            case 'TRAIN':return 'Train';
            case 'Section':return 'SECTION';
            case 'Signal':return 'SIGNAL';
            case 'Switch':return 'SWITCH';
            case 'Station':return 'STATION';
            case 'ZcControl':return 'ZC';
            case 'StationStand':return 'STAND';
            case 'Train':return 'TRAIN';
            }
        },
        covertFaultType(row) {
            let faultType = '';
            if (row && row.id) {
                let type = this.covertType(row.targetDeviceType);
                if (type == 'Station') {
                    type = 'ZcControl';
                }
                const currentList = deviceFaultType[type];
                currentList.forEach(temp=>{
                    if (temp.value === row.faultType) {
                        faultType = temp.label;
                    }
                });
            }
            return faultType;
        },
        closeFaultChoose() {
            this.dialogShow = false;
            this.isAdd = false;
            if (this.$refs.addFault) {
                this.$refs.addFault.resetForm();
            }
        },
        closeAddRules() {
            this.isAdd = false;
        },
        getSimulationFaultRules() {
            if (this.dialogShow) {
                getSimulationFaultRules(this.$route.query.group).then(resp => {
                    this.faultList = resp.data;
                }).catch(() => {
                    this.$messageBox('获取数据异常');
                });
            }
        },
        changeTriggerMode(val) {
            this.resetForm();
            this.triggerMode = val;
            this.faultRule.condition.type = val;
        },
        doShow() {
            this.dialogShow = true;
            this.getSimulationFaultRules();
            this.resetForm();
            this.faultTypeList = deviceFaultType[this.targetDevice._type];
            this.faultRule.targetDeviceCode = this.targetDevice.code;
            this.faultRule.targetDeviceType = this.covertType(this.targetDevice._type);
            this.faultRule.faultType = (this.faultTypeList[0] || {}).value;
            this.$nextTick(()=>{
                this.dragEvent();
            });
        },
        resetForm() {
            this.getSimulationFaultRules();
            this.field = '';
            this.triggerDevice = '';
            this.triggerAssociatedDevice = '';
            this.faultRule = {
                targetDeviceCode:this.targetDevice.code,
                targetDeviceType:this.covertType(this.targetDevice._type),
                faultType:'',
                condition:{
                    triggerDeviceCode:'',
                    triggerDeviceStatus:'',
                    triggerDeviceType :'',
                    type:'DEVICE',
                    triggerTime: '',
                    triggerAssociatedDeviceCode: ''
                }
            };
        },
        doClose() {
            this.dialogShow = false;
        },
        handleAdd() {
            this.isAdd = true;
            this.$nextTick(() => {
                this.$refs.addFault.initValue();
            });
        },
        deleteFailure(index, row) {
            event.cancelBubble = true;
            this.$confirm('删除故障规则，是否继续？', '提 示', {
                confirmButtonText: '确 定',
                cancelButtonText: '取 消',
                type: 'warning'
            }).then(() => {
                deleteFailureRule(row.id).then(resp => {
                }).catch(error => {
                    this.$message.error(`删除故障规则失败: ${error.message}`);
                });
            }).catch( () => { });
        },
        settingFailure(index, row, idx) {
            const faultModel = {ruleId: row.id, auto:true};
            // row['loading' + idx] = true;
            setFailureModeNew(faultModel, this.group).then(() => {
                this.getSimulationFaultRules();
                this.$message.success('设置自动故障成功');
            }).catch(() => {
                this.$messageBox('设置自动故障失败');
            });
        },
        cancleAutoFault() {
            const faultModel = {auto:false};
            setFailureModeNew(faultModel, this.group).then(() => {
                this.getSimulationFaultRules();
                this.$message.success('取消自动故障成功');
            }).catch(() => {
                this.$messageBox('取消自动故障失败');
            });
        },
        addRulesCreate() {
            if (this.triggerMode === 'DEVICE' && this.triggerDevice == '') {
                this.$messageBox('请选择触发设备');
                return;
            }
            if (this.triggerMode === 'DEVICE' && this.faultRule.condition.triggerDeviceStatus == '') {
                this.$messageBox('请选择触发状态');
                return;
            }
            if (this.faultRule.faultType == '') {
                this.$messageBox('请选择故障类型');
                return;
            }
            if (this.triggerMode === 'TIME' && this.faultRule.condition.triggerTime == '') {
                this.$messageBox('请选择触发时间');
                return;
            }
            if (this.triggerMode === 'DEVICE' && this.faultRule.condition.triggerDeviceType === 'TRAIN' && this.faultRule.condition.triggerDeviceStatus === 'Section' && this.faultRule.condition.triggerAssociatedDeviceCode == '') {
                this.$messageBox('请选择关联设备');
                return;
            }
            const param = {
                targetDeviceCode:this.targetDevice.code,
                targetDeviceType:this.covertType(this.targetDevice._type),
                faultType: this.faultRule.faultType,
                condition:{
                    triggerDeviceCode: this.faultRule.condition.triggerDeviceCode || null,
                    triggerDeviceStatus:this.faultRule.condition.triggerDeviceStatus || null,
                    triggerDeviceType :this.faultRule.condition.triggerDeviceType || null,
                    type:this.faultRule.condition.type,
                    triggerTime: this.faultRule.condition.triggerTime || null,
                    triggerAssociatedDeviceCode: this.faultRule.condition.triggerAssociatedDeviceCode || null
                }
            };
            setFailureModeNew(param, this.$route.query.group).then(res=>{
                this.$message.success('创建故障成功！');
                this.resetForm();
            }).catch((error)=>{
                this.$messageBox('创建故障失败: ' + error.message);
            });
        },
        deviceSelect(em) {
            if (this.field.toUpperCase() === 'triggerAssociated'.toUpperCase() && em._type.toUpperCase() === 'Section'.toUpperCase()) {
                // if (em._type == 'Station') {
                //     em = this.$store.getters['map/getDeviceByCode'](em.zcCode);
                // }
                // this.faultRule.targetDeviceType = this.covertType(em._type);
                // this.faultRule.targetDeviceCode = em.code;
                if (em._type.toUpperCase() === 'Section'.toUpperCase() && em.parentName) {
                    this.triggerAssociatedDevice = em._type + '-' + em.parentName + '-' + em.name;
                } else {
                    this.triggerAssociatedDevice = em._type + '-' + em.name;
                }
                this.faultRule.condition.triggerAssociatedDeviceCode = em.code;
            } else if (this.field.toUpperCase() === 'triggerActive'.toUpperCase() && em._type.toUpperCase() === 'Train'.toUpperCase()) {
                this.faultRule.condition.triggerDeviceType = this.covertType(em._type);
                this.faultRule.condition.triggerDeviceCode = em.code;
                if (em._type.toUpperCase() === 'Section'.toUpperCase() && em.parentName) {
                    this.triggerDevice = em._type + '-' + em.parentName + '-' + em.name;
                } else if (em._type.toUpperCase() === 'Train'.toUpperCase()) {
                    this.triggerDevice = em._type + '-' + em.code;
                } else {
                    this.triggerDevice = em._type + '-' + em.name;
                }
                this.triggerStatusList = [];
                const faultStatus = FaultStatusEnum[this.faultRule.condition.triggerDeviceType];
                if (faultStatus) {
                    const list = Object.keys(faultStatus);
                    list.forEach(key=>{
                        this.triggerStatusList.push({label:faultStatus[key], value:key});
                    });
                }
                this.field = '';
                this.faultRule.condition.triggerDeviceStatus = (this.triggerStatusList[0] || {}).value;
            }
        },
        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 lang="scss">
    #faultChoose .card .queryList .el-card .el-card__body .el-table--border .el-table__body-wrapper{
        height: 135px !important;
        overflow-y: auto !important;
    }
    #faultChoose .el-button--mini {
        margin-left: 5px;
    }
    .triggerFaultListLeft{
        display: inline-block;
        float: left;
        width: 730px;
    }
    // 谷歌、safari、qq浏览器、360浏览器滚动条样式
	// 定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸
	#faultChoose .el-table__body-wrapper::-webkit-scrollbar {
		width: 6px;
        height: 6px;
		// height: 110px;
		background-color: #FFFFFF;
	}
	/*定义滚动条轨道 内阴影+圆角*/
	#faultChoose .el-table__body-wrapper::-webkit-scrollbar-track {
		// box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
		border-radius: 10px;
		background-color: #FFFFFF;;
	}
	/*定义滑块 内阴影+圆角*/
	#faultChoose .el-table__body-wrapper::-webkit-scrollbar-thumb {
		border-radius: 10px;
		// box-shadow: inset 0 0 6px rgba(0,0,0,.3);
		background-color: #eaeaea;
	}
	/*滑块效果*/
	#faultChoose .el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
		border-radius: 5px;
		// box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
		background: rgba(0,0,0,0.4);
	}
	/*IE滚动条颜色*/
	html {
		scrollbar-face-color:#bfbfbf;/*滚动条颜色*/
		scrollbar-highlight-color:#000;
		scrollbar-3dlight-color:#000;
		scrollbar-darkshadow-color:#000;
		scrollbar-Shadow-color:#adadad;/*滑块边色*/
		scrollbar-arrow-color:rgba(0,0,0,0.4);/*箭头颜色*/
		scrollbar-track-color:#eeeeee;/*背景颜色*/
	}
</style>
<style scoped rel="stylesheet/scss" lang="scss">
    .triggerFaultInfo{
        margin-bottom:10px;
        padding: 10px 10px 10px 15px;
    }
    .triggerFaultList{
        font-size: 14px;
        margin-top: 10px;
        line-height: 20px;
    }
    .triggerFaultTitle{
        font-size: 15px;
        font-weight: bold;
    }
    .falutChooseTitle{
        padding: 15px;
        cursor: all-scroll;
    }
    #faultChoose{
        width: 1000px;
        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;
    }
    .targetCard{
        box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
        border-top: 1px #ebeef5 solid;
    }
    .targetFormItem{
        margin-bottom: 12px;
    }
    .targetCardHead{
        padding: 5px;
        display: inline-block;
        width: 100%;
        margin-bottom: 10px;
        border-bottom: 1px #f4f4f4 solid;
        text-align: right;
        padding-right: 15px;
    }
</style>
