<template>
  <div class="main" :style="{width: canvasWidth+'px',height:'100%',position:'absolute',overflow:'hidden'}">
    <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" :text-status-height="textStatusHeight" />
      <menu-lesson v-if="isLesson" ref="lessonMenu" :offset="offset" :data-error="dataError" :offset-bottom="offsetBottom" :tip-bottom="tipBottom" />
      <menu-exam v-if="isExam" ref="menuExam" :offset="offset" :data-error="dataError" :offset-bottom="offsetBottom" />
      <menu-script
        v-if="isScript"
        ref="menuScript"
        :offset-bottom="offsetBottom"
        :offset="offset"
        :project="project"
        :text-status-height="textStatusHeight"
        :data-error="dataError"
      />
      <menu-practice
        v-if="isPractice"
        ref="menuPractice"
        :offset="offset"
        :offset-bottom="offsetBottom"
        :data-error="dataError"
      />
    </template>
    <menu-train-list v-if="isDemon" @setCenter="setCenter" />
    <menu-system-time ref="menuSystemTime" :offset="offset" :group="group" />
  </div>
</template>
<script>
import { getSessionStorage } from '@/utils/auth';
import { mapGetters } from 'vuex';
import { OperateMode } from '@/scripts/ConstDic';
import { timeFormat } from '@/utils/date';
import MapSystemDraft from '@/views/newMap/mapsystemNew/index';
import StatusIcon from '@/views/components/StatusIcon/statusIcon';
import MenuDemon from '@/views/newMap/displayNew/menuDemon';
import MenuExam from '@/views/newMap/displayNew/menuExam';
import MenuLesson from '@/views/newMap/displayNew/menuLesson';
import MenuTrainList from '@/views/newMap/displayNew/menuTrainList';
import MenuSystemTime from '@/views/newMap/displayNew/menuSystemTime';
import MenuScript from '@/views/newMap/displayNew/menuScript';
import { clearSimulation, getSimulationInfoNew } from '@/api/simulation';
import { loadNewMapDataByGroup } from '@/utils/loaddata';
import { EventBus } from '@/scripts/event-bus';
export default {
    name: 'DisplayDraft',
    components: {
        MapSystemDraft,
        StatusIcon,
        MenuDemon,
        MenuExam,
        MenuLesson,
        MenuSystemTime,
        MenuTrainList,
        MenuScript
    },
    data() {
        return {
            offset: 15,
            offsetBottom: 15,
            tipBottom: 0,
            textStatusHeight: 0,
            planRunning:false,
            dataError: false,
            group:''
        };
    },
    computed:{
        ...mapGetters([
            'canvasWidth'
        ]),
        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';
        },
        isPractice() {
            return this.mode === 'practice';
        },
        mapId() {
            return this.$route.query.mapId;
        },
        width() {
            return this.$store.state.app.width;
        },
        height() {
            return this.$store.state.app.height;
        },
        project() {
            return getSessionStorage('project');
        }
    },
    watch:{
        '$store.state.socket.permissionOver': function () {
            this.$alert('用户权限已被收回', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                    this.back();
                }
            });
        },
        '$store.state.config.menuBarLoadedCount': function (val) { // menuBar加载完成
            this.setPosition();
        },
        '$store.state.app.windowSizeCount': function() { // 窗口缩放
            this.setWindowSize();
            this.setPosition();
        },
        '$store.state.training.prdType': function (val) { // 根据权限类型计算高度
            this.setPosition();
        },
        '$store.state.map.mapViewLoadedCount': function (val) { // 地图视图加载完成标识 开始加载默认状态
            if (this.planRunning) {
                this.$store.dispatch('training/simulationStart');
            }
        },
        $route() {
            this.initLoadData();
        }
    },
    beforeDestroy() {
        this.quit(this.group);
        this.$store.dispatch('training/reset');
        this.$store.dispatch('map/mapClear');
    },
    async mounted() {
        this.group = this.$route.query.group;
        this.setWindowSize();
        this.initLoadData();
    },
    methods:{
        // 结束加载状态
        endViewLoading(isSuccess) {
            if (!isSuccess) {
                this.$store.dispatch('map/mapClear');
            }
            this.$nextTick(() => {
                EventBus.$emit('viewLoading', false);
            });
        },
        // 销毁仿真
        quit(group) {
            clearSimulation(group);
            this.$store.dispatch('training/over');
        },
        // 仿真错误时，被动退出时调用
        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();
            }
        },
        setCenter(code) {
            this.$jlmap.setCenter(code);
        },
        // 设置 各个按钮的定位
        setPosition() {
            this.$nextTick(() => {
                this.offset = 10;
                this.offsetBottom = 15;
                const menuBar = document.getElementById('menuBar');
                const menuTool = document.getElementById('menuTool');
                const menuBottom = document.getElementById('menuButton');
                const menuButtonsBox = document.getElementById('menuButtons_box');
                const textStatus = document.getElementById('textStatus');
                if (menuBar) {
                    this.offset = (menuBar.offsetHeight || 0) + 15;
                }
                if (menuTool) {
                    this.offset = (menuTool.offsetHeight || 0) + 15;
                }
                const buttonWidth = this.width - 1200; // B box widht
                if (menuBottom && buttonWidth < 780) {
                    this.offsetBottom = (menuBottom.offsetHeight || 0) + 15;
                }
                if (menuButtonsBox) {
                    this.tipBottom = (menuButtonsBox.offsetHeight || 0) + 15;
                }
                if (textStatus) {
                    this.textStatusHeight = textStatus.offsetHeight || 0;
                    textStatus.style.top = this.offset - 15 + 'px';
                }
            });
        },
        // 缩放设置
        setWindowSize() {
            const width = this.width;
            const height = this.height;
            this.$store.dispatch('config/resize', { width, height });
            // this.$store.dispatch('training/updateOffsetStationCode', { offsetStationCode: this.offsetStationCode });
        },
        //  初始化
        initLoadData() {
            this.$store.dispatch('training/reset');
            this.loadSimulationInfo();
            this.loadMapData();
        },
        // 新版地图根据仿真group获取仿真基础信息
        async loadSimulationInfo() {
            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.$store.dispatch('training/setInitTime', +new Date(`${new Date().toLocaleDateString()} ${timeFormat(resp.data.systemTime)}`));
                this.$store.dispatch('training/countTime');
                this.planRunning = resp.data.planRunning;
                if (!this.planRunning) {
                    this.$store.dispatch('training/over');
                }
                if (this.isDemon) {
                    this.$refs.menuDemon.initPlannedDriving(this.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('此地图数据正在维护中,无法运行！');
            }
        },
        // 加载地图数据
        loadMapData() {
            if (parseInt(this.mapId)) {
                this.loadNewMapDataByGroup(this.group);
            } else {
                this.endViewLoading();
            }
        },
        // 通过group加载地图数据
        async loadNewMapDataByGroup(group) {
            try {
                this.$store.dispatch('training/changeOperateMode', { mode: OperateMode.NORMAL }); // 默认为正常模式
                await loadNewMapDataByGroup(group);
                await this.$store.dispatch('training/setMapDefaultState');
            } catch (error) {
                this.$messageBox(`获取地图数据失败: ${error.message}`);
                this.endViewLoading();
            }
        }
    }
};
</script>
