<template>
	<div class="ev-cp-list-container" style="width: 100%; margin: 0 auto">
		<!-- 筛选部分结束 -->
		<!-- 题目列表部分 -->
		<Loading :top="100" v-show="dataLoading" hideMask></Loading>
		<div v-if="exerciseList.length === 0" class="no-data-text">
			<img src="@/assets/icon/no_data_evaluation.png" width="120" />
			<span style="margin-top: 15px; color: #808080">{{$t('evaluation.noData')}}</span>
		</div>
		<div class="cp-content-wrap" ref="mathJaxContainer" v-else>
			<div class="cp-exercise-item" v-for="(item, index) of exerciseList" :key="index">
				<!-- 题干部分 -->
				<div class="item-question"  @click="onQuestionToggle(index, item.id, $event)">
					<div>
						<div class="item-question-order">
							{{ pageSize * (pageNum - 1) + index + 1 }} :
						</div>
						<div class="item-question-text" v-html="item.question"></div>
					</div>
					<span class="item-btn-toggle">
						<Icon :type="collapseList.indexOf(index) > -1 ? 'ios-arrow-dropup' : 'ios-arrow-dropdown' " />
					</span>
				</div>
				<!-- 选项部分 -->
				<div v-for="(option, optionIndex) in item.option" :key="optionIndex" class="item-options"  @click="onQuestionToggle(index, item.id, $event)">
					<div class="item-option-content">
						<div class="item-option-order">
							<!-- {{ String.fromCharCode(64 + parseInt(optionIndex + 1)) }} : -->
							{{ option.code }} :
						</div>
						<div class="item-option-text" v-html="option.value"></div>
					</div>
				</div>
				<div class="exercise-item-children" v-if="item.children.length">
					<BaseChild :children="item.children" :isShowAnalysis="isShowAnalysis" :analysisJson="getChildAnalysisJson(item)" :optionRate="getChildOptionRate(item)"></BaseChild>
				</div>
				<transition name="slide" v-if="item.type !== 'compose'">
					<div v-if="collapseList.includes(exerciseList.indexOf(item))" class="toggle-area">
						<div>
							<!-- 答案展示部分 -->
							<div class="item-explain">
								<span class="explain-title">【{{$t('evaluation.answer')}}】</span>
								<div class="item-explain-details">
									<!-- 问答题答案 -->
									<div v-if="item.type === 'subjective' || item.type === 'complete' || item.type === 'connector' || item.type === 'correct'">
										<span v-for="(answer, index) in item.answer" :key="index" v-html="item.answer.length ? answer : $t('evaluation.noAnswer')"></span>
									</div>
									<!-- 问答题答案 -->
									<div v-else-if="item.type === 'judge'">
										<span>{{ item.answer.length ? (item.answer[0] === 'A' ? $t('evaluation.isTrue') : $t('evaluation.isFalse')) : $t('evaluation.noAnswer') }}</span>
									</div>
									<!-- 其余题型答案 -->
									<div v-else>
										<span :class="[ item.type === 'complete' ? 'item-answer-item' : '' ]" v-for="(answer, index) in item.answer" :key="index">{{ answer }}</span>
									</div>
								</div>
							</div>
							<!-- 解析部分 -->
							<div class="item-explain">
								<span class="explain-title">【{{$t('evaluation.explain')}}】</span>
								<div class="item-explain-details">
									<span v-html="item.explain || $t('evaluation.noExplain')"></span>
								</div>
							</div>
							<!-- 知识点部分 -->
							<div class="item-explain">
								<span class="explain-title">【{{$t('evaluation.knowledgePoints')}}】</span>
								<div class="item-explain-details">
									<span v-if="!item.knowledge || !item.knowledge.length">{{$t('evaluation.noPoints')}}</span>
									<div v-else>
										<span v-for="(point, pointIndex) in item.knowledge" class="item-point-tag" :key="pointIndex">
											{{ point }}
										</span>
									</div>
								</div>
							</div>
							<!-- 认知层次部分 -->
							<div class="item-explain">
								<span class="explain-title" :style="{ color:isShowAnalysis ? '#099209' : '#10abe7' }">【{{$t('evaluation.field')}}】</span>
								<div class="item-explain-details">
									<span>{{ exersicesField[item.field - 1] }}</span>
								</div>
							</div>
							<div class="item-explain" v-if="isShowAnalysis">
								<span class="explain-title">【{{ $t('totalAnalysis.showAnalysis') }}】</span>
								<div class="item-explain-details">
									<AnalysisItemTable :analysisJson="analysisJson[index]"></AnalysisItemTable>
									</br>
									<OptionsTable v-if="item.type === 'single' || item.type === 'multiple' || item.type === 'judge'"
									 :options="item.option.map(i => i.code)" :optionRate="optionRate[index]"
									 :answer="item.answer"
									 ></OptionsTable>
									 </br>
									 <Row>
										 <Col span="12" v-if="item.type === 'single' || item.type === 'multiple' || item.type === 'judge'">
											<BaseRateLine :ids="'R1R6' + index" :echartsData="getOptionLineData(item,index)"></BaseRateLine>
										 </Col>
										 <Col span="12">
										 	<BaseLine :ids="'rateLine' + index" :echartsData="analysisJson[index]"></BaseLine>
										 </Col>
									 </Row>
									 
								</div>
							</div>
						</div>
						<!-- 如果是综合题 则加载子题渲染组件 -->
						<!-- <div v-else>
							<BaseChild :children="item.children"></BaseChild>
						</div> -->
					</div>
				</transition>
				
				<!-- 底部题目操作栏 -->
				<div class="item-tools">
					<span class="item-tools-info">{{$t('evaluation.filter.type')}}：{{ exersicesType[item.type] }}</span>
					<span class="item-tools-info">{{$t('evaluation.filter.diff')}}：{{ exersicesDiff[item.level - 1] }}</span>
					<span class="item-tools-info">{{$t('evaluation.filter.level')}}：{{ exersicesField[item.field - 1] }}</span>
					<span class="item-tools-info">{{$t('evaluation.filter.useCount')}}：{{ item.usageCount || 0 }} {{ $t('unit.text4') }}</span>
					<!-- <span class="item-tools-info">{{$t('evaluation.updateTime')}}：{{ $tools.formatTime(item.createTime)  || 0 }} </span> -->
					<Button type="info" v-if="!isAnalysis" :style="{backgroundColor:selectList.map(i => i.id).indexOf(item.id) > -1 ? '#bbbbbb' : '#2db7f5'}"
					 @click.stop="onSelectItem(item,index)">{{ selectList.map(i => i.id).indexOf(item.id) > -1 ? $t('evaluation.remove') : $t('evaluation.choose')}}</Button>
				</div>
			</div>
		</div>


		<!-- 底部分页区域 -->
		<Page :total="totalNum" v-if="!isAnalysis" show-sizer show-total :page-size="pageSize" :current="pageNum" @on-page-size-change="pageSizeChange"
		 @on-change="pageChange" :page-size-opts="[5, 10, 15, 20]" />
	</div>
</template>
<script>
	import blobTool from "@/utils/blobTool.js";
	import AnalysisItemTable from '@/components/evaluation/AnalysisItemTable'
	import OptionsTable from '@/components/evaluation/OptionsTable'
	import BaseLine from '@/components/student-analysis/total/BaseLine.vue'
	import BaseRateLine from '@/components/student-analysis/total/BaseRateLine.vue'
	export default {
		components:{AnalysisItemTable,OptionsTable,BaseRateLine,BaseLine},
		props:{
			propsList:{
				type:Array,
				default:() => {
					return []
				}
			},
			analysisJson:{
				type:Array,
				default:() => {
					return []
				}
			},
			optionRate:{
				type:Array,
				default:() => {
					return []
				}
			},
			flatIds:{
				type:Array,
				default:() => {
					return []
				}
			},
			selQue: {
			    type: Array,
			    default: () => {
			        return []
			    }
			},
			isAnalysis:{
				type:Boolean,
				default:false
			},
			isShowAnalysis: {
				type: Boolean,
				default: false
			},
			examScope:{
				type:String,
				default:null
			}
		},
		data() {
			return {
				examPropScope:null,
				dataLoading: false,
				exersicesType: this.$GLOBAL.EXERCISE_TYPES(),
				exersicesDiff: this.$GLOBAL.EXERCISE_DIFFS(),
				exersicesField: this.$GLOBAL.EXERCISE_LEVELS(),
				diffColors: ["#32CF74", "#E8BE15", "#F19300", "#EB5E00", "#D30000"],
				totalNum: 0,
				isShowAnswer: true,
				importLoading: false,
				pageSize: 5,
				pageNum: 1,
				currentPage: 1,
				collapseList: [],
				selectList:[],
				originData: [],
				exerciseList:[],
			};
		},
		created() {
			console.log('接收到的',this.analysisJson)
			this.pageSize = this.isAnalysis ? 999 : 5
			this.pageChange(1)
		},
		methods: {
			getBlobList(list){
				return new Promise(async (r,j) => {
					if(list.length){
						/* 如果是评测里面的试题 则不需要从getFullItem取 */
						let blobList = this.examPropScope ? list : await this.$evTools.getFullItem(list)
						r(blobList)
					}else{
						r([])
					}
					
				})
			},
			
			getOptionLineData(item,index){
				let result = []
				let n = this.optionRate[index]
				let total = this.$store.state.totalAnalysis.analysisJson.all.total // 取总人数
				let phCount = Math.floor(total * 0.27) //取高分组低分组人数
				item.option.map(i => i.code).forEach(key => {
					result.push({
						option:key,
						rate:n.record[key] ? ((n.record[key] / total) * 100).toFixed(1) : 0,
						PH: n.ph[key] ? ((n.ph[key] / phCount) * 100).toFixed(1) : 0,
						PL: n.pl[key] ? ((n.pl[key] / phCount) * 100).toFixed(1) : 0,
					})
				})
				return result
			},
			
			getChildAnalysisJson(pItem){
				let result = []
				pItem.children.forEach(child => {
					result.push(this.analysisJson[this.flatIds.indexOf(child.id)])
				})
				return result
			},
			
			getChildOptionRate(pItem){
				let result = []
				pItem.children.forEach(child => {
					result.push(this.optionRate[this.flatIds.indexOf(child.id)])
				})
				return result
			},
			
			onSelectItem(item,index){
				let arrIndex = this.selectList.map(i => i.id).indexOf(item.id)
				console.log(arrIndex)
				if(arrIndex > -1){
					this.selectList.splice(arrIndex,1)
					this.$Message.warning(this.$t('evaluation.cancelSuc'))
				}else{
					this.selectList.push(item)
					this.$Message.success(this.$t('evaluation.addSuc'))
				}
				this.$emit('on-question-change', this.selectList,0)
				console.log(this.selectList)
				console.log(item)
			},

			/**
			 * 全部展开与全部折叠
			 * @param isAllOpen
			 */
			onHandleToggle(isAllOpen) {
				if (isAllOpen) {
					this.collapseList = [];
				} else {
					this.collapseList = [...this.exerciseList.keys()];
				}
				console.log(this.collapseList)
			},

			/**
			 * 题干展开与收缩
			 * @param index
			 * @param id
			 */
			onQuestionToggle(index, id, e) {
				console.log(e)
				let curClassName = e.target.className;
				if (
					curClassName === "item-tools" ||
					curClassName === "richText-video" ||
					curClassName === "richText-audio"
				)
					return;
				e.stopPropagation();
				let listIndex = this.collapseList.indexOf(index);
				if (listIndex > -1) {
					this.collapseList.splice(listIndex, 1);
				} else {
					this.collapseList.push(index);
					let exerciseItemDom = e.path.filter(
						(i) => i.className === "exercise-item"
					);
					if (exerciseItemDom.length) {
						this.$emit("pageScroll", exerciseItemDom[0].offsetTop);
						exerciseItemDom[0].style.border = '2px solid #2db7f5'
						setTimeout(() => {
							exerciseItemDom[0].style.border = '2px solid transparent'
						},2000)
					}
				}

				this.$emit("toggleChange", this.collapseList);
			},

			
			/**
			 * 删除筛选条件里面的False值与All值
			 * @param arr
			 */
			deleteFalse(arr) {
				let list = JSON.parse(JSON.stringify(arr));
				list.forEach((item, index) => {
					if (!item || item === "all") list.splice(index, 1);
				});
				return list;
			},

			/**
			 * 切换页码操作
			 * @param page
			 */
			async pageChange(page) {
				this.dataLoading = true
				this.pageNum = page;
				let start = this.pageSize * (page - 1);
				let end = this.pageSize * page;
				// 拿到当前页码需要展示的数据
				this.$emit("pageScroll", 0);
				let simpleList = this.originData.slice(start, end);
				try {
					// 执行试题换取完整JSON数据
					this.exerciseList = await this.getBlobList(simpleList);
					this.currentPage = page;
					setTimeout(() => {
						this.dataLoading = false
					},1000)
				} catch (e) {
					console.log(e);
					this.dataLoading = false
				}
			},

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

		},
		mounted() {
			this.selectList = this.selQue
			console.log(this.optionRate)
		},
		computed: {
			curScope() {
				return this.filterOrigin === this.$store.state.userInfo.schoolCode ?
					"school" :
					"private";
			},
			hasSchool() {
				return this.$store.state.userInfo.hasSchool;
			},
		},
		watch:{
			propsList:{
				handler(n,o){
					if(n){
						if(n.length){
							this.originData = n
							this.totalNum = n.length
							this.pageChange(1)
						}else{
							this.dataLoading = true
							this.originData = []
							this.exerciseList = []
							this.totalNum = 0
							setTimeout(() => {
								this.dataLoading = false
							},500)
						}
						
					}
				}
			},
			optionRate:{
				handler(n,o){
					if(n){
						console.log(n)
					}
				},
				immediate:true,
				deep:true
			},
			examScope:{
				handler(n,o){
					this.examPropScope = n
				},
				immediate:true
			},
			selQue:{
				handler(n,o){
					if(n){
						console.log('监听到222',n)
					}
				}
			},
		}
	};
</script>
<style src="./ExerciseList.less" lang="less" scoped>
</style>

<style>
	.circle {
		border: solid 1px red;
		background-color: red;
		border-radius: 50%;
		width: 50px;
		height: 50px;
	}

	.slide-enter-active {
		transition: all 0.3s ease;
	}

	.slide-leave-active {
		transition: all 0.3s ease;
	}

	.slide-enter,
	.slide-leave-to {
		transform: translateY(10px);
		opacity: 0;
	}
</style>
