<template>
	<div class="pl-container" ref="plContainer">
		<!-- 条件筛选部分 -->
		<BaseFilter ref="baseFilter" @onChange="onFilterChange" :filterCounts="filterCounts" :isFilterPaper="isFilterPaper"  v-if="!isPreview"></BaseFilter>

		<!-- 空数据展示 -->
		<div v-if="paperList.length === 0" class="no-data-text">
			<img src="@/assets/icon/no_data.svg" width="120" />
			<span style="margin-top:15px;color:#808080">{{$t('evaluation.noData')}}</span>
		</div>

		<!-- 试卷列表页面 -->
		<div class="pl-content-wrap" v-else>
			<Loading :top="100" v-show="dataLoading" type="1" hideMask></Loading>
			<div style="width: 100%;" v-if="!isPreview">
				<div class="paper-item" v-for="(paper,index) in paperList" :key="index" @click="onPreviewPaper(paper)">
					<div class="paper-item-name">
						<span class="paper-item-tag" v-if="isSchool">{{ paper.subjectName }}</span>
						<span style="margin-left: 8px;">{{ paper.name }}</span>
					</div>
					<div class="paper-item-info">
						<span class="info-item" v-if="isSchool">{{$t('evaluation.paperList.usePeriod')}}：<span
								class="info-bold">{{ getPeriodName(paper.periodId) }}</span></span>
						<span class="info-item" v-if="isSchool">{{$t('evaluation.paperList.useGrade')}}：<span
								class="info-bold" v-for="(grade,gIndex) in paper.gradeIds"
								:key="gIndex">{{ getGradeName(paper.periodId,grade) }}
								<span v-show="gIndex !== paper.gradeIds.length - 1"> / </span></span></span>
						<span class="info-item">{{$t('evaluation.paperList.itemCount')}}：<span
								class="info-bold">{{ paper.scoring ? paper.scoring.length : 0 }}</span></span>
						<!-- <span class="info-item">难度系数：<span class="info-bold">{{ paper.item ? handleDiffCalc(paper.item) : 0 }}</span></span> -->
					</div>
					<div class="paper-item-tools" v-if="!chooseModel">
						<!-- <span class="paper-item-tools-edit" @click.stop="goToDownload(paper)">
							<Icon type="md-download" />
							<span>下载试卷</span>
						</span> -->
						<!-- <span class="paper-item-tools-edit" @click.stop="renderAnswerSheet(paper)">
							<Icon type="md-eye" />
							<span>预览答题卡</span>
						</span> -->
						<span class="paper-item-tools-edit" @click.stop="goToPaper(paper)"
							v-if="($access.can('admin.*||exercise-upd') || !isSchool)">
							<Icon type="ios-create" />
							<span>{{$t('evaluation.editItem')}}</span>
						</span>
						<span class="paper-item-tools-delete" @click.stop="onDeletePaper(paper)"
							v-if="($access.can('admin.*||exercise-upd') || !isSchool)">
							<Icon type="md-trash" />
							<span>{{$t('evaluation.deleteItem')}}</span>
						</span>
					</div>
					<div v-if="chooseModel" class="paper-item-select">
						<div @click.stop="onCheckPaper(paper)" v-if="!checkedPaperList.length || (checkedPaperList.length && !checkedPaperList.map(i => i.id).includes(paper.id))">
							<Icon type="md-add" />
							<span>选择试卷</span>
						</div>
						<div @click.stop="onCancelCheck(paper)" v-else>
							<Icon type="md-checkmark-circle" color="#32b67b"/>
							<span>已选择</span>
						</div>
						
					</div>
				</div>

				<!-- 底部分页区域 -->
				<Page :total="totalNum" show-sizer show-total :page-size="pageSize" :current="pageNum"
					@on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="[10,20,30,40]" />
			</div>
			
			<!-- 预览试卷部分 -->
			<div class="pl-review-wrap animated fadeIn" v-if="isPreview">
				<div class="pl-review-wrap-left">
					<TestPaper :paper="evaluationInfo" isExamPaper hidePie></TestPaper>
				</div>

				<div class="pl-review-wrap-right">
					<h2>{{$t('evaluation.paperList.paperAnalysis')}}</h2>
					<p style="margin-bottom: 20px;margin-top: 10px;">
						（{{$t('evaluation.paperList.totalScore')}}：{{ evaluationInfo.score }}
						{{$t('evaluation.paperList.score')}}）</p>
					<BaseTypePie :echartsData="evaluationInfo"></BaseTypePie>
					<BaseObjectivePie :echartsData="evaluationInfo"></BaseObjectivePie>
					<BaseDiffPie :echartsData="evaluationInfo"></BaseDiffPie>
					<BasePointPie :echartsData="evaluationInfo"></BasePointPie>
				</div>
			</div>
			
			<!-- 预览答题卡部分 -->
			<!-- <div class="pl-answersheet-wrap animated fadeIn" v-if="isShowSheet">
				<AnswerSheet></AnswerSheet>
			</div> -->
		</div>
		
		<Modal v-model="isShowDownLoad" width="800px"  title="下载试卷" class-name="preview-modal">
			<DownloadPaper :paper="fullPaperJson"></DownloadPaper>
		</Modal>
		
<!-- 		<Modal v-model="isShowSheet" width="800px"  title="答题卡" class-name="preview-modal" >
			<div v-if="isShowSheet">
				<AnswerSheet></AnswerSheet>
			</div>
		</Modal> -->

	</div>
</template>
<script>
	import Loading from '@/common/Loading.vue'
	import BaseFilter from '../components/BaseFilter'
	import BaseImport from '../components/BaseImport'
	import TestPaper from '../index/TestPaper.vue'
	import AnswerSheet from '../../answersheet/index.vue'
	export default {
		props:{
			chooseModel:{
				type:Boolean,
				default:false
			}
		},
		components: {
			Loading,
			BaseFilter,
			BaseImport,
			TestPaper,
			AnswerSheet
		},
		data() {
			return {
				checkedPaperList:[],
				isShowSheet:false,
				containerClient: null,
				schoolCode: '',
				totalNum: 0,
				pageSize: 10,
				pageNum: 1,
				dataLoading: false,
				randomModal: false,
				isFilterPaper: true,
				paperList: [],
				periodList: [],
				gradeList: [],
				subjectList: [],
				filterParams: {},
				findCountParams: {},
				originList: [],
				schoolInfo: {},
				filterSort: 'createTime',
				evaluationInfo: null,
				isPreview: false,
				paperInfo: {
					name: "",
					score: 100,
					item: []
				},
				fullPaperJson: {
					id:'0'
				},
				isShowDownLoad: false,
				flag:false,
				filterCounts:{
					gradeCountArr:[],
					subjectCountArr:[],
					periodCountArr:[]
				},
				isShowSchoolBank:false
			}
		},
		created() {
			// this.getPaperList()
			// this.doFilter()
			this.isShowSchoolBank = this.$route.name === "schoolBank";

		},
		methods: {
			
			onCheckPaper(item){
				console.log(item)
				this.checkedPaperList.push(item)
			},
			
			onCancelCheck(item){
				this.checkedPaperList.splice(this.checkedPaperList.indexOf(item),1)
			},

			async onPreviewPaper(paper) {
				if(this.chooseModel){
					this.$emit('previewPaper',paper)
					return
				}
				this.dataLoading = true
				let curPaper = paper
				try {
					// 获取完整试卷数据再跳转编辑页面
					let fullPaperJson = this.fullPaperJson.id === curPaper.id ? this.fullPaperJson : await this.$evTools.getFullPaper(curPaper)
					this.fullPaperJson = fullPaperJson
					fullPaperJson.code = curPaper.code
					let paper = fullPaperJson
					let schoolInfo = null
					if (paper.scope === 'school') {
						schoolInfo = await this.getSchoolBaseInfo()
						this.subjectList = schoolInfo ? this.schoolInfo.period.filter(i => i.id === paper.periodId)[0]
							.subjects : []
					}
					this.evaluationInfo = {
						id: paper.id,
						name: paper.name,
						code: paper.code,
						type: paper.scope,
						paperPeriod: schoolInfo && paper.scope === 'school' ? this.schoolInfo.period.map(i => i.id)
							.indexOf(paper.periodId) : null,
						paperGrade: schoolInfo && paper.scope === 'school' ? paper.gradeIds : [],
						paperSubject: schoolInfo && paper.scope === 'school' ? this.subjectList.map(i => i.id)
							.indexOf(paper.subjectId) : [],
						score: paper.score,
						item: paper.item,
						multipleRule: paper.multipleRule,
						startTime: 0,
						endTime: 0,
						createType: 'manual'
					}
					this.isPreview = true
					this.$emit('onPaperClick')
					this.dataLoading = false
				} catch (e) {
					console.log(e)
					this.dataLoading = false
					this.$Message.error(this.$t('evaluation.paperList.paperErrorTip'))
				}
			},

			/** 获取当前学校基础数据 */
			getSchoolBaseInfo() {
				return new Promise((r, j) => {
					this.$store.dispatch("user/getSchoolProfile").then((res) => {
						let schoolBaseInfo = res.school_base;
						if (schoolBaseInfo) {
							r(schoolBaseInfo)
						} else {
							r(null)
						}
					});
				})

			},

			/** 执行筛选条件获取数据 */
			doFilter(filterKey) {
				this.dataLoading = true
				this.isPreview = false
				this.getPaperList(this.filterParams,filterKey)
			},

			onFilterChange(val) {
				let filterParams = val.params
				let filterKey = val.key
				let isSchool = filterParams.code === this.$store.state.userInfo.schoolCode
				this.filterParams = {
					'@DESC': filterParams.filterSort,
					'code': filterParams.code,
					'scope': isSchool ? 'school' : 'private',
					'periodId': isSchool && this.flag ? filterParams.periodId[0] : [],
					"gradeIds[*]": isSchool ? filterParams.gradeIds : [],
					'subjectId': isSchool ? filterParams.subjectId : []
				}
				this.doFilter(filterKey)
			},

			/** 获取试卷列表 */
			getPaperList(params,filterKey) {
				let that = this
				this.$api.learnActivity.FindExamPaper(params).then(async res => {
					let list = res.papers
					if((!this.flag && this.periodList.length && this.filterParams.code === this.$store.state.userInfo.schoolCode) || (this.flag && !this.isShowSchoolBank && this.filterParams.code === this.$store.state.userInfo.schoolCode)){
						this.filterCounts.periodCountArr = this.getPeriodCount(res.papers)
						list = res.papers.filter(i => i.periodId === this.periodList[0].id)
						this.flag = true
					}
					this.getItemsCount(list,filterKey)
					this.paperList = list
					this.originList = list
					this.totalNum = list.length
					this.pageChange(1)
					setTimeout(() => {
						that.dataLoading = false
					}, 1000)
				}).catch(err => {
					console.log(err)
					setTimeout(() => {
						this.$Message.error(this.$t('evaluation.paperList.paperErrorTip'))
						that.dataLoading = false
					}, 1000)
				})
			},
			
			/* 获取所有学段下的试题总数 */
			getPeriodCount(papers){
				let periodIdArr = this.periodList.map(i => i.id)
				let periodCountArr = periodIdArr.map(i => {
					return papers.filter(j => j.periodId === i).length
				})
				return periodCountArr
			},
			
			/* 获取试题的年级、科目的数量统计 */
			getItemsCount(papers,filterKey){
				if(filterKey !== 'grade'){
					let gradeIdArr = this.$refs.baseFilter.gradeList.map((i,index) => index)
					this.filterCounts.gradeCountArr = gradeIdArr.map(i => {
						return papers.filter(j => j.gradeIds && j.gradeIds.includes(i + '')).length
					})
				}
				if(filterKey !== 'subject'){
					let subjectIdArr = this.$refs.baseFilter.subjectList.map(i => i.id)
					this.filterCounts.subjectCountArr = subjectIdArr.map(i => {
						return papers.filter(j => j.subjectId === i).length
					})
				}
			},

			/**
			 * 点击查看试卷详情
			 * @param paper
			 */
			async goToPaper(paper) {
				this.dataLoading = true
				try {
					// 获取完整试卷数据再跳转编辑页面
					let fullPaperJson = this.fullPaperJson.id === paper.id ? this.fullPaperJson : await this.$evTools.getFullPaper(paper)
					this.fullPaperJson = fullPaperJson
					fullPaperJson.code = paper.code
					console.log(fullPaperJson)
					this.dataLoading = false
					this.$router.push({
						name: paper.scope === 'school' ? 'newSchoolPaper' : 'newPrivatePaper',
						params: {
							paper: fullPaperJson
						}
					})
				} catch (e) {
					this.$Message.error(this.$t('evaluation.paperList.paperErrorTip'))
					this.dataLoading = false
				}
			},

			/* 下载试卷 */
			async goToDownload(paper) {
				let fullPaperJson = this.fullPaperJson.id === paper.id ? this.fullPaperJson : await this.$evTools.getFullPaper(paper)
				this.fullPaperJson = fullPaperJson
				this.isShowDownLoad = true
				console.log('要下载的试卷', fullPaperJson)
			},
			
			// async renderAnswerSheet(paper){
			// 	this.dataLoading = true
			// 	try{
			// 		let fullPaperJson = this.fullPaperJson.id === paper.id ? this.fullPaperJson : await this.$evTools.getFullPaper(paper)
			// 		// this.isShowSheet = true
			// 		this.dataLoading = false
			// 		this.$router.push({
			// 			name: 'answerSheet',
			// 			params: {
			// 				paper: fullPaperJson
			// 			}
			// 		})
			// 	}catch(e){
			// 		this.$Message.error(this.$t('evaluation.paperList.paperErrorTip'))
			// 		this.dataLoading = false
			// 	}
				
			// },

			/**
			 * 删除试卷
			 * @param item
			 */
			onDeletePaper(item) {
				this.$Modal.confirm({
					title: this.$t('evaluation.newExercise.modalTip'),
					content: this.$t('evaluation.paperList.confirmDelete'),
					onOk: async () => {
						this.dataLoading = true
						this.$api.learnActivity.DeleteExamPaper({
							id: item.id,
							code: item.code,
							scope: item.scope
						}).then(async res => {
							if (!res.error) {
								this.deleteBlobPrefix(item).then(r => {
									this.$Message.success(this.$t('evaluation.deleteSuc'))
									this.doFilter()
								})
							} else {
								this.$Message.warning(this.$t('evaluation.deleteFail'))
							}
						}).catch(err => {
							console.log(err)
							this.$Message.warning(this.$t('evaluation.deleteFail'))
						})
					}
				})
			},

			/* 删除blob指定试题目录下所有 */
			deleteBlobPrefix(paper) {
				return new Promise((resolve, reject) => {
					this.$api.blob.deletePrefix({
						"cntr": paper.scope === 'school' ? this.$store.state.userInfo.schoolCode : this
							.$store.state.userInfo.TEAMModelId,
						"prefix": "paper/" + paper.name
					}).then(
						(res) => {
							if (!res.error) {
								resolve(200)
							} else {
								resolve(500)
							}
						},
						(err) => {
							reject(err)
						}
					)
				})
			},

			/**
			 * 切换页码操作
			 * @param page
			 */
			pageChange(page) {
				this.pageNum = page
				let start = this.pageSize * (page - 1)
				let end = this.pageSize * page
				// 拿到当前页码需要展示的数据
				this.paperList = this.originList.slice(start, end)
				this.$emit('onBackToTop')
				// this.doFilter()
			},

			/**
			 * 切换每页显示数量
			 * @param val
			 */
			pageSizeChange(val) {
				this.pageSize = val
				this.pageChange(1)
			},

			/** 前往试卷页面 */
			goCreatePaper() {
				this.$router.push({
					name: 'testPaper',
					params: {
						paper: this.paperInfo
					}
				})
			},

			/** 前往手动挑题页面 */
			goPickExercises() {
				this.$router.push({
					name: 'exercisesList'
				})
			},

			/**
			 * 根据SubjectCode换取SubjectName
			 * @param code
			 */
			getPeriodName(code) {
				return code && this.$store.state.user.schoolProfile.school_base ? this.$store.state.user.schoolProfile.school_base
					.period.filter(i => i.id === code)[0].name : this.$t('evaluation.noData')
			},

			/**
			 * 根据GradeCode换取GradeName
			 * @param code
			 */
			getGradeName(periodId, code) {
				return this.$store.state.user.schoolProfile.school_base ? this.$store.state.user.schoolProfile.school_base
					.period.filter(i => i.id === periodId)[0].grades[+code] : this.$t('evaluation.noData')
			},

			/**
			 * 计算试卷题目平均难度
			 * @param arr 试题集合
			 */
			handleDiffCalc(arr) {
				let levelArr = arr.map(i => i.level)
				return this._.meanBy(levelArr).toFixed(1)
			}

		},
		async mounted() {
			let schoolProfile = await this.$store.dispatch('user/getSchoolProfile')
			if (schoolProfile.school_base) {
				this.schoolInfo = schoolProfile.school_base
				this.periodList = this.schoolInfo.period
			}


		},
		computed: {
			isSchool() {
				return this.filterParams.scope === 'school' ? true : false
			}
		}
	}
</script>
<style src="./TestPaperList.less" lang="less" scoped>
</style>

<style>
	
	.preview-modal .ivu-modal-body{
		/* height: 650px; */
		overflow: scroll;
	}
	
	.pl-content-wrap .ivu-page {
		display: flex;
		flex-direction: row;
		justify-content: center;
		margin: 20px 0;
		color: #fff;
	}
	
	.pl-review-wrap-left .paper-base-info{
		top: 50px !important;
	}

	.pl-container .ivu-checkbox-inner {
		display: none !important;
	}

	.random-pick-modal .question-condition-wrap .question-condition-item .condition-label,
	.random-pick-modal .question-condition-wrap .question-condition-item {
		color: #000;
		font-size: 14px;
	}

	.random-pick-modal .question-num-item .ivu-select-selection {
		color: #333333;
	}

	.random-pick-modal .question-num-item .ivu-input-number,
	.random-pick-modal .question-num-item .ivu-input-number-small input {
		color: #000;
	}

	.random-pick-modal .auto-create-wrap {
		background: transparent;
	}

	.random-pick-modal .auto-create-name {
		color: #515a6e;
		text-align: left;
		font-size: 14px;
		font-weight: normal;
		margin-top: 0;
	}

	.random-pick-modal .question-condition-wrap .ivu-btn {
		height: 40px;
		line-height: 40px;
		margin-top: 0;
	}

	.random-pick-modal .question-condition-wrap {
		overflow: hidden;
	}

	.random-pick-modal .ivu-tag {
		background: transparent !important;
	}

	.random-pick-modal .ivu-tag-color-white {
		color: #515a6e !important;
	}

	.random-pick-modal .ivu-tag .ivu-icon-ios-close {
		color: #515a6e !important;
	}
</style>
