<template>
  <el-card>
    <div slot="header" style="text-align: center;">
      <b>试卷名称： {{ examDetails.name }}</b>
    </div>
    <div style="margin:50px; overflow-y: auto;">
      <el-scrollbar wrap-class="scrollbar-wrapper" :style="{ height: height - 190 +'px' }">
        <p class="list-item">
          <span class="list-label">考试时间：</span>
          <span v-if="examDetails.startTime" class="list-elem">
            {{ examDetails.startTime }} - {{ examDetails.endTime }}</span>
          <span v-else class="list-elem">随时都可以考试</span>
        </p>
        <p class="list-item">
          <span class="list-label">考试说明：</span>
          <span class="list-elem">{{ examDetails.remarks }}</span>
        </p>
        <p class="list-item">
          <span class="list-label">考试时长：</span>
          <span class="list-elem">{{ parseInt(examDetails.duration) / 60 }}分钟</span>
        </p>
        <p class="list-item">
          <span class="list-label">考试满分：</span>
          <span class="list-elem">{{ examDetails.fullPoint }}分</span>
        </p>
        <p class="list-item">
          <span class="list-label">考试及格分：</span>
          <span class="list-elem">{{ examDetails.passingPoint }}分</span>
        </p>
        <p class="list-item">
          <span class="list-label">考试规则：</span>
          <span class="list-elem">
            <p class="list-table">
              <el-table :data="examDetails.examDefinitionRulesVOList" border show-summary>
                <el-table-column prop="name" label="实训类型" width="180" />
                <el-table-column prop="num" label="题数" />
                <el-table-column prop="point" label="分值" />
                <el-table-column prop="chapterIdLong" label="总分" />
              </el-table>
            </p>
          </span>
        </p>
      </el-scrollbar>
    </div>
    <div class="btn-start">
      <el-button :loading="loading" type="primary" @click="exmaStart">开始考试</el-button>
    </div>
  </el-card>
</template>
<script>
import { examNotify } from '@/api/simulation';
import { getExamLessonDetail } from '@/api/management/exam';
import { generateExamList } from '@/api/management/userexam';
import { getPublishLessonDetail } from '@/api/jmap/lesson';
import { PermissionType } from '@/scripts/ConstDic';
import { getDetailList } from '@/api/management/dictionary';
import { mapGetters } from 'vuex';
import { launchFullscreen } from '@/utils/screen';
import { UrlConfig } from '@/router/index';
import WindowResizeHandler from '@/mixin/WindowResizeHandler';

export default {
	name: 'ExamDetailView',
	mixins: [
		WindowResizeHandler
	],
	data() {
		return {
			height: '',
			loading: false,
			examDetails: {
				lessonId: '',
				name: '',
				remarks: '',
				examDefinitionRulesVOList: [],
				startTime: '',
				endTime: '',
				fullPoint: '',
				passingPoint: '',
				duration: '',
				type: ''
			},
			typeList: [],
			examList: [],
			trainingOperateTypeMap: {}
		};
	},
	computed: {
		...mapGetters('trainingList', [
			'trainingList'
		])
	},
	watch: {
		'$route.params.examId': function (val) {
			this.loadInitPage(val);
		}
	},
	async mounted() {
		this.trainingOperateTypeMap = {};
		this.$Dictionary.stationControl().then(list => {
			this.trainingOperateTypeMap['01'] = list; // 控制权实训
		});
		this.$Dictionary.signalOperation().then(list => {
			this.trainingOperateTypeMap['02'] = list; // 信号机实训
		});
		this.$Dictionary.switchOperation().then(list => {
			this.trainingOperateTypeMap['03'] = list; // 道岔实训
		});
		this.$Dictionary.sectionOperation().then(list => {
			this.trainingOperateTypeMap['04'] = list; // 区段实训
		});
		this.$Dictionary.stationStandOperation().then(list => {
			this.trainingOperateTypeMap['05'] = list; // 站台实训
		});
		this.$Dictionary.trainPlanOperation().then(list => {
			this.trainingOperateTypeMap['06'] = list; // 行车计划实训
		});
		this.$Dictionary.trainOperation().then(list => {
			this.trainingOperateTypeMap['07'] = list; // 列车实训
		});
		await this.getList();
		this.loadInitPage(this.$route.params.examId);
	},
	methods: {
		resizeHandler: function () {
			this.height = this._clientHeight - 50;
		},
		async getList() {
			this.typeList = [];
			await getDetailList('training_type').then(res => {
				this.typeList = res.data;
			});
		},
		async loadInitPage(examId) {
			if (examId) {
				const res = await getExamLessonDetail(examId);
				this.examDetails = res.data;
				this.examDetails.examDefinitionRulesVOList.forEach((res, index) => {
					res.chapterIdLong = Number(res.num) * Number(res.point);
					this.typeList.forEach(v => {
						if (res.trainingType == v.code) {
							this.examDetails.examDefinitionRulesVOList[index].name = v.name;
							if (res.operateType) {
								this.trainingOperateTypeMap[res.trainingType].forEach(item => {
									if (item.code == res.operateType) {
										this.examDetails.examDefinitionRulesVOList[index].name = `${this.examDetails.examDefinitionRulesVOList[index].name}-${item.name}`;
										return;
									}
								});
							}
						}
					});
				});
				const resp = await generateExamList(this.examDetails.id);
				this.examList = resp.data.userExamQuestionsVOs;
				this.userExam = resp.data;
			}
		},
		buy() {
			this.loading = true;
			getPublishLessonDetail({ id: this.examDetails.lessonId }).then((res) => {
				this.$router.push({
					path: `${UrlConfig.exam.pay}/${this.examDetails.lessonId}`,
					query: { permissionType: PermissionType.EXAM, prdCode: res.data.prdCode, mapId: res.data.mapId }
				});
			}).catch(() => {
				this.$messageBox('获取课程详情失败');
				this.loading = false;
			});

		},
		async examDetail() {
			const data = this.examDetails;
			try {
				const response = await generateExamList(data.id);
				this.userExam = response.data;
				const list = response.data.userExamQuestionsVOs;
				await this.$store.dispatch('exam/setUsedTime', this.userExam.usedTime);
				await this.$store.dispatch('exam/setTotalTime', this.userExam.duration);
				await this.$store.dispatch('trainingList/setTrainingList', list);
			} catch (error) {
				// 判断是否有考试权限，如果没有权限则跳到购买页面，否则报错
				if (error.code === 500004) {
					this.$confirm('无此课程的考试权限，请前往购买！', '提示', {
						cancelButtonText: '取消',
						confirmButtonText: '确定',
						type: 'warning',
						center: true
					}).then(() => {
						this.buy();
					}).catch(() => { });
				} else if (error.code === 500005) {
					this.$messageBox('不在考试范围之内');
				} else {
					this.$messageBox(`${error.message}`);
				}
			}
		},
		exmaStart() {
			this.loading = true;
			this.examDetail();
			if (this.examList.length) {
				examNotify({ examId: this.$route.params.examId }).then(resp => {
					const query = {
						group: resp.data,
						trainingId: this.examList[0].trainingId,
						userExamId: this.userExam.id,
						examQuestionId: this.examList[0].id
					};
					this.$router.push({ path: `${UrlConfig.display}/exam`, query: query });
					launchFullscreen();
				}).catch(error => {
					this.loading = false;
					this.$messageBox(`创建仿真失败: ${error.message}`);
				});
			} else {
				this.loading = false;
			}
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    @import "src/styles/mixin.scss";

    .menu li {
        border-right: solid white 1px;
    }

    ul {
        line-height: 22px;
        margin: 5px;
    }

    .noList {
        text-align: center;
        padding-top: 20px;
        font-size: 20px;
    }

    .btn-buy {
        width: 100%;
        display: flex;
        justify-content: center;
        padding-right: 50px;
        transform: translateY(-30px);
    }

    ::-webkit-scrollbar {
        width: 10px;
        height: 10px;
    }

    /deep/ {
        .el-table__footer-wrapper {
            .is-leaf:nth-child(3) {
                font-size: 0;
            }
        }
    }

    .title {
        font-weight: bold
    }

    .list-item {
        font-size: 16px;
        margin-bottom: 20px;
    }

    .list-label {
        display: -moz-inline-box;
        display: inline-block;
        text-align: right;
        width: 120px;
    }

    .list-table {
        padding-top: 10px;
        padding-left: 120px;
        width: calc(100%);
    }

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

    .btn-start {
        position: relative;
        text-align: center;
        justify-content: center;
        transform: translateY(-20px);
    }
</style>
