<template>
  <div class="main" :style="{width: canvasWidth+'px'}">
    <template v-show="panelShow" :panelShow="panelShow">
      <transition name="el-zoom-in-bottom">
        <map-system-draft ref="mapCanvas" @back="back" />
      </transition>
      <status-icon v-if="$route.query.lineCode == '11' || $route.query.lineCode == '10'" ref="statusIcon" />
      <menu-demon
        v-if="isDemon"
        ref="menuDemon"
        :offset="offset"
        :offset-bottom="offsetBottom"
        :data-error="dataError"
        :script-id="scriptId"
        @hidepanel="hidepanel"
        @passflow="passflow"
        @quitQuest="quitQuest"
        @jl3dstation="jl3dstation"
        @devicemodel="devicemodel"
        @showScheduling="showScheduling"
      />
      <menu-lesson
        v-if="isLesson"
        ref="lessonMenu"
        :offset="offset"
        :data-error="dataError"
        :offset-bottom="offsetBottom"
        :tip-bottom="tipBottom"
        :show-station="showStation"
        :station-list="stationListMode"
        :show-select-station="showSelectStation"
        @switchStationMode="switchStationMode"
      />
      <menu-exam
        v-if="isExam"
        ref="menuExam"
        :offset="offset"
        :data-error="dataError"
        :offset-bottom="offsetBottom"
        :show-station="showStation"
        :station-list="stationListMode"
        :show-select-station="showSelectStation"
        @switchStationMode="switchStationMode"
      />

      <menu-schema
        v-if="isDemon || isScript"
        ref="menuSchema"
        :offset="offset"
        :data-error="dataError"
        :offset-bottom="offsetBottom"
        :show-station="showStation"
        :station-list="stationListMode"
        :show-select-station="showSelectStation"
        @switchMode="switchMode"
        @selectQuest="selectQuest"
        @switchStationMode="switchStationMode"
      />

      <menu-script v-if="isScript" ref="menuScript" :offset-bottom="offsetBottom" :data-error="dataError" @script3ddriveshow="script3ddriveshow" />

      <menu-practice
        v-if="isPractice"
        ref="menuPractice"
        :offset="offset"
        :offset-bottom="offsetBottom"
        :show-station="showStation"
        :station-list="stationListMode"
        :show-select-station="showSelectStation"
        :data-error="dataError"
        @switchMode="switchMode"
        @switchStationMode="switchStationMode"
      />

      <menu-train-list v-if="isDemon" @setCenter="setCenter" />

      <menu-system-time ref="menuSystemTime" :offset="offset" :right="right" :group="group" />
    </template>
    <Jl3d-Device
      v-if="deviceShow"
      ref="Jl3dDevice"
      :panel-show="deviceShow"
      @closedevice3dview="devicemodel"
    />

    <!-- <Jl3d-Simulation v-show="simulationShow" ref="Jl3dSimulation" :panel-show="simulationShow" @showpanel="showpanel" /> -->
    <Jl3d-Drive v-show="drivingShow" ref="Jl3dDrive" :panel-show="drivingShow" @showdriving="showdriving" />

    <scheduling v-if="isShowScheduling" ref="scheduling" :group="group" />
  </div>
</template>
<script>
import MapSystemDraft from '@/views/newMap/mapsystemNew/index';
import MenuDemon from '@/views/newMap/displayNew/menuDemon';
import StatusIcon from '@/views/components/StatusIcon/statusIcon';
import MenuExam from '@/views/newMap/displayNew/menuExam';
import MenuLesson from '@/views/newMap/displayNew/menuLesson';
import MenuSchema from '@/views/newMap/displayNew/menuSchema';
import MenuSystemTime from '@/views/newMap/displayNew/menuSystemTime';
import MenuTrainList from '@/views/newMap/displayNew/menuTrainList';
import MenuScript from '@/views/newMap/displayNew/menuScript';
import MenuPractice from '@/views/newMap/displayNew/menuPractice';
// 三维
// import Jl3dSimulation from '@/views/jlmap3d/simulation/jl3dsimulation';
import Jl3dDrive from '@/views/jlmap3d/drive/jl3ddrive';
import Jl3dDevice from '@/views/jlmap3d/device/jl3ddevice';
import Scheduling from './demon/scheduling';
import { clearSimulation, getSimulationInfoNew, getSimulationMemberList } from '@/api/simulation';
import { getTrainingDetailNew } from '@/api/jmap/training';
import { mapGetters } from 'vuex';
import { EventBus } from '@/scripts/event-bus';
import { OperateMode, TrainingMode } from '@/scripts/ConstDic';
import { getToken } from '@/utils/auth';
import { loadNewMapDataByGroup } from '@/utils/loaddata';
import { timeFormat } from '@/utils/date';
import { getSessionStorage } from '@/utils/auth';

export default {
    name: 'DisplayDraft',
    components: {
        MapSystemDraft,
        MenuDemon,
        StatusIcon,
        MenuSystemTime,
        MenuExam,
        MenuLesson,
        MenuSchema,
        MenuTrainList,
        MenuScript,
        MenuPractice,
        // Jl3dSimulation,
        Jl3dDrive,
        Jl3dDevice,
        Scheduling
    },
    data() {
        return {
            panelShow: true,
            drivingShow: false,
            deviceShow: false,
            // simulationShow: false,
            offset: 15,
            offsetBottom: 15,
            tipBottom: 0,
            scriptId:0,
            dataError: false,
            group:'',
            showStation: '',
            stationListMode: [],
            showSelectStation: false, // 是否展示现地选择设备集中站select
            prdTypeMap: {
                '01': '01', 	// 现地 => 现地
                '02': '02', 	// 行调 => 行调
                '04': '02', 	// 司机 => 行调
                '05': ''		// 派班 => null
            },
            planRunning:false
        };
    },
    computed:{
        ...mapGetters([
            'canvasWidth'
		]),
		...mapGetters('map', [
			'map',
			'stationList'
		]),
		// ...mapGetters('training', [
        //     'offsetStationCode'
        // ]),
        mode() {
            return this.$route.params.mode;
        },
        isDemon() {
            return this.mode === 'demon';
        },
        isExam() {
            return this.mode === 'exam';
        },
        isLesson() {
            return (this.mode === 'teach' || this.mode === 'manage');
        },
        isScript() {
            return this.mode === 'script';
        },
        width() {
            return this.$store.state.app.width;
        },
        height() {
            return this.$store.state.app.height;
        },
        mapId() {
            return this.$route.query.mapId;
        },
        prdType() {
            return this.$route.query.prdType;
        },
        project() {
            return getSessionStorage('project');
        },
        isShowScheduling() {
            return this.$route.query.prdType == '05';
        },
        isPractice() {
            return this.mode === 'practice';
        },
        isDrive() {
            return this.prdType == '04';
        },
        right() {
            return this.$store.state.config.width / 2 - 55;
        },
        trainingId() {
            return this.$route.query.trainingId;
        }
    },
    watch: {
        '$store.state.config.menuBarLoadedCount': function (val) {
            this.setPosition();
        },
        '$store.state.training.prdType': function (val) { // 根据权限类型计算高度
            this.setPosition();
            this.setMode();
        },
        '$store.state.app.windowSizeCount': function() {
            this.setWindowSize();
        },
        $route() {
            this.initLoadData();
        },
        '$store.state.training.centerStationCode': function(code) {
            if (code) {
                this.showStation = code;
            }
        },
        '$store.state.socket.permissionOver': function () {
            this.$alert('用户权限已被收回', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                    this.back();
                }
            });
        },
        'stationList': function () {
            this.setStationList();
        },
        '$store.state.map.mapViewLoadedCount': function (val) { // 地图视图加载完成标识 开始加载默认状态
            if (this.planRunning) {
                this.$store.dispatch('training/simulationStart');
            }
            this.switchStationMode(this.showStation);
        }
    },
    async mounted() {
        this.group = this.$route.query.group;
        this.setWindowSize();
		await this.initLoadData();
		this.setMode();
    },
    beforeDestroy() {
        this.quit(this.group);
        this.$store.dispatch('training/reset');
        this.$store.dispatch('map/mapClear');
    },
    methods:{
        // 加载地图数据
        async initLoadData() {
            this.$store.dispatch('training/reset');
            try {
                await this.loadSimulationInfo();
                if (this.isDemon) {
                    await this.initLoadDemonData();
                } else if (this.isScript) {
                    await this.initLoadScriptData();
                } else if (this.isPractice) {
                    await this.initPracticeData();
                } else {
                    await this.initLoadLessonOrExamData();
                }
            } catch (error) {
                this.$messageBox(`初始化失败: ${error.message}`);
                this.endViewLoading();
            }
        },
        // 仿真错误时，被动退出时调用
        async back() {
            if (this.isExam) {
                await this.$refs.menuExam.back();
            } else if (this.isLesson) {
                await this.$refs.lessonMenu.back();
            } else if (this.isDemon) {
                await this.$refs.menuDemon.back();
            } else if (this.isScript) {
                await this.$refs.menuScript.back();
            }
        },
        // 销毁仿真
        quit(group) {
            clearSimulation(group);
            this.$store.dispatch('training/over');
        },
        // 缩放设置
        setWindowSize() {
            const width = this.width;
			const height = this.height;
            this.$store.dispatch('config/resize', { width, height });
            // this.$store.dispatch('training/updateOffsetStationCode', { offsetStationCode: this.offsetStationCode });
        },
        // 任务录制系统
        async initLoadScriptData() {
            this.$store.dispatch('training/end', TrainingMode.NORMAL);
            this.$store.dispatch('training/changeOperateMode', { mode: OperateMode.NORMAL }); // 默认为正常模式
            this.switchMode('01');

            if (this.mapId) {
                await this.loadNewMapDataByGroup(this.group);
            } else {
                this.endViewLoading();
            }
        },
        script3ddriveshow() {
            this.panelShow = false;
            this.drivingShow = true;
            this.$refs.Jl3dDrive.show(this.mapId, this.group);
        },
        // 课程和考试系统
        async initLoadLessonOrExamData() {
            this.$store.dispatch('training/end', null);
            this.$store.dispatch('training/changeOperateMode', { mode: OperateMode.NORMAL }); // 默认为正常模式

            if (parseInt(this.trainingId)) {
                // 设置地图数据
                // 设置实训数据
                const resp = await getTrainingDetailNew(this.trainingId);
                if (resp && resp.code == 200) {
                    const detail = resp.data;
                    await this.$store.dispatch('training/setPrdType', this.prdTypeMap[detail.prdType]);
                    await this.loadNewMapDataByGroup(this.group);
                } else {
                    this.$messageBox(`获取实训步骤数据失败`);
                    this.endViewLoading();
                }
            } else {
                this.endViewLoading();
            }
        },
        // 加载实操地图数据
        async initPracticeData() {
            this.$store.dispatch('training/end', TrainingMode.NORMAL);
            this.$store.dispatch('training/changeOperateMode', { mode: OperateMode.NORMAL }); // 默认为正常模式
            this.switchMode('01');

            if (parseInt(this.mapId)) {
                await this.loadNewMapDataByGroup(this.group);
            } else {
                this.endViewLoading();
            }
        },
        // 加载仿真信息
        async loadSimulationInfo() {
            // 单人仿真获取人员列表
            getSimulationMemberList(this.$route.query.group).then(resp => {
                this.$store.dispatch('training/setMemberList', {memberList:resp.data, userId: this.$store.state.user.id});
            }).catch(() => {
                this.$messageBox('获取仿真成员列表失败！');
            });
            const resp = await getSimulationInfoNew(this.group);
            if (resp && resp.code == 200 && resp.data && !resp.data.dataError) {
                this.dataError = false;
                this.$store.dispatch('scriptRecord/updateSimulationPause', resp.data.pause);
                this.scriptId = Number(resp.data.scriptId) || 0;
                this.$store.dispatch('training/setInitTime', +new Date(`${new Date().toLocaleDateString()} ${timeFormat(resp.data.systemTime)}`));
                this.planRunning = resp.data.planRunning;
                this.$store.dispatch('map/setRunPlanStatus', this.planRunning);
                if (!resp.data.planRunning) {
                    this.$store.dispatch('training/over');
                }
                if (this.isDemon) {
                    this.$refs.menuDemon.initPlannedDriving(resp.data.planRunning);
                } else if (this.isScript) {
                    // this.$refs.menuScript.initPlannedDriving(resp.data.planRunning);
                }
            } else if (resp && resp.code == 200 && resp.data && resp.data.dataError) {
                this.dataError = true;
                this.$messageBox('此地图数据正在维护中,无法运行！');
            }
        },
        // 结束加载状态
        endViewLoading(isSuccess) {
            if (!isSuccess) {
                this.$store.dispatch('map/mapClear');
            }
            this.$nextTick(() => {
                EventBus.$emit('viewLoading', false);
            });
        },
        switchMode(prdType) {
            this.$store.dispatch('training/setPrdType', prdType); // 改变prdType
        },
        setMode() {
            if (this.map) {
                this.showSelectStation = this.map.skinVO.code === '06' && this.$store.state.training.prdType === '01';
            }
        },
        // 选择脚本
        selectQuest(row) {
            this.scriptId = parseInt(row.id);
            if (this.isDemon) {
                this.$refs.menuDemon.initLoadPage();
            }
            if (this.isScript) {
                this.$refs.menuScript.initLoadPage();
            }
        },
        // 仿真系统
        async initLoadDemonData() {
            this.$store.dispatch('training/end', TrainingMode.NORMAL);
            this.$store.dispatch('training/changeOperateMode', { mode: OperateMode.NORMAL }); // 默认为正常模式
            this.$store.dispatch('training/setPrdType', this.prdTypeMap[this.prdType]);
            if (parseInt(this.mapId)) {
                await this.loadNewMapDataByGroup(this.group);
            } else {
                this.endViewLoading();
            }
        },
        // 通过group加载地图数据
        async loadNewMapDataByGroup(group) {
            try {
                await loadNewMapDataByGroup(group);
                await this.$store.dispatch('training/setMapDefaultState');
            } catch (error) {
                this.$messageBox(`获取地图数据失败: ${error.message}`);
                this.endViewLoading();
            }
        },
        // 退出脚本
        async quitQuest() {
            this.scriptId = 0;
        },
        hidepanel() {
            if (this.isDrive) {
                this.panelShow = false;
                this.drivingShow = true;
                this.$refs.Jl3dDrive.show(this.mapId, this.group);
            } else {
                const routeData = this.$router.resolve({
                    path:'/jlmap3d/sandbox',
                    query:{
                        mapid:this.mapId,
                        group:this.group,
                        token:getToken(),
                        project: this.project,
                        noPreLogout: true
                    }
                });
                window.open(routeData.href, '_blank', 'noopener noreferrer');
            }
        },
        passflow() {
            const routeData = this.$router.resolve({
                path:'/jlmap3d/passengerflow',
                query:{
                    mapid:this.mapId,
                    group:this.group,
                    project: this.project,
                    noPreLogout: true
                }
            });
            window.open(routeData.href, '_blank', 'noopener noreferrer');
        },
        devicemodel() {
            if (this.deviceShow == false) {
                this.deviceShow = true;
            } else {
                this.deviceShow = false;
            }
        },
        jl3dstation() {
            const routeData = this.$router.resolve({
                path:'/jlmap3d/jl3dstation',
                query:{
                    mapid:this.mapId,
                    project: this.project,
                    noPreLogout: true
                }
            });
            window.open(routeData.href, '_blank', 'noopener noreferrer');
        },
        showScheduling() {
            this.$refs.scheduling.doShow();
        },
        showdriving() {
            this.panelShow = true;
            this.drivingShow = false;
        },
        // showpanel() {
        //     this.panelShow = true;
        //     this.simulationShow = false;
        // }
        setPosition() {
            this.$nextTick(() => {
                let offset = 15;
                let offsetBottom = 15;
                const menuBar = document.getElementById('menuBar');
                const menuTool = document.getElementById('menuTool');
                const menuBottom = document.getElementById('menuButton');
                const menuButtonsBox = document.getElementById('menuButtons_box');
                if (menuBar) {
                    offset += (menuBar.offsetHeight || 0);
                }
                if (menuTool) {
                    offset += (menuTool.offsetHeight || 0);
                }
                const buttonWidth = this.width - 1200;
                if (menuBottom && buttonWidth < 550) {
                    offsetBottom = (menuBottom.offsetHeight || 0) + 15;
                }
                if (menuButtonsBox) {
                    this.tipBottom = (menuButtonsBox.offsetHeight || 0) + 15;
                }
                if (this.offset != offset) {
                    this.offset = offset;
                }
                if (this.offsetBottom != offsetBottom) {
                    this.offsetBottom = offsetBottom;
                }
            });
        },
        setCenter(code) {
            this.$jlmap.setCenter(code);
        },
        switchStationMode(val) {
            if (this.stationListMode.length > 0) {
                if (val == null) {
                    this.showStation = this.stationListMode[0].value;
                } else {
                    this.showStation = 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) {
                        if (item === 'trainList') {
                            this.$store.state.map.map[item].forEach(elem => {
                                elem && list.push(elem);
                            });
                        } else {
                            list = [...list, ...this.$store.state.map.map[item]];
                        }
                    }
                });
                this.$jlmap.updateShowStation(list, this.showStation);
                this.setCenter(this.showStation);
                // this.$store.dispatch('map/setShowCentralizedStationCode', this.showStation);
                // this.$store.dispatch('map/setShowCentralizedStationNum');
            }
        },
        setStationList() {
            this.stationListMode = [];
            (this.stationList || []).forEach(item => {
                if (item.centralized) {
                    this.stationListMode.push({value: item.code, name: item.name});
                }
            });
            if (this.stationListMode.length && this.showSelectStation) {
                this.showStation = this.stationListMode[0].value;
            }
        }
    }

};
</script>

<style scoped lang="scss" rel="stylesheep/scss">
	.main {
		display: block;
		width: 100%;
		height: 100%;
		overflow: hidden;
		position: relative;
	}
</style>
