<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" />
    </div>
    <div class="btn-buy">
      <el-button type="success" @click="buy">{{ $t('global.buy') }}</el-button>
      <el-button v-if="hasPermssion" type="primary" @click="distribute">{{ $t('global.distributePermission') }}</el-button>
      <el-button v-if="hasPermssion" type="primary" @click="transfer">{{ $t('global.transferQRCode') }}</el-button>
      <el-button v-show="isStartDemon" :loading="buttonLoading" type="primary" @click="start">{{ $t('demonstration.startSimulation') }}</el-button>
      <el-button v-show="isCreateRoom" :loading="buttonLoading" type="primary" @click="start">{{ $t('demonstration.createRoom') }}</el-button>
      <el-button v-show="isInRoom" :loading="buttonLoading" 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 } from '@/scripts/ConstDic';
import { launchFullscreen } from '@/utils/screen';
import { postCreateRoom, getjointTraining, checkRoomExist } from '@/api/chat';
import { UrlConfig } from '@/router/index';
import { simulationNotify, schedulingNotify } from '@/api/simulation';
import LimitList from '@/views/components/limits/index';
import { getSubSystemDetail } from '@/api/trainingPlatform';

export default {
    name: 'ExamDetailList',
    components: {
        LimitList
    },
    data() {
        return {
            tryTime: 0,
            goodsId: '',
            tryUser: 0,
            loading: true,
            buttonLoading: false,
            currentLessonId: '',
            currentPrdId: '',
            productList: [],
            courseModel: {
                id: '',
                name: '',
                mapId: '',
                lineCode: '',
                remarks: '',
                prdType: '',
                prdId: '',
                pmsList: []
            },
            jointShow: false,
            jointGroup: ''
        };
    },
    computed: {
        hasPermssion() {
            let isShow = false;
            if (this.courseModel.pmsList && this.courseModel.pmsList.length) {
                isShow = true;
            }
            return isShow;
        },
        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 resp = await getSubSystemDetail(this.$route.params.subSystem);
                this.tryUser = 0;
                this.loading = false;
                if (resp.data.mapPrd) {
                    this.courseModel = {
                        id: resp.data.mapPrd.id,
                        name: resp.data.mapPrd.name,
                        mapId: this.mapId,
                        lineCode: resp.data.mapPrd.lineCode,
                        remarks: resp.data.mapPrd.remarks,
                        prdType: resp.data.mapPrd.prdType,
                        prdId: resp.data.mapPrd.id,
                        pmsList: resp.data.permissionList || [],
                        PermissionType: PermissionType.SIMULATION
                    };
                    this.currentPrdId = resp.data.mapPrd.id;
                    if (resp.data.mapPrd.prdType === '03') {
                        this.getJointTrainingList();
                    }
                }
                if (!this.courseModel.pmsList) {
                    this.tryUser = 1;
                    const paras = {
                        mapId: this.mapId,
                        prdId: this.courseModel.prdId,
                        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.$messageBox(this.$t('error.refreshFailed'));
            }
        },
        async getJointTrainingList() {
            try {
                if (this.mapId) {
                    const res = await checkRoomExist({ mapId: this.mapId });
                    this.jointGroup = res.data;
                    this.jointShow = false;
                    if (res.data) {
                        this.jointShow = true;
                    }
                }
            } catch (error) {
                console.error(error, '获取是否拥有综合演练房间');
            }
        },
        async joinRoom() {
            await getjointTraining(this.jointGroup);
            const query = { lineCode: this.courseModel.lineCode, group: this.jointGroup, subSystem: this.$route.params.subSystem};
            this.$router.push({ path: `/trainroom`, query: query });
        },
        async createRoom() {
            try {
                this.buttonLoading = true;
                const param = {
                    mapId: Number(this.mapId),
                    prdId: this.courseModel.prdId
                };
                const res = await postCreateRoom(param);
                if (res && res.code == 200) {
                    const query = { lineCode: this.courseModel.lineCode, group: res.data, subSystem: this.$route.params.subSystem };
                    this.$router.push({ path: `/trainroom`, query: query });
                }
            } catch (error) {
                this.buttonLoading = 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 start() {
            if (this.courseModel.prdType == '05') {
                this.jumpScheduling();
            } else if (this.courseModel.prdType == '03') {
                this.createRoom();
            } 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(() => { this.buttonLoading = false; });
                    } else {
                        this.jump();
                    }
                }
            }
        },
        jumpScheduling() {
            this.buttonLoading = true;
            const data = { mapId: this.courseModel.mapId, prdId: this.currentPrdId };
            schedulingNotify(data).then(resp => {
                const query = { lineCode: this.courseModel.lineCode, group: resp.data, prdType: this.courseModel.prdType, mapId: this.courseModel.mapId, code: this.currentPrdId, goodsId: this.goodsId, try: this.tryUser };
                this.$router.push({ path: `${UrlConfig.display}/demon`, query: query });
                launchFullscreen();
            }).catch(error => {
                this.$messageBox(this.$t('error.createSimulationFailed') + error.message);
                this.buttonLoading = false;
            });
        },
        jump() {
            const data = { mapId: this.courseModel.mapId, mapPrdId: this.currentPrdId };
            this.buttonLoading = true;
            simulationNotify(data).then(resp => {
                const query = { lineCode: this.courseModel.lineCode, group: resp.data, prdType: this.courseModel.prdType, mapId: this.courseModel.mapId, code: this.currentPrdId, goodsId: this.goodsId, try: this.tryUser };
                this.$router.push({ path: `${UrlConfig.display}/demon`, query: query });
                launchFullscreen();
            }).catch(error => {
                this.$messageBox(this.$t('error.createSimulationFailed') + error.message);
                this.buttonLoading = false;
            });
        },
        buy() {
            this.buttonLoading = true;
            this.$router.push({
                path: `${UrlConfig.trainingPlatform.pay}/${this.courseModel.id}`,
                query: { permissionType: PermissionType.SIMULATION, prdId: this.courseModel.prdId, mapId: this.courseModel.mapId, subSystem: this.$route.params.subSystem }
            });
        },
        transfer() {
            this.buttonLoading = false;
            if (this.$refs) {
                this.$refs[`limit`].transfer(this.courseModel);
            }
        },
        distribute() {
            this.buttonLoading = false;
            if (this.$refs) {
                this.$refs[`limit`].distribute(this.courseModel);
            }
        }
    }
};
</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>
