<template>
  <el-card>
    <div v-if="lessonName" slot="header" style="text-align: center;">
      <b>课程名称： {{ lessonName }}</b>
    </div>
    <div :style="{ height: height +'px' }">
      <el-scrollbar wrap-class="scrollbar-wrapper" style="">
        <QueryListPage
          ref="queryListPage"
          :pager-config="pagerConfig"
          :query-form="queryForm"
          :query-list="queryList"
          style="height: 100%;"
        />
      </el-scrollbar>
    </div>
  </el-card>
</template>

<script>
import { getExamList, deleteExam, setExamEfficacy, setExamEffectivey } from '@/api/management/exam';
import { getPublishLessonTree } from '@/api/jmap/lesson';
import { UrlConfig } from '@/router/index';
import WindowResizeHandler from '@/mixin/WindowResizeHandler';

export default {
	name: 'List',
	mixins: [
		WindowResizeHandler
	],
	data() {
		return {
			BizTypeList: [],
			OrderTypeList: [],
			PayTypeList: [],
			PayStatusList: [],
			OrganizationList: [],
			EffectiveTypeList: [],
			userId: this.$store.state.user.id,
			pagerConfig: {
				pageSize: 'pageSize',
				pageIndex: 'pageNum'
			},
			lessonName: '',
			height: '',
			queryForm: {
				labelWidth: '120px',
				queryObject: {
					'lessonId': {
						type: this.$route.query.lessonId ? '' : 'select',
						label: '课程',
						config: {
							data: []
						}
					},
					'name': {
						type: 'text',
						label: '试卷名称'
					},
					'creatorName': {
						type: 'text',
						label: '创建人'
					}
				},
				reset: !this.$route.query.lessonId
			},
			queryList: {
				query: this.queryFunction,
				selectCheckShow: false,
				indexShow: true,
				columns: [
					{
						title: '课程名称',
						prop: 'lessonId',
						type: 'tag',
						show: !this.$route.query.lessonId,
						columnValue: (row) => { return this.convertField(row.lessonId, this.OrganizationList, ['id', 'name']); },
						tagType: (row) => { return ''; }
					},
					{
						title: '试卷名称',
						prop: 'name'
					},
					{
						title: '创建人',
						prop: 'creatorName'
					},
					{
						title: '是否试用',
						prop: 'trial',
						type: 'tag',
						columnValue: (row) => { return this.$ConstSelect.translate(row.trial, 'Whether'); },
						tagType: (row) => {
							switch (row.trial) {
							case true: return 'success';
							case false: return 'danger';
							}
						}
					},
					{
						title: '时长',
						prop: 'duration',
						type: 'tag',
						columnValue: (row) => { return this.durationField(row.duration); },
						tagType: (row) => { return ''; }
					},
					{
						title: '考试时间',
						prop: 'startTime',
						type: 'formatter',
						format: 'yyyy-MM-dd hh:ss'
					},
					{
						title: '满分',
						prop: 'fullPoint'
					},
					{
						title: '及格分',
						prop: 'passingPoint'
					},
					{
						title: '状态',
						prop: 'status',
						type: 'tag',
						columnValue: (row) => { return this.convertField(row.status, this.EffectiveTypeList, ['value', 'label']); },
						tagType: (row) => {
							switch (row.status) {
							case '1': return 'success';
							default: return 'danger';
							}
						}
					},
					{
						type: 'button',
						title: '操作',
						width: '300',
						buttons: [
							{
								name: '快速创建',
								type: 'primary',
								handleClick: this.handleDistribute,
								showControl: (row) => { return row.bizType !== '02'; }
							},
							{
								name: '修改',
								type: 'primary',
								showControl: (row) => { return row.creatorId == this.userId; },
								handleClick: this.handleUpdate
							},
							{
								name: '下架',
								type: 'warning',
								handleClick: this.handleEfficacy,
								showControl: (row) => {
									return (this.$route.query.lessonId ? row.creatorId == this.userId : true) && row.status == 1;
								}
							},
							{
								name: '上架',
								type: 'primary',
								handleClick: this.handleEffective,
								showControl: (row) => {
									return (this.$route.query.lessonId ? row.creatorId == this.userId : true) && row.status != 1;
								}
							},
							{
								name: '删除',
								type: 'danger',
								handleClick: this.deleteList,
								showControl: (row) => { return row.creatorId == this.userId; }
							}
						]
					}
				],
				actions: [
					{ text: '新增', btnCode: 'employee_insert', handler: this.handleNormalAdd }
				]
			}
		};
	},
	created() {
		this.loadInitData();
	},
	mounted() {
		this.$store.dispatch('app/handleCourseDetail', {});
		this.$store.dispatch('app/handleRuleList', []);
	},
	methods: {
		convertList(FromList, ToList, ChecktypeFunction) {
			if (FromList) {
				ToList.length = 0;
				FromList.forEach(elem => {
					if (ChecktypeFunction(elem)) {
						ToList.push({ value: elem.code, label: elem.name });
					}
				});
			}
		},
		resizeHandler: function () {
			if (/\/exam\//.test(`${this.$route.path}`)) {
				this.height = this._clientHeight - 50;
			}
		},
		loadInitData() {
			this.queryForm.queryObject.lessonId.config.data.length = 0;
			getPublishLessonTree({ mapId: '' }).then(response => {
				this.OrganizationList = response.data;
				this.OrganizationList.forEach(elem => {
					if (elem.id == this.$route.query.lessonId) {
						this.lessonName = elem.name;
					}
					this.queryForm.queryObject.lessonId.config.data.push({ value: elem.id, label: elem.name });
				});
			});

			this.$Dictionary.effectiveType().then(list => {
				this.convertList(list, this.EffectiveTypeList, elem => {
					return true;
				});
			});
		},
		convertField(fieldValue, enumList, converFormat) {
			if (converFormat && converFormat.length >= 2) {
				const value = converFormat[0];
				const label = converFormat[1];
				for (let i = 0; enumList && i < enumList.length; i++) {
					if ('' + fieldValue === '' + enumList[i][value]) {
						return enumList[i][label];
					}
				}
			}
		},
		durationField(fieldValue) {
			if (fieldValue) {
				const time = Number(fieldValue) / 60;
				return `${time}分钟`;
			}
		},
		queryFunction(params) {
			if (this.$route.query.lessonId) {
				params.lessonId = this.$route.query.lessonId;
			}
			return getExamList(params);
		},
		handleNormalAdd() {
			const path = `${this.$route.path.match(/(\/.*)\/examRule/)[1]}${UrlConfig.examRuleDraft}`;
			const lessonId = this.$route.query.lessonId ? this.$route.query.lessonId : 0;
			this.$router.push({ path: `${path}/add/0/${lessonId}` });
		},
		handleUpdate(index, data) {
			const path = `${this.$route.path.match(/(\/.*)\/examRule/)[1]}${UrlConfig.examRuleDraft}`;
			const lessonId = this.$route.query.lessonId ? this.$route.query.lessonId : 0;
			this.$router.push({ path: `${path}/edit/${data.id}/${lessonId}` });
		},
		handleDistribute(index, data) {
			const path = `${this.$route.path.match(/(\/.*)\/examRule/)[1]}${UrlConfig.examRuleDraft}`;
			const lessonId = this.$route.query.lessonId ? this.$route.query.lessonId : 0;
			this.$router.push({ path: `${path}/add/${data.id}/${lessonId}` });
		},
		// 删除
		deleteList(index, data) {
			this.$confirm('此操作将删除该试卷, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				deleteExam(data).then(res => {
					this.queryList.reload();
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
				}).catch(res => {
					if (res.code == '500009') {
						this.$message({ type: 'warning', message: '该试卷已被使用，不能删除' });
					} else {
						this.$message({ type: 'error', message: '删除异常，请联系管理员' });
					}
				});
			}).catch(() => { });
		},
		handleEfficacy(index, data) {
			this.$confirm('此操作将此试卷下架?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				setExamEfficacy(data).then(res => {
					this.queryList.reload();
					this.$message({
						type: 'success',
						message: '设置成功!'
					});
				}).catch(res => {
					this.$message({ type: 'warning', message: '设置失败,' + res.message });
				});
			}).catch(() => { });
		},
		handleEffective(index, data) {
			this.$confirm('此操作将此试卷上架?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				setExamEffectivey(data).then(res => {
					this.queryList.reload();
					this.$message({
						type: 'success',
						message: '设置成功!'
					});
				}).catch(res => {
					this.$message({ type: 'warning', message: '设置失败,' + res.message });
				});
			}).catch(() => { });
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    /deep/ {
        .is-always-shadow {
            box-shadow: none;
            border-bottom: none;
        }
    }
</style>
