<template>
	<div class="create-evaluation-container">
		<div class="create-header">
			<p class="create-header-title">{{ isEditPaper ? $t('evaluation.paperList.editPaper') : evaluationInfo.createType === 'auto' ? $t('evaluation.index.autoCreate') : evaluationInfo.createType === 'import' ? $t('evaluation.index.importCreate')  : $t('evaluation.index.manualCreate') }}</p>
			<div style="float: right;" class="common-save-btn">
				<Button class="btn-save" type="text" icon="md-arrow-round-back" @click="goBack">{{$t('evaluation.paperList.backToBank')}}</Button>
				<Button class="btn-save" type="text" icon="md-folder" :loading="isLoading" @click="saveTestPaper">{{ isLoading ? $t('evaluation.paperList.isSaving') : $t('evaluation.paperList.savePaper')}}</Button>
			</div>
		</div>
		<div class="create-body dark-iview-split">
			<Split v-model="split1">
				<div slot="left" class="demo-split-pane">
					<div class="evaluation-attr-wrap">
						<p class="wrap-label">{{$t('evaluation.paperList.baseInfo')}}</p>
						<div style="width:100%; height:calc(100% - 45px);padding-top:30px;">
							<Form ref="evaluationInfo" :model="evaluationInfo" label-position="top" class="evaluation-attr-form" label-colon>
								<FormItem :label="$t('evaluation.paperList.paperType')" prop="type">
									<Select v-model="evaluationInfo.type" disabled>
										<Option value="private">{{$t('evaluation.paperList.praviteBank')}}</Option>
										<Option value="school">{{$t('evaluation.paperList.schoolBank')}}</Option>
									</Select>
								</FormItem>
								<FormItem :label="$t('evaluation.paperList.paperName')" prop="name">
									<Input v-model="evaluationInfo.name"></Input>
								</FormItem>
								<FormItem :label="$t('evaluation.newExercise.choosePeriod')" prop="paperPeriod" v-if="isSchool">
									<Select v-model="evaluationInfo.paperPeriod" @on-change="onPeriodChange">
										<Option v-for="(period,index) in schoolInfo.period" :value="index" :key="index">{{ period.name }}</Option>
									</Select>
								</FormItem>
								<FormItem :label="$t('evaluation.newExercise.chooseGrade')" prop="publish" v-if="isSchool">
									<Select v-model="evaluationInfo.paperGrade" multiple :placeholder="$t('evaluation.newExercise.gradePlaceholder')">
										<Option v-for="(grade,index) in gradeList" :value="index" :key="index">{{ grade }}</Option>
									</Select>
								</FormItem>
								<FormItem :label="$t('evaluation.newExercise.chooseSubject')" class="dark-iview-select" v-if="isSchool">
									<Select v-model="evaluationInfo.paperSubject">
										<Option v-for="(subject,index) in subjectList" :value="index" :key="index">{{ subject.name }}</Option>
									</Select>
								</FormItem>
								<FormItem :label="$t('evaluation.paperList.paperScore')" prop="name" class="evaluation-attr-wrap-inputNumber">
									<InputNumber :max="200" :min="1" v-model="evaluationInfo.score"></InputNumber>
								</FormItem>
							</Form>
						</div>
					</div>
				</div>
				<div slot="right" class="demo-split-pane">
					<div class="evaluation-question-wrap">
						<div class="evaluation-question-main">
							<!-- <div class="create-type-wrap" v-show="!isEditPaper">
								<span>创建方式：</span>
								<RadioGroup v-model="evaluationInfo.createType" style="margin-left:15px;" @on-change="setActiveTab">
									<Radio label="auto" v-if="!isEditPaper">自动组题</Radio>
									<Radio label="manual">手动挑题</Radio>
									<Radio label="import" v-if="!isEditPaper">试题导入</Radio>
								</RadioGroup>
							</div> -->
							<p class="save-tips">* {{ viewModel === 'list' ? $t('evaluation.paperList.saveRule2') : $t('evaluation.paperList.saveRule2') }}
							</p>
							<Tabs v-model="activeTab" type="card" class="question-main-tabs" name="createTest">
								<TabPane :label="$t('evaluation.paperList.tab1')" name="auto" v-if="evaluationInfo.createType == 'auto'" :index="1"
								 tab="createTest">
									<AutoCreate :subject="propSubject" :period="propPeriod" @goToPreview="goToPreview" @autoQuestions="getAutoQuestions"></AutoCreate>
								</TabPane>
								<TabPane :label="$t('evaluation.paperList.tab2')" name="manual" v-if="evaluationInfo.createType == 'manual'"
								 :index="2" tab="createTest">
									<ManualCreate :questionList="questionList" :subjectCode="propSubject" :periodCode="propPeriod" :selQue="evaluationInfo.item"
									 @goToPreview="goToPreview" @selectedQuestion="getSelectedQuestion"></ManualCreate>
								</TabPane>
								<TabPane :label="evaluationInfo.item.length ? $t('evaluation.paperList.tab3') : $t('evaluation.paperList.tab4')"
								 name="import" v-if="evaluationInfo.createType == 'import'" :index="3" tab="createTest">
									<BaseImport @importFinish="onImportFinish"></BaseImport>
								</TabPane>
								<TabPane :label="$t('evaluation.paperList.tab5')" name="preview" :index="4" tab="createTest">
									<!--<TeacherPreview :testPaper="evaluationInfo.testPaper[currentSubjectIndex]" :paperName="evaluationInfo.name"></TeacherPreview>-->
									<vuescroll ref="paperRef" @handle-scroll="handleScroll">
										<TestPaper v-if="!examAnalysisStatus" :paper="evaluationInfo" :class="examAnalysisStatus ? '':'animated fadeIn'"
										 ref="testPaper" @onViewModelChange="onViewModelChange"></TestPaper>
									</vuescroll>
								</TabPane>
								<TabPane :label="$t('evaluation.paperList.tab6')" name="student" :index="5" tab="createTest">
									<StudentPreview></StudentPreview>
								</TabPane>
							</Tabs>
						</div>
					</div>
				</div>
			</Split>
		</div>
	</div>
</template>
<script>
	import blobTool from '@/utils/blobTool.js'
	import AutoCreate from '@/view/learnactivity/AutoCreateNew.vue'
	import ManualCreate from '@/view/learnactivity/ManualCreate.vue'
	import TeacherPreview from '@/view/learnactivity/TeacherPreview.vue'
	import StudentPreview from '@/view/learnactivity/StudentPreview.vue'
	import BaseImport from '../components/BaseImport.vue'
	import TestPaper from './TestPaper.vue'

	export default {
		components: {
			AutoCreate,
			ManualCreate,
			TeacherPreview,
			StudentPreview,
			TestPaper,
			BaseImport
		},
		data() {
			return {
				split1: 0.2,
				isLoading: false,
				isEditPaper: false,
				viewModel: 'list',
				examAnalysisStatus: false,
				comfirmPreviewStatus: false,
				goToManageStatus: false,
				examInfo: {},
				editPaper: null,
				schoolInfo: {},
				paperPeriod: 0,
				paperGrade: [],
				paperSubject: 0,
				periodList: [],
				gradeList: [],
				subjectList: [],
				deleteIndex: -1,
				testSubjects: [],
				activeTab: 'auto',
				addSubjectStatus: false,
				addSubjectBefore: [],
				newAddSubjects: [],
				questionList: [],
				currentSubjectIndex: 0,
				evaluationInfo: {
					name: this.$t('evaluation.paperList.defaultName'),
					target: [],
					type: 'private',
					publish: '',
					paperPeriod: 0,
					paperGrade: [],
					paperSubject: 0,
					score: 100,
					item: [],
					startTime: 0,
					endTime: 0,
					createType: 'auto'
				},
				errorList: [],
				noAnswerList: []
			}
		},
		async created() {
			/* 查询当前是否有保存的组卷方式，如果已经保存则直接读取，优先读取传过来的参数 */
			let curCreateType = localStorage.getItem('curCreateType')
			this.evaluationInfo.createType = this.$route.params.type || curCreateType || 'auto'
			this.setActiveTab(this.evaluationInfo.createType)
			localStorage.setItem('curCreateType', this.evaluationInfo.createType)
			this.evaluationInfo.type = this.$route.name === 'newSchoolPaper' ? 'school' : 'private'
			this.getSchoolBaseInfo().then(res => {
				if (!res) return
				this.schoolInfo = res
				this.onPeriodChange(0)
			})
		},
		methods: {
			/**
			 * 学段切换
			 * @param val
			 */
			onPeriodChange(val) {
				this.gradeList = this.schoolInfo.period[val].grades
				this.subjectList = this.schoolInfo.period[val].subjects
				this.evaluationInfo.paperGrade = []
				this.paperGrade = 0
				this.evaluationInfo.paperSubject = 0
				this.paperSubject = 0
			},

			/* 返回试卷库 */
			goBack() {
				this.$router.push({
					name: this.isSchool ? 'schoolBank' : 'personalBank',
					params: {
						tabName: 'paper'
					}
				})
			},

			onTabChange(val) {
				// console.log(val)
			},

			/* 返回顶部 */
			handleBackToTop() {
				this.$nextTick(() => {
					if (this.$refs.paperRef) {
						this.$refs['paperRef'].scrollTo({
								y: '0'
							},
							500
						)
					}
				})
			},

			onViewModelChange(val) {
				this.viewModel = val
			},

			// 判断容器滚动距离
			handleScroll(vertical, horizontal, nativeEvent) {
				this.$store.commit('updatePaperScroll', vertical.scrollTop)
			},

			/**
			 * 导入试题结束
			 * @param list
			 */
			async onImportFinish(list) {
				this.errorList = []
				this.$refs.testPaper.$refs.exList.errorList = []
				this.evaluationInfo.item = []
				try{
					let importList = await this.refreshImportItems(list)
					this.evaluationInfo.item = importList
					this.activeTab = 'preview'
					this.$Message.success(this.$t('evaluation.importFile.warningTips3'))
					console.log(this.evaluationInfo)
					if (this.errorList.length) {
						this.$EventBus.$emit('importFinish', this.errorList)
					}
				}catch(e){
					this.$Message.error(this.$t('evaluation.importFile.warningTips5'))
				}
				
			},

			/* 给导入的试题 补充最新的试卷学段年级以及科目信息 */
			refreshImportItems(list) {
				return new Promise((r, reject) => {
					let objectiveTypes = ['single', 'multiple']
					let code = this.isSchool ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId
					let gradeIds = this.isSchool ? this.evaluationInfo.paperGrade.length ? this.evaluationInfo.paperGrade : this.gradeList
						.map(i => i.id) : null
					let subjectId = this.isSchool ? this.subjectList[this.evaluationInfo.paperSubject].id : null
					let periodId = this.isSchool ? this.schoolInfo.period[this.evaluationInfo.paperPeriod].id : null
					for (let j = 0; j < list.length; j++) {
						let i = list[j]
						if (i.blob && i.id) {
							console.log('题目已存在不需要刷新基础信息')
							continue;
						}
						/* 如果是导入的试题 没有ID 则试题的信息和当前试卷的学段信息保持一致 */
						i.id = i.id || this.$tools.guid()
						i.code = code
						i.level = i.level || 3
						i.field = i.field || 1
						i.scope = this.isSchool ? 'school' : 'private'
						i.gradeIds = gradeIds
						i.subjectId = subjectId
						i.periodId = periodId
						if (i.children.length) {
							i.children.forEach(j => {
								j.id = j.id || this.$tools.guid()
								j.pid = i.id
								j.scope = i.scope
								j.code = code
								j.level = j.level || 3
								j.field = j.field || 1
								j.gradeIds = gradeIds
								j.subjectId = subjectId
								j.periodId = periodId
							})
						}
						// 如果导入的是客观题 则需要检测答案与选项是否为空
						if (objectiveTypes.includes(i.type) && (!i.question.replace(/\s*/g, "") || !i.option || !i.answer ||
								!i.option.length || !i.answer.length)) {
							this.errorList.push(i)
							reject(500)
						}
					}
					r(list)
				})
			},


			/**
			 * 获取自动组题数据
			 * @param questions
			 */
			async getAutoQuestions(questions) {
				let autoQuestions = await this.$evTools.getFullItem(questions)
				this.evaluationInfo.item = []
				this.evaluationInfo.item = this.evaluationInfo.item.concat([...autoQuestions])
				this.activeTab = 'preview'
			},

			/**
			 * 获取手动组题的数据
			 * @param data
			 */
			getSelectedQuestion(data) {
				console.log(data)
				let arr = data.questions
				// 如果是编辑试卷 则往原试卷添加不包含的新题目进入
				if (this.isEditPaper) {
					let list = this.evaluationInfo.item
					arr.forEach(i => {
						if (list.map(j => j.id).indexOf(i.id) < 0) {
							list.push(i)
						}
					})
				} else {
					this.evaluationInfo.item = arr
				}
				console.log('手动挑题返回')
				console.log(arr)
			},

			/** 预览试卷 */
			goToPreview() {
				this.activeTab = 'preview'
			},

			/**
			 * 设置当前组题方式
			 * @param data
			 */
			setActiveTab(data) {
				if (this.evaluationInfo.item.length) {
					this.$Modal.confirm({
						title: '温馨提示',
						content: '<p>切换组题方式会清空当前所选试题，是否继续？</p>',
						onOk: () => {
							this.evaluationInfo.item = []
							this.$refs.testPaper.$refs.exList.errorList = []
							this.$refs.testPaper.$refs.exList.noAnswerList = []
							this.$EventBus.$emit('onPaperItemChange', [])
							this.activeTab = data
						},
						onCancel: () => {

						}
					})
				} else {
					this.activeTab = data
				}
			},

			/** 获取当前学校基础数据 */
			getSchoolBaseInfo() {
				return new Promise((r, j) => {
					this.$store.dispatch("user/getSchoolProfile").then((res) => {
						let schoolBaseInfo = res.school_base;
						if (schoolBaseInfo) {
							r(schoolBaseInfo)
						} else {
							r(null)
						}
					});
				})
			},

			/* 将list中的试题 保存到Cosmos以及Blob中 */
			async savePaperItems(list, modifyItems, isEdit) {
				let that = this
				console.log('保存的试题列表')
				console.log(list)

				let containerName = this.isSchool ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId
				/* 上传前进行试卷blob查询size */
				// let prefixArr = this.getListPrefixs(list)
				// let beforeSize = await blobTool.checkPrefixSize(prefixArr, containerName)
				// console.log('试题上传前的size', beforeSize)
				// return
				// 获取初始化Blob需要的数据
				let sasData = this.isSchool ? await this.$tools.getSchoolSas() : await this.$tools.getPrivateSas()
				let itemJsonFiles = []
				let blobFiles = []
				//初始化Blob
				let containerClient = new blobTool(sasData.url, sasData.name, sasData.sas, this.evaluationInfo.type)
				return new Promise(async (resolve, j) => {
					let promiseArr = []
					for (let i = 0; i < list.length; i++) {
						let exerciseItem = list[i]
						console.log(exerciseItem)
						// 如果是编辑试卷状态 或者 从题目是来自题库
						if (isEdit || exerciseItem.blob) {
							if (exerciseItem.children.length) {
								// 如果是编辑状态下的综合题
								let composeArr = [exerciseItem, ...exerciseItem.children]
								composeArr.forEach(composeItem => {
									promiseArr.push(new Promise(async (r, j) => {
										if (composeItem.children.length && composeItem.children[0].id) {
											composeItem.children = composeItem.children.map(i => i.id)
										}
										// 保存试题的blob链接
										const itemJsonFile = await this.$evTools.createBlobItem(composeItem)
										let file = new File([JSON.stringify(itemJsonFile)], composeItem.id + ".json");
										blobFiles.push(file)
										itemJsonFiles.push(composeItem)
										r({
											cosmosItem: composeItem,
											blobItem: itemJsonFile
										})
										console.log(composeItem)
									}))
								})
							} else {
								// 如果已有blob字段 说明是已经保存到blob的试题 只需要将最新试题更新到paper目录下（自动手动挑题情况）
								promiseArr.push(new Promise(async (r, j) => {
									// 保存试题的blob链接
									const itemJsonFile = await this.$evTools.createBlobItem(exerciseItem)
									let file = new File([JSON.stringify(itemJsonFile)], exerciseItem.id + ".json");
									blobFiles.push(file)
									itemJsonFiles.push(exerciseItem)
									r({
										cosmosItem: exerciseItem,
										blobItem: itemJsonFile
									})
								}))
							}
						} else if (exerciseItem.children.length) { //如果是导入的 综合题
							// 如果是综合题 则需要把题干和小题都进行保存操作
							let composeArr = [exerciseItem, ...exerciseItem.children]
							composeArr.forEach(composeItem => {
								promiseArr.push(new Promise(async (r, j) => {
									if (composeItem.children.length && composeItem.children[0].id) {
										composeItem.children = composeItem.children.map(i => i.id)
									}
									// 将当前的试题数据转化为BLOB内部的试题JSON格式
									let removeItem = await this.$editorTools.doRemoveMideaHost(composeItem)
									const itemJsonFile = await this.$evTools.createBlobItem(removeItem)
									const cosmosItem = await this.$evTools.createCosmosItem(composeItem)
									// 首先保存新题目的JSON文件到Blob 然后返回URL链接
									let file = new File([JSON.stringify(itemJsonFile)], composeItem.id + ".json");
									blobFiles.push(file)
									try {
										// 等待上传blob的返回结果
										let blobFile = await containerClient.upload(file, 'item/' + composeItem.id, undefined, false, false)
										if (blobFile.blob) {
											// 保存试题JSON文件到试卷文件夹需要
											itemJsonFiles.push(composeItem)
											// 保存到COSMOS是不含base64图片编码的数据 避免数据量过大
											cosmosItem.blob = blobFile.blob
											// 保存当前试题到数据库
											that.saveExercise(cosmosItem).then(res => {
												r({
													cosmosItem: cosmosItem,
													blobItem: blobFile
												})
											})
										} else {
											j(500)
										}
									} catch (e) {
										this.$Message.error(e.spaceError)
										this.isLoading = false
									}
								}))
							})
						} else {
							// 如果没有blob字段 说明试题还没有保存到item目录下 则需要进行保存item文件夹后再保存到paper文件夹（导入试题情况）
							promiseArr.push(new Promise(async (r, j) => {
								// 将当前的试题数据转化为BLOB内部的试题JSON格式
								let removeItem = await this.$editorTools.doRemoveMideaHost(exerciseItem)
								const itemJsonFile = await this.$evTools.createBlobItem(removeItem)
								const cosmosItem = await this.$evTools.createCosmosItem(exerciseItem)
								// 首先保存新题目的JSON文件到Blob 然后返回URL链接
								let file = new File([JSON.stringify(itemJsonFile)], exerciseItem.id + ".json");
								blobFiles.push(file)
								try {
									// 等待上传blob的返回结果
									let blobFile = await containerClient.upload(file, 'item/' + exerciseItem.id, undefined, false, false)
									if (blobFile.blob) {
										// 保存试题JSON文件到试卷文件夹需要
										itemJsonFiles.push(exerciseItem)
										// 保存到COSMOS是不含base64图片编码的数据 避免数据量过大
										cosmosItem.blob = blobFile.blob
										// 保存当前试题到数据库
										that.saveExercise(cosmosItem).then(res => {
											r({
												cosmosItem: exerciseItem,
												blobItem: blobFile
											})
										})
									} else {
										j(500)
									}
								} catch (e) {
									this.$Message.error(e.spaceError)
									this.isLoading = false
								}
							}))
						}
					}
					Promise.all(promiseArr).then(result => {
						let updateSize = this._.sum(blobFiles.map(file => file.size))
						console.log(result)
						// 子题保存之后 统一更新blobSize
						blobTool.updateSize([{
							url: 'item',
							size: updateSize
						}], containerName).then(res => {
							let slides = []
							// 主观题的answer为空数组
							let nullType = ['complete', 'subjective', 'compose', 'correct', 'connector']
							result.map(i => i.cosmosItem).forEach(item => {
								console.log(item)
								let o = {
									url: item.id + '.json',
									type: item.type,
									scoring: {
										score: item.score || 0,
										knowledge: item.knowledge || [],
										field: item.field || 1,
										ans: nullType.includes(item.type) ? [] : (item.answer || [])
									}
								}
								item.type === 'compose' && delete o.scoring
								slides.push(o)
							})
							resolve({
								slides: slides,
								files: itemJsonFiles
							})
						}).catch(err => {
							this.$Message.error(this.$t('evaluation.newExercise.uploadErrorTip'));
						})
					}).catch(err => {
						console.log(err)
						this.$Message.error(this.$t('evaluation.paperList.saveItemsFailTip'))
					})
				})
			},

			/* 获取所有试题Blob前缀 */
			getListPrefixs(list) {
				let prefixArr = []
				list.forEach(item => {
					if (item.type === 'compose' && item.children.length) {
						prefixArr.push('item/' + item.id)
						prefixArr = prefixArr.concat(item.children.map(i => 'item/' + i.id))
					} else {
						prefixArr.push('item/' + item.id)
					}
				})
				console.log('试题的前缀集合', prefixArr)
				return prefixArr
			},

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

			/* 保存单个试题 */
			saveExercise(item) {
				item.code = item.scope === 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId
				return new Promise((r, j) => {
					this.$api.newEvaluation.SaveSingleExercise({
						itemInfo: item,
						option: this.isEditPaper ? 'update' : 'insert'
					}).then(res => {
						if (!res.error) {
							r(res)
						} else {
							j(res)
							this.$Message.error(this.$t('evaluation.paperList.saveItemsFailTip'))
						}

					})
				})
			},

			// 判断试卷是否存在于Blob中
			isPaperExist(paperName) {
				return new Promise(async (r, j) => {
					// 获取初始化Blob需要的数据
					let sasData = this.isSchool ? await this.$tools.getSchoolSas() : await this.$tools.getPrivateSas()
					//初始化Blob
					let containerClient = new blobTool(sasData.url, sasData.name, sasData.sas, this.isSchool ? 'school' : 'private')
					containerClient.exists('paper/' + paperName + '/index.json').then(
						(res) => {
							r(res)
						},
						(err) => {
							j(err)
							this.$Message.error('API Error')
						}
					)
				})
			},

			// 判断试卷是否存在于Blob中
			isContainerFull() {
				return new Promise(async (r, j) => {
					let scope = this.isSchool ? 'school' : 'private'
					// 获取初始化Blob需要的数据
					let sasData = this.isSchool ? await this.$tools.getSchoolSas() : await this.$tools.getPrivateSas()
					//初始化Blob
					let containerClient = new blobTool(sasData.url, sasData.name, sasData.sas, scope)
					containerClient.isContainerFull(scope).then(
						(res) => {
							r(res)
						},
						(err) => {
							j(err)
							this.$Message.error('API Error')
						}
					)
				})
			},

			/** 保存当前试卷数据 */
			async saveTestPaper() {
				let exListVm = this.$refs.testPaper.$refs.exList
				let hasSurplus = exListVm.surPlusScore // 判断是否有剩余分数未分配
				let noScoreList = exListVm.exerciseList.filter(item => item.score === 0) // 判断是否有未配分的题目
				let hasErrorItem = exListVm.errorList.length > 0
				let groupTypeList = exListVm.groupTypeList
				let list = this.evaluationInfo.item
				this.$refs.testPaper.isShowAnalysis = false
				if (this.evaluationInfo.name.trim() === '') {
					this.$Message.warning(this.$t('evaluation.paperList.emptyNameTip'))
					return
				}
				if (!hasErrorItem) {
					if (hasSurplus === 0) {
						if (!noScoreList.length) {
							this.isLoading = true
							let isPaperExist = await this.isPaperExist(this.evaluationInfo.name)
							let isContainerFull = await this.isContainerFull()
							if (!isPaperExist) {
								if (list.length) {
									// 拿到题型顺序的试题数组进行拼接
									let arr = []
									groupTypeList.forEach(i => {
										arr = arr.concat(i.list)
									})
									if (!this.checkComposeScore(arr)) return
									if (isContainerFull) {
										this.$Message.warning(this.$t('evaluation.paperList.noSpaceTip'))
									} else {
										// 只按照默认顺序保存
										// let saveArr = this.viewModel === 'type' ? arr : list
										this.doSavePaper(arr)
									}
								} else {
									this.$Message.warning(this.$t('evaluation.paperList.noItemTip'))
								}
							} else {
								this.$Modal.confirm({
									title: this.$t('evaluation.newExercise.modalTip'),
									content: this.$t('evaluation.paperList.isExistPaperTip'),
									onOk: async () => {
										// 拿到题型顺序的试题数组进行拼接
										let arr = []
										groupTypeList.forEach(i => {
											arr = arr.concat(i.list)
										})
										this.isLoading = true
										if (!this.checkComposeScore(arr)) return
										let blobList = await this.getPaperFiles('paper/' + this.evaluationInfo.name)
										let files = blobList.blobList.map(i => i.blob)
										this.onDeleteBlobPaper(files).then(r => {
											if (isContainerFull) {
												this.$Message.warning(this.$t('evaluation.paperList.noSpaceTip'))
											} else {
												// 只按照默认顺序保存
												// let saveArr = this.viewModel === 'type' ? arr : list
												this.doSavePaper(arr)
											}
										})
									},
									onCancel: () => {
										this.isLoading = false
										this.$Message.warning(this.$t('evaluation.paperList.cancelSaveTip'))
									}
								})
							}
						} else {
							this.$Message.warning(this.$t('evaluation.paperList.hasNoScoreTip'))
							this.isLoading = false
						}
					} else {
						this.$Message.warning(this.$t('evaluation.paperList.noCompleteScoreTip'))
						this.isLoading = false
					}
				} else {
					this.$Message.warning(this.$t('evaluation.paperList.hasErrorItemTip'))
					this.isLoading = false
				}
			},

			/* 检查综合题配分是否正确 */
			checkComposeScore(arr) {
				let flag = true
				for (let index = 0; index < arr.length; index++) {
					let i = arr[index]
					if (i.type === 'compose' && i.children.length) {
						let childTotalScore = i.children.reduce((p, e) => parseInt(p) + parseInt(e.score), 0)
						let hasNoScoreChild = i.children.filter(j => !j.score).length > 0
						if (i.score !== childTotalScore || hasNoScoreChild) {
							console.log(i.score)
							console.log(childTotalScore)
							console.log(index)
							let exList = this.$refs.testPaper.$refs.exList
							let exerciseDom = Array.from(exList.$el.getElementsByClassName('exercise-item')).filter(item => item.dataset.id ===
								i.id)[0]
							exerciseDom.style.backgroundColor = '#ffa7a7'
							this.$nextTick(() => {
								if (this.$refs.paperRef) {
									this.$refs['paperRef'].scrollTo({
											y: exerciseDom.offsetTop
										},
										500
									)
								}
							})
							setTimeout(() => {
								exerciseDom.style.backgroundColor = '#fff'
							}, 2000)
							this.$Message.warning(`${ this.$t('evaluation.createPaper.tip1') } ${ index + 1 } ${ this.$t('evaluation.createPaper.tip2') }${ i.score > childTotalScore ? this.$t('evaluation.createPaper.tip3') : this.$t('evaluation.createPaper.tip4') }，${ this.$t('evaluation.createPaper.tip5') }`)
							flag = false
							this.isLoading = false
							break
						}
					} else {
						flag = true
					}
				}

				return flag
			},

			getPaperFiles(path) {
				return new Promise(async (r, j) => {
					// 获取初始化Blob需要的数据
					let sasData = this.isSchool ? await this.$tools.getSchoolSas() : await this.$tools.getPrivateSas()
					//初始化Blob
					let containerClient = new blobTool(sasData.url, sasData.name, sasData.sas, this.isSchool ? 'school' : 'private')
					// 等待blob的返回结果
					containerClient.listBlob({
						prefix: path
					}).then(
						(res) => {
							r(res)
						},
						(err) => {
							this.$Message.error('API Error')
						}
					)
				})

			},

			onDeleteBlobPaper(files) {
				return new Promise(async (r, j) => {
					// 获取初始化Blob需要的数据
					let sasData = this.isSchool ? await this.$tools.getSchoolSas() : await this.$tools.getPrivateSas()
					//初始化Blob
					let containerClient = new blobTool(sasData.url, sasData.name, sasData.sas, this.isSchool ? 'school' : 'private')
					// 等待blob的返回结果
					containerClient.deleteBlobBatch(files).then(
						(res) => {
							r(res)
						},
						(err) => {
							this.$Message.error('API Error')
						}
					)
				})
			},

			/* 保存试卷业务 */
			async doSavePaper(list) {
				console.log('保存的试卷题目集合', list)
				this.isLoading = true
				let multipleRule = this.$refs.testPaper.$refs.exList.multipleRule
				let modifyItems = this.$refs.testPaper.$refs.exList.modifyItems
				// 将传进来的试题 如果是导入的试题 则需要补充年级学段等信息
				let refreshList = await this.refreshImportItems(list)
				// 保存导入的试题到BLOB以及COSMOS
				this.savePaperItems(refreshList, modifyItems, this.isEditPaper).then(async res => {
					let guid = this.$tools.guid()
					let paperItem = {
						id: this.evaluationInfo.id || guid,
						code: this.editPaper ? this.editPaper.code.replace('Paper-','') : (this.isSchool ? this.$store.state.userInfo.schoolCode : this.$store
							.state.userInfo.TEAMModelId),
						scope: this.isSchool ? 'school' : 'private',
						gradeIds: this.isSchool ? (this.evaluationInfo.paperGrade.length ? this.evaluationInfo.paperGrade.map(i => i + '') : this.gradeList
							.map((i,index) => index + '')) : [],
						subjectId: this.isSchool ? this.subjectList[this.evaluationInfo.paperSubject].id : null,
						subjectName: this.isSchool ? this.subjectList[this.evaluationInfo.paperSubject].name : '',
						periodId: this.isSchool ? this.schoolInfo.period[this.evaluationInfo.paperPeriod].id : null,
						name: this.evaluationInfo.name,
						points: this.getPaperPoints(this.evaluationInfo.item),
						scoring: this.getAnswers(list),
						score: this.evaluationInfo.score,
						multipleRule: multipleRule || 1
					}
					let blobPaper = await this.$evTools.createBlobPaper(paperItem, res.slides)
					// 首先保存新题目的JSON文件到Blob 然后返回URL链接
					let paperFile = new File([JSON.stringify(blobPaper)], "index.json");
					// 获取初始化Blob需要的数据
					let sasData = this.evaluationInfo.type === 'private' ? await this.$tools.getPrivateSas() : await this.$tools.getSchoolSas()
					//初始化Blob
					let containerClient = new blobTool(sasData.url, sasData.name, sasData.sas, this.evaluationInfo.type)

					let containerName = paperItem.scope === 'private' ? this.$store.state.userInfo.TEAMModelId : this.$store.state
						.userInfo.schoolCode
					/* 上传前进行试卷blob查询size */
					let beforeSizeArr = await blobTool.checkPrefixSize(['paper/' + paperItem.name], containerName)
					let beforeSize = this._.sum(beforeSizeArr.map(i => i.size))
					console.log('试卷上传前的size',beforeSize)

					try {
						let promiseArr = []
						let blobFile = null

						console.log('试卷题目的ID集合', res.files)
						console.log('试卷ITEM', paperItem)
						// return
						let privateSas = await this.$tools.getPrivateSas()
						let privateBlob = new blobTool(privateSas.url, privateSas.name, privateSas.sas, 'private')
						let schoolSas = await this.$tools.getSchoolSas()
						let schoolBlob = new blobTool(schoolSas.url, schoolSas.name, schoolSas.sas, 'school')

						// 放入试题json文件以及index.json文件
						for (let i = 0; i < res.files.length; i++) {
							promiseArr.push(new Promise(async (r, j) => {
								// let result = await containerClient.upload(res.files[i], 'paper/' + paperItem.name, undefined, false)
								// r(result)

								let item = res.files[i]
								if (item.scope == 'school') {
									containerClient.copyFolder('paper/' + paperItem.name + '/', 'item/' + item.id, schoolBlob, null, false)
										.then(res => {
											r(200)
										})
								} else {
									containerClient.copyFolder('paper/' + paperItem.name + '/', 'item/' + item.id, privateBlob, null,
										false).then(res => {
										r(200)
									})
								}
							}))
						}
						promiseArr.push(new Promise(async (r, j) => {
							try {
								blobFile = await containerClient.upload(paperFile, 'paper/' + paperItem.name, undefined, false)
								console.log('上传到试卷目录下', blobFile)
								r(blobFile)
							} catch (e) {
								j(e)
								this.$Message.error(e.spaceError)
								this.isLoading = false
							}
						}))
						// 进行试卷文件上传Blob
						Promise.all(promiseArr).then(async result => {
							/* 上传前进行试卷blob查询size */
							let afterSizeArr = await blobTool.checkPrefixSize(['paper/' + paperItem.name], containerName)
							let afterSize = this._.sum(afterSizeArr.map(i => i.size))
							console.log('试卷上传后的size', afterSize)
							if (blobFile.blob) {
								// 保存到COSMOS是不含base64图片编码的数据 避免数据量过大
								paperItem.blob = blobFile.blob.split('/index.json')[0]
								let params = {
									paper: await this.$evTools.createCosmosPaper(paperItem),
									option: this.isEditPaper ? 'update' : 'insert'
								}
								//  保存试卷到cosmos
								this.$api.learnActivity.SaveExamPaper(params).then(
									res => {
										if (res.error == null) {
											this.$Message.success(this.isEditPaper ? this.$t('evaluation.paperList.editSuc') : this.$t(
												'evaluation.paperList.saveSuc'))
											this.isLoading = false

											// 子题保存之后 统一更新blobSize
											blobTool.updateSize([{
												url: 'paper/' + paperItem.name,
												size: afterSize - beforeSize
											}], containerName).then(res => {
												this.$router.push({
													name: this.evaluationInfo.type === 'private' ? 'personalBank' : 'schoolBank',
													params: {
														tabName: 'paper'
													}
												})
											}).catch(err => {
												this.$Message.error(this.$t('evaluation.newExercise.uploadErrorTip'));
											})
										} else {
											this.$Message.error(this.$t('evaluation.paperList.saveFail'))
											this.isLoading = false
										}
									},
									err => {
										this.$Message.error(this.$t('evaluation.paperList.saveFail'))
										this.isLoading = false
									}
								)
							}
						})
					} catch (e) {
						this.$Message.error(this.$t('evaluation.paperList.saveItemsFailTip'))
						this.isLoading = false
					}
				})
			},

			/* 获取整张试卷的答案合计Answers */
			getAnswers(items) {
				let arr = []
				// 主观题的answer为空数组
				let nullType = ['complete', 'subjective', 'compose', 'correct', 'connector']
				items.forEach((i, index) => {
					arr.push({
						type: i.type,
						ans: nullType.includes(i.type) ? [] : i.answer,
						score: i.score
					})
				})
				return arr
			},

			/* 获取整张试卷的知识点集合 */
			getPaperPoints(items) {
				let arr = []
				items.forEach((i, index) => {
					if (i.knowledge) {
						arr = arr.concat(i.knowledge)
					}
				})
				return arr
			},

			/* 判断Blob容器内是否已存在相同容器 */
			hasSamePaper(container, name) {
				containerClient.listBlob({
					prefix: 'paper'
				}).then(
					(res) => {
						console.log(res)
					},
					(err) => {
						this.$Message.error('API Error')
					}
				)
			},

			/* 渲染需要编辑的试卷信息 */
			async doRender(paper) {
				console.log('传进来的paper')
				console.log(paper)
				let schoolInfo = null
				if (paper.scope === 'school') {
					schoolInfo = await this.getSchoolBaseInfo()
					this.subjectList = schoolInfo ? this.schoolInfo.period.filter(i => i.id === paper.periodId)[0].subjects : []
				}
				this.evaluationInfo = {
					id: paper.id,
					name: paper.name,
					code: paper.code,
					type: paper.scope,
					paperPeriod: schoolInfo && paper.scope === 'school' ? this.schoolInfo.period.map(i => i.id).indexOf(paper.periodId) :
						null,
					paperGrade: schoolInfo && paper.scope === 'school' ? paper.gradeIds.map(i => +i) : [],
					paperSubject: schoolInfo && paper.scope === 'school' ? this.subjectList.map(i => i.id).indexOf(paper.subjectId) :
						[],
					score: paper.score,
					item: paper.item,
					multipleRule: paper.multipleRule || 1,
					startTime: 0,
					endTime: 0,
					createType: 'manual'
				}
				console.log(this.evaluationInfo)
			}
		},

		mounted() {
			let routerData = this.$route.params.paper
			if (routerData) {
				this.doRender(routerData)
				this.editPaper = routerData
				this.isEditPaper = true
				this.evaluationInfo.createType == 'manual'
				this.activeTab = 'preview'
				this.$EventBus.$emit('onPaperItemChange', routerData.item)
			}
			this.$EventBus.$off('onBackToTop')
			this.$EventBus.$on('onBackToTop', () => {
				this.handleBackToTop()
			})
		},

		computed: {
			paperScrollTop() {
				return this.$store.state.totalAnalysis.paperScrollTop
			},
			isSchool() {
				return this.$route.name === 'newSchoolPaper'
			},
			propPeriod() {
				return this.$route.name === 'newSchoolPaper' && this.subjectList.length ? this.schoolInfo.period[this.evaluationInfo
					.paperPeriod].id : null
			},
			propSubject() {
				return this.$route.name === 'newSchoolPaper' && this.subjectList.length ? this.subjectList[this.evaluationInfo.paperSubject]
					.id : null
			}
		},

		watch: {
			paperScrollTop: {
				handler(n) {
					this.$refs.testPaper.isShowBackToTop = n > 200
				}
			}
		}
	}
</script>
<style scoped lang="less">
	@import "./CreatePaper.less";
</style>
<style>
	.evaluation-attr-form .ivu-input,
	.evaluation-attr-form .ivu-select-selection {
		background: none;
		color: white;
		border-color: #999999;
		font-size: 14px;
	}

	.evaluation-attr-form .ivu-input {
		/*border:none;
    border-bottom:1px solid #424242;
    border-radius:0px;*/
	}

	.evaluation-attr-wrap .ivu-form .ivu-form-item-label {
		color: #a5a5a5;
	}

	.evaluation-attr-wrap .ivu-tag {
		background-color: #2db6f4;
		border: none;
	}

	.evaluation-attr-wrap .ivu-tag .ivu-tag-text {
		color: #fff;
	}

	.evaluation-attr-wrap .ivu-tag .ivu-icon-ios-close {
		color: #fff;
	}

	.evaluation-attr-wrap-inputNumber .ivu-input-number-input {
		color: #fff;
	}

	.evaluation-question-main .ivu-tabs-bar {
		border-color: #404040;
	}

	.evaluation-question-main .ivu-tabs.ivu-tabs-card>.ivu-tabs-bar .ivu-tabs-tab {
		border: none;
		background-color: #303030;
		color: white;
		margin-right: 2px;
	}

	.evaluation-question-main .ivu-tabs.ivu-tabs-card>.ivu-tabs-bar .ivu-tabs-tab-active {
		background-color: #404040;
		color: white;
		font-weight: 600;
	}

	.evaluation-question-main .ivu-tabs .ivu-tabs-content-animated {
		height: 100%;
	}

	.evaluation-question-main .ivu-tabs-bar {
		margin-bottom: 0px;
	}

	.create-evaluation-container .ivu-input-number-input,
	.create-evaluation-container .ivu-input-number {
		width: 100%;
		background: none;
		border-color: #999999;
	}
</style>
