<template>
  <div class="main" :style="{width: canvasWidth+'px'}" @mousemove="mousemove">
    <Jl3d-Drive v-show="drivingShow" ref="Jl3dDrive" :panel-show="drivingShow" @showdriving="showdriving" />
    <Jl3d-Maintainer v-if="jl3dmaintainershow" @back="back" />
    <ibp-plate v-show="ibpShow" ref="ibpPlate" @hideIbp="hideIbp" />
    <template v-show="panelShow" :panelShow="panelShow">
      <transition name="el-zoom-in-bottom">
        <map-system-draft ref="mapCanvas" @back="back" />
      </transition>

      <menu-demon-joint
        ref="demonMenu"
        :group="group"
        :offset-bottom="offsetBottom"
        :data-error="dataError"
        :user-role="userRole"
        :is-admin="isAdmin"
        :device-code="deviceCode"
        :countdown-time="countdownTime"
        :admin-mode="adminMode"
        @getUserRole="getUserRole"
        @hidepanel="hidepanel"
        @startCounting="startCounting"
        @hidejl3dcctv="hidejl3dcctv"
        @handlerMemberManage="handlerMemberManage"
      />
      <menu-demon-schema
        ref="menuSchema"
        :group="group"
        :offset="offset"
        :user-role="userRole"
        :is-admin="isAdmin"
        :show-station="showStation"
        :station-list="stationList"
        :show-select-station="showSelectStation"
        :data-error="dataError"
        @runPlanLoadShow="runPlanLoadShow"
        @runPlanViewShow="runPlanViewShow"
        @faultChooseShow="faultChooseShow"
        @switchStationMode="switchStationMode"
        @changeAdminMode="changeAdminMode"
      />
      <join-fault-choose ref="faultChoose" :group="group" :offset="offset" />
      <join-run-plan-Load ref="runPlanLoad" :group="group" />
      <join-run-plan-view ref="runPlanView" :group="group" />
      <menu-system-time ref="menuSystemTime" :offset="offset" :group="group" :right="right" />
      <menu-train-list v-if="prdType=='02'" @setCenter="setCenter" />
      <js-question v-if="project == 'jsxt'" :offset="offset" :question-list="questionList" />
      <members-manage ref="membersManage" :is-admin="isAdmin" @addSimulationMember="addSimulationMember" /> <!-- 成员管理 -->
      <add-member ref="addMember" />
      <Jl3d-Device
        v-if="deviceShow"
        ref="Jl3dDevice"
        :panel-show="deviceShow"
        @closedevice3dview="devicemodel"
      />
    </template>
  </div>

</template>

<script>
import MapSystemDraft from '@/views/newMap/mapsystemNew/index';
import MenuDemonJoint from './menuDemon';
import MenuDemonSchema from './menuSchema';
import JsQuestion from './jsQuestion';
import JoinFaultChoose from '@/views/newMap/displayNew/demon/faultChoose';
import JoinRunPlanLoad from '@/views/newMap/displayNew/demon/runPlanLoad';
import JoinRunPlanView from '@/views/newMap/displayNew/demon/runPlanView';
import menuSystemTime from '@/views/newMap/displayNew/menuSystemTime';
import IbpPlate from '@/views/ibp/ibpsystem/index';
import MenuTrainList from './menuTrainList';
import { mapGetters } from 'vuex';
import { OperateMode, TrainingMode } from '@/scripts/ConstDic';
import { checkLoginLine } from '@/api/login';
import { loadNewMapDataByGroup } from '@/utils/loaddata';
import { clearSimulation, getSimulationInfoNew, getSimulationUserInfo, getSimulationMemberList, getAllSimulationUser } from '@/api/simulation';
import {getRaceUserById, getTestPaperDatail} from '@/api/competition';
import { getSessionStorage } from '@/utils/auth';
import Jl3dDrive from '@/views/jlmap3d/drive/jl3ddrive';
import Jl3dDevice from '@/views/jlmap3d/device/jl3ddevice';
import Jl3dMaintainer from '@/views/jlmap3d/maintainer/jl3dmaintainer';
import { EventBus } from '@/scripts/event-bus';
import { timeFormat } from '@/utils/date';
import { Message } from 'element-ui';
import Vue from 'vue';
import localStore from 'storejs';
import MembersManage from './memberManage/membersManage';
import AddMember from './memberManage/addMember';

export default {
    name: 'JointTrainingDraft',
    components: {
        MapSystemDraft,
        MenuDemonJoint,
        MenuDemonSchema,
        JoinFaultChoose,
        JoinRunPlanLoad,
        JoinRunPlanView,
        MenuTrainList,
        menuSystemTime,
        Jl3dDrive,
        Jl3dMaintainer,
        IbpPlate,
        JsQuestion,
        MembersManage,
        AddMember,
        Jl3dDevice
    },
    data() {
        return {
            trainingObj: {},
            checkLine: null,
            timeDemonNum: 0,
            offset: 10,
            offsetBottom: 15,
            mouseNum: 1,
            ierval: null,
            mouseNumTime: 0,
            mapBoxP: null,
            userRole: '',
            deviceCode: '',
            group: '',
            mapId: '',
            lineCode: '',
            simulationShow: false,
            drivingShow: false,
            jl3dmaintainershow:false,
            ibpShow: false,
            panelShow: true,
            ibpPart: '',
            showStation: '',
            stationList: [],
            showSelectStation: false,
            mapViewLoadedOver: false,
            dataError: false,
            countdownTime: '00:00:00',
            practicalTime: 0,
            countdown: null,
            questionList: [],
            practicalExamTime: 0,
            isAdmin: false,
            adminMode: true,
            deviceShow: false
        };
    },
    computed: {
        ...mapGetters([
            'canvasWidth',
            'canvasHeight'
        ]),
        ...mapGetters('map', [
            'map',
            'bigScreenConfig'

        ]),
        ...mapGetters('training', [
            'offsetStationCode'
        ]),
        ...mapGetters('config', [
            'canvasId'
        ]),
        width() {
            return this.$store.state.app.width;
        },
        height() {
            return this.$store.state.app.height;
        },
        right() {
            return this.$store.state.config.width / 2 - 55;
        },
        userId() {
            return this.$store.state.user ? this.$store.state.user.id : '';
        },
        prdType() {
            return this.$store.state.training.prdType;
        },
        project() {
            return getSessionStorage('project');
        }
    },
    watch: {
        '$store.state.config.menuBarLoadedCount': function (val) {
            this.setPosition();
        },
        '$store.state.training.prdType': function (val) {
            this.setPosition();
            if (val == '01' && this.$route.query.lineCode == '06') {
                this.showSelectStation = true;
                this.mapViewLoadedOver && this.setShowStation(this.showStation);
                this.cancelBigScreenMode();
            } else if (val == '02' && this.$route.query.lineCode == '06') {
                this.showSelectStation = false;
                this.mapViewLoadedOver && this.setShowStation('');
                this.cancelBigScreenMode();
            } else if (val == '07') { // 大屏
                this.setBigScreenMode();
            } else {
                this.cancelBigScreenMode();
            }
        },
        '$store.state.map.mapViewLoadedCount': function (val) {
            this.mapBoxP = document.getElementById(this.canvasId).children[0];
            this.mapBoxP.style.cursor = '';
            this.mapViewLoadedOver = true;
            this.showSelectStation && this.setShowStation(this.showStation);
            this.initMemberUserInfo();
            if (this.$route.query.type === 'VR_PSD') {
                this.deviceShow = true;
            }
            if (this.$route.query.type === 'DRIVE') {
                this.hidepanel();
            }
        },
        '$store.state.socket.memberChangeCount': function () {
            this.initMemberUserInfo();
        },
        '$store.state.socket.permissionOver': function () {
            this.$alert(this.$t('tip.userRightsHaveBeenReclaimed'), this.$t('tip.hint'), {
                confirmButtonText: this.$t('global.confirm'),
                showClose: false,
                callback: async (action) => {
                    await this.$store.dispatch('training/over');
                    await clearSimulation(this.group);
                    this.$router.go(-1);
                }
            });
        },
        '$store.state.app.windowSizeCount': function() {
            this.setWindowSize();
        },
        $route() {
            this.$nextTick(() => {
                this.initLoadData();
            });
        },
        '$store.state.map.map': function (val) {
            if (val) {
                this.showSelectStation = val.skinVO.code === '06' && this.$store.state.training.prdType === '01';
                this.setStationList(val);
            }
        },
        '$store.state.socket.simulationRoleList':function(val) {
            if (val && val.length) {
                this.checkRoleChange(val);
            }
        }
    },
    async created() {
        this.group = this.$route.query.group;
        this.mapId = this.$route.query.mapId;
        this.lineCode = this.$route.query.lineCode;
        // this.drawWay = this.$route.query.drawWay;
        Message.closeAll();
    },
    async mounted() {
        await this.setWindowSize();
        await this.initLoadData();
    },
    async beforeDestroy() {
        await this.clearAllTimer();
        await this.$store.dispatch('training/end', null);
        await this.$store.dispatch('training/reset');
        await this.$store.dispatch('map/mapClear');
        await this.$store.dispatch('training/setGroup', '');
        if (this.countdown) {
            clearInterval(this.countdown);
        }
        Message.closeAll();
    },
    methods: {
        mousemove(e) {
            this.mouseNum = 1;
        },
        // 清除检查在线定时器
        clearAllTimer() {
            if (this.ierval) {
                clearTimeout(this.ierval);
                this.ierval = null;
            }

            if (this.checkLine) {
                clearTimeout(this.checkLine);
                this.checkLine = null;
            }
        },
        // 设置检查在线定时器
        checkLoginLineTimer() {
            if (this.checkLine) {
                clearTimeout(this.checkLine);
            }

            this.checkLine = setInterval(() => {
                checkLoginLine();
            }, 5000 * 60);
        },
        // 设置手标显示状态
        checkMouseStatusTimer() {
            if (this.ierval) {
                clearTimeout(this.ierval);
            }

            this.ierval = setInterval(() => {
                if (this.mouseNum) {
                    this.mouseNum = 0;
                    this.mouseNumTime = 0;
                    if (this.mapBoxP) {
                        this.mapBoxP.style.cursor = this.mapBoxP.style.cursor != 'none' ? this.mapBoxP.style.cursor : '';
                    }
                } else {
                    this.mouseNumTime += 1;
                }
                if (this.mapBoxP) {
                    if (this.mouseNumTime >= 12) {
                        this.mapBoxP.style.cursor = 'none';
                    }
                }
            }, 1000);
        },
        // 设置菜单和工具栏位置
        setPosition() {
            this.$nextTick(() => {
                let offset = 10;
                let offsetBottom = 15;
                const menuBar = document.getElementById('menuBar');
                const menuTool = document.getElementById('menuTool');
                const menuBottom = document.getElementById('menuButton');
                if (menuBar) {
                    offset += (menuBar.offsetHeight || 0);
                }
                if (menuTool) {
                    offset += (menuTool.offsetHeight || 0);
                }
                if (menuBottom) {
                    offsetBottom += (menuBottom.offsetHeight || 0);
                }
                if (this.$store.state.training.prdType === '07') {
                    offset = 10;
                }
                if (this.offset != offset) {
                    this.offset = offset;
                }
                if (this.offsetBottom != offsetBottom) {
                    this.offsetBottom = offsetBottom;
                }
            });
        },
        // 结束加载状态
        endViewLoading(isSuccess) {
            if (!isSuccess) {
                this.$store.dispatch('map/mapClear');
            }

            this.$nextTick(() => {
                EventBus.$emit('viewLoading', false);
            });
        },
        setCenter(code) {
            this.$refs.mapCanvas.setCenter(code);
        },
        // 加载地图数据
        initLoadData() {
            const width = document.documentElement.clientWidth;
            const height = document.documentElement.clientHeight + 200;
            this.$store.dispatch('config/resize', { width, height });

            try {
                this.loadSimulationInfo();
                this.initLoadDemonData();
                this.checkLoginLineTimer();
                this.checkMouseStatusTimer();
            } catch (error) {
                this.$messageBox( this.$t('error.initializationFailed') + error.message);
                this.endViewLoading();
            }
        },
        async initDeviceVo() {
            // getLoginInfo(getToken()).then(resp => {
            //     this.$store.dispatch('SetProjecteDevice', resp.data.deviceVO);
            // });
        },
        initMemberUserInfo() {
            getSimulationMemberList(this.$route.query.group).then(resp => {
                this.$store.dispatch('training/setMemberList', {memberList:resp.data, userId: this.$store.state.user.id});
            }).catch(() => {
                this.$messageBox('获取仿真成员列表失败！');
            });
            getAllSimulationUser(this.$route.query.group).then(resp => {
                this.$store.dispatch('training/setSimulationUserList', resp.data);
            }).catch(() => {
                this.$messageBox('获取所有仿真用户失败！');
            });
        },
        devicemodel() {
            if (this.deviceShow == false) {
                this.deviceShow = true;
            } else {
                this.deviceShow = false;
            }
        },
        async loadSimulationInfo() {
            const resp = await getSimulationInfoNew(this.group);
            if (resp && resp.code == 200 && resp.data && !resp.data.dataError) {
                this.$store.dispatch('scriptRecord/updateSimulationPause', resp.data.pause);
                this.questId = Number(resp.data.questId) || 0;
                this.$store.dispatch('training/setInitTime', +new Date(`${new Date().toLocaleDateString()} ${timeFormat(resp.data.systemTime)}`));
                this.$store.dispatch('map/setRunPlanStatus', resp.data.planRunning);
                if (resp.data.planRunning) {
                    this.$store.dispatch('training/simulationStart');
                } else {
                    this.$store.dispatch('training/over');
                }
            } else if (resp && resp.code == 200 && resp.data && resp.data.dataError) {
                this.dataError = true;
                this.$messageBox('此地图数据正在维护中,无法运行！');
            }
        },
        async getUserRole() {
            const res = await getSimulationUserInfo(this.group);
            const data = res.data || {};
            this.userRole = data.type || 'AUDIENCE';
            this.deviceCode = data.deviceCode;
            this.isAdmin = data.admin;

            const deviceVO = this.$store.state.user.projectDevice;
            if (deviceVO && deviceVO.type === 'VR_IBP') {
                this.showIbp(this.deviceCode);
                const config = JSON.parse(deviceVO.config);
                this.ibpPart = config.part.toLowerCase();
            } else {
                this.hideIbp();
            }
            return res;
        },
        // 仿真系统
        async initLoadDemonData() {
            this.$store.dispatch('training/end', TrainingMode.NORMAL);
            this.$store.dispatch('training/changeOperateMode', { mode: OperateMode.NORMAL }); // 默认为正常模式

            if (this.lineCode) {
                // 01 现地 02 行调 '' 观众
                let resp = {data: {}};
                if (this.project == 'jsxt' ) {
                    resp = await getRaceUserById(this.$route.query.raceId);
                    resp.data.userRole = resp.data.type;
                    const paperResp = await getTestPaperDatail(this.$route.query.raceId);
                    if (paperResp.data && paperResp.data.practicalQuestions) {
                        this.questionList = [];
                        this.practicalExamTime = paperResp.data.practicalExamTime;
                        const storeKey = this.$store.state.user.id + '' + this.$route.query.raceId + 'practical';
                        const startTime = localStore.get(storeKey);
                        if (startTime) {
                            const dt = new Date().getTime() - startTime;
                            this.practicalTime = paperResp.data.practicalExamTime * 60 - Math.floor(dt / 1000);
                        } else {
                            this.practicalTime = this.practicalExamTime * 60;
                        }
                        this.countdownTime = this.computationTime(this.practicalTime);
                        paperResp.data.practicalQuestions.forEach(elem => {
                            this.questionList.push({name: elem.question.name, description:elem.question.description});
                        });
                    }
                } else if (this.project == 'refereeJsxt') {
                    resp['code'] = 200;
                    resp.data['userRole'] = 'ADMIN';
                } else {
                    await this.initDeviceVo();
                    resp = await this.getUserRole();
                }
                if (resp && resp.code == 200) {
                    this.setSimulationPrdType();
                }
                await this.getTrainDetail();
            } else {
                this.endViewLoading();
            }
        },
        // 设置prdType和role
        setSimulationPrdType(swch) {
            // Admin 管理员 Dispatcher 行调 STATION_SUPERVISOR 车站 Audience 观众 Driver 司机 MAINTAINER 通号 IBP:IBP盘
            switch (this.userRole) {
            // case 'ADMIN': this.$store.dispatch('training/setPrdType', '02'); this.$store.dispatch('training/setRoles', 'ADMIN'); this.hideIbp(); break;
            case 'DISPATCHER':
                this.$store.dispatch('training/setPrdType', '02');
                this.$store.dispatch('training/setRoles', 'DISPATCHER');
                this.hideIbp();
                this.drivingShow = false;
                break;
            case 'STATION_SUPERVISOR':
                this.$store.dispatch('training/setPrdType', '01');
                this.$store.dispatch('training/setRoles', 'STATION_SUPERVISOR');
                this.hideIbp();
                this.drivingShow = false;
                break;
            case 'AUDIENCE':
                this.$store.dispatch('training/setPrdType', '');
                this.$store.dispatch('training/setRoles', 'AUDIENCE');
                this.hideIbp();
                break;
            case 'DRIVER':
                this.$store.dispatch('training/setPrdType', '');
                this.$store.dispatch('training/setRoles', 'DRIVER');
                break;
            case 'MAINTAINER':
                this.$store.dispatch('training/setPrdType', '');
                this.$store.dispatch('training/setRoles', 'MAINTAINER');
                this.hideIbp();
                this.jl3dmaintainershow = true;
                break;
            }
            if (this.isAdmin && this.adminMode) {
                this.$store.dispatch('training/setPrdType', swch || '02');
                this.$store.dispatch('training/setRoles', 'AUDIENCE');
                this.hideIbp();
            }
        },
        startCounting() {
            const storeKey = this.$store.state.user.id + '' + this.$route.query.raceId + 'practical';
            const startTime = localStore.get(storeKey);
            if (!startTime) {
                const storeValue = new Date().getTime();
                localStore.set(storeKey, storeValue);
            }
            this.countdown = setInterval(() => {
                if (this.practicalTime <= 0) {
                    if (this.countdown) {
                        clearInterval(this.countdown);
                    }
                    this.$refs.demonMenu.submit();
                }
                this.practicalTime--;
                this.countdownTime = this.computationTime(this.practicalTime);
            }, 1000);
        },
        async getTrainDetail() {
            try {
                await loadNewMapDataByGroup(this.group);
                await this.$store.dispatch('training/setMapDefaultState');
                if (this.userRole == 'MAINTAINER') {
                    this.jl3dmaintainershow = true;
                }
            } catch (error) {
                this.$messageBox(this.$t('error.getMapDataFailed'));
                this.endViewLoading();
            }
        },
        back() {
            this.$refs.demonMenu.back();
        },
        runPlanViewShow() { // 运行图预览
            this.$refs.runPlanView.doShow();
        },
        runPlanLoadShow() { // 运行图加载
            this.$refs.runPlanLoad.doShow();
        },
        faultChooseShow() { // 故障列表加载
            this.$refs.faultChoose.doShow();
        },
        computationTime(time) {
            let hours = Math.floor(time / 3600);
            const newTime = time % 3600;
            let minutes = Math.floor(newTime / 60) + '';
            let seconds = newTime % 60;
            if (hours < 0) {
                hours = '00';
            } else if (hours < 10) {
                hours = '0' + hours;
            }
            if (minutes < 0) {
                minutes = '00';
            } else if (minutes < 10) {
                minutes = '0' + minutes;
            }
            if (seconds < 0) {
                seconds = '00';
            } else if (seconds < 10) {
                seconds = '0' + seconds;
            }
            return hours + ':' + minutes + ':' + seconds;
        },
        showdriving() {
            this.panelShow = true;
            this.drivingShow = false;
            this.ibpShow = false;
        },
        showIbp(deviceCode) {
            this.drivingShow = false;
            this.panelShow = false;
            this.ibpShow = true;
            this.$refs.ibpPlate.show(deviceCode, this.ibpPart);
        },
        hidejl3dcctv() {
            const routeData = this.$router.resolve({
                path:'/jlmap3d/passengerflow',
                query:{
                    mapid:this.mapId,
                    group:this.group,
                    project: this.project
                }
            });
            window.open(routeData.href, '_blank', 'noopener noreferrer');
        },
        hidepanel() { // 司机视角
            this.panelShow = false;
            this.drivingShow = true;
            this.ibpShow = false;
            this.$refs.Jl3dDrive.show(this.mapId, this.group);
        },

        hideIbp() {
            Message.closeAll();
            this.jl3dmaintainershow = false;
            // this.drivingShow = false;
            this.panelShow = true;
            this.ibpShow = false;
            if (this.$refs && this.$refs.ibpPlate) {
                this.$refs.ibpPlate.ibpDestroy();
            }
        },
        messageInfo(message, type) {
            this.$message({
                showClose: true,
                message: message,
                type: type
            });
        },
        setWindowSize() {
            this.$nextTick(() => {
                if (this.prdType == '07') {
                    const width = this.$store.state.app.width - 2;
                    const height = this.$store.state.app.height;
                    this.$store.dispatch('config/resize', { width, height });
                    this.setBigScreenMode();
                } else {
                    this.$store.dispatch('config/resize', { width: this.width, height: this.height });
                    this.$store.dispatch('training/updateOffsetStationCode', { offsetStationCode: this.offsetStationCode });
                }
            });
        },
        switchStationMode(val) {
            this.showStation = val;
            this.setShowStation(this.showStation);
        },
        setShowStation(val) {
            const nameList = Object.keys(this.$store.state.map.map);
            let list = [];
            nameList.forEach(item => {
                if (this.$store.state.map.map[item] && this.$store.state.map.map[item].constructor === Array) {
                    list = [...list, ...this.$store.state.map.map[item]];
                }
            });
            Vue.prototype.$jlmap.updateShowStation(list, val);
            Vue.prototype.$jlmap.setCenter(val);
        },
        setStationList(val) {
            this.stationList = [];
            (val.stationList || []).forEach(item => {
                if (item.centralized) {
                    this.stationList.push({value: item.code, name: item.name});
                }
            });
            if (this.stationList.length) {
                this.showStation = this.stationList[0].value;
            }
        },
        setBigScreenMode() {
            if (this.bigScreenConfig.bigScreenSplitConfig.length) {
                const offsetList = this.bigScreenConfig.offsetList;
                const width = this.bigScreenConfig.width;
                const height = this.bigScreenConfig.height;
                const size = {
                    width: this.$store.state.app.width * width,
                    height: (this.$store.state.app.height - 60) * height,
                    offsetY: 60,
                    list: this.bigScreenConfig.bigScreenSplitConfig.map(ele => ele.position),
                    offsetList: offsetList
                };
                this.$jlmap.off('zoom');
                this.$jlmap.setUpdateScreen(size);
            }
        },
        cancelBigScreenMode() {
            this.$jlmap.on('zoom');
            this.$jlmap.setRevoverBigScreen();
        },
        handlerMemberManage() {
            this.$refs.membersManage.doShow();
        },
        addSimulationMember() {
            this.$refs.addMember.doShow();
        },
        changeAdminMode(adminMode, swch) { // (管理/演练)模式
            this.adminMode = adminMode;
            this.setSimulationPrdType(swch);
        },
        checkRoleChange(data) {
            data.forEach(item => {
                if (item.messageType === 'KICK_OUT' && item.userId == this.userId) {
                    this.$messageBox('您已经被请离房间！');
                    this.$refs.demonMenu.back();
                } else if (item.messageType === 'PLAY_CHANGE' && item.userId == this.userId) {
                    this.userRole = item.type || 'AUDIENCE';
                    this.setSimulationPrdType();
                }
            });
        }
    }
};
</script>
<style scoped lang="scss" rel="stylesheep/scss">
	.main {
		display: block;
		width: 100%;
		height: 100%;
		overflow: hidden;
		position: relative;
	}
</style>
