<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">{{$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="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="goAnswerSheet" v-show="paperInfo.item.length">{{  $t('evaluation.paperList.goAnswerSheet') }}</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="goAnswerSheet" v-show="paperInfo.item.length">{{  $t('evaluation.paperList.goAnswerSheet') }}</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="isSetScore" :title="$t('evaluation.paperList.setPaperScore')" width="400px" class="related-point-modal" style="z-index:99999">
			<span>{{$t('evaluation.paperList.totalScore')}}</span>
			<InputNumber :max="200" :min="1" v-model="paperInfo.score" style="margin-left:20px"></InputNumber>
			<div slot="footer">
				<Button type="text" @click="isSetScore = false">{{$t('evaluation.cancel')}}</Button>
				<Button type="primary" @click="onSetScore">{{$t('evaluation.confirm')}}</Button>
			</div>
		</Modal>

		<!-- 设置试卷标题 -->
		<!--<Modal v-model="isSetPaperName" title="设置试卷名称" width="400px" class="related-point-modal" style="z-index:99999">
			<span>试卷名称</span>
			<Input v-model="paperInfo.name" style="margin:20px 0"></Input>
			<div slot="footer">
				<Button type="text" @click="isSetPaperName = false">取消</Button>
				<Button type="primary" @click="isSetPaperName = false">确定</Button>
			</div>
		</Modal>-->
	</div>
</template>
<script>
	import BaseExerciseList from '../components/BaseExerciseList'
	import BaseTypePie from '../components/BaseTypePie'
	import ExamPaperAnalysis from '@/view/learnactivity/ExamPaperAnalysis.vue'
	export default {
		components: {
			BaseExerciseList,
			ExamPaperAnalysis,
			BaseTypePie
		},
		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 {
				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: []
				},
				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,
				analysisColumns: [{
						title: '题型',
						key: 'name'
					},
					{
						title: '数量（占比）',
						key: 'value'
					}
				],
				analysisTableData: [],
				viewModel: 'list',
				paperDiff: 0

			}
		},
		created() {

		},
		methods: {
			goAnswerSheet(){
				this.$router.push({
					name: 'answerSheet',
					params: {
						paper: this.paperInfo
					}
				})
			},
			/**
			 * 标题切换
			 * @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('_paperInfo'))
			if (!paper) return
			// 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
			}
		},
		watch: {
			paper: {
				handler(newValue, oldValue) {
					this.paperInfo = newValue
					// localStorage.setItem('_paperInfo', JSON.stringify(newValue))
					this.paperDiff = newValue.item ? this.handleDiffCalc(newValue.item) : 4
				},
				deep: true
			}
		}
	}
</script>
<style src="../index/TestPaper.less" lang="less" scoped>
</style>
<style>
	.complete-line {
		padding: 0 45px;
		border-bottom: 2px solid rgb(128, 128, 128);
	}
</style>
