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

<script>
import Vue from 'vue';
import Iscs from '@/iscs/iscs';
import { parser, deviceFactory } from '@/iscs/utils/parser';
import {getIscsData} from '@/iscs/constant/iscsData';
import { mapGetters } from 'vuex';
import { exitFullscreen } from '@/utils/screen';
import { putJointTrainingSimulationUser } from '@/api/chat';
import { putJointTrainingSimulationUserNew} from '@/api/jointTraining';
// import { handlerIscsEvent } from '@/api/simulation';
// import { IscsOperation } from '@/scripts/ConstDic';
import { deepAssign } from '@/utils/index';
import { getUID } from '@/iscs/utils/Uid';

export default {
    name: 'Iscs',
    props: {
        size: {
            type: Object,
            default() {
                return null;
            }
        }
    },
    data() {
        return {
            dataZoom: {
                offsetX: '0',
                offsetY: '0',
                scaleRate: '1'
            },
            config: {
                scaleRate: '1',
                origin: {
                    x: 0,
                    y: 0
                }
            },
            selected: null, // 选择复制元素
            copyModel: {}, // 复制元素内容
            copyList: [],
            showBackButton: true,
            initTime: '',
            started: false,
            loading: false,
            stationCode: '',
            banUpOpenScreenDoor: false,
            banDownOpenScreenDoor: false
        };
    },
    computed: {
        ...mapGetters([
            'canvasWidth',
            'canvasHeight'
        ]),
        ...mapGetters('iscs', [
            'iscs'
        ]),
        iscsId() {
            return ['iscs', (Math.random().toFixed(5)) * 100000].join('_');
        },
        drawWay() {
            return this.$route.query.drawWay + '';
        },
        width() {
            return this.$store.state.config.width;
        },
        height() {
            return this.$store.state.config.height;
        }
    },
    watch: {
        '$store.state.config.canvasSizeCount': function (val) {
            this.reSize();
        },
        '$store.state.socket.equipmentStatus': function (val) {
            if (val.length) {
                this.statusMessage(val);
            }
        }
    },
    mounted() {
    },
    beforeDestroy() {
        this.iscsDestroy();
    },
    methods: {
        show (mode, system, part) {
            if (!mode || !system || !part) {
                return;
            }
            document.getElementById(this.iscsId).oncontextmenu = function (e) {
                return false;
            };
            this.iscsDestroy();
            this.loading = true;
            const data = parser(getIscsData(mode, system, part), {width: this.canvasWidth, height: this.canvasHeight});
            this.$iscs = new Iscs({
                dom: document.getElementById(this.iscsId),
                config: {
                    renderer: 'canvas',
                    width: this.width,
                    height: this.height
                },
                options: {
                    scaleRate: 1,
                    offsetX: 0,
                    offsetY: 0
                },
                methods: {
                    viewLoaded: this.handleViewLoaded
                }
            });
            Vue.prototype.$iscs = this.$iscs;
            this.$iscs.on('contextmenu', this.onContextMenu, this);
            if (this.$route.query.group) {
                this.$iscs.on('selected', this.onSelected, this);
            }
            this.setIscs(data, getIscsData(mode, system, part));
            this.$store.dispatch('iscs/setIscsData', getIscsData(mode, system, part));
            if (this.$route.path.startsWith('/iscs/design')) {
                this.$iscs.on('keyboard', this.onKeyboard, this);
            }
            window.document.oncontextmenu = function () {
                return false;
            };
        },
        setIscs(data, oldData) {
            this.$iscs.setIscs(oldData, data);
        },
        // 键盘快捷键事件
        onKeyboard(hook) {
            if (this.selected && this.selected.code) {
                switch (hook) {
                case 'Ctrl_C': {
                    const list = this.getSelectList();
                    if (list.length) {
                        this.copyList = [];
                        const mapIscs = {};
                        list.forEach(item => {
                            if (item && item.code) {
                                const copyModel = this.copyModelInfo(item, 30);
                                const type1 = item._type.charAt(0).toLowerCase() + item._type.slice(1);
                                if (!mapIscs[type1 + 'List']) {
                                    mapIscs[type1 + 'List'] = this.iscs[type1 + 'List'] || [];
                                }
                                const list = mapIscs[type1 + 'List'] || [];
                                copyModel.code = getUID(item._type, list);
                                mapIscs[type1 + 'List'].push(copyModel);
                                this.copyList.push(copyModel);
                            }
                        });
                    } else if (this.selected._type != 'CheckBox') {
                        this.copyModel = this.copyModelInfo(this.selected, 10);
                        const type1 = this.selected._type.charAt(0).toLowerCase() + this.selected._type.slice(1);
                        this.copyModel.code = getUID(this.selected._type, this.iscs[type1 + 'List'] || []);
                    } else {
                        this.copyModel = {};
                    }
                } break;
                case 'Ctrl_V': {
                    const list = this.getSelectList();
                    if (list.length) {
                        this.copyList.forEach(item => {
                            item.code && this.createDataModel(item);
                        });
                    } else {
                        this.copyModel.code && this.createDataModel(this.copyModel);
                    }
                } break;
                case 'Delete': {
                    const list = this.getSelectList();
                    if (list.length) {
                        list.forEach(item => {
                            item && item.code && this.$store.dispatch('iscs/deleteIscsDevices', item);
                        });
                    } else {
                        this.copyModel.code && this.$store.dispatch('iscs/deleteIscsDevices', this.copyModel);
                    }
                } break;
                }
            }
        },
        copyModelInfo(model, length) { // copy 模块信息
            const copyModel = deepAssign({}, model);
            if (copyModel._type == 'IscsLine') {
                copyModel.point1 = {
                    x: model.point1.x + length,
                    y: model.point1.y + length
                };
                copyModel.point2 = {
                    x: model.point2.x + length,
                    y: model.point2.y + length
                };
            }
            copyModel.point = {
                x: model.point.x + length,
                y: model.point.y + length
            };
            return copyModel;
        },
        getSelectList() {
            return this.$iscs.getCopyList() || [];
        },
        createDataModel(model) {
            const newModel = deviceFactory(model._type, model);
            this.$store.dispatch('iscs/updateIscsDevices', newModel.model);
        },
        // 点击选择事件
        onSelected(em) {
        },
        // 右键点击事件
        onContextMenu(em) {
            if (em.eventTarget) {
                this.selected = em.eventTarget.model;
                this.$store.dispatch('iscs/setUpdateDeviceData', em.eventTarget.model);
            }
        },
        // 绘图时调用，元素可拖拽
        drawIscsInit() {
            this.$iscs && this.$iscs.drawIscsInit();
            this.showBackButton = false;
        },
        reSize() {
            this.$nextTick(() => {
                this.$iscs && this.$iscs.resize({ width: this.width, height: this.height });
            });
        },
        back() {
            this.group = this.$route.query.group;
            this.$store.dispatch('training/over').then(() => {
                if (this.drawWay === 'true') {
                    putJointTrainingSimulationUserNew(this.group).then(() => {
                        this.$router.replace({ path: `/trainroom`, query: { group: this.group, lineCode:this.$route.query.lineCode, drawWay: this.drawWay } });
                        exitFullscreen();
                    });
                } else {
                    putJointTrainingSimulationUser(this.group).then(() => {
                        this.$router.replace({ path: `/trainroom`, query: { group: this.group, lineCode:this.$route.query.lineCode } });
                        exitFullscreen();
                    });
                }
            });
        },
        iscsDestroy() {
            if (this.$iscs) {
                this.$iscs.dispose();
                this.$iscs = '';
                Vue.prototype.$iscs = '';
            }
        },
        handleViewLoaded() {
            this.loading = false;
        },
        statusMessage(val) {
            this.$iscs && this.$iscs.setDeviceStatus(val);
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .iscs-button{
        position: absolute;
        float: right;
        right: 20px;
        bottom: 15px;
    }
    .iscs-canvas{
    }
</style>
