<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>
						{{ $t("studentWeb.queNaire.noAns1")}}
						<span class="undoNum">{{ undo }}{{ $t("studentWeb.queNaire.noAns2")}} </span>
						{{ $t("studentWeb.queNaire.noAns3")}}
					</p>
					<button class="messageCardBtn" @click="closeWarmMessage()">
						{{ $t("studentWeb.queNaire.noAns4")}}
					</button>
				</div>
			</div>
		</div>

		<!-- <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> -->
		<!-- <div class="load-box">
			<Load :active.sync="isLoad"
				background-color="#000">
				<template slot="default">
					<svg-icon icon-class="loader" class="loader-icon" />
				</template>
			</Load>
		</div> -->
		<Loading v-show="isLoad" bgColor="rgba(0, 0, 0, 0.3)"></Loading>
		<EventBasicInfo :info="nowActive" />
		<div>
			<!-- 已提交 -->
			<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" @click="showImg($event)"></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;" @click="showImg($event)"></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>
		</div>
		<!--图片放大显示-->
		<Modal v-model="imgPreview.show" width="95">
            <img :src="imgPreview.img" style="width: 100%" />
        </Modal>
        <!-- <div class="imgDolg"
             v-show="imgPreview.show"
             @click.stop="imgPreview.show = false">
            <i class="el-icon-close"
               id="imgDolgClose"
               @click.stop="imgPreview.show = false"></i>
            <img @click.stop="imgPreview.show = true" :src="imgPreview.img" />
        </div> -->

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

<script>
	import QuesNaireReport from "./QuesNaireReport";
	import EventBasicInfo from "../../EventBasicInfo";
	import BillBoardandLightBox from "../../EventView/BillBoardandLightBox";
	import Loading from '@/common/Loading.vue'
	// import Load from "vue-loading-overlay";
	import { mapGetters } from 'vuex';
	export default {
		name: "QuesNaire",
		components: {
			EventBasicInfo,
			BillBoardandLightBox,
			QuesNaireReport,
			Loading
		},
		data(vm) {
			return {
				isLoad: false,
				surveyInfo: { //问卷信息
					items: []
				},
				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: [], //填写的数据
				checkers: [],
				imgPreview: {
                    img: "",
                    show: false
                },
			};
		},
		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 k = 0
				this.submitArr.map(item =>{
					if(item.length) {
						k += 1
					}
				})
				// 问卷填写完
				if(k == this.submitArr.length) {
					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;
						}
						
					})
				}
				// 问卷漏题
				else {
					this.showMessageNum = 2
					this.undo = this.submitArr.length - k
					this.WarmMessageisOpen = true
					console.log("问卷未填写完");
				}
				
				

			},
			// 判断当前学生是否已作答该问卷
			isAnswerd(params){
				return new Promise((r,j) => {
					this.$api.studentWeb.isAnswerd(params).then(async res => {
						r(res.answered)
					})
				})
			},
			//获取问卷数据
			// 获取surveyInfo的数据
			async getSurveyInfo() {
				// this.surveyInfo = {}
				this.isLoad = true
				if(this.getItemTitle.id) {
					let params = {
						"id": this.getItemTitle.id,
						"code": this.getItemTitle.scode
					}
					let isAnswerd = await this.isAnswerd(params)
					if(!isAnswerd) {
						// 没有提交
						this.$api.studentWeb.getSurveyInfo(params).then(async res => {
							if (res) {
								this.isLoad = false
								if(res.status == 404) {
									this.$Modal.confirm({
										title: "问卷已被删除，是否删除此条记录？",
										okText: "删除",
										cancelText: "取消",
										onOk: () => {
											this.delActivity()
										}
									})
								} else if(res.status == 200) {
									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.isLoad = false
						this.alreadyAnswered = true
					}
				}
			},
			//放大图片
            showImg(e) {
                this.imgPreview = {
                    img: "",
                    show: false
                }
                if (e.target.tagName == 'IMG') {
                    this.imgPreview.img = e.target.src
                    this.imgPreview.show = true
                }
            },
			// 删除不存在的问卷
            delActivity() {
                let roles = ""
                if(this.$store.state.userInfo.roles.indexOf('student') > -1) {
                    roles = "student"
                } else {
                    roles = "teacher"
                }
                let param = {
                    "id": this.getItemTitle.id,
                    "code": this.getItemTitle.code,
                    "role": roles
                }
                this.$api.studentWeb.delActivity(param).then(res => {
                    if(res) {
						if(res.status == 200) {
							this.$Message.success('问卷已删除！')
							this.$EventBus.$emit('delNotFound', this.getItemTitle.id)
							this.$store.commit("ChangeItemName", {})
						}
					}
                })
            },
			// 获取blob里的问卷内容
			getBlobItems(qnItem) {
				return new Promise(async (resolve, reject) => {
					let blobHost = this.$tools.getBlobHost()
					let cntr = qnItem.scope === 'school' ? qnItem.school : qnItem.code.replace('Survey-','')
					let sasString = await this.$tools.getBlobSas(cntr)
					let fullIndexJsonPath = blobHost + '/' + cntr + qnItem.blob + sasString
					// 根据试卷的Blob地址 去读取JSON文件
					let promiseArr = []
					let indexJson = await this.getBlobJsonFile(fullIndexJsonPath)
					if(indexJson.slides.length) {
						for (let item of indexJson.slides) {
							promiseArr.push(new Promise(async (r, j) => {
								try {
									let itemFullPath = blobHost + '/' +  cntr + item + sasString
									let itemJson = JSON.parse(await this.$tools.getFile(itemFullPath))
									r(itemJson)
								} catch (e) {
									j(e)
								}
							}))
						}
						Promise.all(promiseArr).then(result => {
							resolve(result)
						}).catch(err => {
							reject(err)
						})
					}else{
						resolve([])
					}
					
				})
			},
			
			// 获取blob里的问卷信息
			getBlobJsonFile(indexJsonUrl) {
				return new Promise(async (resolve, reject) => {
					try {
						let itemJson = JSON.parse(await this.$tools.getFile(indexJsonUrl))
						resolve(itemJson)
					} catch(e) {
                        this.$Message.error(this.$t('studentWeb.queNaire.fileErr'))
						reject(e)
					}
				})
			},
			closeWarmMessage() {
				this.WarmMessageisOpen = false;
			},

			/* ========未调用======= */
			qesNaire() {
				return this.getItemTitle.qesNaire;
			},

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

			createdSaveCheckers() {
				if (this.getResetSurvey) {
					this.checkers = [];
					var mockcheckersheet = [];
					for (let i = 0; i < 10; i++) {
						if (
							!this.getItemTitle.isDone &&
							!this.getFinishedItem.includes(
								this.getItemTitle.eventID
							)
						) {
							mockcheckersheet.push([]);
						} else if (
							this.getFinishedItem.includes(
								this.getItemTitle.eventID
							) ||
							this.getItemTitle.isDone
						) {
							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 = [];
				}
			},
		},

		mounted() {
			this.getSurveyInfo()
		},

		watch: {
			/* $route: {
				handler() {
					this.alreadyAnswered = false
					this.getSurveyInfo()
				},
				// 深度观察监听
				deep: true
			}, */
			nowActive: {
				handler() {
					this.alreadyAnswered = false
					this.getSurveyInfo()
				}
			}
		},
		
		computed: {
			...mapGetters([
				"getItemTitle",
				"getResetSurvey",
				"getFinishedItem"
			]),
			nowActive() {
                return this.getItemTitle
            },
		},
	};
</script>

<style scoped>
	@import "~@/assets/student-web/component_styles/quesnaire.css";
</style>
<style lang="less" scoped>
.quesnaire {
	.imgDolg {
        width: 100vw;
        height: 100vh;
        position: fixed;
        z-index: 9999;
        background-color: rgba(140, 134, 134, 0.6);
        top: 0;
        left: 0;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .imgDolg img {
        width: 60%;
        border: 1px solid #eee;
        // height: 95%;
    }

    .imgDolg #imgDolgClose {
        position: fixed;
        top: 35px;
        cursor: pointer;
        right: 17%;
        font-size: 50px;
        color: white;
    }
}
</style>