<template>
  <div>
    <div :id="ibpId" v-loading="loading" :style="{ width: canvasWidth+'px', height: canvasHeight +'px',background:'#000' }" class="ibp-canvas" />
    <el-button v-if="showBackButton" class="ibp-button" type="primary" @click="back">{{ $t('global.back') }}</el-button>
  </div>
</template>

<script>
import Vue from 'vue';
import IbpPan from '@/ibp/ibpPan';
// import ibpData from '@/ibp/constant/ibpData';
import { parser } from '@/ibp/utils/parser';
import { mapGetters } from 'vuex';
import { exitFullscreen } from '@/utils/screen';
import { handlerIbpEvent } from '@/api/simulation';
import { IbpOperation } from '@/scripts/ConstDic';

import { getIbpInfoByStation } from '@/api/ibp';

export default {
    name: 'Ibp',
    props: {
        size: {
            type: Object,
            default() {
                return null;
            }
        }
    },
    data() {
        return {
            width: this.$store.state.config.width,
            height: this.$store.state.config.height,
            dataZoom: {
                offsetX: '0',
                offsetY: '0',
                scaleRate: '1'
            },
            config: {
                scaleRate: '1',
                origin: {
                    x: 0,
                    y: 0
                }
            },
            showBackButton: true,
            initTime: '',
            started: false,
            loading: false,
            stationCode: '',
            banUpOpenScreenDoor: false,
            banDownOpenScreenDoor: false
        };
    },
    computed: {
        ...mapGetters([
            'canvasWidth',
            'canvasHeight'
        ]),
        ibpId() {
            return ['ibp', (Math.random().toFixed(5)) * 100000].join('_');
        },
        drawWay() {
            return this.$route.query.drawWay + '';
        }
    },
    watch: {
        '$store.state.config.canvasSizeCount': function (val) {
            this.reSize();
        },
        '$store.state.training.initTime': function (initTime) {
            this.initTime = initTime;
            if (this.$ibp) {
                this.initClockTime(initTime);
            }
        },
        '$store.state.training.started': function (started) {
            this.started = started;
            if (this.$ibp) {
                this.setClockStart(started);
            }
        },
        '$store.state.socket.equipmentStatus': function (val) {
            if (val.length) {
                this.statusMessage(val);
            }
        }
    },
    async mounted() {
        this.setWindowSize();
        this.initIbp();
        if (this.$route.query.loadAll && this.$route.query.stationCode) {
            await this.show(this.$route.query.stationCode);
            await this.setMoveInit(true);
            this.showBackButton = false;
        }
    },
    beforeDestroy() {
        this.ibpDestroy();
    },
    methods: {
        initIbp(offsetX = 0) {
            this.ibpDestroy();
            this.loading = true;
            this.$ibp = new IbpPan({
                dom: document.getElementById(this.ibpId),
                config: {
                    renderer: 'canvas',
                    width: this.canvasWidth,
                    height: this.canvasHeight
                },
                options: {
                    scaleRate: 1,
                    offsetX: offsetX,
                    offsetY: 0
                },
                methods: {
                    viewLoaded: this.handleViewLoaded
                }
            });
            Vue.prototype.$ibp = this.$ibp;
            this.$ibp.on('contextmenu', this.onContextMenu, this);
            if (this.$route.query.group) {
                this.$ibp.on('selected', this.onSelected, this);
                this.$ibp.on('mouseDown', this.onMouseDown, this);
            }
        },
        async show (deviceCode, ibpPart) {
            if (!deviceCode) {
                return;
            }
            try {
                // const ibpDatas = ibpData[deviceCode];
                const res = await getIbpInfoByStation(this.$route.query.mapId, deviceCode);
                if (res.data.data) {
                    const ibpDatas = JSON.parse(res.data.data).drawData;
                    this.stationCode = deviceCode;
                    document.getElementById(this.ibpId).oncontextmenu = function (e) {
                        return false;
                    };
                    let offsetX = 0;
                    if (ibpPart === 'left') {
                        offsetX = 0;
                    } else if (ibpPart === 'right') {
                        offsetX = 1920;
                    }
                    const data = parser(ibpDatas, {width: this.canvasWidth, height: this.canvasHeight}); // ibp 绘图编译数据
                    this.initIbp(offsetX);

                    this.setIbp(data, ibpDatas);
                    this.$store.dispatch('ibp/setIbpData', ibpDatas);
                    this.handleBanOpenScreenDoorStatus();
                    this.initClockTime(this.initTime);
                } else {
                    // 无数据
                    this.loading = false;
                    this.$alert('当前ibp盘数据不存在', '信息', {
                        confirmButtonText: '确定',
                        callback: action => {}
                    });
                }
            } catch (error) {
                this.loading = false;
                this.$alert('当前ibp盘数据不存在', '信息', {
                    confirmButtonText: '确定',
                    callback: action => {}
                });
            }
            window.document.oncontextmenu = function () {
                return false;
            };

        },
        setIbp(data, oldData) {
            this.$ibp.setIbp(oldData, data);
            this.$store.dispatch('ibp/setIbpData', oldData);
        },
        handleBanOpenScreenDoorStatus() {
            this.$store.state.ibp.ibp['keyList'].forEach(item => {
                if (item.mean === 'SXYS') {
                    item.status === 'on' ? this.banDownOpenScreenDoor = false : this.banDownOpenScreenDoor = true;
                } else if (item.mean === 'XXYS') {
                    item.status === 'on' ? this.banUpOpenScreenDoor = false : this.banUpOpenScreenDoor = true;
                }
            });
        },
        // 点击选择事件
        onSelected(em) {

        },
        onMouseDown(em) {
            if (em.deviceModel.mean) {
                if (IbpOperation[em.deviceModel.mean]) {
                    handlerIbpEvent(this.$route.query.group, {button: IbpOperation[em.deviceModel.mean].event, stationCode: this.stationCode});
                }
            }
        },
        openScreenDoor(flag, buttonOperate) {
            if (flag) {
                handlerIbpEvent(this.$route.query.group, {button: buttonOperate, stationCode: this.stationCode});
            }
        },
        // 右键点击事件
        onContextMenu(em) {
            this.$store.dispatch('ibp/setUpdateDeviceData', em.eventTarget.model);
        },
        // 绘图时调用，元素可拖拽
        drawIbpInit() {
            this.$ibp && this.$ibp.drawIbpInit();
            this.showBackButton = false;
        },
        // 地图可拖拽
        setMoveInit(data) {
            this.$ibp && this.$ibp.setMoveOnMouseMove(data);
        },
        // 初始化电子表时间
        initClockTime(initTime) {
            this.$ibp.initClockTime(initTime);
        },
        // 设置电子时钟开始或停止
        setClockStart(started) {
            this.$ibp.setClockStart(started);
        },
        reSize() {
            this.width = this.$store.state.config.width;
            this.height = this.$store.state.config.height;
            this.$ibp && this.$ibp.resize({ width: this.width, height: this.height });
        },
        setWindowSize() {
            const width = this.size ? this.size.width : this.$store.state.app.width;
            const height = this.size ? this.size.height : this.$store.state.app.height;
            this.$store.dispatch('config/resize', { width: width, height: height });
        },
        back() {
            this.group = this.$route.query.group;
            this.$store.dispatch('training/over').then(() => {
                if (this.$route.query.projectDevice) {
                    this.$store.dispatch('LogOut').then(() => {
                        location.reload();
                    });
                } else {
                    history.go(-1);
                    exitFullscreen();
                }
            });
        },
        ibpDestroy() {
            if (this.$ibp) {
                this.$ibp.dispose();
                this.$ibp = '';
                Vue.prototype.$ibp = '';
            }
        },
        handleViewLoaded() {
            this.loading = false;
        },
        statusMessage(val) {
            this.$ibp && this.$ibp.setDeviceStatus(val);
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .ibp-button{
        position: absolute;
        float: right;
        right: 20px;
        bottom: 15px;
		z-index: 38;
    }
    .ibp-canvas{
		position: absolute;
		z-index: 37;
    }
</style>
