<template>
  <div class="train">
    <div v-show="maskOpen" class="trainMask" />
    <component :is="menus" :selected="selected" />
    <jlmap-visual ref="jlmapVisual" @onSelect="clickEvent" @onMenu="onContextmenu" />
    <menu-demon ref="menuDemon" />
    <voice-chat-box v-if="$route.query.lineCode == '19'" ref="chatbox" :group="group" :user-role="userRole" />
    <chat-box v-else ref="chatbox" :group="group" :user-role="userRole" />
    <training-tip ref="trainingTip" />
    <div class="trainBack">
      <el-button-group>
        <!--        <el-button @click="nextStep">下一步</el-button>-->
        <el-button v-if="!trainingSwitch && trainingDetail" type="success" @click="handlerStart">开始</el-button>
        <el-button v-if="trainingSwitch" type="danger" @click="handlerEnd">结束</el-button>
        <el-button type="primary" @click="back">返回</el-button>
      </el-button-group>
    </div>
  </div>
</template>
<script>
import JlmapVisual from '@/views/newMap/jlmapNew/index';
import {loadMapDataById } from '@/utils/loaddata';
import { clearSimulation } from '@/api/simulation';
import { startTraining, endTraining, endTrainingStep } from '@/api/jmap/training';
import { creatSubscribe, clearSubscribe, displayTopic} from '@/utils/stomp';
import { getToken } from '@/utils/auth';
import chatBox from '@/views/newMap/chatView/chatBox.vue';
import VoiceChatBox from '@/views/newMap/chatView/voiceChatBox.vue';
import MenuDemon from './demonMenu.vue';
import TrainingTip from './trainingTip';
import deviceType from '@/jmapNew/constant/deviceType.js';
import { EventBus } from '@/scripts/event-bus';
import { getDeviceMenuByDeviceType, MouseEvent } from '@/scripts/ConstDic';
import { getSimulationMemberList, getAllSimulationUser } from '@/api/simulation';
import { getMemberListCommon, getUserListCommon } from '@/api/rtSimulation';
export default {
    name: 'TrainingDesign',
    components: {
        JlmapVisual,
        MenuDemon,
        chatBox,
        VoiceChatBox,
        TrainingTip
    },
    props: {
        widthLeft: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            maskOpen: false,
            offsetBottom: 0,
            trainingObj: null,
            starting: false,
            selected: null,
            menus: null
        };
    },
    computed: {
        mapId() {
            return this.$route.query.mapId;
        },
        width() {
            return this.$store.state.app.width;
        },
        height() {
            return this.$store.state.app.height;
        },
        group() {
            return this.$route.query.group;
        },
        teachMode() {
            return this.$store.state.trainingNew.teachMode;
        },
        trainingSwitch() {
            return this.$store.state.trainingNew.trainingSwitch;
        },
        trainingDetail() {
            return this.$store.state.trainingNew.trainingDetail;
        },
        userRole() {
            let role = 'AUDIENCE';
            switch (this.$store.state.training.prdType) {
            case '02': { role = 'DISPATCHER'; break; }
            case '01': { role = 'STATION_SUPERVISOR'; break; }
            case '04': { role = 'DRIVER'; break; }
            case '05': { role = 'DEPOT_DISPATCHER'; break; }
            default: { role = 'AUDIENCE'; break; }
            }
            return role;
        }
    },
    watch: {
        $route() {
            this.$nextTick(() => {
                this.initLoadData();
            });
        },
        '$store.state.app.windowSizeCount': function() { // 窗口缩放
            this.setWindowSize();
        },
        '$store.state.map.mapViewLoadedCount':function() {
            this.$store.dispatch('map/setTrainWindowShow', false);
            if (this.$route.query.group && !this.$route.path.includes('displayIscs')) {
                this.subscribe();
            }
        },
        '$store.state.socket.equipmentStatus': function (val) {
            if (val.length && this.$route.query.group) {
                this.statusMessage(val);
            }
        },
        '$store.state.socket.simulationOver':function(val) {
            this.backOut();
        },
        '$store.state.trainingNew.trainingOperate':function(val) {
            if (this.trainingSwitch && val) {
                const stepList = JSON.parse(this.trainingDetail.stepJson);
                const step = stepList.find(item => item.id == this.$store.state.trainingNew.stepOrder );
                const operateIndex = step.operations.findIndex(item => item.id == this.$store.state.trainingNew.operateOrder);
                this.checkOperation(val, step.operations[operateIndex], step.operations.length === (operateIndex + 1 ));
            }
        },
        '$store.state.map.mapDataLoadedCount': function () {
            const lineCode = this.$jlmap.lineCode;
            if (lineCode) {
                this.menus = this.$theme.loadMenuComponent(lineCode);
                // this.$store.commit('training/notifyGetCommandDefinition', lineCode);
            }
            this.initMemberUserInfo(true);
        }
    },
    async beforeDestroy() {
        await this.$store.dispatch('map/mapClear');
        this.$store.dispatch('training/setPrdType', '');
        this.$store.dispatch('socket/clearTrainingOverCount');
    },
    mounted() {
        this.setWindowSize();
        this.initLoadData();
    },
    methods: {
        initLoadData() { // 加载地图数据
            if (this.$route.query.group) {
                loadMapDataById(this.mapId, 'simulation');
            } else {
                this.$store.dispatch('training/changeMode', { mode: null });
                loadMapDataById(this.mapId, 'preview');
            }
        },
        checkOperation(now, data, stepOver) {
            let flag = true;
            if (now.cmdType || data.operationType) {
                const cmd = now.cmdType ? now.cmdType.value : '';
                flag = (cmd === data.operationType) && flag;
                console.log(flag, '1111111111');
            }
            if (now.code || data.deviceCode) {
                flag = (now.code === data.deviceCode) && flag;
                console.log(flag, '2222222222');
            }
            if (now.operation || data.domId) {
                flag = (now.operation === data.domId) && flag;
                console.log(flag, '33333333333');
            }
            if (now.userOperationType || data.userOperationType) {
                flag = (now.userOperationType === data.userOperationType) && flag;
                console.log(flag, '4444444444');
            }
            for (const param in data.params) {
                flag = (now.params[param] === data.params[param]) && flag;
                console.log(flag, '5555555555');
            }
            console.log(now, data, stepOver, flag);
            if (flag && stepOver) {
                this.nextStep();
            } else if (flag) {
                this.$store.dispatch('trainingNew/operateOrderIncrease');
            } else {
                console.error('校验失败；');
            }
        },
        overallTranslation(flag) {
            const panel = document.getElementById('leftSlider');
            if (flag) {
                panel.style.transform = 'translateX(400px)';
            } else {
                panel.style.transform = '';
            }
        },
        async statusMessage(list) {
            await this.$store.dispatch('training/updateMapState', list);
            await this.$store.dispatch('socket/setEquipmentStatus');
        },
        setWindowSize() {
            const width = this.width;
            const height = this.height;
            this.$store.dispatch('config/resize', { width, height });
        },
        async back() {
            if (this.$route.query.group) {
                await clearSimulation(this.$route.query.group);
                this.clearSubscribe();
            }
            this.$store.dispatch('training/over').then(() => {
                history.go(-1);
            });
        },
        backOut() {
            if (this.$route.query.projectDevice) {
                this.$store.dispatch('LogOut').then(() => {
                    location.reload();
                });
            }
        },
        async subscribe() {
            this.clearSubscribe();
            const header = { group: this.$route.query.group || '', 'X-Token': getToken() };
            creatSubscribe(`${displayTopic}\/${this.$route.query.group}`, header);
        },
        clearSubscribe() {
            clearSubscribe(`${displayTopic}\/${this.$route.query.group}`);
        },
        handlerStart() {
            startTraining(this.group, {mode: this.teachMode}).then(() => {
                this.$store.dispatch('trainingNew/trainingStart');
            }).catch(() => {
                this.$message.error('开始实训失败！');
            });
        },
        nextStep() {
            endTrainingStep(this.group, this.$store.state.trainingNew.stepOrder).then(resp => {
                this.$store.dispatch('trainingNew/clearOperateOrder');
                this.$store.dispatch('trainingNew/stepOrderIncrease');
            }).catch(() => {
                this.$message.error('进入下一步实训失败！');
            });
        },
        handlerEnd() {
            endTraining(this.group).then(() => {
                this.$store.dispatch('trainingNew/trainingEnd');
                this.$store.dispatch('socket/clearTrainingStepTip');
                this.$store.dispatch('trainingNew/clearStepOrder');
                this.$store.dispatch('trainingNew/setTrainingDetail', null);
            }).catch(() => {
                this.$message.error('结束实训失败！');
            });
        },
        clickEvent(em) {
            this.$store.dispatch('map/setTrainWindowShow', false);
            var device = { _type: em.deviceType, _code: em.deviceCode, _event: MouseEvent.Left };

            const lineCode = this.$store.getters['map/lineCode'];
            if (em.deviceType === 'StationStand' && lineCode === '01') {
                const menu = getDeviceMenuByDeviceType(device._type) || [];
                this.$store.dispatch('menuOperation/setPopMenu', { position: { x: em.clientX, y: em.clientY }, menu: menu });
            }

            if (em.deviceCode) {
                device = this.getDeviceByEm(em);
            }
            this.selected = { ...device, _event: MouseEvent.Left };
            this.$store.dispatch('menuOperation/setSelected', {device: this.selected, subType: em.subType});
            this.$store.dispatch('menuOperation/setLeftClickCount');
            if (this.$route.query.lineCode == '07') {
                this.$store.dispatch('menuOperation/setMenuChange', {device: device, subType: em.subType});
            }
            this.$store.dispatch('training/emitTipFresh');
            if (this.$store.state.map.selectDevice && this.$store.state.map.selectDevice.flag && device._type) {
                if (device._type.toUpperCase() == this.$store.state.map.selectDevice.type.toUpperCase()) {
                    EventBus.$emit('selectDevice', device);
                } else {
                    const name = this.typeObj[this.$store.state.map.selectDevice.type];
                    const info = '选择的设备类型不正确' + (name ? `，请选择${name}类型` : '');
                    this.$message.info(info);
                }
            }

        },
        onContextmenu(em) {
            var menu = null;
            var device = null;
            const point = { x: em.clientX, y: em.clientY };
            const lineCode = this.$store.getters['map/lineCode'];
            if (em.subType === 'TrainWindow') {
                if (lineCode != '06') {
                    device = { _type: deviceType.TrainWindow, code: em.deviceCode, _event: MouseEvent.Right };
                    this.$store.dispatch('map/setTrainWindowShow', true);
                }
            } else if (em.subType == 'button' && em.deviceType == 'Station') { // 宁波一号线右键显示控制模式
                const equipment = this.getDeviceByEm(em);
                this.$store.dispatch('menuOperation/setSelected', {device:equipment, subType: em.subType});
                menu = getDeviceMenuByDeviceType('StationControl');
                this.$store.dispatch('menuOperation/setPopMenu', { position: point, menu: menu });
                this.$store.dispatch('training/emitTipFresh');
                device = this.getDeviceByEm(em);
                this.selected = { ...device, _event: MouseEvent.Right};
                return;
            } else if (em.subType == 'light' && em.deviceType == 'Station') { // 宁波一号线右键显示强制点灯
                const equipment = this.getDeviceByEm(em);
                this.$store.dispatch('menuOperation/setSelected', { device: equipment, subType: em.subType });
                menu = getDeviceMenuByDeviceType('StationLight');
                this.$store.dispatch('menuOperation/setPopMenu', { position: point, menu: menu });
                this.$store.dispatch('training/emitTipFresh');
                device = this.getDeviceByEm(em);
                this.selected = { ...device, _event: MouseEvent.Right};
                return;
            } else if (em.subType == 'preReset' && em.deviceType == 'Station') { // 宁波一号线右键显示计轴复位
                const equipment = this.getDeviceByEm(em);
                this.$store.dispatch('menuOperation/setSelected', { device: equipment, subType: em.subType });
                menu = getDeviceMenuByDeviceType('StationPreReset');
                this.$store.dispatch('menuOperation/setPopMenu', { position: point, menu: menu });
                this.$store.dispatch('training/emitTipFresh');
                device = this.getDeviceByEm(em);
                this.selected = { ...device, _event: MouseEvent.Right};
                return;
            } else if (em.subType == 'enabled' && em.deviceType == 'Switch') {
                menu = getDeviceMenuByDeviceType('Enabled');
                const equipment = this.getDeviceByEm(em);
                this.$store.dispatch('menuOperation/setSelected', { device: equipment, subType: em.subType });
                this.$store.dispatch('menuOperation/setPopMenu', { position: point, menu: menu });
                device = this.getDeviceByEm(em);
                this.selected = { ...device, _event: MouseEvent.Right};
                return;
            } else if (em.subType === 'enabled' && em.deviceType === 'Signal') {
                menu = getDeviceMenuByDeviceType('Enabled');
                const equipment = this.getDeviceByEm(em);
                this.$store.dispatch('menuOperation/setSelected', { device: equipment, subType: em.subType });
                this.$store.dispatch('menuOperation/setPopMenu', { position: point, menu: menu});
                device = this.getDeviceByEm(em);
                this.selected = { ...device, _event: MouseEvent.Right};
                return;
            } else if (em.deviceCode && !this.isScreen) {
                device = this.getDeviceByEm(em);
            }
            if (device) {
                device = this.getSelectedByLineCode(device);
                this.selected = { ...device, _event: MouseEvent.Right};
                if (!this.buttonOperation) {
                    this.$store.dispatch('menuOperation/setSelected', {device: this.selected, subType: em.subType});
                    if (!this.checkShouldPop(device)) {
                        this.$store.dispatch('menuOperation/setPopMenu', { position: point, menu: null });
                    } else {
                        if (em.deviceType === 'StationStand' && lineCode === '01') {
                            return;
                        }
                        menu = getDeviceMenuByDeviceType(device._type);
                        this.$store.dispatch('menuOperation/setPopMenu', { position: point, menu: menu });
                    }
                } else if (this.$route.query.ctc) {
                    this.$store.dispatch('menuOperation/setSelected', {device: this.selected, subType: em.subType});
                    menu = getDeviceMenuByDeviceType(device._type);
                    this.$store.dispatch('menuOperation/setPopMenu', { position: point, menu: menu });
                }
            } else {
                menu = getDeviceMenuByDeviceType('Cancel');
                this.$store.dispatch('menuOperation/setPopMenu', { position: point, menu: menu });
            }
            this.$store.dispatch('training/emitTipFresh');
        },
        // 获取设备数据
        getDeviceByEm(em) {
            var device = this.$store.getters['map/getDeviceByCode'](em.deviceCode) || null;
            if (device) {
                device._viewVal = em.val;
            }
            return device;
        },
        // 根据皮肤类型转换激活的菜单类型
        getSelectedByLineCode(device) {
            const switchSectionIsWitchLineCodeList = ['03'];
            const lineCode = this.$store.getters['map/lineCode'];
            if (switchSectionIsWitchLineCodeList.includes(lineCode) && device._type == deviceType.Section) {
                const section = this.$store.getters['map/getDeviceByCode'](device._code);
                if (section) {
                    device = this.$store.getters['map/getDeviceByCode'](section.relSwitchCode);
                }
            }
            // 过滤道岔相关区段变成道岔model
            if (device._type == 'Section' && device.type == '03') {
                device = this.$store.getters['map/getDeviceByCode'](device.switch.code);
            }

            return device;
        },
        initMemberUserInfo(isFirst = false) {
            if (this.$route.query.newApi + '' === 'true') {
                getMemberListCommon(this.$route.query.group).then(resp => {
                    this.$store.dispatch('training/setMemberList', { memberList: resp.data, userId: this.$store.state.user.id });
                    getUserListCommon(this.$route.query.group).then(res => {
                        this.$store.dispatch('training/setSimulationUserList', res.data);
                    }).catch(() => {
                        this.$messageBox('获取所有仿真用户失败！');
                    });
                }).catch(() => {
                    this.$messageBox('获取仿真成员列表失败！');
                });
            } else {
                // 获取仿真成员列表
                getSimulationMemberList(this.group).then(resp => {
                    this.$store.dispatch('training/setMemberList', { memberList: resp.data, userId: this.$store.state.user.id });
                    getAllSimulationUser(this.group).then(res => {
                        this.$store.dispatch('training/setSimulationUserList', res.data);
                    }).catch(() => {
                        this.$messageBox('获取所有仿真用户失败！');
                    });
                }).catch(() => {
                    this.$messageBox('获取仿真成员列表失败！');
                });
            }
        }
    }
};
</script>
<style lang="scss" scoped>
    .train {
        width: 100%;
		overflow: hidden;
        position: relative;
    }
	.trainMask{
        opacity: 1;
        background: #000;
        position: absolute;
        right: 0;
        top: 0;
        width: 100%;
        height: 100%;
        z-index: 9;
    }
	.trainBack {
        position: absolute;
        float: right;
        right: 15px;
        bottom: 15px;
		z-index: 19;
    }
</style>
