<template>
	<div class="ev-container" :id="refId">
		<div class="display-flex">
			<div class="exersices-attr my-radio-style">
				<IconText :text="$t('evaluation.newExercise.field')" :color="'#00b8ff'" :icon="'md-planet'"></IconText>
				<Select v-model="exerciseField">
					<Option v-for="(item, index) in fieldList" :value="index" :key="index">{{ item }}</Option>
				</Select>
			</div>
			<div class="exersices-attr my-radio-style">
				<IconText :text="$t('evaluation.newExercise.knowledge')" :color="'#00b8ff'" :icon="'md-infinite'"></IconText>
				<Button type="info" style="margin-top: 20px" @click="onSelectPoints" v-if="exercisePoints.length === 0">{{$t('evaluation.newExercise.choosePoint')}}</Button>
				<div v-else style="margin-top: 10px">
					<span v-for="(item, index) in exercisePoints" :key="index" class="exercise-item-point">
						{{ item }}
						<span class="exercise-item-point-close">
							<Icon type="md-close" @click="onDeletePoint(index)" /></span>
					</span>
					<span class="exercise-item-point-modify" @click="selectPointsModal = true">{{ $t('evaluation.newExercise.modify') }}</span>
				</div>
			</div>
		</div>
		<div class="exersices-attr display-flex">
			<div class="exersices-attr my-radio-style">
				<IconText :text="$t('evaluation.newExercise.type')" :color="'#00b8ff'" :icon="'md-pricetags'"></IconText>
				<RadioGroup v-model="exersicesType" type="button" @on-change="typeChange">
					<Radio label="single" :disabled="isEdit">{{ $t('evaluation.single') }}</Radio>
					<Radio label="multiple" :disabled="isEdit">{{ $t('evaluation.multiple') }}</Radio>
					<Radio label="judge" :disabled="isEdit">{{ $t('evaluation.judge') }}</Radio>
					<Radio label="complete" :disabled="isEdit">{{ $t('evaluation.complete') }}</Radio>
					<Radio label="subjective" :disabled="isEdit">{{ $t('evaluation.subjective') }}</Radio>
					<Radio label="connector" :disabled="isEdit">{{ $t('evaluation.connector') }}</Radio>
					<Radio label="correct" :disabled="isEdit">{{ $t('evaluation.correct') }}</Radio>
				</RadioGroup>
			</div>
			<div class="exersices-attr edit-exersices-attr-diff my-radio-style">
				<IconText :text="$t('evaluation.newExercise.diff')" :color="'#00b8ff'" :icon="'md-pulse'"></IconText>
				<RadioGroup v-model="exersicesDiff" type="button">
					<Radio label="1" @click.native="diffChange($event, '1')">{{$t('evaluation.diff1')}}</Radio>
					<Radio label="2" @click.native="diffChange($event, '2')">{{$t('evaluation.diff2')}}</Radio>
					<Radio label="3" @click.native="diffChange($event, '3')">{{$t('evaluation.diff3')}}</Radio>
					<Radio label="4" @click.native="diffChange($event, '4')">{{$t('evaluation.diff4')}}</Radio>
					<Radio label="5" @click.native="diffChange($event, '5')">{{$t('evaluation.diff5')}}</Radio>
				</RadioGroup>
			</div>
		</div>

		<BaseSingle v-if="exersicesType === 'single'" ref="single" :editInfo="editInfo"></BaseSingle>
		<BaseMultiple v-else-if="exersicesType === 'multiple'" ref="multiple" :editInfo="editInfo"></BaseMultiple>
		<BaseJudge v-else-if="exersicesType === 'judge'" ref="judge" :editInfo="editInfo"></BaseJudge>
		<BaseCompletion v-else-if="exersicesType === 'complete'" ref="complete" :editInfo="editInfo"></BaseCompletion>
		<BaseConnector v-else-if="exersicesType === 'connector'" ref="connector" :editInfo="editInfo"></BaseConnector>
		<BaseCorrect v-else-if="exersicesType === 'correct'" ref="correct" :editInfo="editInfo"></BaseCorrect>
		<BaseSubjective v-else-if="exersicesType === 'subjective'" ref="subjective" :editInfo="editInfo"></BaseSubjective>

		<!-- 解析的富文本部分 -->
		<div class="exersices-analysis child-exercise-analysis">
			<IconText :text="$t('evaluation.explain')" :color="'#2892DD'" :icon="'md-list'" style="margin-bottom: 10px"></IconText>
			<div>
				<div ref="analysisEditor" style="text-align: left"></div>
			</div>
		</div>

		<!-- 补救的富文本部分 -->
		<!-- 补救的富文本部分 -->
		<div class="exersices-analysis" v-show="exersicesType !== 'compose'">
			<IconText :text="$t('evaluation.newExercise.repair')" :color="'#2892DD'" :icon="'md-link'" style="margin-bottom: 10px"></IconText>
			<BaseRepair ref="repairRef" :repairs="editInfo.repair"></BaseRepair>
		</div>

		<div class="save-wrap display-flex">
			<Button type="success" @click="getContent(exersicesType)" :loading="saveLoading">{{ $t('evaluation.newExercise.save') }}</Button>
		</div>

		<!-- 选择知识点弹窗 -->
		<Modal v-model="selectPointsModal" :title="$t('evaluation.newExercise.choosePoint')" width="600px" class="related-point-modal" style="z-index: 99999">
			<BasePoints v-if="selectPointsModal" ref="pointRef" :period="schoolInfo.period[curPeriodIndex].id" :subject="schoolInfo.period[curPeriodIndex].subjects[curSubjectIndex].id"
			 @onCheckChange="onCheckChange" :points="exercisePoints" :scope="curScope"></BasePoints>
			<!--<CreateNewChild v-if="isLoadModal" ref="newChild" :isChildEdit="isChildEdit" :editItem="editChild"></CreateNewChild>-->
			<div slot="footer">
				<Button type="text" @click="selectPointsModal = false">{{ $t('evaluation.cancel') }}</Button>
				<Button type="primary" @click="selectPointsModal = false">{{ $t('evaluation.confirm') }}</Button>
			</div>
		</Modal>
	</div>
</template>
<script>
	import "videojs-contrib-hls.js/src/videojs.hlsjs";
	import IconText from "@/components/evaluation/IconText.vue";
	import BaseSingle from "@/view/evaluation/types/BaseSingle.vue";
	import BaseMultiple from "@/view/evaluation/types/BaseMultiple.vue";
	import BaseCompletion from "@/view/evaluation/types/BaseCompletion.vue";
	import BaseJudge from "@/view/evaluation/types/BaseJudge.vue";
	import BaseSubjective from "@/view/evaluation/types/BaseSubjective.vue";
    import BaseCorrect from "@/view/evaluation/types/BaseCorrect.vue";
    import BaseConnector from "@/view/evaluation/types/BaseConnector.vue";
	import NewChooseContent from "@/components/selflearn/NewChooseContent";
	import E from "wangeditor";
	// 默认创建题目模板
	const defaultExercise = {
		question: "",
		option: [],
		level: 1,
		answer: [],
		explain: "",
		type: "",
	};
	export default {
		name:'BaseCreateChild',
		components: {
			IconText,
			BaseSingle,
			BaseJudge,
			BaseMultiple,
			BaseCompletion,
			BaseSubjective,
			BaseCorrect,
			BaseConnector,
			NewChooseContent,
		},
		props: {
			editItem: {
				type: Object,
				default: null,
			},
			refId: {
				type: String,
				default: "createChild",
			},
			curPeriodIndex: {
				type: Number,
				default: 0,
			},
			curSubjectIndex: {
				type: Number,
				default: 0,
			},
		},
		data() {
			return {
				isRelatedContent: false,
				selectPointsModal: false,
				isEdit: false,
				isFalse: false,
				isLoading: false,
				relateFileList: [],
				editInfo: {},
				schoolInfo: {},
				saveLoading: false,
				exersicesType: "single",
				exerciseField: 0,
				exercisePeriod: 0,
				exerciseGrade: [],
				exerciseSubject: 0,
				exerciseScope: 0,
				exercisePoints: [],
				scopeList: [this.$t('evaluation.filter.schoolBank'),this.$t('evaluation.filter.privateBank')],
				fieldList: [this.$t('evaluation.level1'),this.$t('evaluation.level2'),this.$t('evaluation.level3'),
				this.$t('evaluation.level4'),this.$t('evaluation.level5'),this.$t('evaluation.level6')],
				periodList: [],
				gradeList: [],
				subjectList: [],
				exersicesDiff: "1",
				analysisContent: "",
				repairContent: "",
				stemContent: "",
				analysisEditor: null,
				repairEditor: null,
				curId:''
			};
		},
		created() {
			this.getSchoolInfo();
		},
		methods: {
			getSchoolInfo() {
				this.$store.dispatch("user/getSchoolProfile").then((res) => {
					let schoolBaseInfo = res.school_base;
					if (schoolBaseInfo) {
						this.schoolInfo = schoolBaseInfo;
						if (schoolBaseInfo.period.length) {
							this.gradeList = schoolBaseInfo.period[0].grades;
							this.subjectList = schoolBaseInfo.period[0].subjects;
						}
					}
				});
			},
			
			onSelectPoints(){
				if(this.hasSchool){
					console.log(this.schoolInfo)
					console.log(this.curPeriodIndex)
					console.log(this.curSubjectIndex)
					this.selectPointsModal = true
				}else{
					this.$Message.warning(this.$t('evaluation.newExercise.noSchoolTip'))
				}
			},


			onSelectFile(val) {
				this.relateFileList = val.files;
			},

			onConfirmRelate() {
				console.log(this.relateFileList);
				this.isRelatedContent = false;
			},

			async getContent(type) {
				
				let exerciseItem = this.editInfo && this.editInfo.id ? JSON.parse(JSON.stringify(this.editInfo)) : Object.assign({}, defaultExercise);
				switch (type) {
					case "single":
						this.$refs.single.doSave()
						exerciseItem.question = this.$refs.single.stemContent;
						exerciseItem.option = this.checkOptionNull(this.$refs.single.optionsContent) ? this.$refs.single.optionsContent : null;
						exerciseItem.type = this.exersicesType;
						exerciseItem.level = +this.exersicesDiff;
						exerciseItem.explain = this.analysisContent;
						exerciseItem.answer = [
							String.fromCharCode(64 + parseInt(this.$refs.single.trueIndex + 1)),
						];
						break;
					case "multiple":
					this.$refs.multiple.doSave()
						exerciseItem.question = this.$refs.multiple.stemContent;
						exerciseItem.option = this.checkOptionNull(this.$refs.multiple.optionsContent) ?
							this.$refs.multiple.optionsContent :
							null;
						exerciseItem.type = this.exersicesType;
						exerciseItem.level = +this.exersicesDiff;
						exerciseItem.explain = this.analysisContent;
						exerciseItem.answer = this.$refs.multiple.multipleAnswers;
						break;
					case "judge":
						exerciseItem.question = this.$refs.judge.stemContent;
						exerciseItem.option = [];
						exerciseItem.type = this.exersicesType;
						exerciseItem.level = +this.exersicesDiff;
						exerciseItem.explain = this.analysisContent;
						exerciseItem.answer = [this.$refs.judge.trueAnswer];
						break;
					case "complete":
						exerciseItem.question = this.$refs.complete.stemContent;
						exerciseItem.option = [];
						exerciseItem.type = this.exersicesType;
						exerciseItem.level = +this.exersicesDiff;
						exerciseItem.explain = this.analysisContent;
						exerciseItem.answer = [this.$refs.complete.answerContent];
						exerciseItem.blankCount = this.$refs.complete.blankCount || 1;
						break;
					case "subjective":
						exerciseItem.question = this.$refs.subjective.stemContent;
						exerciseItem.option = [];
						exerciseItem.type = this.exersicesType;
						exerciseItem.level = +this.exersicesDiff;
						exerciseItem.explain = this.analysisContent;
						exerciseItem.answer = [this.$refs.subjective.answerContent];
						break;
					case "connector":
						exerciseItem.question = this.$refs.connector.stemContent;
						exerciseItem.option = [];
						exerciseItem.type = this.exersicesType;
						exerciseItem.level = +this.exersicesDiff;
						exerciseItem.explain = this.analysisContent;
						exerciseItem.answer = [this.$refs.connector.answerContent];
						break;
					case "correct":
						exerciseItem.question = this.$refs.correct.stemContent;
						exerciseItem.option = [];
						exerciseItem.type = this.exersicesType;
						exerciseItem.level = +this.exersicesDiff;
						exerciseItem.explain = this.analysisContent;
						exerciseItem.answer = [this.$refs.correct.answerContent];
						break;		
				}
				exerciseItem.repair = this.repairContent;
				exerciseItem.repair = this.formatRepairResource(
					this.$refs.repairRef.datas
				);
				exerciseItem.field = this.exerciseField + 1;
				exerciseItem.knowledge = this.exercisePoints;
				exerciseItem.code =
					this.$parent.$parent.exerciseScope === 0 ?
					this.$store.state.userInfo.TEAMModelId :
					this.$store.state.userInfo.schoolCode;

				// 判断获取的数据是否有空数据以及是否为空字符串
				if (
					this.checkContent(exerciseItem) &&
					this.getSimpleText(exerciseItem.question)
				) {
					// this.saveLoading = true
					exerciseItem.id = this.curId;
					console.log('编辑后的小题',exerciseItem)
					this.$emit("addFinish", exerciseItem);
				} else {
					console.log(exerciseItem);
					this.$Message.warning(this.$t('evaluation.newExercise.unCompleteTip'));
				}
			},

			/* 知识点勾选变动事件 */
			onCheckChange(val, list) {
				this.exercisePoints = val;
			},

			/**
			 * 移除指定知识点
			 * @param index
			 */
			onDeletePoint(index) {
				this.exercisePoints.splice(index, 1);
				// this.$refs.pointRef.$children[1].onDeletePoint(index)
			},

			// 题目类型转换
			typeChange(val) {
				if (this.isEdit) {
					this.$Message.warning(this.$t('evaluation.newExercise.typeChangeTip'));
				}else {
					this.exersicesType = val;
					this.analysisEditor.txt.clear();
					// this.repairEditor.txt.clear()
				}
			},

			// 重置本页面
			doReset() {
				this.exerciseField = 0;
				this.exercisePoints = [];
				this.exersicesDiff = "1";
				this.exersicesType = "single";
				this.analysisEditor.txt.clear();
				// this.repairEditor.txt.clear()
				this.editInfo = null;
			},

			/* 检测补救资源超链接 去除无效链接 */
			formatRepairResource(list) {
				if (list.length) {
					let arr = [];
					list.forEach((i, index) => {
						i.blobUrl.forEach(j => {
							arr.push({
								blobUrl:j.url,
								name:i.name,
								type:i.type
							})
						})
					});
					return arr;
				} else {
					return [];
				}
			},

			// 难度与背景颜色切换
			diffChange(e, type) {
				this.exersicesDiff = +type;
				e.preventDefault();
				let colorArr = ["#10abe7", "#E8BE15", "#F19300", "#EB5E00", "#D30000"];
				let ac = document
					.getElementById(this.refId)
					.getElementsByClassName("edit-exersices-attr-diff")[0].children[1]
					.children;
				for (let i = 0; i < ac.length; i++) {
					ac[i].style.background = "#fff";
					ac[i].style.color = "#515a6e";
				}
				e.target.style.background = colorArr[type - 1];
				e.target.style.color = "#fff";
			},

			// 提取富文本内容中的文本
			getSimpleText(html) {
				var r = /<(?!img|video|audio).*?>/g;
				return html.replace(r, "");
			},

			/* 检测数组是否有空数据 */
			checkOptionNull(arr) {
				let flag = true;
				for (let i = 0; i < arr.length; i++) {
					if (this.getSimpleText(arr[i].value) === "") {
						flag = false;
					}
				}
				return flag;
			},

			// 排除对象空属性
			checkContent(Obj) {
				let flag = true;
				let whiteList = this.getWhiteListByType(Obj.type);
				console.log("验证的");
				console.log(Obj);
				for (let key in Obj) {
					if (whiteList.includes(key) && typeof Obj[key] === "string") {
						if (!this.getSimpleText(Obj[key])) {
							console.log(key);
							flag = false;
						}
					} else if (whiteList.includes(key) && key === "answer") {
						if (Obj[key].length === 0) {
							console.log(key);
							flag = false;
						}
					} else {
						if (whiteList.includes(key) && !Obj[key]) {
							console.log(key);
							flag = false;
						}
					}
				}
				return flag;
			},

			// 根据不同题型 给出需要必填选项
			getWhiteListByType(type) {
				switch (type) {
					case "single":
						return ["question", "option", "answer"];
						break;
					case "multiple":
						return ["question", "option", "answer"];
						break;
					case "complete":
						return ["question", "answer"];
						break;
					default:
						return ["question", "answer"];
						break;
				}
			},

			// 渲染编辑习题内容回显
			async renderExercise(editItem) {
				this.isEdit = true;
				this.exersicesDiff = editItem.level.toString() || "0";
				this.exerciseScope =
					editItem.code === this.$store.state.userInfo.TEAMModelId ? 0 : 1;
				this.exersicesType = editItem.type;
				this.exerciseField = editItem.field - 1;
				this.exercisePoints = editItem.knowledge || editItem.points;

				if (editItem.level) {
					let ac = document
						.getElementById(this.refId)
						.getElementsByClassName("edit-exersices-attr-diff")[0].children[1]
						.children;
					for (let i = 0; i < ac.length; i++) {
						ac[i].style.background = "#fff";
						ac[i].style.color = "#515a6e";
					}
					// 重新渲染题目难度
					let diffDom = document
						.getElementById(this.refId)
						.getElementsByClassName("edit-exersices-attr-diff")[0].children[1]
						.children[editItem.level - 1];
					let colorArr = ["#32CF74", "#E8BE15", "#F19300", "#EB5E00", "#D30000"];
					diffDom.style.background = colorArr[editItem.level - 1];
					diffDom.style.color = "#fff";
				} else {
					let ac = document
						.getElementById(this.refId)
						.getElementsByClassName("edit-exersices-attr-diff")[0].children[1]
						.children;
					for (let i = 0; i < ac.length; i++) {
						ac[i].style.background = "#fff";
						ac[i].style.color = "#515a6e";
					}
				}

				this.childList = editItem.children || [];
				let schoolInfo = await this.$store.dispatch('user/getSchoolProfile');
				this.schoolInfo = schoolInfo.school_base;
				
				this.stemContent = editItem.question;
				this.relateFileList = editItem.repair || [];
				this.optionsContent = editItem.option;
				this.analysisContent = editItem.explain;
				this.analysisEditor.txt.html(editItem.explain);
				this.editInfo = editItem;
			},
		},
		mounted() {
			let analysisEditor = new E(this.$refs.analysisEditor);
			analysisEditor.config.uploadImgShowBase64 = true;
			analysisEditor.config.onchange = (html) => {
				this.analysisContent = html;
			},
			this.$editorTools.initMyEditor(analysisEditor,this)
			analysisEditor.create();
			this.analysisEditor = analysisEditor;
			
			this.curId = this.$tools.guid()
			if (this.editItem && this.editItem.id) {
				this.renderExercise(JSON.parse(JSON.stringify(this.editItem)));
				// 先生成随机ID
				this.curId = this.editItem.id || this.$tools.guid()
			}
		},
		computed:{
			curScope(){
				return this.exerciseScope === 1 ? 'school' : 'private'
			},
			hasSchool() {
			  let user = JSON.parse(
			    decodeURIComponent(localStorage.user_profile, "utf-8")
			  );
			  return (
				user.schools && 
			    user.schools.length &&
			    user.schools.filter((i) => i.status === "join").length > 0
			  );
			},
		},
		watch: {
			editItem: {
				handler(newValue, oldValue) {
					if (newValue) {
						console.log("要编辑的小题");
						console.log(newValue);
						this.renderExercise(JSON.parse(JSON.stringify(newValue)));
						this.curId = newValue.id || this.$tools.guid()
						// this.$refs.pointRef.doReset()
					}
				},
				//immediate:true
			}
		},
	};
</script>
<style src="../index/CreateExercises.less" lang="less" scoped>
</style>

<style>

	.related-point-modal .ivu-modal-header-inner {
		font-weight: bold;
	}

	.exersices-attr .ivu-select-multiple .ivu-tag {
		height: 32px;
		line-height: 31px;
	}

	.exersices-attr .ivu-select-multiple .ivu-tag i {
		top: 9px;
	}

	.exersices-attr .ivu-select-multiple .ivu-select-selection .ivu-select-placeholder {
		line-height: 38px;
	}
	
	.child-exercise-analysis .w-e-toolbar{
		z-index: 0 !important;
	}
	
	.child-exercise-analysis .w-e-text-container{
		position: unset;
	}
	
	
</style>
