<template>
	<view class="content">
		<view id="top-box" class="cu-bar bg-white solid-bottom">
			<view class="action text-black">
				<uni-tag 
				 :text="currentQuestionName" 
				 type="error" :circle="true">
				</uni-tag>
			</view>
			<view class="action">
				<button class="cu-btn bg-green shadow" 
				@tap="commitPaperQuestion" data-target="modalCard">提 交</button>
			</view>
		</view>
		<view class="cu-modal" :class="modalCard=='modalCard'?'show':''" @tap="hideCardModal">
			<view class="cu-dialog" @tap.stop>
				<scroll-view class="page padding" :scroll-y=true :style="{'height':swiperHeight}" >				
					<view class="cu-bar solid-bottom">
						<view class="action">
							<text class="cuIcon-title text-red"></text>答题卡
						</view>					
					</view>
						<!-- :class="[item.userInfoAnswer === item.asnwer ? 'line-grey':'bg-red']" -->
					 <view class="grid col-5 ">
						<view class="margin-tb-sm text-center" 
						v-for="(item, index) in paperQuestionList" :key="index">
							<button class="cu-btn round" 
							:class="{
								'line-green': item.userInfoAnswer,
							}"
							 @click="appointedQuestion(index)" >{{index + 1}}</button>
						</view>
					</view> 
				</scroll-view>
			</view>
		</view>
		<view class="cu-modal padding " :class="modalError=='modalError'?'show':''" @tap="hideErrorModal">
			<view class="cu-dialog bg-white" @tap.stop>								
				
				<view class="cu-bar solid-bottom ">
					<view class="action">
						<text class="cuIcon-title text-red"></text>试题纠错
					</view>					
				</view>
				<textarea @blur="bindTextAreaBlur" :value="questionError" auto-height /></textarea>
				<!-- <text class="dialog-text">输入内容：{{value}}</text> -->
				<!-- <radio-group class="block" >
					<view class="cu-list menu text-left">
					<view class="cu-item cu-item-error" v-for="error in errorList" >
						<radio :value="error"></radio>
						<view class="title text-black margin-left">{{error}}</view>
					</view>	
					</view>	
				</radio-group>				
				 -->
				<view class="padding flex flex-direction ">				
					<button class="cu-btn bg-red margin-tb-sm lg" @click="SubmitError">提 交</button>
				</view>
			</view>
		</view>
		<form>
			<swiper
			 :current="questionIndex"
			  class="swiper-box" @change="swiperChange" :style="{'height':swiperHeight}">
				<swiper-item v-for="(questionInfo, index) in paperQuestionList">
					
				<scroll-view class="scroll-v list" :style="{'height':swiperHeight}" :scroll-y="true">
					<view class="cu-bar bg-white solid-bottom">
						<view class="action text-black">
							<!-- <uni-tag text="1"></uni-tag> -->
							 <!-- <div>1.</divs> -->
							<!-- App端（vue页面V3编译模式）和H5端支持v-html，其他端不支持v-html。-->
							
							<view class="questionInfo_content" style="margin-top: 15px; display: inline-block;">
								<!-- <uParse :className="'uParse'" :content="questionInfo.content"/> -->
								<rich-text class="uParse" :nodes="questionInfo.content"></rich-text>
							</view> 
						</view>
					</view>
					<view>
                        <!-- 判断题 -->  
						<radio-group 
						  v-if="questionInfo.question_type === 6"
						  class="block" @change="radioboxChange">
							 <view class="cu-form-group" > 
								<radio 
								value="1" 
								:checked="questionInfo.userInfoAnswer === 1"></radio>
								<view class="title text-black">对</view>
							 </view> 
							 <!-- :disabled="questionInfo.userInfoAnswer !== ''" -->
							 <view class="cu-form-group">
							 	<radio
							 	value="0" 
							 	:checked="questionInfo.userInfoAnswer === 0"></radio>
							 	 <view class="title text-black">错</view> 
							 </view>
						</radio-group>
						
                        <!-- 单选题 -->  
						<radio-group
						  v-if="questionInfo.question_type === 3"
						  class="block" @change="radioboxChange">
							<view class="cu-form-group" v-for="item in questionInfo.options">
								<radio 
								:value="item.value" 
								:checked="item.userInfoAnswer === item.value">{{item.option}}</radio>
								<view class="title text-black"></view>
							</view>
						</radio-group>
						
						<checkbox-group 
						  v-if="questionInfo.question_type === 4" 
						  class="block" @change="checkboxChange">
							<view class="cu-form-group" v-for="item in questionInfo.options">
								<checkbox
								 :value="item.value" 
								 :checked="item.userInfoAnswer === item.value"></checkbox>
								 <view class="title text-black">{{item.option}}</view> 
							</view>
						</checkbox-group>
					</view>

					<view v-show="questionInfo.showAnswerFlag" class="margin-top solid-top">
						<view class="cu-bar">
							<view class="action  text-grey">
								<text>正确答案：</text>
								<uParse :content="questionInfo.show_answer"/>
								<!-- <view v-html="questionInfo.show_answer" ></view> -->
								<!-- <text class="solid-bottom  padding-left text-green">{{subject.answer}}</text> -->
							</view>
						</view>
						<view class="cu-bar cu-bar-title">
							<view class="action  text-grey">
								<text>解析：</text>
							</view>
						</view>
						<view 
						class="text-content padding  text-grey">
						   <uParse :content="questionInfo.analysis"/>
						</view>
					</view>

					</scroll-view>
				</swiper-item>
			</swiper>
		</form>
		<view id="foot-box" class="cu-bar tabbar bg-white shadow foot">
			<view class="action" @tap="showErrorModal"  data-target="modalError">
				<view class="cuIcon-cu-image">
					<text class="lg text-gray cuIcon-warn"></text>
				</view>
				<view class="text-gray">纠错</view>
			</view>
			
			<view  class="action" @tap="showCardModal"data-target="modalCard">
				<uni-icons type="compose" size="30"></uni-icons>
				<view :class="[userFavor?'text-red':'text-gray']">答题卡</view>
			</view>
			
			<view class="action" @click="changeQuestionInfo(-1)">
				 <view class="cuIcon-cu-image">
					<text class="lg cuIcon-back text-gray"></text>
				</view> 
				<view class="text-gray">上一题</view> 
				
			</view>
			<view class="action" @click="changeQuestionInfo(1)">
				 <view class="cuIcon-cu-image">
					<text class="lg text-gray cuIcon-right"></text>
				</view>
				<view class="text-gray">下一题</view>
			</view>


			<!-- <view class="action" @click="showAnswerChange">
				<view class="cuIcon-cu-image">
					<text class="lg text-gray cuIcon-question"></text>
				</view>
				<view class="text-gray">解答</view>
			</view> -->
		</view>
		<uni-popup :show="showCommitErrorMsg" type="center" :custom="true" :mask-click="false">
			<view class="uni-tip">
				<view class="uni-tip-title">提示</view>
				<view class="uni-tip-content">{{commitErrorMsg}}</view>
				<view class="uni-tip-group-button">
					<view @click="showCommitErrorMsg = false" class="uni-tip-button">取消</view>
					<view @click="goToUserForm" class="uni-tip-button">确定</view>
				</view>
			</view>
		</uni-popup>
		
		<uni-popup 
		:show="userFormFlag" 
		type="center" 
		:custom="true" :mask-click="false">
			<view class="uni-tip">
				<view class="uni-tip-title">完善信息</view>
				<view class="uni-tip-content">
					<view class="form-container-box">
						<!-- 待用活动表单 -->
						<active-form 
						  :formDate="formDate"
						  @sure-btn="sure" @input-val="inputVal">								
						</active-form>
						
						<cover-view class="submit-data">
							{{submitData}}
						</cover-view>
						
						<view style="margin: 100rpx; color: red;">
							温馨提示: 请准确填写相关信息帮助系统对您或您的孩子生成精准学习分析报告和推荐的学习路径
						</view>
						
					</view>
				</view>
				<view class="uni-tip-group-button">
					<view @click="userFormFlag = false" class="uni-tip-button">取消</view>
					<view @click="submitForm" class="uni-tip-button">确定</view>
				</view>
			</view>
		</uni-popup>
	
		
	</view>
</template>

<script>
	import uniTag from '@/components/uni-tag/uni-tag.vue'
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import uniIcons from '@/components/uni-icons/uni-icons.vue'
	import activeForm from '@/components/userInfo/active_form.vue'
	import uParse from '@/components/uParse/src/wxParse.vue'
	import { mapGetters } from 'vuex'
	export default {
		components: {uniTag, uniPopup, uniIcons, uParse, activeForm},
		data() {
			return {
				// showCommitErrorMsg1: false,
				userFormFlag: false,
				submitData: "",
				formDate: [
					{
						placeholder: "请输入姓名",
						label: "姓名",
						type: "text",
						rules: {
							name: "name",
							value: "",
							verify: "req",
							errMess: "请输入姓名"
						}
					},
					
					{
						placeholder: "请输入就读学校",
						label: "就读学校",
						type: "text",
						rules: {
							name: "from_school_name",
							value: "",
							verify: "req",
							errMess: "请输入就读学校"
						}
					},
					
					{
						placeholder: "请填写联系方式",
						label: "手机号",
						type: "number",
						rules: {
							name: "mobile",
							value: "",
							verify: "req|phone",
							errMess: "手机号填写不正确"
						}
					}],
				direction: 'prop',
				questionError: '',
				studentExamTimer: null,
				studentExamTime: 0, // 学生考试用时
				userQuestionList: [],
				commitErrorMsg: '',
				showCommitErrorMsg: false,
				paperQuestionList: [], // 试卷试题列表
				questionTotal: 0, // 试题数量
				currentQuestionName: '', // 当前试题名称
				userFavor:false,//是否已收藏
				currentType: 0, //当前题型
				questionIndex: 0,//跳转索引
				autoShowAnswer: false,//答错是否显答案
				autoRadioNext:true,//判断题、单项题，自动移下一题
				swiperHeight: '800px',//
				title: '',
				examParams: null,
				// subjectList:[],	
				modalCard: null ,//显示答题卡
				modalError: null , //纠错卡
				errorList:['题目不完整', '答案不正确', '含有错别字', '图片不存在', '解析不完整', '其他错误']
			}
		},
		
		computed: {
		   ...mapGetters({
			    fromSchoolId: 'paper/getFromSchoolId',
				paperInfo: 'paper/getPaperInfo'
		   })
		},
		
		onReady() {
			var tempHeight = 800;
			var _me = this;
			uni.getSystemInfo({
				//获取手机屏幕高度信息，让swiper的高度和手机屏幕一样高                
				success: function(res) {
					tempHeight = res.windowHeight;
					uni.createSelectorQuery().select("#top-box").fields({
						size: true,
						scrollOffset: true
					}, (data) => {
						tempHeight -= data.height;
						uni.createSelectorQuery().select("#foot-box").fields({
							size: true,
							scrollOffset: true
						}, (data) => {
							tempHeight -= data.height;
							_me.swiperHeight = tempHeight + 'px';
						}).exec();
					}).exec();
				}
			});
		},

		destroyed () {
			clearInterval(this.studentExamTimer)
		},

		onLoad() {
			uni.setNavigationBarTitle({
				title: this.paperInfo ? this.paperInfo.name : 'test测试'
			})		
			this.getPaperQuestionList()

			this.studentExamTimer = setInterval(() => {
			    this.startCountStudentExamTime() // 开始计算考试时间
			}, 1000)
		},
		methods: {
			
			submitForm () {
				// 表单验证 可选项 otherPra:otherPra
				var otherPra = {
					reqEmptyVal: true,
				}
				if (this.$vervify({
						formDate: this.formDate,
						otherPra: otherPra
					   })
					) {
						
					let formArray = []
					this.formDate.forEach(item => {
						let itemValue = item.rules
						if (itemValue.name === 'sex') {
							if (itemValue.value === '男') {
								itemValue.value = 1
							} else if (itemValue.value === '女') {
								itemValue.value = 0
							}
						}
						formArray.push({
							name: itemValue.name,
							value: itemValue.value,
						})
					})
					uni.showLoading({
						title: '正在生成测试报告, 请稍后...'
					})
					this.$httpApi.post('/front/potentialStudentInfo', {formList: formArray, fromSchoolId: parseInt(this.fromSchoolId)})
					.then(response => {
						if (response.code === 1) {
							let studentId = response.data
							this.$store.commit('paper/updateStudentId', response.data)
							this.sendCommitQuestionHttp(studentId)
						} else {
							uni.hideLoading()
							setTimeout(() => {
								uni.showToast({
									title: response.message
								})
							}, 100)
						}
					})
				}
			},
			
			sendCommitQuestionHttp (studentId) {
				let form = this.examParams
				form.potentialStudentInfoId = studentId
				
				this.$httpApi.post('/front/aiCt/commitAiPaperQuestion', form)
				 .then(response => {
					uni.hideLoading()
					if (response.code === 1) {
						uni.showToast({
							icon: 'none',
							title: '报告生成成功'
						})
						setTimeout(() => {
							// 跳转测评报告结果页
							uni.redirectTo({
								url: 'ctReport'
							})
						}, 100) 
					} else {
						uni.showToast({
							icon: 'none',
							title: '报告生成失败'
						})
					}
				})
			},
			
			bindTextAreaBlur (e) {
				this.questionError = e.detail.value
			},
			
			startCountStudentExamTime () {
			   this.studentExamTime++
			},

			// 获取试卷试题列表
			getPaperQuestionList () {
				let params = {
					sqlId: 'test.paper.question.info.list',
					testPaperInfoId: this.paperInfo.id // 
				}
				this.$httpApi.get('/front/paper/getQuestionByPaperId', params)
				   .then(response => {
					//if (response.data.code === 1) {
						this.paperQuestionList = response.data
						if (this.paperQuestionList.length > 0) {
							// 添加字段是否显示答案
							this.paperQuestionList.forEach(item => {
								item.content= item.content.replace(/\<img/g,'<img style="max-width: 100%;height:auto;"');
								this.$set(item, "showAnswerFlag", false);
								// 区分 传递到后台的试题答案和显示在前端的试题答案 item.answer
								this.$set(item, "show_answer", item.answer);
							})
							this.questionTotal = this.paperQuestionList.length
							this.currentQuestionName = this.paperQuestionList[0].questionName
						}
					//}
				}) 
			}, 
			
			// 提交试题
			commitPaperQuestion () {
				let noAnswerQuestionNumber = 0 // 未答题数
				this.paperQuestionList.forEach(question => {
					if (!question.userInfoAnswer) {
						noAnswerQuestionNumber++
					}
					let userQuestionInfo = {
						questionInfoId: question.id,
						questionAnswer: question.answer,  // 试题答案
						questionType: question.question_type, // 试题类型
						answerEnclosure: [], // 答案附件
						mark: question.mark, // 试题得分
						userInfoAnswer: question.userInfoAnswer,  //学员试题答案
						languagePointsId: question.language_points_id
					}
					this.userQuestionList.push(userQuestionInfo)
				})
				
				if (noAnswerQuestionNumber > 0) {
					this.commitErrorMsg = '亲，你还有' + noAnswerQuestionNumber + '道试题未作答，确定提交吗?'
					this.showCommitErrorMsg = true
				} else {
					this.commitErrorMsg = '亲, 确定提交吗?'
					this.showCommitErrorMsg = true
				} 
			},
			
			goToUserForm () {
			    clearInterval(this.studentExamTimer) // 清除定时器
				let form = {
					studentQuestionAnswerList: this.userQuestionList,
					testPaperId: this.paperInfo.id,
					subjectId: this.paperInfo.subject_id,
					languagePointsIds: this.paperInfo.languagePointsList,
					examTime: this.studentExamTime
				}
				
				// this.examParams = form 
			    this.$store.commit('paper/updateExamParams', form)
				
				this.showCommitErrorMsg = false
				
				uni.navigateTo({
					url: './examCommit'
				})
				// this.userFormFlag = true
				// this.direction = 'center'
				//打开弹窗
				//this.$refs.pop.show();
				
			/* 	uni.redirectTo({
				    url: 'userForm'
				}) */
			},
			
			
			showCardModal (e) {
				this.modalCard = e.currentTarget.dataset.target
			},
			
			hideCardModal (e) {
				this.modalCard = null
			},
			
			showErrorModal (e) {
				this.modalError = e.currentTarget.dataset.target
			},
			
			hideErrorModal (e) {
				this.modalError = null
			},
			
			swiperChange (e) { //滑动事件
				let index = e.target.current;
				if (index != undefined) {
					this.questionIndex = index;
					this.currentQuestionName = this.paperQuestionList[this.questionIndex].questionName
				}								
			},			
			
			radioboxChange (evt) { //单选选中
			   var value = evt.detail.value
			   let questionInfo = this.paperQuestionList[this.questionIndex]
			   questionInfo.userInfoAnswer = value
			   /* this.paperQuestionList[this.questionIndex] = que
			   alert(questionInfo.userInfoAnswer)
			   alert(value)
			   alert(questionInfo.userInfoAnswer === value) */
			},
			
			checkboxChange (e) { //复选选中
			    let options = this.paperQuestionList[this.questionIndex].options
			    let values = e.detail.value
			    let userInfoAnswer = ''
			    for (var i = 0, lenI = options.length; i < lenI; ++i) {
					const item = options[i]
					if (values.includes(item.value)) {
						this.$set(item, 'checked', true)
						userInfoAnswer += item.value + ','
					} else {
						this.$set(item, 'checked', false)
					}
			    }
				if (userInfoAnswer) {
					userInfoAnswer = userInfoAnswer.substr(0, userInfoAnswer.length - 1)
				}
				this.paperQuestionList[this.questionIndex].userInfoAnswer = userInfoAnswer
			},
					
			showAnswerChange (e) { // 显示答案
			    let item = this.paperQuestionList[this.questionIndex]
				if (item.question_type === 6) {
					if (parseInt().answer === 1) {
						item.show_answer = '对'
					} else {
						item.show_answer = '错'
					}
				}
				if (item.showAnswer) {
					item.showAnswerFlag = false;					
				} else {
					item.showAnswerFlag = true;
				}				
			},
			
			//上一题、下一题
			changeQuestionInfo (val) {
				if (val === -1 && this.subjectIndex != 0) {
					this.questionIndex -= 1;
				}
				if (val === 1 && this.questionIndex < this.paperQuestionList.length - 1) {
					this.questionIndex += 1;
				} 
				else if (this.questionIndex  === this.paperQuestionList.length - 1) {
					uni.showToast({
						icon: 'none',
						title: '亲, 已经是最后一题了'
					})
				}
			},
			
			// 答题卡试题切换
			appointedQuestion (val) { 
				this.modalCard = null
				this.questionIndex = val									
			},			
			
			SubmitError: function(e) { //提交纠错
				 
				 let question = this.paperQuestionList[this.questionIndex]
				 let form = {
					questionInfoId: question.id,
					content: this.questionError,
					modeId: 0
				 }
				 
				 this.$httpApi.post('/front/questionFeedback', form)
				 .then(res => {
				 	if (res.code === 1) {
						 uni.showToast({
							 title: '提交成功'
						 })
				 	}
				 })
				 
				 this.modalError = null;														
			}
			
		}
	}
</script>
<style>
	.action p {
		display: contents !important;
	}
</style>
<style scoped>
	@import "../../colorui/animation.css";
	@import "../../colorui/main.css";
	@import "../../colorui/icon.css";
	/*每个页面公共css */
	page {
		background-color: #FFFFFF;
	}
	uni-radio:before {
		content: ''
	}
	uni-checkbox:before {
		content: ''
	}
    
    .line-green {
	   background-color: #409eff !important;
	   color: #F0F0F0;
	} 
	.cu-form-group {
		justify-content: flex-start
	}

	.cu-form-group .title {
		padding-left: 30upx;
		padding-right: 0upx;
	}

/* 提示窗口 */
	.uni-tip {
		padding: 15px;
		width: 300px;
		background: #fff;
		box-sizing: border-box;
		border-radius: 10px;
	}

	.uni-tip-title {
		text-align: center;
		font-weight: bold;
		font-size: 16px;
		color: #333;
	}

	.uni-tip-content {
		padding: 15px;
		font-size: 14px;
		color: #666;
	}

	.uni-tip-group-button {
		margin-top: 10px;
		display: flex;
	}

	.uni-tip-button {
		width: 100%;
		text-align: center;
		font-size: 14px;
		color: #3b4144;
	}

	.cu-form-group+.cu-form-group {
		border-top: none;
	}

	.cu-bar-title {
		min-height: 50upx;
	}
	.cu-list.menu>.cu-item-error{justify-content: flex-start;}
</style>
