<template>
  <div v-loading="loading" class="joylink-card">
    <div class="card-title">
      <span><b>{{ $t('demonstration.simulationName') + courseModel.name }}</b></span>
    </div>
    <div class="simulation-detail">
      <p class="list-item">
        <span class="list-label">{{ $t('demonstration.productDescription') }}</span>
        <span class="list-elem">{{ courseModel.remarks }}</span>
      </p>
      <p class="list-item">
        <span class="list-label">{{ $t('global.permissionList') }}</span>
      </p>
      <limit-list :ref="`limit`" :course-model="courseModel" @initLoadPage="refresh" />
    </div>
    <div class="btn-buy">
      <el-button v-if="!isLocal" type="success" :disabled="disabled" @click="buy">{{ $t('global.buy') }}</el-button>
      <el-button v-if="hasPermssion && !isComprehensive && !isLocal" type="primary" :disabled="disabled" @click="distribute">{{ $t('global.distributePermission') }}</el-button>
      <el-button v-show="isStartDemon" :disabled="disabled" type="primary" @click="start">{{ $t('demonstration.startSimulation') }}</el-button>
      <el-button v-show="isCreateRoom" :disabled="disabled" type="primary" @click="start">{{ $t('demonstration.createRoom') }}</el-button>
      <el-button v-show="isInRoom" :disabled="disabled" type="primary" @click="joinRoom">{{ $t('demonstration.enterRoom') }}</el-button>
    </div>
  </div>
</template>

<script>
import { getPublishMapInfo } from '@/api/jmap/map';
import { getGoodsTryUse } from '@/api/management/goods';
import { PermissionType, UrlConfig } from '@/scripts/ConstDic';
import { launchFullscreen } from '@/utils/screen';
import { postCreateRoom, getjointTraining } from '@/api/chat';
import { postCreateRoomNew, getjointTrainingNew, checkRoomExistNew } from '@/api/jointTraining';
import { } from '@/scripts/ConstDic';
import { simulationNotify, schedulingNotify, createSimulationNew } from '@/api/simulation';
import LimitList from '@/views/components/limits/index';
import { getSubSystemDetail } from '@/api/trainingPlatform';
import { getSessionStorage } from '@/utils/auth';

export default {
    name: 'ExamDetailList',
    components: {
        LimitList
    },
    data() {
        return {
            tryTime: 0,
            goodsId: '',
            tryUser: 0,
            loading: true,
            disabled: false,
            currentLessonId: '',
            currentPrdType: '',
            productList: [],
            courseModel: {
                id: '',
                name: '',
                mapId: '',
                lineCode: '',
                remarks: '',
                prdType: '',
                pmsList: []
            },
            jointShow: false,
            jointGroup: '',
            lineCode:'',
            drawWay: false // 是否新版地图
        };
    },
    computed: {
        hasPermssion() {
            let isShow = false;
            if (this.courseModel.pmsList && this.courseModel.pmsList.length) {
                let count = 0;
                this.courseModel.pmsList.forEach(element => {
                    count += element.remains;
                });
                if (count > 0) {
                    isShow = true;
                }
            }
            return isShow;
        },
        isLocal() { // 是否为本地项目
            return process.env.VUE_APP_PRO === 'local';
        },
        isComprehensive() {
            return this.courseModel.prdType === '03';
        },
        isStartDemon() {
            return this.courseModel.prdType !== '03' && (this.hasPermssion || this.tryTime > 0);
        },
        isCreateRoom() {
            return this.courseModel.prdType === '03' && this.hasPermssion && !this.jointShow;
        },
        isInRoom() {
            return this.courseModel.prdType === '03' && this.hasPermssion && this.jointShow;
        },
        mapId() {
            return this.$route.query.mapId;
        }
    },
    watch: {
        '$route': function (val) {
            this.loadInitData();
        }
    },
    async mounted() {
        this.loadInitData();
    },
    methods: {
        async loadInitData() {
            this.loading = true;
            try {
                const res = await getPublishMapInfo(this.mapId);
                const resp = await getSubSystemDetail(this.$route.params.subSystem);
                this.tryUser = 0;
                this.loading = false;
                this.drawWay = res.data.drawWay;
                const remarksList = {'01':'ATS现地工作站原理级仿真实训课程', '02':'ATS行调工作站原理级仿真实训课程', '03':'各岗位应急综合演练', '04':'桌面版模拟驾驶系统', '05':'派班工作站主要是供车辆段/停车场派班员进行派班操作，可以自动生成派班计划，极大的简化了派班计划管理的复杂性', '06': '综合监控管理原理及仿真实训'};
                this.courseModel = {
                    id: resp.data.id,
                    name: resp.data.name,
                    mapId: this.mapId,
                    lineCode: res.data.lineCode,
                    remarks: remarksList[resp.data.prdType],
                    prdType: resp.data.prdType,
                    pmsList: resp.data.permissionList || [],
                    PermissionType: PermissionType.SIMULATION
                };
                this.currentPrdType = resp.data.prdType;
                if (resp.data.prdType === '03') {
                    this.getJointTrainingList();
                }
                if (!this.courseModel.pmsList) {
                    this.tryUser = 1;
                    const paras = {
                        mapId: this.mapId,
                        prdType: this.courseModel.prdType,
                        permissionType: PermissionType.SIMULATION
                    };

                    try {
                        const resr = await getGoodsTryUse(paras);
                        if (resr.data.tryTime <= 0) {
                            this.tryTime = 0;
                        } else {
                            this.tryTime = resr.data.tryTime;
                            this.goodsId = resr.data.goodsId;
                        }
                    } catch (error) {
                        this.tryTime = 0;
                    }
                }
            } catch (error) {
                this.loading = false;
                this.$message.error(this.$t('error.refreshFailed'));
            }
        },
        refresh() {
            this.loadInitData();
        },
        async getJointTrainingList() {
            try {
                if (this.mapId) {
                    const res = await checkRoomExistNew({mapId: this.mapId});
                    this.jointGroup = res.data;
                    this.jointShow = false;
                    if (res.data) {
                        this.jointShow = true;
                    }
                }
            } catch (error) {
                console.error(error, '获取是否拥有综合演练房间');
            }
        },
        async joinRoom() {
            this.disabled = true;
            if (this.drawWay) {
                await getjointTrainingNew(this.jointGroup);
            } else {
                await getjointTraining(this.jointGroup);
            }
            this.$store.dispatch('socket/setInRoom', true);
            const query = { lineCode: this.courseModel.lineCode, group: this.jointGroup, drawWay: this.drawWay};
            this.$router.push({ path: `/trainroom`, query: query });
        },
        async createRoom() {
            try {
                this.disabled = true;
                const param = {
                    mapId: Number(this.mapId),
                    prdType: this.courseModel.prdType
                };
                let res = '';
                if (this.drawWay) {
                    res = await postCreateRoomNew(param);
                } else {
                    res = await postCreateRoom(param);
                }
                if (res && res.code == 200) {
                    const query = { lineCode: this.courseModel.lineCode, group: res.data, drawWay: this.drawWay };
                    this.$router.push({ path: `/trainroom`, query: query });
                }
            } catch (error) {
                this.disabled = false;
                if (error.code == 20001) {
                    this.$confirm(this.$t('tip.createRoomFailedHint'), this.$t('global.tips'), {
                        confirmButtonText: this.$t('global.confirm'),
                        cancelButtonText: this.$t('global.cancel'),
                        type: 'warning'
                    }).then(() => {}).catch(() => {});
                }
                if (error.code == 500009) {
                    this.$messageBox(error.message);
                }
            }
        },
        async enterISCS() {
            try {
                this.disabled = true;
                const data = { mapId: this.courseModel.mapId, prdType: this.currentPrdType };
                let res = {};
                if (!this.drawWay) {
                    res = await simulationNotify(data);
                } else {
                    res = await createSimulationNew(data);
                }
                if (res && res.code == 200) {
                    const query = { group: res.data };
                    this.$router.push({ path: `/displayIscs/system`, query: query });
                }
            } catch (error) {
                this.disabled = false;
                console.log(error);
            }
        },
        async enterScreen() {
            this.$router.push({ path: `/displayBigScreen/${this.courseModel.mapId}` });
        },
        async start() {
            if (this.courseModel.prdType == '05') {
                this.jumpScheduling();
            } else if (this.courseModel.prdType == '03') {
                this.createRoom();
            } else if (this.courseModel.prdType == '06') {
                this.enterISCS();
            } else if (this.courseModel.prdType == '07') {
                this.enterScreen();
            } else {
                if (this.courseModel.pmsList && this.courseModel.pmsList.length) {
                    this.jump();
                } else {
                    if (this.tryTime <= 1) {
                        this.$confirm(this.$t('tip.noPermissionHint'), this.$t('global.tips'), {
                            confirmButtonText: this.$t('global.confirm'),
                            cancelButtonText: this.$t('global.cancel'),
                            type: 'warning'
                        }).then(() => {
                            this.buy();
                        }).catch(() => { });
                    } else {
                        this.jump();
                    }
                }
            }
        },
        jumpScheduling() {
            this.disabled = true;
            setTimeout(() => {
                const data = { mapId: this.courseModel.mapId, prdType: this.currentPrdType };
                try {
                    if (this.drawWay) {
                        createSimulationNew(data).then(resp => {
                            const query = { lineCode: this.courseModel.lineCode, group: resp.data, prdType: this.courseModel.prdType, mapId: this.courseModel.mapId, goodsId: this.goodsId, try: this.tryUser };
                            this.$router.push({ path: `${UrlConfig.displayNew}/demon`, query: query });
                            launchFullscreen();
                        });
                    } else {
                        schedulingNotify(data).then(resp => {
                            const query = { lineCode: this.courseModel.lineCode, group: resp.data, prdType: this.courseModel.prdType, mapId: this.courseModel.mapId, goodsId: this.goodsId, try: this.tryUser };
                            this.$router.push({ path: `${UrlConfig.display}/demon`, query: query });
                            launchFullscreen();
                        });
                    }
                } catch (e) {
                    this.$messageBox(this.$t('error.createSimulationFailed') + e.message);
                    this.disabled = false;
                }
            }, 100);
        },
        jump() {
            this.disabled = true;
            setTimeout(() => {
                if (!this.drawWay) {
                    const data = { mapId: this.courseModel.mapId, prdType: this.currentPrdType };
                    simulationNotify(data).then(resp => {
                        const query = { lineCode: this.courseModel.lineCode, group: resp.data, prdType: this.courseModel.prdType, mapId: this.courseModel.mapId, goodsId: this.goodsId, try: this.tryUser, project: getSessionStorage('project') };
                        this.$router.push({ path: `${UrlConfig.display}/demon`, query: query });
                        launchFullscreen();
                    }).catch(error => {
                        this.$messageBox(this.$t('error.createSimulationFailed') + error.message);
                        this.disabled = false;
                    });
                } else {
                    const data = { mapId: this.courseModel.mapId, prdType: this.currentPrdType };
                    createSimulationNew(data).then(resp => {
                        const query = { lineCode: this.courseModel.lineCode, group: resp.data, prdType: this.courseModel.prdType, mapId: this.courseModel.mapId, goodsId: this.goodsId, try: this.tryUser, project: getSessionStorage('project') };
                        this.$router.push({ path: `${UrlConfig.displayNew}/demon`, query: query });
                        launchFullscreen();
                    }).catch(error => {
                        this.$messageBox(this.$t('error.createSimulationFailed') + error.message);
                        this.disabled = false;
                    });
                }
            }, 100);
        },
        buy() {
            // this.disabled = true;
            // setTimeout(() => {
            //     this.$router.push({
            //         path: `${UrlConfig.trainingPlatform.pay}/${this.courseModel.id}`,
            //         query: { permissionType: PermissionType.SIMULATION, prdType: this.courseModel.prdType, mapId: this.courseModel.mapId, subSystem: this.$route.params.subSystem }
            //     });
            // }, 100);
            this.$messageBox(this.$t('global.buyingTips'));
        },
        distribute() {
            this.disabled = true;
            if (this.$refs) {
                this.$refs[`limit`].distribute(this.courseModel);
            }
            this.disabled = false;
        }
    }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .joylink-card{
        height: 100%;
        overflow: hidden;
        .card-title{
            height: 47px;
            line-height: 47px;
            text-align: center;
            border-bottom: 1px solid #d6d6d6;
        }
    }
    .simulation-detail {
        padding: 50px;
        padding-bottom: 0;
        height: calc(100% - 107px);
        overflow: auto;
    }

    .list-item {
        font-size: 14px;
        margin-bottom: 20px;
        padding: 0px;
    }

    .list-label {
        display: -moz-inline-box;
        display: inline-block;
        text-align: left;
    }

    .list-elem {
        color: #808080 !important;
    }

    .btn-buy {
        text-align: center;
        padding: 10px 0;
    }

    .el-tabs--border-card>.el-tabs__header .el-tabs__item {
        font-weight: bold !important;
    }
</style>
