<template>
  <div
    v-loading="loading"
    element-loading-text="玩命初始化中"
    element-loading-background="rgba(0, 0, 0, 0.5)"
    class="main"
    :style="{width: canvasWidth+'px',height:'100%',position:'absolute',overflow:'hidden'}"
  >
    <template>
      <transition name="el-zoom-in-bottom">
        <map-system-draft ref="mapCanvas" @back="back" />
      </transition>
      <menu-demon v-if="isDemon" ref="menuDemon" :offset="offset" :offset-bottom="offsetBottom" :data-error="dataError" :text-status-height="textStatusHeight" @start="start" @end="end" />
    </template>
    <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 MenuDemon from './menuDemon';
import MenuSystemTime from '@/views/newMap/displayCity/menuSystemTime';
import { getSimulationInfoNew, ranAsPlan } from '@/api/simulation';
import { destroySimulation, initSimulation, getSimulationInfoByGroup } from '@/api/rtSimulation';
import { loadMapDataById } from '@/utils/loaddata';
import { EventBus } from '@/scripts/event-bus';

export default {
    name: 'DisplayDraft',
    components: {
        MapSystemDraft,
        MenuDemon,
        MenuSystemTime
    },
    data() {
        return {
            offset: 15,
            offsetBottom: 15,
            tipBottom: 0,
            textStatusHeight: 0,
            planRunning:false,
            dataError: false,
            group:'',
            loading: false
        };
    },
    computed:{
        ...mapGetters([
            'canvasWidth'
        ]),
        mode() {
            return this.$route.params.mode;
        },
        project() {
            return getSessionStorage('project');
        },
        isDemon() {
            return this.mode === 'demon' && this.project != 'drts';
        },
        isContest() {
            return this.mode === 'demon' && this.project == 'drts';
        },
        isExam() {
            return this.mode === 'exam';
        },
        isLesson() {
            return (this.mode === 'teach' || this.mode === 'manage');
        },
        isScript() {
            return this.mode === 'script';
        },
        mapId() {
            return this.$route.query.mapId;
        },
        width() {
            return this.$store.state.app.width;
        },
        height() {
            return this.$store.state.app.height;
        }
    },
    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();
        },
        '$store.state.training.prdType': function (val) { // 根据权限类型计算高度
            this.setPosition();
            if (val == '01') { this.switchModeInner('01'); } else { this.switchModeInner('02'); }
        },
        '$store.state.map.mapViewLoadedCount': function (val) { // 地图视图加载完成标识 开始加载默认状态
            if (this.planRunning) {
                this.$store.dispatch('training/simulationStart');
            }
        },
        $route() {
            if (!this.isLesson && !this.isExam) {
                this.initLoadData();
            }
        }
    },
    beforeDestroy() {
        destroySimulation(this.group);
        this.$store.dispatch('training/reset');
        // this.$store.dispatch('map/mapClear');
    },
    async mounted() {
        this.setWindowSize();
        this.initLoadData();
    },
    methods:{
        // 结束加载状态
        endViewLoading(isSuccess) {
            if (!isSuccess) {
                this.$store.dispatch('map/mapClear');
            }
            this.$nextTick(() => {
                EventBus.$emit('viewLoading', false);
            });
        },
        // 仿真错误时，被动退出时调用
        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();
            } else if (this.isContest) {
                await this.$refs.menuDispatherContest.back();
            }
        },
        // 设置各个按钮的定位
        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.group = this.$route.query.group;
            this.$store.dispatch('training/reset');
            this.loadSimulationInfo();
            this.loadMapData();
        },
        // 新版地图根据仿真group获取仿真基础信息
        async loadSimulationInfo() {
            const resp = await getSimulationInfoByGroup(this.group);
            if (resp && resp.code == 200 && resp.data) {
                if (!resp.data.dataError) {
                    this.$store.dispatch('socket/handleSimulationState', resp.data.state);
                    this.$store.dispatch('runPlan/setRunPlanInfo', resp.data.runPlan);
                    this.$store.dispatch('socket/setSimulationSpeed', resp.data.speed);
                    this.planRunning = resp.data.planRunning;
                    if (resp.data.planRunning) {
                        this.$store.commit('training/start');
                    }
                } else {
                    this.$messageBox('此地图数据正在维护中,无法运行！');
                }
                this.dataError = resp.data.dataError;
            }
        },
        // 通过showMode切换显示效果
        switchModeInner(swch) {
            // let showMode = '03';
            // if (swch == '01') {
            //     showMode = '03';
            // } else if (swch == '02') {
            //     showMode = '02';
            // }

            const list = [];
            const mapDevice = this.$store.state.map.mapDevice;
            for (const key in mapDevice) {
                list.push(mapDevice[key]);
            }

            if (swch == '01') {
                this.$jlmap.updateShowStation(list, this.$store.state.training.centerStationCode); // 显示全部元素
            } else {
                this.$jlmap.updateShowStation(list, ''); // 显示全部元素
            }

            // this.$jlmap.updateShowMode(list, showMode); // 二次过滤
        },
        // 加载地图数据
        loadMapData() {
            if (parseInt(this.mapId)) {
                this.$store.dispatch('training/changeOperateMode', { mode: OperateMode.NORMAL }); // 默认为正常模式
                loadMapDataById(this.mapId, 'simulation');
            } else {
                this.endViewLoading();
            }
        },
        start(model) { // 开始仿真
            const data = {
                time: model.initTime
            };
            if (this.$route.query.prdType === '04') {
                data.loadNumber = model.loadNum;
            }
            ranAsPlan(data, this.group).then(res => {
                this.$store.dispatch('training/setInitTime', +new Date(`${new Date().toLocaleDateString()} ${model.initTime}`));
            }).catch(error => {
                let message = '';
                switch (error.code) {
                case '5001':
                    message = this.$t('error.mapDataError');
                    break;
                case '5002':
                    message = this.$t('error.runningChartDataError');
                    break;
                case '5003':
                    message = this.$t('error.runningChartIsNotLoaded');
                    break;
                case '5004':
                    message = this.$t('error.runningDataError');
                    break;
                case '5000':
                    message = this.$t('error.systemError');
                    break;
                case '4000':
                    message = this.$t('error.simulationDoesNotExist');
                    break;
                case '4001':
                    message = this.$t('error.simulationOperationIsNotDefined');
                    break;
                case '4002':
                    message = this.$t('error.simulationOperationProcessingMethodNotFound');
                    break;
                case '4003':
                    message = this.$t('error.simulationOperationFailed');
                    break;
                case '4004':
                    message = this.$t('error.operationConflict');
                    break;
                default:
                    message = '按计划行车异常,请退出重试!';
                    // this.$messageBox('按计划行车异常,请退出重试!');
                    break;
                }
                this.$messageBox(message + '，' + this.$t('error.startSimulationFailed'));
            });
        },
        end() {
            this.loading = true;
            initSimulation(this.group).then(() => {
                this.$store.dispatch('training/over').then(() => {
                    this.$store.dispatch('training/setMapDefaultState').then(() => {
                        this.$store.dispatch('map/clearJlmapTrainView');
                        this.$store.dispatch('map/resetActiveTrainList', false);
                        this.$store.dispatch('map/setTrainWindowShow', false);
                        this.$store.dispatch('map/initSimulationButton');
                    });
                });
                setTimeout(() => {
                    this.loading = false;
                }, 1500);
            }).catch(() => {
                this.loading = false;
                this.$messageBox(this.$t('display.demon.endSimulationFail'));
            });
        }
    }
};
</script>
