<template>
	<div class="ev-container">
		<span class="ev-title">
			<Icon type="ios-paper" />{{ exerciseScope === 1 ? $t('evaluation.newExercise.newSchoolItem') : $t('evaluation.newExercise.newPrivateItem') }}</span>
		<Divider />
		<div class="display-flex" v-if="isSchool">
			<div class="exersices-attr my-radio-style">
				<IconText :text="$t('evaluation.newExercise.choosePeriod')" :color="'#00b8ff'" :icon="'md-school'"></IconText>
				<Select v-model="exercisePeriod" @on-change="onPeriodChange">
					<Option v-for="(period, index) in schoolInfo.period" :value="index" :key="index">{{ period.name }}</Option>
				</Select>
			</div>
			<div class="my-radio-style exersices-attr">
				<IconText :text="$t('evaluation.newExercise.chooseGrade')" :color="'#00b8ff'" :icon="'logo-buffer'"></IconText>
				<Select v-model="exerciseGrade" multiple :placeholder="$t('evaluation.newExercise.gradePlaceholder')">
					<Option v-for="(grade, index) in gradeList" :value="index" :key="index">{{ grade }}</Option>
				</Select>
			</div>
			<div class="exersices-attr my-radio-style">
				<IconText :text="$t('evaluation.newExercise.chooseSubject')" :color="'#00b8ff'" :icon="'md-bookmarks'"></IconText>
				<Select v-model="exerciseSubject" @on-change="onSubjectChange">
					<Option v-for="(subject, index) in subjectList" :value="index" :key="index">{{ subject.name }}</Option>
				</Select>
			</div>
		</div>
		<div class="display-flex">
			<div class="exersices-attr exercises-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 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-type 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>
					<Radio label="compose" :disabled="isEdit">{{ $t('evaluation.compose') }}</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>
		<BaseSubjective v-else-if="exersicesType === 'subjective'" ref="subjective" :editInfo="editInfo"></BaseSubjective>
		<BaseConnector v-else-if="exersicesType === 'connector'" ref="connector" :editInfo="editInfo"></BaseConnector>
		<BaseCorrect v-else-if="exersicesType === 'correct'" ref="correct" :editInfo="editInfo"></BaseCorrect>
		<BaseCompose v-else-if="exersicesType === 'compose'" ref="compose" :editInfo="editInfo"></BaseCompose>

		<!-- 解析的富文本部分 -->
		<div class="exersices-analysis" v-show="exersicesType !== 'compose'">
			<IconText :text="$t('evaluation.explain')" :color="'#2892DD'" :icon="'md-list'" style="margin-bottom: 10px"></IconText>
			<div id="analysisEditor">
				<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"></BaseRepair>
		</div>

		<!-- 小题展示区域 -->
		<div class="child-list-wrap" v-show="exersicesType === 'compose' && childList.length">
			<IconText :text="$t('evaluation.newExercise.childList')" :color="'#00b8ff'" :icon="'md-list'"></IconText>
			<BaseChildList :childList="childList"></BaseChildList>
		</div>

		<div class="save-wrap display-flex">
			<Button type="info" @click="onAddChild" style="margin-right: 10px" v-show="exersicesType === 'compose'">{{ $t('evaluation.newExercise.addChild')}}</Button>
			<Button type="success" @click="getContent(exersicesType)" :loading="saveLoading">{{ $t('evaluation.newExercise.save') }}</Button>
		</div>

		<Button type="text" @click="backToBank" class="btn-back-to-bank" icon="md-arrow-round-back" style="margin-left: 10px">{{ $t('evaluation.newExercise.backToBank')}}</Button>

		<Modal v-model="selectPointsModal" :title="$t('evaluation.newExercise.choosePoint')"  width="600px" class="related-point-modal" style="z-index: 99999">
			<BasePoints v-if="selectPointsModal" :period="schoolInfo.period[exercisePeriod].id" :subject="subjectList[exerciseSubject].id"
			 @onCheckChange="onCheckChange" :points="exercisePoints" :scope="curScope" ref="pointRef"></BasePoints>
			<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>

		<!-- 添加小题弹窗 -->
		<Modal v-model="addComposeChildModal" width="1080" footer-hide class="">
			<div class="modal-header" slot="header">{{ $t('evaluation.newExercise.addChild') }}</div>
			<BaseCreateChild @addFinish="onAddChildFinish" ref="createAddChild" v-if="addComposeChildModal" :curPeriodIndex="exercisePeriod"
			 :curSubjectIndex="exerciseSubject"></BaseCreateChild>
		</Modal>
	</div>
</template>
<script>
	import blobTool from "@/utils/blobTool.js";
	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 BaseCompose from "@/view/evaluation/types/BaseCompose.vue";
	import BasePoints from "@/view/evaluation/components/BasePoints";
	import BaseRepair from "@/view/evaluation/components/BaseRepair";
	import BaseCreateChild from "@/view/evaluation/components/BaseCreateChild";
	import E from "wangeditor";
	// 默认创建题目模板
	const defaultExercise = {
		question: "",
		option: [],
		level: 1,
		answer: [],
		explain: "",
		type: "",
	};
	export default {
		components: {
			IconText,
			BaseSingle,
			BaseJudge,
			BaseMultiple,
			BaseCompletion,
			BaseSubjective,
			BaseCorrect,
			BaseConnector,
			BaseCompose,
			BasePoints,
			BaseRepair,
			BaseCreateChild,
		},
		data() {
			return {
				fromScope: "",
				isRelatedContent: false,
				selectPointsModal: false,
				addComposeChildModal: 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: [],
				childList: [],
				exersicesDiff: "1",
				analysisContent: "",
				repairContent: "",
				stemContent: "",
				analysisEditor: null,
				repairEditor: null,
				curId: '',
				isComplete: false
			};
		},
		created() {
			// 初始化区班校信息
			this.getSchoolInfo();

			let scope = this.$route.name === 'newSchoolExercise' ? 'school' : 'private'; // 编辑题目
			if (scope) {
				this.exerciseScope = scope === "private" ? 0 : 1;
				this.fromScope = scope;
			}
			// 先生成随机ID
			this.curId = this.$tools.guid()

		},
		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) {
					if(this.exersicesType === 'compose'){
						this.$Message.warning(this.$t('evaluation.newExercise.composeTip'))
					}else{
						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 = 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;
					case "compose":
						exerciseItem.question = this.$refs.compose.stemContent;
						exerciseItem.option = [];
						exerciseItem.type = this.exersicesType;
						exerciseItem.level = +this.exersicesDiff;
						exerciseItem.explain = this.analysisContent;
						exerciseItem.children = this.childList;
						exerciseItem.answer = []
						break;
					default:
						break;
				}
				exerciseItem.repair = this.formatRepairResource(this.$refs.repairRef.datas);
				exerciseItem.field = this.exerciseField + 1;
				exerciseItem.knowledge = this.exercisePoints; //新知识点
				exerciseItem.periodId = this.isSchool ? this.schoolInfo.period[this.exercisePeriod].id : null;
				exerciseItem.gradeIds = this.isSchool ?
					this.exerciseGrade.length ?
					this.exerciseGrade.map(i => i + '') :
					this.gradeList.map((i,index) => index + '') :
					null;
				exerciseItem.subjectId = this.isSchool ?
					this.schoolInfo.period[this.exercisePeriod].subjects[
						this.exerciseSubject
					].id :
					null;
				exerciseItem.code =
					this.exerciseScope === 0 ?
					this.$store.state.userInfo.TEAMModelId :
					this.schoolInfo.id;
				exerciseItem.scope = this.exerciseScope === 0 ? "private" : "school";
				
				// 收集编辑器宽度 方便压缩富文本图片中宽度为百分比的图片
				let editorWidth = {}
				if(exerciseItem.type === 'single'){
					editorWidth.questionWidth = this.$refs.single.stemEditor.$textContainerElem.elems[0].clientWidth
					editorWidth.optionWidth = this.$refs.single.optionEditors[0].$textContainerElem.elems[0].clientWidth
				}else if(exerciseItem.type === 'multiple'){
					editorWidth.questionWidth = this.$refs.multiple.stemEditor.$textContainerElem.elems[0].clientWidth
					editorWidth.optionWidth = this.$refs.multiple.optionEditors[0].$textContainerElem.elems[0].clientWidth
				}else{
					editorWidth.questionWidth = this.analysisEditor.$textContainerElem.elems[0].clientWidth
				}
				
				// 判断获取的数据是否有空数据以及是否为空字符串
				if (this.checkContent(exerciseItem)) {
					exerciseItem = await this.$editorTools.transBase64Src(exerciseItem,editorWidth)
					console.log('转换后的试题')
					console.log(exerciseItem)
					this.saveLoading = true;
					// 生成JSON文件名称以及新增试题的ID
					const guid = this.curId;
					// 给新增的试题赋值ID
					exerciseItem.id = guid;
					// 如果是综合题 则需要完善子题的信息 并且进行保存
					if (exerciseItem.children && exerciseItem.children.length && exerciseItem.type === 'compose') {
						exerciseItem.children.forEach((child) => {
							child.periodId = exerciseItem.periodId
							child.gradeIds = exerciseItem.gradeIds
							child.subjectId = exerciseItem.subjectId
							child.scope = exerciseItem.scope
							child.code = exerciseItem.code
							child.pid = exerciseItem.id
						})
						let containerName = exerciseItem.scope === 'private' ? this.$store.state.userInfo.TEAMModelId : this.$store.state.userInfo.schoolCode
						// 保存完题目返回子题的ID集合 作为cosmos内综合题的children字段
						exerciseItem.children = await this.saveChildrens(exerciseItem.children,containerName)
					}
					// 将当前的试题数据转化为BLOB内部的试题JSON格式
					const itemJsonFile = await this.$evTools.createBlobItem(exerciseItem);
					// 首先保存新题目的JSON文件到Blob 然后返回URL链接
					let file = new File([JSON.stringify(itemJsonFile)], guid + ".json", {
						type: "",
					});
					// 获取初始化Blob需要的数据
					let sasData =
						this.exerciseScope === 0 ?
						await this.$tools.getPrivateSas() :
						await this.$tools.getSchoolSas();
					//初始化Blob
					let containerClient = new blobTool(
						sasData.url,
						sasData.name,
						sasData.sas,
						exerciseItem.scope
					);

					try {
						// 等待上传blob的返回结果
						let blobFile = await containerClient.upload(file, "item/" + guid);
						if (blobFile.blob) {
							// 保存到COSMOS是不含base64图片编码的数据 避免数据量过大
							exerciseItem.blob = blobFile.blob;
							this.saveExercise({
								itemInfo: await this.$evTools.createCosmosItem(exerciseItem),
								option: "insert",
							}).then((res) => {
								this.isComplete = true
								localStorage.setItem('noSave','[]')
								this.$router.push({
									name: this.exerciseScope === 0 ? "personalBank" : "schoolBank",
									params: {
										tabName: "exercise",
									},
								});
								this.saveLoading = false;
							});
						} else {
							this.$Message.error(this.$t('evaluation.newExercise.uploadErrorTip'));
						}
					} catch (e) {
						this.$Message.error(e.spaceError);
					}
				} else {
					console.log(exerciseItem);
					this.$Message.warning(this.$t('evaluation.newExercise.unCompleteTip'));
					this.saveLoading = false;
				}
			},

			/* 保存综合题的子题 */
			saveChildrens(childrens,containerName) {
				return new Promise(async (resolve, reject) => {
					let promiseArr = []
					childrens.forEach(exerciseItem => {
						promiseArr.push(new Promise(async (r, j) => {
							// 将当前的试题数据转化为BLOB内部的试题JSON格式
							const itemJsonFile = await this.$evTools.createBlobItem(exerciseItem);
							// 首先保存新题目的JSON文件到Blob 然后返回URL链接
							let file = new File([JSON.stringify(itemJsonFile)], exerciseItem.id + ".json");
							// 获取初始化Blob需要的数据
							let sasData =
								exerciseItem.scope === 'private' ?
								await this.$tools.getPrivateSas() :
								await this.$tools.getSchoolSas();
							//初始化Blob
							let containerClient = new blobTool(
								sasData.url,
								sasData.name,
								sasData.sas,
								exerciseItem.scope
							);
							try {
								// 等待上传blob的返回结果
								let blobFile = await containerClient.upload(file, "item/" + exerciseItem.id,{},true,false);
								if (blobFile.blob) {
									// 保存到COSMOS是不含base64图片编码的数据 避免数据量过大
									exerciseItem.blob = blobFile.blob;
									this.saveExercise({
										itemInfo: await this.$evTools.createCosmosItem(exerciseItem),
										option: "insert",
									}).then((res) => {
										r({
											cosmosItem:res.itemInfo,
											blobItem:blobFile
										})
									});
								} else {
									this.$Message.error(this.$t('evaluation.newExercise.uploadErrorTip'));
								}
							} catch (e) {
								this.$Message.error(e.spaceError);
							}
						}))
					})
					
					Promise.all(promiseArr).then(result => {
						if (result.length) {
							// 子题保存之后 统一更新blobSize
							blobTool.updateSize(result.map(i => i.blobItem),containerName).then(res => {
								resolve(result.map(i => i.cosmosItem.id))
							}).catch(err => {
								this.$Message.error(this.$t('evaluation.newExercise.uploadErrorTip'));
							})
						} else {
							resolve([])
						}
					})
				})
			},


			/* 保存单个试题 */
			saveExercise(item) {
				return new Promise((r, j) => {
					this.$api.newEvaluation.SaveSingleExercise(item).then((res) => {
						if (res) {
							r(res);
						} else {
							j(res);
							this.$Message.error("服务器繁忙！");
							this.saveLoading = false;
						}
					});
				});
			},

			/* 检测补救资源超链接 去除无效链接 */
			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 [];
				}
			},

			/* 添加小题 重置新增页面 */
			onAddChild() {
				this.addComposeChildModal = true;
				if (this.$refs.createAddChild) this.$refs.createAddChild.doReset();
			},

			/* 添加小题完成 */
			onAddChildFinish(item) {
				console.log(item);
				this.addComposeChildModal = false;
				this.childList.push(item);
			},

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

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

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

			// 难度与背景颜色切换
			diffChange(e, type) {
				console.log(document.getElementsByClassName("exercises-attr-diff"))
				this.exersicesDiff = +type;
				e.preventDefault();
				let colorArr = ["#10abe7", "#E8BE15", "#F19300", "#EB5E00", "#D30000"];
				let ac = document.getElementsByClassName("exercises-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";
			},

			/* 学段变化 */
			onPeriodChange(val) {
				this.gradeList = this.schoolInfo.period[val].grades;
				this.subjectList = this.schoolInfo.period[val].subjects;
				this.exerciseGrade = 0;
				this.exerciseSubject = 0;
				this.exercisePoints = []; // 切换学段后 知识点需要重新选择
			},

			/* 切换科目 将知识点重置 */
			onSubjectChange() {
				this.exercisePoints = []
			},

			// 提取富文本内容中的文本
			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("富文本获取的原始试题数据", 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;
			},

			// 重置编辑器
			backToBank() {
				this.$router.push({
					name: this.fromScope === "private" ? "personalBank" : "schoolBank",
					params: {
						tabName: "exercise",
					},
				});
			},

			// 重置
			reloadCreate() {
				location.reload();
			},

			// 根据不同题型 给出需要必填选项
			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"];
						break;
				}
			},
		},
		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;
		},
		computed: {
			isSchool() {
				return this.$route.name === 'newSchoolExercise';
			},
			curScope() {
				return this.$route.name === 'newSchoolExercise' ? '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
				);
			},
		},
		// 路由离开生命周期函数
		beforeRouteLeave(to, from, next) {
			if (this.isComplete) {
				next()
			} else {
				this.$Modal.confirm({
					title: this.$t('evaluation.newExercise.modalTip'),
					content: this.$t('evaluation.newExercise.unSaveTip'),
					onOk: () => {
						next();
					}
				});
			}

		},
	};
</script>
<style src="../index/CreateExercises.less" lang="less" scoped>
	/*@import"../index/CreateExercises.css";*/
</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;
	}
</style>
