<template>
	<div class="quesnaire">
		<!-- <div v-if="WarmMessageisOpen" class="warmMessage">
			<div class="messageCard animate__animated animate__fadeInDown">
				<div v-if="showMessageNum == 1">
					<h2>提交成功</h2>
					<svg-icon icon-class="quesnaireFinished" class="quesnairefinished-icon" />

					<p>提交成功，活動結束前仍可進行修改再次提交</p>
				</div>
				<div v-if="showMessageNum == 2">
					<h2>有必答題目未回答</h2>
					<svg-icon icon-class="quesnaireUnfinished" class="quesnairefinished-icon" />

					<p>
						你有
						<span class="undoNum">{{ undo }} 題 </span>必答問題未答，請先完成再提交
					</p>
					<button class="messageCardBtn" @click="closeWarmMessage()">
						確定
					</button>
				</div>
			</div>
		</div>
		<br />

		<div v-if="this.$store.getters.getItemTitle.isDone == false">
			<div v-if="this.$store.getters.getItemTitle.endTime <= '2020.02.10'">
				<br />
				<div class="dec animate__animated animate__bounceInLeft">
					<svg-icon icon-class="handonHint" class="warm-icon" />
					<span class="warm-hint">問卷時間已經結束，您本次問卷並未提交，問卷結果如下。</span>
				</div>
				<QuesNaireReport />
			</div>
		</div> -->
		<br />
		<EventBasicInfo />
		<!-- 已提交 -->
		<div v-if="alreadyAnswered" style="text-align: center;padding-top: 15%;">
			<Icon type="md-checkmark-circle-outline" color="#00ad6c" size="80"/>
			<p style="font-size: 30px;color:#00ad6c;font-weight: 600; margin:20px;">{{ $t('survey.studentWeb.already') }}</p>
		</div>
		<!-- 活动结束 -->
		<div v-if="!alreadyAnswered && surveyInfo.progress === 'finish'" style="text-align: center;padding-top: 15%;">
			<Icon type="md-stopwatch" color="#00ad6c" size="80"/>
			<p style="font-size: 30px;color:#00ad6c;font-weight: 600; margin:20px;">{{ $t('survey.studentWeb.overtime') }}</p>
		</div>
		

		<!--問卷完成後，在時間結束前仍可修改答案再提交-->
		<div v-if="surveyInfo.progress !== 'finish' && !alreadyAnswered">
			<BillBoardandLightBox :activityData="surveyInfo" />
			<div class="title-rect-group">
				<!-- <div class="title-rect" /> -->
				<h2 class="title-rect-name">{{ $t('survey.studentWeb.content') }}</h2>
			</div>
			<br />
			<!-- 问卷内容 -->
			<div v-for="(item, index) in surveyInfo.items" :key="index" class="survey-item">
				<!-- <br /> -->
				<div style="display: flex;font-weight: bold;">
					<span>{{ index + 1 }}. </span>
					<span v-html="item.question"></span>({{ typeList[item.type] }})<span></span>
				</div>
				<!-- 非问答 -->
				<div v-if="item.type !== 'subjective'">
					<div class="unitTestBtn" v-for="(option, optionIndex) in item.option" :key="optionIndex">
						<div class="unitTestbg" @click="onOptionClick(item,index,option.code)"
							:style="{ backgroundColor: submitArr[index].includes(option.code) ?  '#24b880' : 'transparent' }">
							{{ option.code }}. <span v-html="option.value" style="margin-left: 10px;"></span>
						</div>
					</div>
				</div>
				<!-- 问答 -->
				<div v-if="item.type === 'subjective'">
					<Input v-model="submitArr[index][0]" type="textarea" :rows="8" :placeholder="$t('studentWeb.exam.inputAnswers')" />
				</div>
				<Divider v-if="index != surveyInfo.items.length - 1" />
			</div>
			<br />
			<br />
			<button class="uploadBtn" @click="submitMessage()">
				<svg-icon icon-class="quesnaire" class="uloadBtn-icon" />
				<span>{{ $t('survey.studentWeb.submit') }}</span>
			</button>
		</div>

		<!-- {{ createdSaveCheckers() }} -->
	</div>
</template>

<script>
	import QuesNaireReport from "./QuesNaireReport";
	import EventBasicInfo from "../../EventBasicInfo";
	import BillBoardandLightBox from "../../EventView/BillBoardandLightBox";
	export default {
		name: "QuesNaire",
		components: {
			EventBasicInfo,
			BillBoardandLightBox,
			QuesNaireReport,
		},
		data(vm) {
			return {
				surveyInfo: { //问卷信息
					items: []
				},
				checkers: [],
				alreadyAnswered:false, //提交状态
				undo: 0,
				showMessageNum: 0,
				WarmMessageisOpen: false,
				isFirstSubmitted: false,
				hintnoAns: false,
				noAnsNo: [],
				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')
				},
				submitArr: [] //填写的数据
			};
		},

		created() {
			this.WarmMessageisOpen = false;
			this.isFirstSubmitted = false;
			this.hintnoAns = false;
			this.showMessageNum = 0;

			this.checkers = [];
			this.noAnsNo = [];
			this.createdSaveCheckers();

		},
		methods: {
			onOptionClick(item, index, code) {
				if (this.submitArr[index].includes(code)) {
					this.submitArr[index].splice(this.submitArr[index].indexOf(code), 1)
				} else {
					if (item.type !== 'multiple') {
						this.submitArr[index] = []
						this.submitArr[index].push(code)
					} else {
						this.submitArr[index].push(code)
					}
				}
				this.$forceUpdate()
			},

			submitMessage() {
				let params = {
					"id": this.surveyInfo.id,
					"code": this.surveyInfo.code,
					"userid": this.$store.state.userInfo.sub,
					"record": this.submitArr
				}
				//檢查使用者是否有漏題，有漏題進行提示
				this.$api.studentWeb.answerSurvey(params).then(async res => {
					switch (res.msgid){
						case 1:
							this.$Message.success(this.$t('studentWeb.queNaire.submitSuccess'))
							this.alreadyAnswered = true
							break;
						case 2:
                            this.$Message.error(this.$t('studentWeb.queNaire.overTime'))
							break;
						case 3:
                            this.$Message.error(this.$t('studentWeb.queNaire.answerErr'))
							break;		
						default:
							break;
					}
					
				})

			},
			closeWarmMessage() {
				this.WarmMessageisOpen = false;
			},
			createdSaveCheckers() {
				if (this.$store.getters.getResetSurvey == true) {
					this.checkers = [];
					var mockcheckersheet = [];
					for (let i = 0; i < 10; i++) {
						if (
							this.$store.getters.getItemTitle.isDone == false &&
							this.$store.getters.getFinishedItem.includes(
								this.$store.getters.getItemTitle.eventID
							) == false
						) {
							mockcheckersheet.push([]);
						} else if (
							this.$store.getters.getFinishedItem.includes(
								this.$store.getters.getItemTitle.eventID
							) == true ||
							this.$store.getters.getItemTitle.isDone == true
						) {
							mockcheckersheet.push("B");
						}
					}
					this.checkers = mockcheckersheet;
					this.$store.commit("resetSurvey", false);
					this.WarmMessageisOpen = false;
					this.showMessageNum = 0;
					this.isFirstSubmitted = false;
					this.hintnoAns = false;
					this.noAnsNo = [];
				}
			},
			qesNaire() {
				return this.$store.getters.getItemTitle.qesNaire;
			},
			
			/* 判断当前学生是否已作答该问卷 */
			isAnswerd(params){
				return new Promise((r,j) => {
					this.$api.studentWeb.isAnswerd(params).then(async res => {
						r(res.answered)
					})
				})
				
			},
			
			//获取投票数据
			// 获取surveyInfo的数据
			async getSurveyInfo() {
				if (this.$store.getters.getItemTitle.id) {
					let params = {
						"id": this.$store.getters.getItemTitle.id,
						"code": this.$store.getters.getItemTitle.scode
					}
					let isAnswerd = await this.isAnswerd(params)
					if(!isAnswerd){
						// 没有提交
						this.$api.studentWeb.getSurveyInfo(params).then(async res => {
							if (res) {
								this.surveyInfo = res.survey
								this.surveyInfo.items = await this.getBlobItems(res.survey)
								this.submitArr = []
								this.surveyInfo.items.forEach(i => {
									this.submitArr.push([])
								})
								this.$forceUpdate()
							}
						}).catch(err => {
							console.log(err)
						})
					}else{
						this.alreadyAnswered = true
					}
					
				}
				
				console.log(this.alreadyAnswered)
				console.log(this.surveyInfo)
			},

			// 获取blob里的问卷内容
			getBlobItems(qnItem) {
				return new Promise(async (resolve, reject) => {
					let schoolBlobHost = JSON.parse(decodeURIComponent(localStorage.student_profile, "utf-8")).blob_uri
					let privateBlobHost = schoolBlobHost.slice(0,schoolBlobHost.lastIndexOf('/')) + '/' +  qnItem.creatorId
					let cntr = qnItem.scope === 'school' ? this.$store.state.userInfo.azp : qnItem.creatorId
					let blobHost = qnItem.scope === 'school' ?  schoolBlobHost : privateBlobHost
					// 根据试卷的Blob地址 去读取JSON文件
					let sasString = qnItem.scope === 'private' ? await this.$tools.getPrivateSas(cntr) : await this.$tools.getSchoolSas(cntr)
					let promiseArr = []
					let indexJson = await this.getBlobJsonFile(qnItem.scope,qnItem.blob,cntr)
					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,container){
				return new Promise(async (resolve,reject) => {
					let blobUrl = JSON.parse(decodeURIComponent(localStorage.student_profile, "utf-8")).blob_uri
					let blobHost = blobUrl.slice(0,blobUrl.lastIndexOf('/')) + '/' +  container
					// 根据试卷的Blob地址 去读取JSON文件
					let sasString = scope === 'private' ?  await this.$tools.getPrivateSas(container) : await this.$tools.getSchoolSas(container)
					try{
						let itemJson = JSON.parse(await this.$tools.getFile(blobHost + url + sasString.sas))
						resolve(itemJson)
					}catch(e){
                        this.$Message.error(this.$t('studentWeb.queNaire.fileErr'))
						reject(e)
					}
				})
			},

			typeOption: function(type) {
				//console.log(type);
				if (type == "multiple") {
					return "checkbox";
				} else return "radio";
			},
		},

		mounted() {
			this.getSurveyInfo()
		},

		watch: {
			$route: {
				handler() {
					this.alreadyAnswered = false
					this.getSurveyInfo()
				},
				// 深度观察监听
				deep: true
			},
		},
	};
</script>

<style scoped>
	@import "~@/assets/student-web/component_styles/quesnaire.css";
</style>
