<template>
  <div class="map-view">
    <div v-show="maskOpen" class="mask" :style="{'width': maskWidth}" />
    <div v-show="disPlay" class="display-draft display-select">
      <el-select v-model="value" placeholder="请选择" style="width: 125px;" @change="changeSplit">
        <el-option
          v-for="item in optionsList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <jlmap-visual ref="jlmapVisual" />
    <div v-show="disPlay" class="display-draft">
      <el-button-group>
        <el-button type="primary" @click="back">{{ $t('scriptRecord.scriptBack') }}</el-button>
      </el-button-group>
    </div>
  </div>
</template>
<script>
import JlmapVisual from '@/views/newMap/jlmapNew/index';
import { loadNewMapDataByGroup, loadMapDataById } from '@/utils/loaddata';
import { clearSimulation } from '@/api/simulation';
import { EventBus } from '@/scripts/event-bus';
import { mapGetters } from 'vuex';
import { creatSubscribe, clearSubscribe, displayTopic} from '@/utils/stomp';
import { getToken } from '@/utils/auth';
import { getSessionStorage } from '@/utils/auth';

export default {
    name: 'MapPreview',
    components: {
        JlmapVisual
    },
    props: {

    },
    data() {
        return {
            maskOpen: false,
            maskWidth: '100%',
            disPlay: false,
            value: 1,
            optionsList: []
        };
    },
    computed: {
        mapId() {
            return this.$route.params.mapId;
        },
        ...mapGetters('map', [
            'bigScreenConfig'
        ]),
        ...mapGetters('config', [
            'canvasId'
        ])
    },
    watch: {
        $route() {
            this.$nextTick(() => {
                this.initLoadData();
            });
        },
        '$store.state.app.windowSizeCount': function() {
            this.setWindowSize();
        },
        '$store.state.map.mapViewLoadedCount':function() {
            this.$store.dispatch('map/setTrainWindowShow', false);
            this.$jlmap.off('zoom');
            this.$jlmap.off('pan');
            this.handleUpdateScreen();
            if (this.$route.query.group) {
                this.subscribe();
            }
        },
        '$store.state.socket.equipmentStatus': function (val) {
            if (val.length && this.$route.query.group) {
                this.statusMessage(val);
            }
        }
    },
    async beforeDestroy() {
        await this.$store.dispatch('map/mapClear');
    },
    async mounted() {
        await this.setWindowSize();
        await this.initLoadData();
        this.disPlay = true;
        if (this.$route.path.includes('design/bigScreen')) {
            this.disPlay = false;
        }
        if (this.$route.query.projectDevice) {
            this.disPlay = false;
            const data = JSON.parse(JSON.parse(getSessionStorage('projectDevice')).config);
            console.log(data, data.quadrant);
            this.changeSplit(data.quadrant);
        }
    },
    methods: {
        async initLoadData() { // 加载地图数据
            if (this.$route.query.group) {
                await loadNewMapDataByGroup(this.$route.query.group);
            } else {
                this.loadMapDataById(this.$route.params.mapId);
            }
        },
        // 通过id加载地图数据
        async loadMapDataById(mapId) {
            try {
                await this.$store.dispatch('training/changeMode', { mode: null });
                loadMapDataById(mapId).then(()=>{
                    this.$store.dispatch('training/over');
                    this.$store.dispatch('training/setMapDefaultState');
                    this.$store.dispatch('map/clearJlmapTrainView');
                });
            } catch (error) {
                this.$messageBox(`获取地图数据失败: ${error.message}`);
                this.endViewLoading();
            }
        },
        async statusMessage(list) {
            await this.$store.dispatch('training/updateMapState', list);
            await this.$store.dispatch('socket/setEquipmentStatus');
        },
        setWindowSize() {
            this.$nextTick(() => {
                const width = this.$store.state.app.width;
                const height = this.$store.state.app.height;
                this.$store.dispatch('config/resize', { width, height });
                this.handleUpdateScreen();
            });
        },
        changeSplit(data) {
            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 * height
            };
            this.$refs.jlmapVisual.setOffset(size, data, this.optionsList.length);
        },
        handleUpdateScreen() {
            this.maskOpen = false;
            if (this.bigScreenConfig.bigScreenSplitConfig && this.bigScreenConfig.bigScreenSplitConfig.length) {
                const offsetList = this.bigScreenConfig.offsetList;
                const width = this.bigScreenConfig.width;
                const height = this.bigScreenConfig.height;
                const num = width * height;
                this.optionsList = [];
                for (let index = 0; index < num; index++) {
                    const param = { value: index + 1, label: `第${index + 1}屏` };
                    this.optionsList.push(param);
                }
                const size = {
                    width: this.$store.state.app.width * width,
                    height: this.$store.state.app.height * height,
                    list: this.bigScreenConfig.bigScreenSplitConfig.map(ele => ele.position),
                    offsetList: offsetList
                };
                this.$jlmap.setUpdateScreen(size);
                this.$refs.jlmapVisual.handleStateLoaded();
            } else {
                this.maskOpen = true;
            }
        },
        async back() {
            if (this.$route.query.group) {
                await clearSimulation(this.$route.query.group);
                this.clearSubscribe();
            }
            this.$store.dispatch('training/over').then(() => {
                EventBus.$emit('runPlanStop');
                EventBus.$emit('chatSubscribeStop');
                history.go(-1);
            });
        },
        async subscribe() {
            this.clearSubscribe();
            const header = { group: this.$route.query.group || '', 'X-Token': getToken() };
            creatSubscribe(`${displayTopic}\/${this.$route.query.group}`, header);

            await this.$store.dispatch('training/setHasSubscribed');
        },
        clearSubscribe() {
            clearSubscribe(`${displayTopic}\/${this.$route.query.group}`);
        }
    }
};
</script>
<style lang="scss" scoped>
    .map-view {
        float: left;
        width: auto;
    }
	.mask{
        opacity: 1;
        background: #000;
        position: absolute;
        right: 0;
        top: 0;
        width: 100%;
        height: 100%;
        z-index: 9;
    }
	.display-draft {
        position: absolute;
        float: right;
        right: 15px;
        bottom: 15px;
		z-index: 19;
    }
	.display-select {
        top: 15px;
    }
</style>
