<template>
  <div>
    <demon-chat ref="chatbox" :group="group" :user-role="userRole" />
    <div class="display-card" :style="{top: offset+'px'}">
      <el-row>
        <span v-if="countTime" class="display-score">{{ $t('display.demon.trialTime') }} {{ countTime }}</span>
      </el-row>
    </div>
    <div v-if="!dataError" 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">{{ jl3dmodel }}</el-button>
        <!-- 三维视图 -->
        <el-button v-if="!isShowScheduling" size="small" @click="jumpjlmap3d">{{ jl3dname }}</el-button>
        <!-- cctv视图 -->
        <el-button v-if="!isShowScheduling" size="small" @click="jumpjl3dpassflow">{{ jl3dpassflow }}</el-button>
        <!-- 排班计划 -->
        <el-button v-if="isShowScheduling && !runing" type="primary" size="small" @click="jumpScheduling">派班计划加载</el-button>
        <el-button v-if="isShowScheduling && runing" type="primary" size="small" @click="schedulingView">派班计划预览</el-button>
      </el-button-group>
    </div>
    <div class="display-draft" :class="{'haerbin_btn_box': $route.query.lineCode == '07'}" :style="{bottom: offsetBottom + 'px'}">
      <el-button-group class="button-group-box">
        <el-button type="primary" size="small" @click="back">{{ projectDevice?'退出':$t('display.demon.back') }}</el-button>
        <template v-if="!dataError">
          <template v-if="isShowQuest">
            <el-button v-if="!isDesignPlatform" type="danger" size="small" @click="handleQuitQuest">退出剧本</el-button>
          </template>
          <template v-else-if="!projectDevice">
            <el-button type="danger" size="small" @click="end">{{ $t('display.demon.initialize') }}</el-button>
            <el-button type="success" :disabled="isDisable" size="small" @click="selectBeginTime">{{ $t('display.demon.drivingByPlan') }}</el-button>
          </template>
        </template>
      </el-button-group>
    </div>
    <set-time ref="setTime" @ConfirmSelectBeginTime="start" />
  </div>

</template>

<!-- 单人仿真 -->
<script>
import SetTime from './demon/setTime';
import DemonChat from './demonChat';
import { Notification } from 'element-ui';
import { getGoodsTryUse } from '@/api/management/goods';
import { ranAsPlan, exitRunPlan, clearSimulation, getSimulationInfoNew } from '@/api/simulation';
import { PermissionType } from '@/scripts/ConstDic';
import { getCountTime } from '@/utils/index';
import { quitScriptNew } from '@/api/simulation';
import { setGoodsTryUse } from '@/api/management/goods';

export default {
    name: 'MenuDemon',
    components: {
        SetTime,
        DemonChat
    },
    props: {
        offset: {
            type: Number,
            required: true
        },
        offsetBottom: {
            type: Number,
            required: true
        },
        scriptId: {
            type: Number,
            default() {
                return 0;
            }
        },
        showStation: {
            type: String,
            default() {
                return '';
            }
        },
        dataError: {
            type: Boolean,
            default() {
                return false;
            }
        }
    },
    data() {
        return {
            isDisable: false,
            tryTime: 0, 				// 进入页面多少秒
            timeNow: 0, 				// 进入页面 相对时间
            time: null, 				// 定时器
            countTime: 0, 				// 显示 倒计时
            remainingTime: 0,
            goodsId: this.$route.query.goodsId,
            try: this.$route.query.try, // 是否是试用权限
            training: {
                id: '',
                name: '',
                remarks: ''
            },
            jl3dpassflow:this.$t('display.demon.passengerflow'),
            jl3dname: this.$t('display.demon.threeDimensionalView'),
            jl3dstation: this.$t('display.demon.threeDimensionalStation'),
            jl3dmodel: this.$t('display.demon.deviceView'),
            isShow3dmodel :false,
            isGoback: false,
            hoverBtn: false,
            btnWidth: 0,
            runing:false
        };
    },
    computed: {
        isShowQuest() {
            return this.scriptId;
        },
        isShowScheduling() {
            return this.$route.query.prdType == '05';
        },
        isDesignPlatform() {
            return this.$route.fullPath.includes('design/display/demon');
        },
        group() {
            return this.$route.query.group;
        },
        userRole() {
            if (this.$route.query.prdType == '02') {
                return 'DISPATCHER';
            } else if (this.$route.query.prdType == '01') {
                return 'STATION_SUPERVISOR';
            } else if (this.$route.query.prdType == '04') {
                return 'DRIVER';
            } else if (this.$route.query.prdType == '05') {
                return 'DEPOT_DISPATCHER';
            } else {
                return 'AUDIENCE';
            }
        },
        projectDevice() {
            return this.$route.query.projectDevice;
        }
    },
    watch: {
        '$store.state.training.subscribeCount': function () {
            this.group && this.initLoadPage();
        },
        '$store.state.socket.simulationRoleList':function(val) {
            (val || []).forEach(item => {
                if (item.messageType === 'KICK_OUT' && item.userId == this.$store.state.user.id) {
                    !this.isGoback && this.back();
                }
            });
        },
        '$store.state.socket.simulationOver':function(val) {
            !this.isGoback && this.back();
        },
        '$store.state.training.started': function (val) {
            this.setRuning(val);
        },
        '$store.state.socket.simulationStart':function(val) {
            if (val) {
                this.setRuning(true);
            }
        },
        '$store.state.socket.simulationReset':function(val) {
            this.setRuning(false);
        }
    },
    beforeDestroy() {
        if (this.time) {
            this.setTryTime();
            clearTimeout(this.time);
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.menuClick();
        });
    },
    methods: {
        async initLoadPage() {
            try {
                if (this.try != '0') {
                    this.loadInitData();
                }
                this.change3dname();
            } catch (error) {
                console.log(error);
            }
        },
        initPlannedDriving(isDisable) {
            this.isDisable = isDisable;
        },
        loadInitData() {
            const data = {
                mapId: this.$route.query.mapId,
                prdType: this.$route.query.prdType,
                permissionType: PermissionType.SIMULATION
            };
            getGoodsTryUse(data).then(res => {
                this.remainingTime = res.data.tryTime;
                this.timeNow = Date.parse(new Date()) / 1000 + this.remainingTime;
                if (this.try) {
                    this.time = setInterval(() => {
                        this.tryTime += 1;
                        this.countTime = getCountTime(this.timeNow);
                        if (this.countTime == -1) {
                            this.back();
                        }
                    }, 1000);
                }
            }).catch(() => {
                this.$messageBox(this.$t('display.demon.getTimeFail'));
            });
        },
        selectBeginTime() {
            this.$refs.setTime.doShow();
        },
        start(model) { // 开始仿真
            this.isDisable = true;
            const data = {
                time: model.initTime
            };
            if (this.$route.query.prdType === '04') {
                data.loadNumber = model.loadNum;
            }
            ranAsPlan(data, this.group).then(res => {
                this.$store.dispatch('training/simulationStart').then(() => {
                    this.$store.dispatch('map/setRunPlanStatus', true);
                    this.$store.dispatch('training/setInitTime', +new Date(`${new Date().toLocaleDateString()} ${model.initTime}`));
                    this.$store.dispatch('map/setShowCentralizedStationNum');
                    if (this.$route.query.lineCode == '06') {
                        this.$emit('switchStationMode', this.showStation); // 宁波线 过滤列车显示
                    }
                });
            }).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'));
                }
            });
        },
        setRuning(run) {
            this.runing = run;
        },
        end() {
            this.isDisable = false;
            exitRunPlan(this.group).then(() => {
                this.$store.dispatch('training/over').then(() => {
                    this.$store.dispatch('training/setMapDefaultState').then(() => {
                        this.$store.dispatch('map/setRunPlanStatus', false);
                        this.$store.dispatch('map/resetActiveTrainList');
                        this.$store.dispatch('map/clearJlmapTrainView');
                        this.$store.dispatch('map/setTrainWindowShow', false);
                    });
                });
            }).catch(() => {
                this.isDisable = true;
                this.$messageBox(this.$t('display.demon.endSimulationFail'));
            });
        },
        handleQuitQuest() {
            quitScriptNew(this.group).then(resp => {
                getSimulationInfoNew(this.group).then((res)=>{
                    this.quitQuest();
                    this.initLoadPage();
                    this.clearAllData();
                }).catch(()=>{
                    this.$messageBox(this.$t('display.demon.exitTaskFail'));
                });
            }).catch(() => {
                this.$messageBox(this.$t('display.demon.exitTaskFail'));
            });
        },
        quitQuest() {
            this.$emit('quitQuest');
            this.$store.dispatch('scriptRecord/updateSimulationPause', false);
        },
        clearAllData() {
            this.$refs.chatbox.clearAllData();
        },
        async back() {
            this.isGoback = true;
            if (this.projectDevice) {
                this.$store.dispatch('training/over').then(() => {
                    this.$store.dispatch('LogOut').then(() => {
                        location.reload();
                    });
                });
            } else {
                await clearSimulation(this.group);
                this.$store.dispatch('training/over').then(() => {
                    this.$store.dispatch('map/setShowCentralizedStationCode', '');
                    history.go(-1);
                    Notification.closeAll();
                });
            }

        },
        jumpjl3dpassflow() {
            this.$emit('passflow');
        },
        // jumpjl3dstation() {
        //     this.$emit('jl3dstation');
        // },
        jumpjlmap3d() {
            this.$emit('hidepanel');
        },
        jumpjlmap3dmodel() {
            this.$emit('devicemodel');
        },
        jumpScheduling() {
            this.$emit('showScheduling');
        },
        schedulingView() {
            this.$emit('schedulingView');
        },
        setTryTime() {
            if (this.try) {
                const data = { time: this.tryTime, goodsId: this.goodsId };
                if (data.goodsId) {
                    setGoodsTryUse(data);
                }

            }
        },
        change3dname() {
            if (this.$route.query.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";

    .display-card {
        z-index: 9;
        display: inline-block;
        position: absolute;
        top: 17px;
        left: 160px;
        height: 32px;
    }

    .display-card .el-row {
        line-height: 32px !important;
    }

    .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;
    }
	.haerbin_btn_box{
		width: 450px;
		bottom: 15px!important;
	}
</style>
<style lang="scss">
.display-draft {
    position: absolute;
    right: 10px;
    bottom: 15px;
	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);
		}
	}
</style>
