<template>
	<div class="paper-container">
		<div class="back-to-top flex-col-center" :title="$t('evaluation.backToTop')" v-if="isShowBackToTop"
			@click="handleBackToTop">
			<Icon type="ios-arrow-up" />
		</div>
		<div class="paper-main-wrap">
			<!-- 试卷内容 -->
			<div class="paper-content">
				<div class="paper-body">
					<!-- 试卷基础信息 -->
					<div class="paper-base-info" v-show="!isPreview">
						<div style="display: flex;">
							<div class="paper-info-items">
								<span class="base-info-item">{{$t('evaluation.paperList.paperScore')}}：<span
										class="analysis-info"
										style="cursor: pointer;">{{ paperInfo.score }}</span>{{$t('evaluation.paperList.score')}}</span>
								<span class="base-info-item" @click="onShowScoreTable"
									style="cursor: pointer;">{{$t('evaluation.paperList.alreadyScore')}}：<span
										class="analysis-info">{{ allocatedScore || 0 }}</span>{{$t('evaluation.paperList.score')}}</span>
							</div>
							<div class="paper-info-items">
								<span class="base-info-item">{{$t('evaluation.filter.diff')}}：
									<Rate allow-half v-model="paperInfo.item.length ? +paperDiff : 0" disabled />
								</span>
								<span class="base-info-item">{{$t('evaluation.paperList.itemCount')}}：<span
										class="analysis-info">{{ paperInfo.item ? paperInfo.item.length : 0 }}</span></span>
							</div>
						</div>
						<div v-if="isShowBaseInfo && !isExamPaper">
							<Button class="base-info-btn" type="info" @click="addNewModal = true"
								v-show="!isShowAnalysis">{{ $t('evaluation.index.addExercise') }}</Button>
							<Button class="base-info-btn" type="info" @click="onHandleToggle"
								v-show="paperInfo.item.length && !isShowAnalysis">{{ isAllOpen ? $t('evaluation.index.collapseAll') : $t('evaluation.index.openAll')}}</Button>
							<Button class="base-info-btn" type="info" @click="onSetScoreByType"
								v-show="paperInfo.item.length && !isShowAnalysis">{{$t('evaluation.exerciseList.typeScore')}}</Button>
							<!-- <Button class="base-info-btn" type="info" @click="onCleanPaper" v-show="paperInfo.item.length && !isShowAnalysis">{{$t('evaluation.paperList.cleanItems')}}</Button> -->
							<Button class="base-info-btn" type="info" @click="onViewModelChange"
								v-show="paperInfo.item.length && !isShowAnalysis">{{ `${ viewModel === 'type' ? this.$t('evaluation.paperList.orderByList') : this.$t('evaluation.paperList.orderByType') }` }}</Button>
							<Button class="base-info-btn" type="info" @click="isShowAnalysis = !isShowAnalysis"
								v-show="paperInfo.item.length">{{ isShowAnalysis ? this.$t('evaluation.paperList.paperDetails') : this.$t('evaluation.paperList.paperAnalysis')}}</Button>
							<Button class="base-info-btn" type="info" @click="downloadSheet" :loading="downLoading"
								v-show="paperInfo.item.length && paperInfo.id && paper.sheet">{{ $t('evaluation.paperList.goAnswerSheet') }}</Button>
							<Button class="base-info-btn" type="info" @click="goAnswerSheet"
								v-show="paperInfo.item.length && paperInfo.id">{{ paper.sheet ?  $t('evaluation.paperList.reCreateSheet') : $t('evaluation.paperList.createSheet') }}</Button>
						</div>
						<div v-if="isExamPaper">
							<Button class="base-info-btn" type="info" @click="onHandleToggle"
								v-show="paperInfo.item.length && !isShowAnalysis">{{ isAllOpen ? $t('evaluation.index.collapseAll') : $t('evaluation.index.openAll')}}</Button>
							<Button class="base-info-btn" type="info" @click="onViewModelChange"
								v-show="paperInfo.item.length && !isShowAnalysis">{{ `${ viewModel === 'type' ? this.$t('evaluation.paperList.orderByList') : this.$t('evaluation.paperList.orderByType') }` }}</Button>
							<Button class="base-info-btn" type="info" @click="isShowAnalysis = !isShowAnalysis"
								v-show="paperInfo.item.length && !isHideAnalysis">{{ isShowAnalysis ? this.$t('evaluation.paperList.paperDetails') : this.$t('evaluation.paperList.paperAnalysis')}}</Button>
							<Button class="base-info-btn" type="info" @click="downloadSheet" :loading="downLoading"
								v-show="paperInfo.item.length && paperInfo.id && paper.sheet">{{ $t('evaluation.paperList.goAnswerSheet') }}</Button>
							<Button class="base-info-btn" type="info" @click="goAnswerSheet"
								v-show="paperInfo.item.length && paperInfo.id">{{ paper.sheet ?  $t('evaluation.paperList.reCreateSheet') : $t('evaluation.paperList.createSheet') }}</Button>
						</div>
					</div>
					<!-- 试卷头部信息 -->
					<div class="paper-header flex-col-center">
						<p class="paper-title">{{paperInfo.name}}</p>
					</div>
					<!-- 试卷分析部分 -->
					<ExamPaperAnalysis :testPaper="paperInfo" v-if="isShowAnalysis" :hidePie="hidePie">
					</ExamPaperAnalysis>
					<!-- 题目类型及列表 -->
					<BaseExerciseList :paper="paperInfo" @dataUpdate="onListUpdate" v-show="!isShowAnalysis"
						ref="exList" :isShowTools="!isPreview" :isExamPaper="isExamPaper" @toggleChange="onToggleChange"
						@scoreUpdate="scoreUpdate"></BaseExerciseList>
				</div>
			</div>
		</div>

		<!-- 新建试题 -->
		<Modal v-model="addNewModal" :title="$t('evaluation.index.addExercise')" width="1000px"
			class="related-point-modal" footer-hide>
			<Tabs value="name1" name="newExerciseTab" @on-click="onTabChange">
				<TabPane label="手动出题" name="name1" tab="newExerciseTab">
					<BaseCreateChild @addFinish="onAddNewFinish" v-if="addNewModal"
						:curPeriodIndex="paperInfo.paperPeriod" :curSubjectIndex="paperInfo.paperSubject">
					</BaseCreateChild>
				</TabPane>
				<!-- <TabPane label="快速出题" name="name2" tab="newExerciseTab">
					<BasePasteTool></BasePasteTool>
				</TabPane> -->
			</Tabs>
		</Modal>

	</div>
</template>
<script>
	import ExamPaperAnalysis from '@/view/learnactivity/ExamPaperAnalysis.vue'
	import AnswerSheet from '@/view/answersheet/index.vue'
	export default {
		components: {
			ExamPaperAnalysis,
			AnswerSheet,
		},
		props: {
			paper: {
				type: Object,
				default: null
			},
			isShowTools: {
				type: Boolean,
				default: true
			},
			isPreview: {
				type: Boolean,
				default: false
			},
			isShowBaseInfo: {
				type: Boolean,
				default: true
			},
			isExamPaper: {
				type: Boolean,
				default: false
			},
			hidePie: {
				type: Boolean,
				default: false
			},
			isHideAnalysis: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				addNewModal: false,
				scoreTableModal: false,
				isShowAnswerSheet: false,
				isShowBackToTop: false,
				isAllOpen: false,
				isShowAnalysis: false,
				isSetPaperName: false,
				isSetScore: false,
				isSetRules: false,
				isShowSave: false,
				exersicesList: [],
				allocatedScore: 0,
				list: [],
				schoolInfo: {},
				paperInfo: {
					name: "",
					score: 100,
					answers: [],
					multipleRule: 1,
					item: [],
					paperSubject: 0,
					paperPeriod: 0
				},
				exersicesType: this.$GLOBAL.EXERCISE_TYPES(),
				exersicesDiff: this.$GLOBAL.EXERCISE_DIFFS(),
				exersicesField: this.$GLOBAL.EXERCISE_LEVELS(),
				diffColors: ['#32CF74', '#E8BE15', '#F19300', '#EB5E00', '#D30000'],
				filterType: '0',
				filterDiff: '0',
				filterSort: '0',
				pageSize: 5,
				pageNum: 1,
				totalNum: 100,
				allList: [],
				isShowAnswer: false,
				isShowPart: false,
				isShowConcept: false,
				isShowTitle: true,
				isShowInfo: false,
				downLoading:false,
				analysisColumns: [{
						title: '题型',
						key: 'name'
					},
					{
						title: '数量（占比）',
						key: 'value'
					}
				],
				analysisTableData: [],
				viewModel: 'type',
				paperDiff: 0

			}
		},
		methods: {
			onTabChange(val) {
				if (val === 'name1') {
					document.removeEventListener('paste')
				}
			},
			/* 下载Blob答题卡 */
			async downloadSheet() {
				console.log(this.paperInfo)
				this.downLoading = true
				let examId = this.paperInfo.examId
				let pdfName = `${this.paperInfo.name}-${this.paperInfo.sheetNo}.pdf`
				let path = examId ? `exam/${examId}/paper/${this.paperInfo.name}/` : `paper/${this.paperInfo.name}/`
				let curScope = examId ? this.paperInfo.examScope : this.paperInfo.scope
				let cntr = curScope === 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId
				let sasData = curScope === 'school' ? await this.$tools.getSchoolSas() : await this.$tools.getPrivateSas()
				let blobHost = this.$evTools.getBlobHost()
				let fullPath = blobHost + '/' + cntr + '/' + path + pdfName + sasData.sas
				const downloadRes = async () => {
				      let response = await fetch(fullPath); // 内容转变成blob地址
				      let blob = await response.blob();  // 创建隐藏的可下载链接
				      let objectUrl = window.URL.createObjectURL(blob);
				      let a = document.createElement('a');
				      a.href = objectUrl;
				      a.download = pdfName;
				      a.click()
				      a.remove(); 
					  this.downLoading = false
				   }
				downloadRes();
				console.log(fullPath);
			},
			goAnswerSheet() {
				if (!this.isExamPaper) {
					localStorage.setItem('c_edit_paper', JSON.stringify(this.paperInfo))
				}
				console.log(this.paperInfo)
				this.$router.push({
					name: 'answerSheet',
					params: {
						paper: this.paperInfo
					}
				})
			},
			onShowScoreTable() {
				this.$refs.exList.scoreTableModal = true
			},
			/* 新增题目回调 */
			onAddNewFinish(item) {
				console.log(item);
				sessionStorage.setItem('isSave', 0)
				this.paperInfo.item.push(item)
				this.addNewModal = false
			},
			/**
			 * 标题切换
			 * @param e
			 */
			titleChange(e) {
				this.paperInfo.name = e.target.innerHTML
			},

			handleBackToTop() {
				console.log(this)
				this.$EventBus.$emit('onBackToTop')
			},

			onSetMarkingRules() {
				this.isSetRules = false
			},

			onShowAnalysis() {
				this.isShowAnalysis = true
			},

			/** 切换全部展开与折叠 */
			onHandleToggle() {
				this.$refs.exList.onHandleToggle(this.isAllOpen)
				this.isAllOpen = !this.isAllOpen
			},

			/**
			 * exList的collapseList变化
			 * @param list
			 */
			onToggleChange(list) {
				this.isAllOpen = list.length !== 0
			},

			/** 返回试卷库 */
			onBackToBank() {
				this.$router.push({
					name: 'testPaperList',
					params: {
						tabName: 'paper'
					}
				})
			},

			/* 清空试卷试题 */
			onCleanPaper() {
				this.paperInfo.item = []
				this.$refs.exList.errorList = []
				this.$refs.exList.noAnswerList = []
				this.$EventBus.$emit('onPaperItemChange', [])
			},

			onSetScore() {
				this.isSetScore = false
				this.$refs.exList.exerciseList.map(item => item.score = 0)
			},

			/**
			 * 组件更新删除题目时的处理
			 * @param list
			 */
			onListUpdate(list) {
				this.paperInfo.item = list
			},

			/**
			 * 处理试题分析数据
			 * @param list 试题列表
			 */
			handleAnalysisData(list) {
				let that = this
				this.analysisTableData = []
				this.exersicesList = list // 给试题列表组件传的值
				this.paperInfo.item = list
				const groupList = this._.groupBy(list, 'type')
				this._.mapKeys(groupList, function(value, key) {
					that.analysisTableData.push({
						name: that.exersicesType[key],
						value: value.length
					})
				});
			},

			/** 重新挑题 */
			goToPickExercise() {
				this.$router.push({
					name: 'exercisesList',
					params: {
						paperInfo: this.paperInfo
					}
				})
			},

			/** 点击题型配分 */
			onSetScoreByType() {
				this.$refs.exList.onSetScoreByType()
			},


			/**
			 * 试卷的视图模式切换
			 * @param val
			 */
			onViewModelChange(val) {
				this.viewModel = this.viewModel === 'type' ? 'list' : 'type'
				this.$refs.exList.viewModel = this.viewModel
				this.$refs.exList.collapseList = []
				// this.$refs.exList.doRenderMathJax()
				this.$emit('onViewModelChange', this.viewModel)
			},

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

			scoreUpdate(score) {
				this.allocatedScore = this.paperInfo.score - score
			}



		},
		mounted() {
			// this.isShowSave = window.location.pathname === '/home/evaluation/testPaper'
			let paper = this.paper || this.$route.params.paper || JSON.parse(localStorage.getItem('c_edit_paper'))
			if (!paper || !paper.item) return
			console.log('xxxx', paper)
			this.$EventBus.$emit('getNewPaper', paper)
			// localStorage.setItem('_paperInfo', JSON.stringify(paper))
			this.paperInfo = paper // 自己页面的值
			this.paperDiff = paper.item ? this.handleDiffCalc(paper.item) : 0

		},
		computed: {
			isAuto() {
				return this.paperInfo.markConfig ? this.paperInfo.markConfig.auto : false
			},
			ruleType() {
				return this.paperInfo.markConfig ? this.paperInfo.markConfig.type : 0
			},
			isSchool() {
				return this.$route.name === 'newSchoolPaper'
			},
		},
		watch: {
			paper: {
				handler(newValue, oldValue) {
					if (newValue.item && newValue.item.length) {
						this.$nextTick(() => {
							console.log('TestPaper组件接受的paper', newValue)
							this.$EventBus.$emit('getNewPaper', newValue)
						})
						this.paperInfo = newValue
					}
					this.paperDiff = newValue.item ? this.handleDiffCalc(newValue.item) : 4
				},
				immediate: true,
				deep: true
			}
		}
	}
</script>
<style src="../index/TestPaper.less" lang="less" scoped>
</style>
<style>
	.ex-score-modal {
		font-family: "NotoSerif", "微软正黑体", "Microsoft JhengHei UI",
			"Microsoft JhengHei", Sans-serif;
	}

	.complete-line {
		padding: 0 45px;
		border-bottom: 2px solid rgb(128, 128, 128);
	}
</style>
