<template>
  <div style="height:100%">
    <div class="schema" :style="{top: offset+'px'}">
      <!--<el-select v-if="showSelectStation" v-model="chiShowStation" style="width: 100px;" size="small" @change="switchStationMode">-->
      <!--<el-option v-for="item in stationList" :key="item.value" :label="item.name" :value="item.value" />-->
      <!--</el-select>-->
      <el-select v-if="isAdmin && isSystemAdmin" 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>
      <el-button-group>
        <el-button v-if="userRole=== 'STATION_SUPERVISOR'&&$route.query.lineCode ==='16'" size="small" @click="goCtc">车务终端</el-button>
        <el-button v-if="userRole=== 'STATION_SUPERVISOR'&&$route.query.lineCode ==='16'" size="small" @click="goRpManage">车务管理终端</el-button>
        <el-button v-if="$route.query.lineCode ==='16'&&$store.state.training.prdType === '01'" size="small" @click="showTrainTicket">路票</el-button>
        <el-button v-if="showRegisterBookBtn" size="small" @click="showRegisterBook">簿册</el-button>
        <el-button v-if="showDispatcherStation" size="small" @click="changeShowMap">调度台</el-button>
        <el-button v-if="ibpShow" size="small" @click="goIbp">IBP盘</el-button>
        <el-button v-if="userRole=== 'DISPATCHER' && !$route.query.projectDevice && hasBigScreen" size="small" @click="goBigScreen">大屏</el-button>
        <el-button v-if="(userRole==='DISPATCHER' || userRole=== 'STATION_SUPERVISOR') && !$route.query.projectDevice && iscsShow" size="small" @click="goIscs">ISCS</el-button>
        <el-button v-if="running && !dataError && $route.query.type !== 'ILW' && !datie" size="small" :disabled="viewDisabled" @click="viewRunPlan">{{ $t('joinTraining.runGraphPreview') }}</el-button>
        <template v-if="isAdmin">
          <el-button v-if="!running && !dataError && $route.query.type !== 'ILW' && !datie" size="small" type="warning" @click="loadRunPlan">
            {{ $t('joinTraining.runGraphLoading') }}</el-button><!-- 运行图加载 -->
        </template>
      </el-button-group>
      <el-button v-if="(isAdmin || $route.query.type === 'ILW') && !dataError && !isScreen" size="small" :type="faultMode ? '' : 'primary' " @click="changeOperateMode()">{{ faultMode?' 切换到普通模式[Tab]':'切换到故障模式[Tab]' }}</el-button>
      <!-- isCenter && !dataError && !isAdmin 此判断用于以后(目前 暂时不用) -->
      <el-button v-if="isShowDirective" size="small" :type="directiveMode ? 'primary' : ''" @click="changeDirectiveMode()">{{ directiveMode? '切换到普通模式[Tab]':'切换到指令模式[Tab]' }}</el-button>
    </div>
    <!-- running &&  -->
    <join-run-plan-view v-if="!dataError" ref="runPlanView" :group="group" />
    <select-ibp ref="selectIbp" />
    <train-ticket ref="trainTicket" />
    <register-book ref="registerBook" />
  </div>

</template>
<script>
import { mapGetters } from 'vuex';
import { OperateMode } from '@/scripts/ConstDic';
import { getByGroupStationList } from '@/api/jmap/map';
import { getSessionStorage } from '@/utils/auth';
import JoinRunPlanView from '@/views/newMap/displayNew/demon/runPlanView';
import SelectIbp from '@/views/newMap/displayNew/demon/selectIbp';
import { getIbpInfoByStation } from '@/api/ibp';
import { loadRunPlanData } from '@/utils/loaddata';
import { EventBus } from '@/scripts/event-bus';
import { timesSpeedPlayback } from '@/api/rtSimulation';
import { queryHasIscs } from '@/api/iscs';
import { getToken } from '@/utils/auth';
import TrainTicket from '../trainTicket/index';
import RegisterBook from '../registerBook/index';
export default {
    name: 'MenuDemonSchema',
    components:{
        JoinRunPlanView,
        SelectIbp,
        TrainTicket,
        RegisterBook
    },
    props: {
        group: {
            type: String,
            required: true
        },
        offset: {
            type: Number,
            required: true
        },
        userRole: {
            type: String,
            required: true
        },
        showSelectStation: {
            type: Boolean,
            default() {
                return false;
            }
        },
        stationList: {
            type: Array,
            default() {
                return [];
            }
        },
        dataError: {
            type: Boolean,
            default() {
                return false;
            }
        },
        isAdmin: {
            type: Boolean,
            default() {
                return false;
            }
        },
        deviceCode: {
            type: String,
            default() {
                return '';
            }
        }
    },
    data() {
        return {
            mode: OperateMode.NORMAL,
            OperateMode: OperateMode,
            viewDisabled: true,
            realData: {},
            series: [],
            chiShowStation: '',
            kmRangeMap: {},
            runPlanData: {},
            userId: '',
            faultMode: false,
            directiveMode: false,
            firstLoad: true,
            iscsShow:false,
            speedList:[
                { 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倍速' }
            ],
            speed: 1
        };
    },
    computed: {
        ...mapGetters('runPlan', [
            'stations'
        ]),
        ...mapGetters('map', [
            'bigScreenConfig'
        ]),
        running() {
            return this.$store.state.training.started;
        },
        datie() {
            return ['16', '19'].includes(this.$route.query.lineCode);
        },
        isScreen() {
            return this.$store.state.training.prdType === '07';
        },
        project() {
            return getSessionStorage('project');
        },
        isShowDirective() { // 哈尔滨项目 行调设备显示
            return this.$route.query.type == 'CW' && this.project == 'heb';
        },
        hasBigScreen() {
            return this.bigScreenConfig.bigScreenSplitConfig && this.bigScreenConfig.bigScreenSplitConfig.length;
        },
        isSystemAdmin() {
            return this.$store.state.user.roles.includes('04') || this.$store.state.user.roles.includes('05');
        },
        showDispatcherStation() {
            return this.$route.query.lineCode === '16' && this.$store.state.training.prdType === '02';
        },
        ibpShow() {
            const lineCodeList = ['08', '16'];
            return this.userRole === 'STATION_SUPERVISOR' && !this.$route.query.projectDevice && !lineCodeList.includes(this.$route.query.lineCode);
        },
        showRegisterBookBtn() {
            const roleList = ['STATION_SUPERVISOR', 'STATION_ASSISTANT', 'STATION_SIGNALER', 'STATION_SWITCH_MAN', 'STATION_MASTER', 'STATION_WORKER', 'DEVICE_MANAGER'];
            return this.$route.query.lineCode === '16' && roleList.includes(this.$store.state.training.userRole);
        }
    },
    watch: {
        // '$store.state.training.switchcount': async function () {
        //     if (this.group) {
        //         const started = this.$store.state.training.started;
        //         if (started && !this.firstLoad) {
        //             await this.loadRunData(this.$route.query);
        //         } else if (this.firstLoad) {
        //             await this.loadRunData(this.$route.query);
        //         }
        //     }
        // }
        '$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.map.mapDataLoadedCount': function () {
        //     this.loadRunData(this.$route.query);
        // },
        '$store.state.training.subscribeCount': function () {
            this.loadRunData(this.$route.query);
        },
        '$store.state.training.triggerFaultCount': function () {
            this.setFault();
        },
        '$store.state.runPlan.loadRunPlanCount': function () {
            this.viewDisabled = false;
            this.firstLoad = false;
            if (JSON.stringify(this.$store.state.runPlan.updateTrainRpData) != '{}') {
                this.$store.dispatch('runPlan/updateTrainRunplan', this.$store.state.runPlan.updateTrainRpData);
                this.$store.dispatch('runPlan/setUpdateTrainRpData', {});
            }
        }
    },
    async mounted() {
        this.userId = this.$store.state.user.id;
        EventBus.$on('CheckFaultModeEvent', () => {
            if ((this.isAdmin || this.$route.query.type === 'ILW') && !this.dataError && !this.isScreen) {
                this.changeOperateMode();
            }
            if (this.isShowDirective) {
                this.changeDirectiveMode();
            }
        });
        queryHasIscs({mapId: this.$route.query.mapId}).then(resp => {
            if (resp.data) {
                this.iscsShow = true;
            } else {
                this.iscsShow = false;
            }
        }).catch(() => {
            this.$message.error('查询ISCS数据异常');
        });
    },
    methods: {
        loadRunData(opt) {
            this.$store.dispatch('runPlan/clear').then(resp => {
                if (opt && opt.mapId) {
                    this.viewDisabled = true;
                    getByGroupStationList(this.$route.query.group).then(response => {
                        const stations = response.data;
                        this.$store.dispatch('runPlan/setStations', stations).then(() => {
                            loadRunPlanData(this.group, this.dataError);
                        });
                    }).catch(() => {
                        this.$messageBox(this.$t('error.obtainStationListFailed'));
                    });
                }
            });
        },
        // initPlannedDriving(isDisable) {
        //     this.isDisable = isDisable;
        // },
        changeOperateMode() {
            this.faultMode = !this.faultMode;
            let mode = OperateMode.NORMAL;
            if (this.faultMode) {
                mode = OperateMode.FAULT;
            }
            this.$store.dispatch('training/changeOperateMode', { mode: mode });
        },
        goCtc() {
            const routeData = this.$router.resolve({
                path:'/displayNew/demon',
                query:{
                    lineCode:this.$route.query.lineCode,
                    group: this.$route.query.group,
                    prdType: '01',
                    mapId:this.$route.query.mapId,
                    project: this.project,
                    newApi: false,
                    joint: true,
                    ctc: true,
                    try: this.$route.query.try || 0,
                    token:getToken(),
                    noPreLogout: true
                }
            });
            window.open(routeData.href, '_blank');
        },
        changeDirectiveMode() { // 调整指令模式
            this.directiveMode = !this.directiveMode;
            let mode = OperateMode.NORMAL;
            if (this.directiveMode) {
                mode = OperateMode.DIRECTIVE;
            }
            this.$store.dispatch('training/changeOperateMode', { mode: mode });
        },
        setFault() {
            this.$emit('faultChooseShow');
        },
        loadRunPlan() {
            this.$emit('runPlanLoadShow');
        },
        viewRunPlan() {
            if (this.$route.query.type === 'CW') {
                const routeData = this.$router.resolve({
                    path:`/runPlanViewWindow`,
                    query:{
                        lineCode: this.$route.query.lineCode,
                        mapId:this.$route.query.mapId,
                        group:this.$route.query.group,
                        initTime: this.$store.state.training.initTime,
                        noPreLogout: true
                    }
                });
                window.open(routeData.href, '_blank');
            } else {
                this.$refs.runPlanView.doShow();
            }
        },
        // 选择车站
        switchStationMode(stationCode) {
            this.$emit('switchStationMode', stationCode);
        },
        // 点击大屏预览
        goBigScreen() {
            const routeData = this.$router.resolve({
                path:`/displayBigScreen/${this.$route.query.mapId}`,
                query:{
                    lineCode: this.$route.query.lineCode,
                    mapId:this.$route.query.mapId,
                    group:this.$route.query.group,
                    prdType: '07',
                    try:0,
                    noPreLogout: true
                }
            });
            window.open(routeData.href, '_blank');
        },
        goIscs() {
            const routeData = this.$router.resolve({
                path:`/displayIscs/system`,
                query:{
                    lineCode: this.$route.query.lineCode,
                    mapId: this.$route.query.mapId,
                    group: this.$route.query.group,
                    noPreLogout: true
                }
            });
            window.open(routeData.href, '_blank');
        },
        speedChange(val) {
            timesSpeedPlayback(this.$route.query.group, val).then(resp => {
                this.$message.success(`设置${val}倍速成功!`);
            }).catch(e => {
                this.$message.error('设置倍速失败！');
            });
        },
        showTrainTicket() {
            this.$refs.trainTicket.doShow();
        },
        showRegisterBook() {
            this.$refs.registerBook.doShow();
        },
        changeShowMap() {
            this.$emit('changeShowMap', false);
        },
        // 点击ibp预览
        goIbp() {
            // this.$refs.selectIbp.doShow();
            getIbpInfoByStation(this.$route.query.mapId, this.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: this.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盘数据异常');
                }
            });

        },
        goRpManage() {
            const routeData = this.$router.resolve({
                path:'/bigTrainRunplanManage',
                query:{
                    group: this.$route.query.group,
                    mapId:this.$route.query.mapId,
                    project: this.project,
                    prdType: this.$store.state.training.prdType,
                    lineCode:this.$route.query.lineCode,
                    // stationCode:this.$store.state.training.roleDeviceCode,
                    // token:getToken(),
                    noPreLogout: true
                }
            });
            window.open(routeData.href, '_blank');
        }
    }
};
</script>
<style>
    .schema {
        z-index: 18;
        display: inline;
        position: absolute;
        right: 5px;
    }

    .schema .el-radio-group .el-radio-button__inner {
        padding: 0px 15px 0px 15px;
        height: 32px;
        line-height: 32px;
        font-size: 12px;
    }

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