<template>
  <div>
    <chat-box :group="group" :user-role="userRole" />
    <!-- 地图没有报错-->
    <!-- 地图错误判断 -->
    <div v-if="!dataError&&hasOneButton" class="display_top_draft" :style="{top: offset+'px'}">
      <div class="btn_hover" @click="menuClick">菜单</div>
      <el-button-group ref="button_group_box" class="button_group_box" :style="`transform: translateX(-${btnWidth}px)`">
        <!-- 设备视图 -->
        <el-button v-if="isShow3dmodel && isShowScheduling" size="small" @click="jumpjlmap3dmodel">{{ $t('display.demon.deviceView') }}</el-button>
        <!-- 三维视图 / 司机视角 -->
        <el-button v-if="isShowScheduling || isDriver" size="small" @click="jumpjlmap3d">{{ jl3dname }}</el-button>
        <!-- cctv视图 -->
        <el-button v-if="isShowScheduling || isStationSupervisor" size="small" @click="jumpjl3dpassflow">{{ $t('display.demon.passengerflow') }}</el-button>
        <el-button v-if="isAdmin && !noQrcodeList.includes(project)" type="primary" size="small" @click="generateQrCode">生成二维码</el-button>
        <el-button v-if="isAdmin" size="small" @click="memberManage">成员管理</el-button>
        <el-button v-if="isAdmin && isProject" size="small" @click="handleEquipment">设备管理</el-button>
      </el-button-group>
    </div>
    <div class="display-draft" :class="{'display-type-hb': lineCode == '07' && $store.state.training.prdType=='01', 'haerbin_btn_box': lineCode == '07'}" :style="{bottom: offsetBottom + 'px'}">
      <el-button-group class="button-group-box">
        <el-button v-if="project==='refereeJsxt'" type="success" size="small" @click="refeeEndCompetition">退出</el-button> <!-- 竞赛退出 -->
        <el-button v-if="project!=='jsxt' && project!=='refereeJsxt'" type="primary" :loading="backLoading" size="small" @click="back">退出</el-button>
        <template v-if="!dataError"> <!-- 地图错误判断 -->
          <template v-if="isAdmin && project != 'refereeJsxt'">
            <el-button type="danger" size="small" @click="end">{{ $t('joinTraining.initialize') }}</el-button>
            <!-- 按计划行车 -->
            <el-button type="success" :disabled="isDisable" size="small" @click="selectBeginTime">{{ $t('joinTraining.drivingByPlan') }}</el-button>
          </template>
          <template v-if="project == 'jsxt'">
            <div style="background: #FFF;display: inline-block;height: 40px;line-height: 40px;padding: 0 5px;border: 2px solid #F00;border-radius: 6px;margin-right: 8px;">{{ '剩余时间:' + countdownTime }}</div>
            <el-button :disabled="!jsStart" type="success" size="small" @click="startCompetition">开始</el-button>
            <el-button :disabled="jsStart" type="danger" size="small" @click="endCompetition">提交</el-button>
          </template>
        </template>
      </el-button-group>
    </div>
    <qr-code ref="qrCode" />
    <set-time ref="setTime" @ConfirmSelectBeginTime="start" />
    <equipment ref="equipment" />
  </div>
</template>

<script>
import QrCode from '@/components/QrCode';
import ChatBox from './chatView/chatBox';
import Equipment from '@/views/newMap/displayNew/demon/equipment';
import SetTime from '@/views/newMap/displayNew/demon/setTime';
import { ranAsPlan, exitRunPlan, clearSimulation } from '@/api/simulation';
import { exitFullscreen } from '@/utils/screen';
import { getSimulationQrcode } from '@/api/jointSimulation';
import { getSessionStorage } from '@/utils/auth';
import { refereeExitSimulation, quitCurrentRace, startPracticalCompetition, submitPracticalCompetition } from '@/api/competition';
import { NoQrcodeList } from '@/scripts/ProjectConfig';
import localStore from 'storejs';

export default {
    name: 'MenuDemonJoint',
    components: {
        ChatBox,
        QrCode,
        SetTime,
        Equipment
    },
    props: {
        group: {
            type: String,
            required: true
        },
        userRole: {
            type: String,
            required: true
        },
        countdownTime: {
            type: String,
            required: true
        },
        deviceCode: {
            type: String,
            default() {
                return '';
            }
        },
        dataError: {
            type: Boolean,
            default() {
                return false;
            }
        },
        isAdmin: {
            type: Boolean,
            default() {
                return false;
            }
        },
        offset: {
            type: Number,
            required: true
        },
        offsetBottom: {
            type: [String, Number],
            default: 15
        }
    },
    data() {
        return {
            isDisable: false,
            backLoading: false,
            chatShow: true,
            jsStart: true,
            isGoback: false,
            noQrcodeList: NoQrcodeList,
            isShow3dmodel :false,
            jl3dname: this.$t('display.demon.threeDimensionalView'),
            hoverBtn: false,
            btnWidth: 0
        };
    },
    computed: {
        lineCode() {
            return this.$route.query.lineCode;
        },
        isShowScheduling() {
            // 行调与管理员 可显示
            return (this.$store.state.training.prdType == '02' || this.isAdmin) && !this.$route.query.projectDevice;
        },
        isSpeaking() {
            return this.userRole != 'DRIVER' && this.userRole != '';
        },
        isStationSupervisor() {
            return this.userRole == 'STATION_SUPERVISOR' && !this.$route.query.projectDevice;
        },
        isDriver() {
            return this.userRole == 'DRIVER' && !this.$route.query.projectDevice;
        },
        project() {
            return getSessionStorage('project');
        },
        isProject() {
            return getSessionStorage('project') != 'login' && getSessionStorage('project') != 'design';
        },
        hasOneButton() {
            let num = 0;
            if ((this.isShow3dmodel && this.isShowScheduling) ||
                (this.isShowScheduling || this.isDriver) ||
                (this.isShowScheduling || this.isStationSupervisor) ||
                (this.isAdmin && !this.noQrcodeList.includes(this.project)) ||
                (this.isAdmin) || (this.isAdmin && this.isProject)) {
                num++;
            }
            return num > 0;
        }
    },
    watch: {
        '$store.state.socket.roleList': function (roleList) { // 综合演练室用户消息
            if (roleList && roleList.length) {
                this.$nextTick(() => {
                    this.addrolesList(roleList);
                    this.$store.dispatch('config/updateMenuBar');
                });
            }
        },
        '$store.state.training.started': function (val) {
            if (val) {
                this.isDisable = true;
            }
        },
        '$store.state.socket.simulationOver':function(val) {
            if (val && this.project == 'refereeJsxt') {
                this.$router.go(-1);
            } else {
                if (!this.isGoback) {
                    this.back();
                }
            }
        },
        '$store.state.training.prdType': function(prdType) {
            this.change3dname();
        },
        '$store.state.socket.simulationStart': async function (val) {
            if (val) {
                this.$store.dispatch('training/setInitTime', +new Date(val));
                this.$store.dispatch('training/start');
            }
        }
    },
    async mounted() {
        this.change3dname();
        this.$nextTick(() => {
            this.menuClick();
        });
    },
    beforeDestroy() {
        this.$store.dispatch('training/setGroup', '');
        if (this.project === 'jsxt') {
            quitCurrentRace(this.$route.query.raceId, {group:this.group}).then(res=>{
            });
        }
    },
    methods: {
        // 设置用户角色  Admin 管理员 Instructor 教员 Dispatcher 行调 Attendant 车站 Audience 观众 Driver 司机 MAINTAINER 通号
        addrolesList(list) {
            list.forEach(item => {
                if (this.$store.state.user.id == item.id) {
                    switch (item.userRole) {
                    case 'INSTRUCTOR':
                        this.$store.dispatch('training/setPrdType', '02'); this.$store.dispatch('training/setRoles', 'INSTRUCTOR');
                        this.$emit('getUserRole');
                        break;
                    case 'DISPATCHER':
                        this.$store.dispatch('training/setPrdType', '02'); this.$store.dispatch('training/setRoles', 'DISPATCHER');
                        this.$emit('getUserRole');
                        break;
                    case 'STATION_SUPERVISOR':
                        if (!item['deviceCode']) {
                            this.$store.dispatch('training/setPrdType', ''); this.$store.dispatch('training/setRoles', 'STATION_SUPERVISOR');
                            break;
                        }
                        this.$store.dispatch('training/setPrdType', '01'); this.$store.dispatch('training/setRoles', 'STATION_SUPERVISOR');
                        this.$emit('getUserRole');
                        break;
                    case 'CI':
                        this.$store.dispatch('training/setPrdType', '01'); this.$store.dispatch('training/setRoles', 'CI');
                        this.$emit('getUserRole');
                        break;
                    case 'DRIVER':
                        this.$store.dispatch('training/setPrdType', '04'); this.$store.dispatch('training/setRoles', 'DRIVER');
                        this.$emit('getUserRole');
                        break;
                    case 'MAINTAINER':
                        this.$store.dispatch('training/setPrdType', ''); this.$store.dispatch('training/setRoles', 'MAINTAINER');
                        this.$emit('getUserRole');
                        break;
                    case 'IBP':
                        this.$store.dispatch('training/setPrdType', ''); this.$store.dispatch('training/setRoles', 'IBP');
                        this.$emit('getUserRole');
                        break;
                    case 'BIGSCREEN':
                        this.$store.dispatch('training/setPrdType', ''); this.$store.dispatch('training/setRoles', 'BIGSCREEN');
                        this.$emit('getUserRole');
                        break;
                    default:
                        this.$store.dispatch('training/setPrdType', ''); this.$store.dispatch('training/setRoles', 'AUDIENCE');
                        this.$emit('getUserRole');
                        break;
                    }
                }
            });
            if (this.$refs.chatView) {
                this.$refs.chatView.getUserRole();
            }
        },
        selectBeginTime() {
            this.$refs.setTime.doShow();
        },
        // 开始仿真
        start(model) {
            this.isDisable = true;
            const data = {
                time: model.initTime
            };
            ranAsPlan(data, this.group).then(res => {
                this.$store.dispatch('training/simulationStart').then(() => {
                    if (this.project == 'jsxt') {
                        this.jsStart = false;
                    }
                    this.$store.dispatch('map/setRunPlanStatus', true);
                    this.$store.dispatch('training/setInitTime', +new Date(`${new Date().toLocaleDateString()} ${model.initTime}`));
                });
            }).catch((error) => {
                this.isDisable = false;
                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'));
                }
            });
        },
        end() {
            this.isDisable = false;
            exitRunPlan(this.group).then(()=>{
                this.$store.dispatch('map/setRunPlanStatus', false);
                this.$store.dispatch('map/setTrainWindowShow', false);
                this.$store.dispatch('map/resetActiveTrainList');
            }).catch(() => {
                this.$store.dispatch('training/over').then(() => {
                    this.isDisable = true;
                    this.$store.dispatch('map/resetActiveTrainList');
                    this.$messageBox(this.$t('error.endSimulationFailed'));
                });
            });
        },
        handleEquipment() {
            this.$refs.equipment.doShow();
        },
        async back() {
            this.isGoback = true;
            if (this.isAdmin) {
                await clearSimulation(this.group);
            }
            this.$store.dispatch('training/setMemberList', {memberList:[], userId: this.$store.state.user.id});
            this.$store.dispatch('training/setSimulationUserList', []);
            this.$store.dispatch('map/setRunPlanStatus', false);
            this.$store.dispatch('training/over').then(() => {
                this.backLoading = true;
                this.$store.dispatch('map/resetActiveTrainList');
                if (this.$route.query.projectDevice) {
                    this.$store.dispatch('LogOut').then(() => {
                        location.reload();
                    });
                } else {
                    history.go(-1);
                    exitFullscreen();
                }
            });
        },
        jumpjlmap3d() {
            this.$emit('hidepanel');
        },
        jlmap3dcctv() {
            this.$emit('hidejl3dcctv');
        },
        jumpjl3dpassflow() {
            this.$emit('passflow');
        },
        jumpjlmap3dmodel() {
            this.$emit('devicemodel');
        },
        startCompetition() {
            startPracticalCompetition(this.group, this.$route.query.raceId).then(resp => {
                this.$emit('startCounting');
                this.jsStart = false;
            }).catch(()=> {
                this.$message.error('开始竞赛失败');
            });
        },
        endCompetition() {
            this.$confirm('此操作将结束并提交本次竞赛，是否继续', this.$t('global.tips'), {
                confirmButtonText: this.$t('global.confirm'),
                cancelButtonText: this.$t('global.cancel'),
                type: 'warning'
            }).then(() => {
                this.submit();
            });
        },
        // 竞赛退出
        refeeEndCompetition() {
            refereeExitSimulation(this.group).then(resp => {
                this.$router.replace({ path: `/refereeJsxt/home`, query: { raceId: this.$route.query.raceId } });
            }).catch(()=> {
                this.$message.success('退出系统失败');
            });
        },
        // 竞赛提交
        submit() {
            submitPracticalCompetition(this.group, this.$route.query.raceId).then(resp => {
                const storeKey = this.$store.state.user.id + '' + this.$route.query.raceId + 'practical';
                localStore.remove(storeKey);
                this.$router.replace({ path: `/jsxt/result`, query: { subSystem: this.$route.query.subSystem, mapId: this.$route.query.mapId, type: 'operate', raceId:this.$route.query.raceId } });
            }).catch(()=> {
                this.$message.error('提交试卷失败！');
            });
        },
        memberManage() {
            this.$emit('handlerMemberManage');
        },
        generateQrCode() {
            getSimulationQrcode(this.$route.query.group).then(resp => {
                const param = {
                    url: resp.data,
                    title: this.$t('综合演练二维码'),
                    group: this.$route.query.group
                };
                if (this.$refs) {
                    this.$refs.qrCode.doShow(param);
                }
            }).catch(() => {
                this.$messageBox('仿真生成二维码失败！');
            });
        },
        change3dname() {
            if (this.$store.state.training.prdType == '04') {
                this.jl3dname = this.$t('display.demon.driverPerspective'); // 司机视角
            } else {
                this.jl3dname = this.$t('display.demon.threeDimensionalView'); // 三维视图
                this.isShow3dmodel = true;
            }
        },
        menuClick() {
            this.hoverBtn = !this.hoverBtn;
            if (this.hoverBtn) {
                // this.$refs.button_group_box.$el.clientWidth ||
                this.btnWidth = 500;
            } else {
                this.btnWidth = 0;
            }
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
	@import "src/styles/mixin.scss";
	.tabs-roles {
		overflow: hidden;
		border-bottom: 1px solid #e4e7ed;
		height: 40px;
		line-height: 40px;
		-webkit-box-sizing: border-box;
		box-sizing: border-box;

		.roles {
			padding: 0 20px;
			height: 41px;
			list-style: none;
			font-size: 14px;
			font-weight: 500;
			color: #303133;
			cursor: pointer;
			border-left: 1px solid #e4e7ed;
			border-right: 1px solid #e4e7ed;
			float: left;
		}

		.roles-first {
			border-right: none;
		}

		.roles-active {
			border-bottom-color: #fff;
			color: #409EFF;
		}

	}

	.tabs-content {
		height: 300px;
		width: 100%;
		display: flex;
	}

	.display-score {
		background-color: black;
		display: -moz-inline-box;
		display: inline-block;
		text-align: left;
		height: 32px;
		line-height: 24px;
		border-radius: 4px;
		padding-left: 2px;
		margin-left: 10px;
		font-family: "Microsoft" !important;
		font-size: 18px !important;
		color: #fff;
	}

	.reminder-drag {
		position: absolute;
		float: left;
		left: 10px;
		bottom: 10px;
		width: 500px;
		height: 340px;
		background-color: #fff;
		border-radius: 5px;
		overflow: hidden;
		z-index: 2;
		font-size: 18px;

		/deep/ {
			.el-tabs__header {
				margin: 0;
			}
		}

		.title-bar {
			height: 40px;
		}

		.content {
			height: 300px;
		}
	}

	.display-draft {
		position: absolute;
		right: 10px;
		bottom: 28px;
		// transform: translateX(calc(100% + 40px));
		// transition: all 0.5s;
		// &.active{
		// 	transform: translateX(0);
		// }
		button {
			float: right!important;
		}
		.button-group-box{
			float: right;
		}
		/deep/ .el-button-group>.el-button:last-child {
			border-top-right-radius: 0;
			border-bottom-right-radius: 0;
			border-top-left-radius: 4px;
			border-bottom-left-radius: 4px;
		}
		/deep/ .el-button-group>.el-button:first-child{
			border-top-right-radius: 4px;
			border-bottom-right-radius: 4px;
			border-top-left-radius: 0;
			border-bottom-left-radius: 0;
			border-right-color: transparent;
		}
	}
	.display_top_draft{
		position: absolute;
		left: 5px;
		top: 15px;
		height: 32px;
		overflow: hidden;
		padding-left: 44px;
        z-index: 35;
		.btn_hover{
			position: absolute;
			left: 0;
			top: 0;
			z-index: 2;
			color: #4e4d4d;
			font-size: 14px;
			background: #fff;
			padding: 8px;
			border-radius: 5px;
			display: table;
			cursor: pointer;
			float: left;
			height: 32px;
		}
		.button_group_box{
			float: left;
			transition: all 0.5s;
			overflow: hidden;
			transform: translateX(0px);
		}
	}
	.haerbin_btn_box{
		width: 450px;
		bottom: 15px!important;
	}
	.display-type-hb{
		bottom: 105px;
	}
</style>
