<template>
  <div>
    <div class="schema" :style="{top: offset+'px'}">
      <select-station v-if="isShowSelectStation && !isScript" ref="selectStation" :style-css="'width: 100px;'" />
      <el-select v-model="speed" style="width: 100px;" size="small" @change="speedChange">
        <el-option
          v-for="item in speedList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <template v-if="!dataError">
        <el-button-group v-if="project !== 'bjd'">
          <el-button v-if="$route.query.lineCode === '16'&&!isCtc && project !== 'teaching'" size="small" @click="goCtc">CTC</el-button>
          <!-- <el-button v-if="$route.query.lineCode === '16'&&!isCtc" size="small" @click="goRpManage">管理终端</el-button> -->
          <!-- <el-button v-if="$route.query.lineCode === '16'&&!isCtc" size="small" @click="goDsManage">调度台</el-button> -->
          <el-button v-if="isLocalStation && $route.query.lineCode!='08' && $route.query.lineCode!='16' && project !== 'teaching'" size="small" @click="goIbp">IBP盘</el-button>
          <el-button v-if="isScheduling && isDepot && project !== 'teaching'" size="small" type="primary" @click="runPlanEditShow">运行图编辑</el-button>
          <!-- 加载剧本 -->
          <el-button v-if="isDemon && !isScheduling && !isContest && !isDepoltSim && $route.query.lineCode!='16' && project !== 'teaching'" size="small" :disabled="viewDisabled" type="success" @click="viewRunQuest">{{ $t('display.schema.loadScript') }}</el-button>
          <!-- 运行图加载 -->
          <!-- notScript &&  -->
          <el-button v-if="running && project !== 'teaching'" size="small" :disabled="viewDisabled" @click="viewRunPlan">{{ $t('display.schema.previewRunDiagram') }}</el-button>
          <!-- notScript &&  -->
          <el-button v-if="!running && $route.query.lineCode!='16' && project !== 'teaching'" size="small" type="warning" @click="loadRunPlan">{{ $t('display.schema.loadRunDiagram') }}</el-button>
        </el-button-group>
        <el-button v-if="!isScheduling && project !== 'bjd'" size="small" :type="faultMode ? '':'primary' " @click="changeOperateMode()">{{ faultMode?'切换到普通模式[Tab]':'切换到故障模式[Tab]' }}</el-button>
        <el-button v-if="running&&project == 'bjd'" size="small" :disabled="viewDisabled" @click="viewRunPlan">{{ $t('display.schema.previewRunDiagram') }}</el-button>
        <!-- <el-button v-if="!isLocalStation" size="small" :type="faultMode ? 'danger' : ''" @click="changeDirectiveMode()">指令模式</el-button> -->
      </template>
    </div>
    <fault-choose ref="faultChoose" :group="group" :offset="offset" />
    <run-plan-Load ref="runPlanLoad" :group="group" />
    <!-- v-if="project!== 'bjd'"  -->
    <run-plan-view ref="runPlanView" :group="group" />
    <!-- 加载剧本列表弹窗 -->
    <add-quest ref="addQuest" @selectQuest="selectQuest" />
    <line-board ref="lineBoard" />
    <!-- <run-plan-edit v-if="isScheduling && isDepot" ref="runPlanEdit" /> -->
  </div>
</template>
<script>
import SelectStation from './selectStation';
import RunPlanLoad from './demon/runPlanLoad';
import RunPlanView from './demon/runPlanView';
import FaultChoose from './demon/faultChoose';
import LineBoard from '../displayCity/lineBoard';
import AddQuest from './demon/addQuest';
import { OperateMode } from '@/scripts/ConstDic';
import { getByGroupStationList } from '@/api/jmap/map';
import { generateRunPlanInfoSync } from '@/api/jmap/mapdraft.js';
import { getSessionStorage } from '@/utils/auth';
import { getToken } from '@/utils/auth';
import { getIbpInfoByStation } from '@/api/ibp';
import { loadRunPlanData } from '@/utils/loaddata';
import { EventBus } from '@/scripts/event-bus';
import { timesSpeedPlayback } from '@/api/rtSimulation';

// 右上角操作
export default {
    name: 'MenuSchema',
    components: {
        RunPlanLoad,
        RunPlanView,
        FaultChoose,
        AddQuest,
        // RunPlanEdit,
        SelectStation,
        LineBoard
    },
    props: {
        offset: {
            type: Number,
            required: true
        },
        dataError: {
            type: Boolean,
            default() {
                return false;
            }
        }
    },
    data() {
        return {
            mode: OperateMode.NORMAL,
            OperateMode: OperateMode,
            viewDisabled: true,
            swch: '02',
            isScriptCommand:false,
            faultMode: false,
            speed: 1
            // firstLoad: true
        };
    },
    computed: {
        group() {
            return this.$route.query.group;
        },
        notScript() {
            return this.$route.params.mode !== 'script';
        },
        isCtc() {
            return !!this.$route.query.ctc;
        },
        isScript() {
            return this.$route.params.mode === 'script';
        },
        project() {
            return getSessionStorage('project');
        },
        isDemon() {
            return this.$route.params.mode === 'demon';
        },
        isScheduling() {
            return this.$route.query.prdType === '05';
        },
        isDepoltSim() {
            return this.$route.query.prdType === '09';
        },
        isLocalStation() {
            return this.$store.state.training.prdType === '01';
        },
        isShowSelectStation() {
            return this.$store.state.training.prdType === '01' || this.$store.state.training.prdType === '09';
        },
        running() {
            return this.$store.state.training.started;
        },
        isDepot() {
            return this.$route.query.type === 'DEPOT';
        },
        isContest() {
            return this.project.includes('drts');
        },
        isAdmin() {
            return this.$store.state.user.roles.includes('04') || this.$store.state.user.roles.includes('05');
        },
        speedList() {
            return this.isAdmin ? [
                { value: 1, label: '1倍速' },
                { value: 2, label: '2倍速' },
                { value: 3, label: '3倍速' },
                { value: 4, label: '4倍速' },
                { value: 5, label: '5倍速' },
                { value: 6, label: '6倍速' },
                { value: 7, label: '7倍速' },
                { value: 8, label: '8倍速' },
                { value: 9, label: '9倍速' },
                { value: 10, label: '10倍速' }
            ] : [
                { value: 1, label: '1倍速' },
                { value: 2, label: '2倍速' },
                { value: 3, label: '3倍速' },
                { value: 4, label: '4倍速' },
                { value: 5, label: '5倍速' }
            ];
        }
    },
    watch: {
        '$store.state.scriptRecord.bgSet':function (val) {
            this.isScriptCommand = val;
            if (!val) {
                this.swch = '01';
            }
        },
        // '$store.state.map.mapDataLoadedCount': function () {
        //     this.loadRunData();
        // },
        '$store.state.training.subscribeCount': function () {
            this.loadRunData();
        },
        '$store.state.socket.simulationPlanChange': function (val) {
            // 判断是否已经加载运行图，若加载只处理运行图数据，否则，缓存数据
            if (JSON.stringify(this.$store.state.runPlan.planData) == '{}') {
                this.$store.dispatch('runPlan/setUpdateTrainRpData', val);
            } else {
                this.$store.dispatch('runPlan/updateTrainRunplan', val);
            }
        },
        '$store.state.training.triggerFaultCount': function () {
            this.setFault();
        },
        '$store.state.runPlan.loadRunPlanCount': function () {
            this.viewDisabled = false;
            if (JSON.stringify(this.$store.state.runPlan.updateTrainRpData) != '{}') {
                this.$store.dispatch('runPlan/updateTrainRunplan', this.$store.state.runPlan.updateTrainRpData);
            }
        },
        '$store.state.socket.simulationSpeed': function (val) {
            this.speed = val;
        }
    },
    mounted() {
        EventBus.$on('CheckFaultModeEvent', () => {
            if (!this.isScheduling) {
                this.changeOperateMode();
            }
        });
        EventBus.$on('showLineBoard', () => {
            this.showLineBoard();
        });
    },
    methods: {
        loadRunData() {
            this.$store.dispatch('runPlan/clear').then(() => {
                if (this.group) {
                    this.viewDisabled = true;
                    // 获取排序的车站列表
                    getByGroupStationList(this.group).then(response => {
                        this.$store.dispatch('runPlan/setStations', response.data).then(() => {
                            loadRunPlanData(this.group, this.dataError);
                        });
                    }).catch(() => {
                        this.$messageBox(this.$t('display.schema.getStationListFail'));
                    });
                }
            });
        },
        showLineBoard() {
            this.$refs.lineBoard.doShow();
        },
        goCtc() {
            const routeData = this.$router.resolve({
                path:'/displayNew/demon',
                query:{
                    lineCode:this.$route.query.lineCode,
                    group: this.$route.query.group,
                    prdType: this.$route.query.prdType,
                    mapId:this.$route.query.mapId,
                    project: this.project,
                    newApi: this.$route.query.newApi,
                    ctc: true,
                    try: this.$route.query.try,
                    token:getToken(),
                    noPreLogout: true
                }
            });
            window.open(routeData.href, '_blank');
        },
        // goRpManage() {
        //     const routeData = this.$router.resolve({
        //         path:'/bigTrainRunplanManage',
        //         query:{
        //             group: this.$route.query.group,
        //             mapId:this.$route.query.mapId,
        //             project: this.project,
        //             prdType: this.$route.query.prdType,
        //             lineCode:this.$route.query.lineCode,
        //             // stationCode:this.$store.state.training.roleDeviceCode,
        //             // token:getToken(),
        //             noPreLogout: true
        //         }
        //     });
        //     window.open(routeData.href, '_blank');
        // },
        // goDispatcherStation() {
        //     const routeData = this.$router.resolve({
        //         // path:'/bigTrainDispatcherStation',
        //         path:'/displayNew/demon',
        //         query:{
        //             group: this.$route.query.group,
        //             mapId:this.$route.query.mapId,
        //             project: this.project,
        //             prdType: this.$route.query.prdType,
        //             lineCode:this.$route.query.lineCode,
        //             newApi: this.$route.query.newApi,
        //             dispatcherStation:true,
        //             // stationCode:this.$store.state.training.roleDeviceCode,
        //             // token:getToken(),
        //             try: this.$route.query.try,
        //             token:getToken(),
        //             noPreLogout: true
        //         }
        //     });
        //     window.open(routeData.href, '_blank');
        // },
        // goDsManage() {
        //     const routeData = this.$router.resolve({
        //         path:'/dispatcherStationManage',
        //         query:{
        //             group: this.$route.query.group,
        //             mapId:this.$route.query.mapId,
        //             project: this.project,
        //             prdType: this.$route.query.prdType,
        //             lineCode:this.$route.query.lineCode,
        //             // stationCode:this.$store.state.training.roleDeviceCode,
        //             token:getToken(),
        //             noPreLogout: true
        //         }
        //     });
        //     window.open(routeData.href, '_blank');
        // },
        changeOperateMode() {
            this.faultMode = !this.faultMode;
            let mode = OperateMode.NORMAL;
            if (this.faultMode) {
                mode = OperateMode.FAULT;
            }
            this.$store.dispatch('training/changeOperateMode', { mode: mode });
        },
        // changeDirectiveMode() { // 调整指令模式 (暂时不使用 等项目更新 在使用)
        //     this.directiveMode = !this.directiveMode;
        //     let mode = OperateMode.NORMAL;
        //     if (this.directiveMode) {
        //         mode = OperateMode.DIRECTIVE;
        //     }
        //     this.$store.dispatch('training/changeOperateMode', { mode: mode });
        // },
        speedChange(val) {
            timesSpeedPlayback(this.$route.query.group, val).then(resp => {
                this.$message.success(`设置${val}倍速成功!`);
            }).catch(e => {
                this.$message.error('设置倍速失败！');
            });
        },
        setFault() {
            this.$refs.faultChoose.doShow();
        },
        loadRunPlan() {
            this.$refs.runPlanLoad.doShow();
        },
        viewRunPlan() {
            this.$refs.runPlanView.doShow();
        },
        viewRunQuest() {
            this.$refs.addQuest.doShow();
        },
        selectQuest(row, id, mapLocation, roleName) {
            this.$emit('selectQuest', {row, id, mapLocation, roleName});
        },
        runPlanEditShow() {
            generateRunPlanInfoSync(this.$route.query.mapId).then(resp => {
                const routeData = this.$router.resolve({
                    path:'/plan/newTool',
                    query:{
                        mapId:this.$route.query.mapId,
                        lineCode:this.$route.query.lineCode,
                        token:getToken(),
                        project: this.project,
                        noPreLogout: true
                    }
                });
                window.open(routeData.href, '_blank');
            });
        },
        goIbp() {
            const deviceCode = this.$refs.selectStation.showStation;
            getIbpInfoByStation(this.$route.query.mapId, deviceCode).then(resp => {
                if (resp.data) {
                    const routeData = this.$router.resolve({
                        path:`/ibpShow`,
                        query:{
                            lineCode: this.$route.query.lineCode,
                            mapId: this.$route.query.mapId,
                            group: this.$route.query.group,
                            stationCode: deviceCode,
                            loadAll: true,
                            noPreLogout: true
                        }
                    });
                    window.open(routeData.href, '_blank');
                } else {
                    this.$messageBox('本车站暂无IBP盘数据！');
                }
            }).catch((error) => {
                if (error.code == '10007') {
                    this.$messageBox('本车站暂无IBP盘数据！');
                } else {
                    this.$message.error('获取IBP盘数据异常');
                }
            });

        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .schema {
        z-index: 36;
        display: inline;
        position: absolute;
        right: 5px;
    }

    /deep/ .el-button+.el-button {
        margin-left: 0px;
    }
</style>
