<template>
	<div class="test-paper-container">
		<div class="review-header" v-if="!isNewPaper">
			<div class="review-title">
				<Icon type="md-arrow-back" @click="goBack" />
				<span>{{ data.targetName }} 【 {{ data.no}} {{ data.name }} 】</span>
			</div>
			<div class="ability-des">
				<p>{{ data.desc }}</p>
			</div>
		</div>
		
		<div class="questions-wrap">
			<div v-if="!items.length">
				<EmptyData textContent="当前能力点下暂无检测试题数据"></EmptyData>
			</div>
			<div ref="testPaperRef" v-else>
				<div class="question-item" v-for="(item,index) in items" :key="index">
					<span>{{ index + 1 }}. </span>
					<p v-html="item.question" class="question-item-stem"></p>
					<span> ({{ item.type === 'single' ? '单选' : item.type === 'multiple' ? '多选' : '判断'}})</span>
					<span class="question-item-tools" v-if="isNewPaper &&  $access.can('area.*')">
						<Icon type="md-create" title="编辑试题" @click="onEditQues(item,index)"/>
						<Icon type="md-trash" title="删除试题" @click="onDeleteQues(item,index)"/>
					</span>
					<div class="question-item-options">
						<RadioGroup v-model="isNewPaper ? answerArr[index][0] : answerArr[index]" type="button" button-style="solid" v-if="item.type !== 'multiple'">
							<Radio v-for="(option,optionIndex) in item.options" :key="optionIndex" :label="option.code" :disabled="isNewPaper">{{ option.code + ' . ' + getSimpleText(option.value) }}</Radio>
						</RadioGroup>
						<CheckboxGroup v-model="answerArr[index]" v-if="item.type === 'multiple'">
							<Checkbox v-for="(option,optionIndex) in item.options" :key="optionIndex" :label="option.code" border  :disabled="isNewPaper">{{ option.code + ' . ' + getSimpleText(option.value) }}</Checkbox>
						</CheckboxGroup>
					</div>
					<Divider />
				</div>
			</div>
			
		</div>
		
		<Button v-if="!isNewPaper && items.length" type="success" size="large" :loading="isBtnLoading" style="margin-left: 30px;background-color: #16c18e;border: none;" icon="ios-paper-plane" @click="onSubmit">提交答案</Button>
		<Button v-if="isNewPaper && hasModify" type="success" :loading="isBtnLoading" style="margin-left: 30px;background-color: #16c18e;border: none;" icon="ios-paper-plane" @click="onSavePaper">保存试卷</Button>
	
		<!-- 新建题目弹窗 -->
		<Modal v-model="addModal" width="800" footer-hide class="related-modal survey-modal" @on-visible-change="onModalChange">
			<div class="modal-header" slot="header">{{ $t('survey.questionaire.add') }}{{ typeList[curType] }}{{ $t('survey.questionaire.item') }}</div>
			<template v-if="isUpdate">
				<!-- <BaseAddItem ref="addItem" :type="curType" :currentQn="curItem"></BaseAddItem> -->
				<BaseSingle v-if="curType==='single'" ref="addItem" :editInfo="curItem" @onSave="onSave" needAnswer></BaseSingle>
				<BaseMultiple v-if="curType==='multiple'" ref="addItem" :editInfo="curItem" @onSave="onSave" needAnswer></BaseMultiple>
				<BaseJudge v-if="curType==='judge'" ref="addItem" :editInfo="curItem" @onSave="onSave" needAnswer></BaseJudge>
				<Button class="modal-btn" @click="onConfirmAdd">{{ $t('survey.questionaire.confirm') }}</Button>
			</template>
		</Modal>
		
		<!-- 新建题目弹窗 -->
		<Modal v-model="importModal" width="800" footer-hide class="related-modal">
			<div class="modal-header" slot="header">试题导入</div>
			<AbilityUpload :acceptTypes="['xls','xlsx']" mode="import" @uploadFinish="uploadFinish"></AbilityUpload>
		</Modal>
	</div>
</template>

<script>
	import blobTool from "@/utils/blobTool.js";
	import BaseSingle from "@/components/questionnaire/BaseSingle.vue"
	import BaseMultiple from "@/components/questionnaire/BaseMultiple.vue"
	import BaseJudge from "@/components/questionnaire/BaseJudge.vue"
	export default{
		components:{
			BaseSingle,
			BaseMultiple,
			BaseJudge
		},
		props: {
			mode:{
				type:String,
				default:'self'
			},
			abilityData:{
				type:Object,
				default:() => {
					id:''
				}
			},
			isNewPaper:{
				type:Boolean,
				default:false
			}
		},
		data(vm) {
			return {
				importModal:false,
				hasModify:false,
				curItem:null,
				typeList: {
					'single': vm.$t('survey.questionaire.single'),
					'multiple': vm.$t('survey.questionaire.multiple'),
					'judge':vm.$t('survey.questionaire.judge'),
					'subjective': vm.$t('survey.questionaire.subjective')
				},
				curType:'',
				addModal:false,
				isBtnLoading:false,
				data:{
					name:''
				},
				items:[],
				answerArr:[],
				trueAnswerArr:[],
				editIndex:null,
				isUpdate:false,
			}
		},
		created() {
			this.answerArr = this.isNewPaper ? this.items.map(i => i.answer) : []
		},
		methods:{
			/* 返回上级 */
			goBack() {
				this.$emit('goBack')
			},
			// 重置所有富文本编辑器内容 初始化
			onModalChange(val){
				this.isUpdate = val
			},
			/* 新增试题 */
			onChooseType(type){
				console.log(type);
				if(type === 'import'){
					this.importModal = true
				}else{
					this.curItem = null
					this.editIndex = null
					this.addModal = true
					this.curType = type
				}
			},
			/* 导入试题 */
			uploadFinish(res){
				this.items.push(...res)
				this.answerArr = this.items.map(i => i.answer)
				this.importModal = false
				this.$Message.success('导入成功！')
				this.hasModify = true
			},
			/* 编辑试卷题目 */
			onEditQues(item,index){
				item.option = item.options
				this.curItem = item
				this.editIndex = index
				this.curType = item.type
				this.addModal = true
			},
			/* 删除试卷题目 */
			onDeleteQues(item,index){
				this.$Modal.confirm({
					title: this.$t('survey.questionaire.confirmTitle'),
					content: this.$t('survey.questionaire.confirmText'),
					onOk: () => {
						this.items.splice(index, 1)
						this.hasModify = true
					}
				})
			},
			// 确认添加题目
			onConfirmAdd() {
				this.$refs.addItem.doSave()
			},
			/* 获取指定路径试卷下的所有文件 */
			getPaperFiles(path) {
				return new Promise(async (r, j) => {
					// 获取初始化Blob需要的数据
					let s = this.$store.state.user.osblob_uri
					let sasData = {
						sas: '?' + this.$store.state.user.osblob_sas,
						name: 'teammodelos',
						url: s.split(s.substring(s.lastIndexOf('/')))[0]
					}
					//初始化Blob
					let containerClient = new blobTool(sasData.url, sasData.name, sasData.sas, 'school')
					// 等待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 s = this.$store.state.user.osblob_uri
					let sasData = {
						sas: '?' + this.$store.state.user.osblob_sas,
						name: 'teammodelos',
						url: s.split(s.substring(s.lastIndexOf('/')))[0]
					}
					//初始化Blob
					let containerClient = new blobTool(sasData.url, sasData.name, sasData.sas, 'school')
					// 等待blob的返回结果
					containerClient.deleteBlobBatch(files).then(
						(res) => {
							r(res)
						},
						(err) => {
							this.$Message.error('API Error')
						}
					)
				})
			},
			/* 保存自我评测试卷 */
			async onSavePaper(){
				console.log(this.items)
				console.log(this.data)
				this.isBtnLoading = true;
				try{
					let qnBaseInfo = this.data
					let qnItems = this.items
					if(qnBaseInfo.blob){
						let blobList = await this.getPaperFiles(`yxpt/${this.curStandard}/train/` + qnBaseInfo.name + '/')
						let files = blobList.blobList.map(i => i.blob)
						await this.onDeleteBlobPaper(files)
					}
					qnBaseInfo.blob = await this.doUploadBlob(qnBaseInfo, qnItems);
					// 开始保存问卷
					this.$api.ability.SaveOrUpdateVolume(qnBaseInfo).then(res => {
						if(!res.error){
							this.$Message.success(this.$t('survey.doSuc'));
							this.hasModify = false
						}
					}).catch((error) => {
						this.$Message.error(`${error}`);
					}).finally(data => {
						this.isBtnLoading = false;
					});
				}catch(e){
					this.isBtnLoading = false;
				}
			},
			/* 上传index.json */
			async doUploadItems(qnBaseInfo,items){
				return new Promise(async (resolve, reject) => {
					let promiseArr = []
					// 获取初始化Blob需要的数据
					let s = this.$store.state.user.osblob_uri
					let sasData = {
						sas: '?' + this.$store.state.user.osblob_sas,
						name: 'teammodelos',
						url: s.split(s.substring(s.lastIndexOf('/')))[0]
					}
					//初始化Blob
					let containerClient = new blobTool(
						sasData.url,
						sasData.name,
						sasData.sas,
						'school'
					);
					
					for (let item of items) {
						let curId = item.id || this.$tools.guid()
						promiseArr.push(new Promise(async (r, j) => {
							// let itemJsonFile = await this.$evTools.createBlobItem(exerciseItem);
							let file = new File([JSON.stringify(item)], curId + ".json");
							try {
								// 等待上传blob的返回结果
								let blobFile = await containerClient.upload(file, `yxpt/${this.curStandard}/train/` + qnBaseInfo.name);
								if (blobFile.blob) {
									console.log('上传Blob成功', blobFile)
									r(`/train/${qnBaseInfo.name}/${curId}.json`)
								} else {
									this.$Message.error(this.$t('evaluation.newExercise.uploadErrorTip'));
								}
							} catch (e) {
								j(e)
								this.isBtnLoading = false;
								this.$Message.error(e.spaceError);
							}
						}))
					}
					Promise.all(promiseArr).then(result => {
						resolve(result)
					})
				})
			},
			/* 保存问卷题目到Blob */
			doUploadBlob(qnBaseInfo, items) {
				return new Promise(async (resolve,reject) => {
					try {
						if(items.length === 0){
							resolve('')
						}
						let itemUrls = await this.doUploadItems(qnBaseInfo, items)
						qnBaseInfo.slides = itemUrls
						// 获取初始化Blob需要的数据
						let s = this.$store.state.user.osblob_uri
						let sasData = {
							sas: '?' + this.$store.state.user.osblob_sas,
							name: 'teammodelos',
							url: s.split(s.substring(s.lastIndexOf('/')))[0]
						}
						//初始化Blob
						let containerClient = new blobTool(
							sasData.url,
							sasData.name,
							sasData.sas,
							'school'
						);
						let file = new File([JSON.stringify(qnBaseInfo)], "index.json");
						// 等待上传blob的返回结果
						let blobFile = await containerClient.upload(file, `yxpt/${this.curStandard}/train/` + qnBaseInfo.name);
						if (blobFile.blob) {
							delete qnBaseInfo.slides
							resolve(blobFile.blob)
						} else {
							this.$Message.error(this.$t('evaluation.newExercise.uploadErrorTip'));
						}
					} catch (e) {
						this.isBtnLoading = false;
						reject(e);
					}
				})
				
			},
			// 保存新增试题
			onSave(addItem){
				console.log(addItem)
				// 判断获取到的新题是否规范
				if ( this.getSimpleText(addItem.stemContent) && this.checkOptionNull(addItem.optionsContent)){
					let newItem = {
						question: addItem.stemContent,
						options: addItem.optionsContent,
						type: this.editIndex === null ? this.curType : this.curItem.type,
						answer:addItem.answer
					}
					console.log(newItem)
					if(this.editIndex === null){
						this.items.push(newItem)
						console.log(this.items)
					}else{
						this.$set(this.items, this.editIndex, newItem)
					}
					this.addModal = false
					this.answerArr = this.items.map(i => i.answer)
					this.hasModify = true
				}else{
					this.$Message.warning(this.$t('survey.questionaire.noCompleteTip'))
				}
			},
			// 提取富文本内容中的文本
			getSimpleText(html) {
				html = html + ''
				var r = /<(?!img|video|audio).*?>/g;
				return html.replace(r, "").replace(/&nbsp;/g, '　');
			},
			// 检测是否有空选项
			checkOptionNull(arr) {
				let flag = true
				for (let i = 0; i < arr.length; i++) {
					if (this.getSimpleText(arr[i].value + '') === '') {
						flag = false
					}
				}
				return flag
			},
			// 提交作答结果
			onSubmit(){
				let myAnswer = this.answerArr.map(i => Array.isArray(i) ? i.sort().join(',') : i)
				let trueAnswer =  this.trueAnswerArr.map(i => Array.isArray(i) ? i.sort().join(',') : i)
				console.log(myAnswer);
				console.log(trueAnswer);
				let exerciseScore = 1
				trueAnswer.forEach((i,index) => {
					if(myAnswer[index] !== i){
						exerciseScore = 0
					}
				})
				this.$api.jyzx.pointAction({
					"tmdid": this.$store.state.userInfo.TEAMModelId,
					"abilityId": this.data.id,
					"school": this.$store.state.userInfo.schoolCode,
					"opt": "ExerciseScore",
					"exercise":exerciseScore
				}).then(res => {
					this.isBtnLoading = false
					this.goBack()
					this.$Message.success('提交成功！自评结果为' + (exerciseScore ? '通过！' : '未通过！'))
				})
			},
			/* 获取能力点详情 */
			async getDetailById(id){
				let abilityDetail = await this.$evTools.getAbilityDetailById(id)
				console.log(abilityDetail)
				if(abilityDetail.blob){
					console.log(abilityDetail.blob)
					this.items = await this.getBlobItems(abilityDetail)
					this.trueAnswerArr = this.items.map(i => i.answer)
					this.answerArr = this.isNewPaper ? this.items.map(i => i.answer) : []
				}else{
					this.items = []
					this.answerArr = []
				}
				// if(this.$refs.testPaperRef){
				// 	this.$refs.testPaperRef.scrollIntoView()
				// }
				this.hasModify = false
				return abilityDetail
			},
			// 获取blob里的试题数据
			getBlobItems(qnItem){
				return new Promise(async (resolve,reject) => {
					let blobHost = this.$store.state.user.osblob_uri
					// 根据试卷的Blob地址 去读取JSON文件
					let sasString = '?' + this.$store.state.user.osblob_sas
					let promiseArr = []
					let indexJson = await this.getBlobJsonFile(qnItem.scope,qnItem.blob)
					let basePath = qnItem.blob.split('/train')[0]
					console.log(basePath);
					if(indexJson.slides.length){
						for (let item of indexJson.slides) {
							promiseArr.push(new Promise(async (r,j) => {
								try{
									let itemJson = JSON.parse(await this.$tools.getFile(blobHost + basePath + item + sasString))
									r(itemJson)
								}catch(e){
									j(e)
								}
							}))
						}
						Promise.all(promiseArr).then(result => {
							resolve(result)
						}).catch(err => {
							reject(err)
						})
					}else{
						resolve([])
					}
					
				})
			},
			// 获取blob里的试题数据
			getBlobJsonFile(scope,url){
				return new Promise(async (resolve,reject) => {
					let blobHost = this.$store.state.user.osblob_uri
					// 根据试卷的Blob地址 去读取JSON文件
					let sasString =  '?' + this.$store.state.user.osblob_sas
					try{
						let itemJson = JSON.parse(await this.$tools.getFile(blobHost + url + sasString))
						resolve(itemJson)
					}catch(e){
						reject(e)
					}
				})
			},
		},
		computed:{
			curStandard(){
				return this.$store.state.user.schoolProfile.school_base.standard
			}
		},
		watch:{
			abilityData:{
				async handler(n,o){
					if(n && n.id){
						this.data = await this.getDetailById(n.id)
						console.log(this.data)
					}
				},
				immediate:true,
				deep:true
			}
		}
	}
</script>

<style lang="less" src="./TestPaper.less"></style>
