<template>
	<div class="component-questionnaire">
		<!-- 问卷的基本操作栏 -->
		<p class="qn-title">{{currentQn.name}}</p>
		<p class="qn-description" v-html="currentQn.description"></p>
		<div class="qn-item-box">
			<div v-if="items.length === 0" class="no-data-text">
			    <img src="@/assets/icon/no_data.svg" width="120" />
			    <span style="margin-top:15px;color:#808080">{{ $t('survey.questionaire.noItemData') }}</span>
			</div>
			<!-- 问卷题目单元 -->
			<draggable class="list-group" tag="div" v-model="items" v-bind="dragOptions" @start="drag = true" @end="onDragEnd" v-else>
				<transition-group type="transition" :name="!drag ? 'flip-list' : null">
					<div class="qn-item animated fadeInUp" v-for="(item,index) in items" :key="index">
						<div class="qn-item-content">
							<!-- 题干 -->
							<p class="qn-stem">
								<span style="color: red;" v-show="item.required">* </span>
								<span>{{ index + 1 }}. </span>
								<span v-html="item.question"></span>
								<span>( {{ typeList[item.type] }} )</span>
							</p>
							<!-- 单选题-选项 -->
							<RadioGroup v-model="radioModel" v-if="item.type === 'single' || item.type === 'judge'">
								<Radio v-for="(option,optionIndex) in item.option" :key="optionIndex" :label="getSimpleText(option.value)" disabled></Radio>
							</RadioGroup>
							<!-- 多选题-选项 -->
							<CheckboxGroup v-model="multipleModel" v-if="item.type === 'multiple'">
								<Checkbox v-for="(option,optionIndex) in item.option" :key="optionIndex" :label="getSimpleText(option.value)" disabled>
								</Checkbox>
							</CheckboxGroup>
							
							
							<!-- 数据分析 -->
							<transition name="indexFade">
							      <div>
									  <!-- <BaseQnBar :barId="'bar' + index" :barData="item.result || []" v-if="curIndexList.includes(index) && item.type !== 'subjective'"></BaseQnBar> -->
									  <BaseAnsList v-if="curIndexList.includes(index) && item.type === 'subjective'" :ansList="item.result.details"></BaseAnsList>
								  </div>
							</transition>
							<!-- 工具栏 -->
							<div class="qn-tools">
								<div class="qn-tools-item" @click="onItemEdit(item,index)" v-if="editable">
									<Icon type="md-create" />
									<span>{{ $t('survey.questionaire.edit') }}</span>
								</div>
								<div class="qn-tools-item" @click="onItemDelete(index)"  v-if="editable">
									<Icon type="md-trash" />
									<span>{{ $t('survey.questionaire.remove') }}</span>
								</div>
								<!-- <div class="qn-tools-item" @click="onItemAnalysis(index)"> -->
								<div class="qn-tools-item" @click="onItemAnalysis(index,item)" v-if="currentQn.progress === 'finish' && item.type === 'subjective'">
									<Icon type="md-podium" />
									<span>{{ $t('survey.questionaire.analysisData') }}</span>
								</div>
							</div>
						</div>
						<div class="qn-item-charts" v-if="currentQn.progress === 'finish' && item.type !== 'subjective'">
							<BaseMiniBar :barId="'minibar' + index" :barData="item.result || []"></BaseMiniBar>
						</div>
					</div>
				</transition-group>
			</draggable>
		</div>

		<!-- 新建题目弹窗 -->
		<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">
			<vuescroll>
				<!-- <BaseAddItem ref="addItem" :type="curType" :currentQn="curItem"></BaseAddItem> -->
				<BaseSingle v-if="curType==='single'" ref="addItem" :editInfo="curItem" @onSave="onSave"></BaseSingle>
				<BaseMultiple v-if="curType==='multiple'" ref="addItem" :editInfo="curItem" @onSave="onSave"></BaseMultiple>
				<BaseJudge v-if="curType==='judge'" ref="addItem" :editInfo="curItem" @onSave="onSave"></BaseJudge>
				<BaseSubjective v-if="curType==='subjective'" ref="addItem" :editInfo="curItem" @onSave="onSave"></BaseSubjective>
				<Button class="modal-btn" @click="onConfirmAdd">{{ $t('survey.questionaire.confirm') }}</Button>
			</vuescroll>
			</template>
		</Modal>
	</div>
</template>
<script>
	import draggable from "vuedraggable"
	import BaseSingle from "./BaseSingle.vue"
	import BaseMultiple from "./BaseMultiple.vue"
	import BaseJudge from "./BaseJudge.vue"
	import BaseSubjective from "./BaseSubjective.vue"
	import BaseQnBar from "./BaseQnBar.vue"
	import BaseMiniBar from "./BaseMiniBar.vue"
	import BaseAnsList from "@/components/questionnaire/BaseAnsList.vue";
	
	export default {
		components: {
			draggable,
			BaseQnBar,
			BaseMiniBar,
			BaseSingle,
			BaseMultiple,
			BaseJudge,
			BaseSubjective,
			BaseAnsList
		},
		props: ["currentQn","isEdit","students"],
		data(vm) {
			return {
				curIndexList:[],
				curItem:null,
				isUpdate:false,
				barData:[],
				editIndex:null,
				editable:false,
				isShowAnalysis:false,
				isShowAllAnalysis:false,
				addModal: false,
				drag: false,
				radioModel: '',
				multipleModel: [],
				items: [],
				itemAnswers: [],
				curType: '',
				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')
				}
			};
		},
		created() { },
		methods: {
			// 拖拽完成之后
			onDragEnd() {
				this.drag = false
			},
			
			// 添加题目
			onMenuClick(name) {
				this.curType = name
				this.curItem = null
				this.editIndex = null
				this.addModal = true
				this.$nextTick(() => {
					this.$refs.addItem.resetContent()
				})
			},
			
			// 重置所有富文本编辑器内容 初始化
			onModalChange(val){
				this.isUpdate = val
			},
			
			// 确认添加题目
			onConfirmAdd() {
				this.$refs.addItem.doSave()
			},
			
			onSave(addItem){
				console.log(addItem)
				// 判断获取到的新题是否规范
				if ( this.getSimpleText(addItem.stemContent) && this.checkOptionNull(addItem.optionsContent)){
					let newItem = {
						id: this.editIndex === null && !this.curItem ? this.$tools.guid() : this.curItem.id,
						question: addItem.stemContent,
						option: addItem.optionsContent,
						type: this.editIndex === null ? this.curType : this.curItem.type,
						description:this.editIndex === null ? '' : this.curItem.description,
						required: true,
					}
					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
				}else{
					this.$Message.warning(this.$t('survey.questionaire.noCompleteTip'))
				}
			},

			// 提取富文本内容中的文本
			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
			},

			/* 编辑单个题目 */
			onItemEdit(item, index) {
				if(this.editIndex === index && this.curItem === item ){
					// this.$refs.addItem.doRender(item)
				}else{
					this.curItem = item
					this.editIndex = index
				}
				this.curType = item.type
				this.addModal = true
			},

			/* 删除单个题目 */
			onItemDelete(index) {
				this.$Modal.confirm({
					title: this.$t('survey.questionaire.confirmTitle'),
					content: this.$t('survey.questionaire.confirmText'),
					onOk: () => {
						this.items.splice(index, 1)
					}
				})
			},
			
			// 开启或关闭查看所有题目的数据分析
			onShowAllAnalysis(){
				this.curIndexList = !this.isShowAllAnalysis ? [... new Set(this.currentQn.items.keys())] : []
				this.isShowAllAnalysis = !this.isShowAllAnalysis
			},

			/* 查看单个题目的数据分析 */
			async onItemAnalysis(index,item) {
				if(this.curIndexList.includes(index)){
					this.isShowAnalysis = false
					this.curIndexList.splice(this.curIndexList.indexOf(index) , 1)
				}else{
					// 如果还没有获取单个题目详细数据 则需要访问Blob获取
					if(item.result.count.length === 0 || Object.keys(item.result.details).length === 0){
						let curItemRecordUrl = `/survey/${ this.currentQn.id }/qrecord/${ index }.json`
						let curItemRecord = await this.getBlobJsonFile(this.currentQn.scope,curItemRecordUrl)
						if(item.type === 'subjective'){
							let result = []
							for(let key in curItemRecord.other){
								result.push({
									id:key,
									name:this.students.filter(i => i.id === key)[0].name,
									value:curItemRecord.other[key]
								})
							}
							item.result.details = result
						}else{
							for(let key in curItemRecord.opt){
								curItemRecord.opt[key] = curItemRecord.opt[key].map(id => this.students.filter(i => i.id === id)[0].name) 
							}
							item.result.details = curItemRecord.opt
						}
					}
					this.isShowAnalysis = true
					this.curIndexList.push(index)
				}
			},
			
			// 获取blob里的试题数据
			getBlobItems(qnItem){
				return new Promise(async (resolve,reject) => {
					let blobHost = qnItem.scope === 'private' ?  JSON.parse(decodeURIComponent(localStorage.user_profile, "utf-8")).blob_uri : JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri
					// 根据试卷的Blob地址 去读取JSON文件
					let sasString = qnItem.scope === 'private' ?  await this.$tools.getPrivateSas() : await this.$tools.getSchoolSas()
					let promiseArr = []
					let indexJson = await this.getBlobJsonFile(qnItem.scope,qnItem.blob)
					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 + item + sasString.sas))
									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 = scope === 'private' ?  JSON.parse(decodeURIComponent(localStorage.user_profile, "utf-8")).blob_uri : JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri
					// 根据试卷的Blob地址 去读取JSON文件
					let sasString = scope === 'private' ?  await this.$tools.getPrivateSas() : await this.$tools.getSchoolSas()
					try{
						let itemJson = JSON.parse(await this.$tools.getFile(blobHost + url + sasString.sas))
						resolve(itemJson)
					}catch(e){
						reject(e)
					}
				})
			},
			
			/* 根据学生的作答记录 处理成 图表需要的记录 */
			makeItemResult(result,items) {
				let arr = [];
				items.forEach((item, index) => {
					let obj = {};
					let resultArr = [];
					item.result = { count:[],details:{}}
					item.option.forEach((opt,optIndex) => {
						obj.key = opt.code,
						obj.code = this.getSimpleText(opt.value);
						obj.value = this.getSelectNum(result.records, index, opt.code);
						resultArr.push(obj);
						obj = {};
					});
					item.result.count = resultArr;
					let curItemRecord = result.question[index]
					if(item.type === 'subjective'){
						let result = []
						for(let key in curItemRecord.other){
							result.push({
								id:key,
								name:this.students.filter(i => i.id === key)[0].name,
								value:curItemRecord.other[key]
								
							})
						}
						item.result.details = result
					}else{
						console.log(this.students)
						for(let key in curItemRecord.opt){
							curItemRecord.opt[key] = curItemRecord.opt[key].map(id => this.students.filter(i => i.id === id)[0].name) 
						}
						item.result.details = curItemRecord.opt
					}
				});
				this.items = items
			},
			
			/* 查找指定题目指定选项在作答数据里出现的次数 */
			getSelectNum(origin, itemIndex, option) {
				if(!origin.length){
					return 0
				}
				let target = origin[itemIndex].ans
				if(Object.keys(target).includes(option)){
					return target[option]
				}else{
					return 0 
				}
			},
			
			// 提取富文本内容中的文本
			getSimpleText(html) {
				var r = /<(?!img|video|audio).*?>/g;
				return html.replace(r, "");
			},
			
			async getQnRecord(item) {
				return new Promise(async (r, j) => {
					if(item.progress === 'finish' && item.recordUrl){
						try{
							let finishRecord = await this.getBlobJsonFile(item.scope,item.recordUrl)
							r(finishRecord)
						}catch(e){
							j(e)
						}
					}else{
						this.$api.questionnaire
							.FindRecordSurvey({
								id: item.id,
								code: item.code
							})
							.then((res) => {
								if (!res.error) {
									r(res);
								} else {
									j(500);
								}
						});
					}
					
				});
			},
		},

		mounted() {
            console.log(this.currentQn)
            console.log(this.isEdit)
		},
		computed: {
			dragOptions() {
				return {
					animation: 200,
					group: "description",
					disabled: this.currentQn.progress !== 'pending',
					ghostClass: "ghost"
				};
			}
		},
		watch: {
			currentQn: {
				async handler(newValue) {
					/** 编辑回显 */
					if (newValue && newValue.id) {
						if(newValue.progress !== 'pending'){
							try{
								let records = await this.getQnRecord(newValue)
								let items = await this.getBlobItems(newValue)
								this.makeItemResult(records,items)
							}catch(e){
								console.log(e)
								this.$Message.error(this.$t('survey.getFileFailTip'))
							}
							
						}else{
							this.items = await this.getBlobItems(newValue)
						}
						this.isShowAllAnalysis = false
						this.curIndexList = []
					} else {
						/** 新增 */
						this.items = []
					}
				},
				deep: true,
				immediate: true
			},
			isEdit:{
				handler(n,o){
					this.editable = n
				}
			}
		}
	};
</script>

<style lang="less">
	@import "./BaseQuestionnaire.less";
</style>
