<template>
  <div class="map-view" :style="{width: canvasWidth+'px',height:'100%',position:'absolute',overflow:'hidden'}">
    <div v-show="maskOpen" class="mask" :style="{'width': maskWidth}" />
    <jlmap-visual ref="jlmapVisual" />
    <div class="display-draft">
      <el-button-group>
        <el-button type="success" :disabled="isDisable" size="small" @click="selectBeginTime">{{ $t('display.demon.drivingByPlan') }}</el-button>
        <el-button type="danger" size="small" @click="end">{{ $t('display.demon.initialize') }}</el-button>
        <el-button type="small" @click="back">{{ $t('scriptRecord.scriptBack') }}</el-button>
      </el-button-group>
    </div>
    <set-time ref="setTime" @ConfirmSelectBeginTime="start" />
    <menu-system-time ref="menuSystemTime" :offset="15" :group="group" />
  </div>
</template>
<script>
import SetTime from '@/views/newMap/displayNew/demon/setTime';
import JlmapVisual from '@/views/newMap/jlmapNew/index';
import { Notification } from 'element-ui';
import { loadMapDataById } from '@/utils/loaddata';
import { ranAsPlan, exitRunPlan, clearSimulation, getSimulationInfoNew } from '@/api/simulation';
import { creatSubscribe, clearSubscribe, displayTopic} from '@/utils/stomp';
import MenuSystemTime from '@/views/newMap/displayNew/menuSystemTime';
import { getToken } from '@/utils/auth';
import { mapGetters } from 'vuex';
import { timeFormat } from '@/utils/date';
export default {
    name:'TestRunplan',
    components: {
        SetTime,
        JlmapVisual,
        MenuSystemTime
    },
    data() {
        return {
            maskOpen: false,
            maskWidth: '100%'
        };
    },
    computed:{
        ...mapGetters([
            'canvasWidth'
        ]),
        group() {
            return this.$route.query.group;
        },
        mapId() {
            return this.$route.query.mapId;
        },
        isDisable() {
            return this.$store.state.training.started;
        },
        width() {
            return this.$store.state.app.width;
        },
        height() {
            return this.$store.state.app.height;
        }
    },
    watch:{
        '$store.state.map.mapViewLoadedCount':function() {
            this.$store.dispatch('map/setTrainWindowShow', false);
            // this.$jlmap.off('zoom');
            if (this.group) {
                this.subscribe();
            }
        },
        '$store.state.app.windowSizeCount': function() { // 窗口缩放
            this.setWindowSize();
        },
        '$store.state.socket.equipmentStatus': function (val) {
            if (val.length && this.$route.query.group) {
                this.statusMessage(val);
            }
        },
        '$store.state.socket.simulationStart': function(val) {
            this.$store.dispatch('training/simulationStart').then(() => {
                this.$store.dispatch('map/setShowCentralizedStationNum');
            });
        }
    },
    async beforeDestroy() {
        await this.$store.dispatch('map/mapClear');
    },
    async mounted() {
        this.setWindowSize();
        await this.initLoadData();
    },
    methods:{
        initLoadData() { // 加载地图数据
            if (this.mapId) {
                this.loadSimulationInfo();
                loadMapDataById(this.mapId, 'simulation');
            }
        },
        // 缩放设置
        setWindowSize() {
            const width = this.width;
            const height = this.height;
            this.$store.dispatch('config/resize', { width, height });
        },
        async back() {
            if (this.group) {
                await clearSimulation(this.group);
                this.clearSubscribe();
            }
            this.$store.dispatch('map/setShowCentralizedStationCode', '');
            history.go(-1);
            Notification.closeAll();
        },
        selectBeginTime() {
            this.$refs.setTime.doShow();
        },
        async statusMessage(list) {
            await this.$store.dispatch('training/updateMapState', list);
            await this.$store.dispatch('socket/setEquipmentStatus');
        },
        end() {
            exitRunPlan(this.group).then(() => {
                this.$store.dispatch('training/over').then(() => {
                    this.$store.dispatch('training/setMapDefaultState').then(() => {
                        this.$store.dispatch('map/resetActiveTrainList', false);
                        this.$store.dispatch('map/clearJlmapTrainView');
                        this.$store.dispatch('map/setTrainWindowShow', false);
                    });
                });
            }).catch(() => {
                this.$messageBox(this.$t('display.demon.endSimulationFail'));
            });
        },
        async subscribe() {
            this.clearSubscribe();
            const header = { group: this.group || '', 'X-Token': getToken() };
            creatSubscribe(`${displayTopic}\/${this.$route.query.group}`, header);
            // await this.$store.dispatch('training/setHasSubscribed');
        },
        clearSubscribe() {
            clearSubscribe(`${displayTopic}\/${this.group}`);
        },
        async loadSimulationInfo() {
            const resp = await getSimulationInfoNew(this.group);
            if (resp && resp.code == 200 && resp.data) {
                if (!resp.data.dataError) {
                    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 (resp.data.planRunning) {
                        this.$store.commit('training/start');
                    }
                } else {
                    this.$messageBox('此地图数据正在维护中,无法运行！');
                }
                this.dataError = resp.data.dataError;
            }
        },
        start(model) { // 开始仿真
            const data = {
                time: model.initTime
            };
            ranAsPlan(data, this.group).then(res => {
                this.$store.dispatch('training/setInitTime', +new Date(`${new Date().toLocaleDateString()} ${model.initTime}`));
            }).catch(error => {
                if (error.code == '5001') {
                    this.$messageBox(this.$t('error.mapDataError') + ',' + this.$t('error.startSimulationFailed'));
                } else if (error.code == '5002') {
                    this.$messageBox(this.$t('error.runningChartDataError') + ',' + this.$t('error.startSimulationFailed'));
                } else if (error.code == '5003') {
                    this.$messageBox(this.$t('error.runningChartIsNotLoaded') + ',' + this.$t('error.startSimulationFailed'));
                } else if (error.code == '5004') {
                    this.$messageBox(this.$t('error.runningDataError') + ',' + this.$t('error.startSimulationFailed'));
                } else if (error.code == '5000') {
                    this.$messageBox(this.$t('error.systemError') + ',' + this.$t('error.startSimulationFailed'));
                } else if (error.code == '4000') {
                    this.$messageBox(this.$t('error.simulationDoesNotExist') + ',' + this.$t('error.startSimulationFailed'));
                } else if (error.code == '4001') {
                    this.$messageBox(this.$t('error.simulationOperationIsNotDefined') + ',' + this.$t('error.startSimulationFailed'));
                } else if (error.code == '4002') {
                    this.$messageBox(this.$t('error.simulationOperationProcessingMethodNotFound') + ',' + this.$t('error.startSimulationFailed'));
                } else if (error.code == '4003') {
                    this.$messageBox(this.$t('error.simulationOperationFailed') + ',' + this.$t('error.startSimulationFailed'));
                } else if (error.code == '4004') {
                    this.$messageBox(this.$t('error.operationConflict') + ',' + this.$t('error.startSimulationFailed'));
                } else {
                    this.$messageBox('按计划行车异常,请退出重试!');
                }
            });
        }
    }
};
</script>
<style lang="scss" scoped>
.display-draft {
    position: absolute;
    float: right;
    right: 15px;
    bottom: 15px;
}
</style>
