<template>
	<view class="containers">
		<view class="steps">
			<uni-steps :options="steps" :active="stepActive" active-color="#044ed7" />
		</view>
		<view class="expire" v-if="studyInfo.expire_day">
			通过测验后，{{studyInfo.expire_day}}天内可不再重复学习。
		</view>
		<view class="asks">
			<view v-for="(item,index) in askList">
				<view>{{index+1}}、{{item.title}}({{item.type==1?'单选':'多选'}})</view> 
				<view v-if="item.type==1">
					<uni-data-checkbox v-model="result[index]" @change="e=>radioAnswer(e,index)"
						:localdata="item.answer" :wrap='true' :map="{text:'content',value:'content'}" />
				</view>
				<view v-if="item.type==2">
					<uni-data-checkbox v-model="resultArr[index]" @change="e=>chenckAnswer(e,item,index)"
						:localdata="item.answer" :wrap='true' multiple :map="{text:'content',value:'content'}" />
				</view>
			</view>
		</view>
		
		<view disabled class="justify-between submitBtn">
			<text>需要正确率达{{rate}}%</text>
			<text @click="submitAnswer">提交</text>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				type: 1,
				steps: [{
					title: '填报'
				}, {
					title: '测验'
				}, {
					title: '完成'
				}],
				stepActive: 1,
				studyInfo: {},
				rate: 0,
				askList: [],
				correctNum: {},
				answerList: [], 
				result: {}, //单选
				resultArr: [], // 多选
				formData: {},
				askData:{},
				askContent:[],

			}
		},
		onLoad(options) {
			this.type = options.type
			this.getFormdata()
			if (!this.askData || typeof this.askData !== 'object') {
				this.askData = {}
			}
			this.askData.type = parseInt(options.type)
			this.getStudy()
		},
		onShareAppMessage() {
			return {
				title: 'BD访客系统',
				path: '/pages/index/index',
				// imageUrl: this.logoIndex
			}
		},
		onShareTimeline() {
			return {
				title: 'BD访客系统',
				path: '/pages/index/index',
				// imageUrl: this.logoIndex
			}
		},

		methods: {
			getFormdata(){
				let res = uni.getStorageSync('studydata') || {}
				this.askData = res
			},
			async getStudy() {
				let that = this
				const fd = uni.getStorageSync('formdata') || {}
				const sd = uni.getStorageSync('studydata') || {}
				const mobileParam = (that.askData && that.askData.mobile) || fd.mobile || sd.mobile || ''
				this.util.request({
					api: '/api/mobile/visit/get-ask',
					data: {
						type: that.type,
						mobile: mobileParam
					},
					utilSuccess: function(res) {
						if (Number(res.quiz_required) === 0) {
							that.submitWatchOnlyFromTest(res)
							return
						}
						that.studyInfo = res
						that.askList = res.asks || []
						that.rate = parseInt(res.rate)
						that.askData.ask = res.asks
						that.askData.expire_day = res.expire_day
						for(let i=0;i<(res.asks || []).length;i++){
							that.resultArr.push([])
						}
					},
					utilFail: function(res) {}
				})
			},
			submitWatchOnlyFromTest(studyRes) {
				const form = uni.getStorageSync('formdata') || this.askData || {}
				const that = this
				this.util.request({
					api: '/api/mobile/visit/ask-save',
					method: 'POST',
					data: {
						type: parseInt(this.type),
						name: form.name,
						mobile: form.mobile,
						idcard: form.idcard || form.passcard,
						expire_day: studyRes.expire_day,
						content: [],
						ask: []
					},
					utilSuccess: function(res) {
						if (uni.getStorageSync('studydata')) {
							uni.removeStorageSync('studydata')
						}
						uni.showToast({
							title: '学习已完成',
							duration: 1500,
							icon: 'none'
						})
						setTimeout(function() {
							if (uni.getStorageSync('formdata')) {
								uni.redirectTo({
									url: '/pages/visit/addrecord'
								})
							} else {
								uni.redirectTo({
									url: '/pages/index/index'
								})
							}
						}, 1500)
					},
					utilFail: function(res) {
						uni.showToast({
							title: res || '提交失败',
							duration: 2000,
							icon: 'none'
						})
					}
				})
			},
			// 获取选择的答案
			radioAnswer(e, index) {
				this.correctNum[index] = e.detail.data.result
				this.askContent[index] = e.detail.data.content
			},
			chenckAnswer(e, item, index) {
				let answer = item.answer
				let correctLength = 0
				let data = e.detail.data
				for (var k of answer) {
					if (k.result == 1) {
						correctLength++
					}
				}
				//  多选少于正确答案数量 返回0 错误
				if (data.length != correctLength) {
					this.correctNum[index] = 0
					return
				} else {
					for (var m of data) {
						if (m.result == 0) {
							this.correctNum[index] = 0
						} else {
							this.correctNum[index] = 1
						}
					}
				}
			},
			// 匹配答案正确率
			submitAnswer() {
				let correctLength = 0
				console.log("this.correctNum",this.correctNum)
				for (var key in this.correctNum) {
					if (this.correctNum[key] == 1) {
						correctLength++
					}
				}
				let per = parseFloat(correctLength / this.askList.length) * 100
				if (per < this.rate) {
					this.util.alert("正确率不达标")
				} else {
					this.submitForm()
				}

			},
			submitForm() {
				let that = this
				this.resultArr.map((k,index)=>{
					if(k.length>0){
						this.askContent[index] = k
					}
				})
				this.askData.content = this.askContent
				console.log(this.result,this.resultArr,'---',this.askContent)
				console.log("askdata",this.askData)
				that.submitStudy()
				return
				this.util.request({
					api: '/api/mobile/visit/visit-save',
					method: "POST",
					data: that.formData,
					utilSuccess: function(res) {
						uni.showToast({
							title: res.msg,
							duration: 2000,
							icon: 'none'
						})
						that.newsSubscription()
					},
					utilFail: function(res) {
						console.log(res)
						uni.showToast({
							title: res,
							duration: 2000,
							icon: 'none'
						})
					}
				})
			},
			submitStudy() {
				let that = this
				console.log("that.askData",that.askData)
				// return
				this.util.request({
					api: '/api/mobile/visit/ask-save',
					method: "POST",
					data: that.askData,
					utilSuccess: function(res) {
						if(uni.getStorageSync('studydata')){
							uni.removeStorageSync('studydata')
						}
						
						uni.showToast({
							title: '提交成功',
							duration: 1500,
							icon: 'none'
						})
						setTimeout(function(){
							if (uni.getStorageSync('formdata')) {
								uni.redirectTo({
									url: '/pages/visit/addrecord'
								})
							} else {
								uni.redirectTo({
									url: '/pages/index/index'
								})
							}
						},1500)
					},
					utilFail: function(res) {
						uni.showToast({
							title: res,
							duration: 2000,
							icon: 'none'
						})
					}
				})
			},
			
			
			newsSubscription() {
				uni.getSetting({
					withSubscriptions: true, //是否获取用户订阅消息的订阅状态，默认false不返回
					success(res) {
						if (res.authSetting['scope.subscribeMessage']) {
							uni.removeStorageSync('formdata')
							uni.redirectTo({
								url: '/pages/visit/successform'
							})
						} else {
							// 用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息
							uni.requestSubscribeMessage({
								tmplIds: [
									'O898NDrqGUUeSR42uraqr2PLEg05sNbYVu46I0qLkhE',
									'Caa0O6pPtQDHQMPsqE6PHyzueeI11JvlpenbgwkYC0s'
								],
								success(res) {
									console.log("res", res)
									uni.showToast({
										title:'订阅成功'
									})
									uni.removeStorageSync('formdata')
									uni.redirectTo({
										url: '/pages/visit/successform'
									})
								}
							})
						}
					}
				});
			},

		}
	}
</script>

<style scoped>
	.containers {
		background-color: #fff;
		padding: 20rpx;
		padding-bottom: 60rpx;
		position: relative;
		overflow: hidden;
	}

	.asks {
		min-height: 80vh;
		overflow-y: auto;
		padding-bottom:60rpx
	}

	.asks>view,
	.asks>view>view {
		margin-bottom: 20rpx
	}

	.containers>.submitBtn {
		position: fixed;
		bottom: 0;
		width: 100%;
		left:0
	}

	.containers>.submitBtn text {
		display: inline-block;
		padding: 0 10px;
		text-align: center;
		width: 70%;
		background-color: #f8f8f8;
		font-size: 36rpx;
		border-radius: 10rpx;
		padding: 28rpx;
	}

	.containers>.submitBtn text:first-child {
		border-radius: 0rpx 0 0 10rpx;
	}

	.containers>.submitBtn text:last-child {
		width: 30%;
		background-color: #044ed7;
		color: #fff;
		display: inline-block;
		border-radius: 0 0rpx 10rpx 0;
	}

	.steps {
		margin-bottom: 40rpx
	}
	.expire{
		text-align: center;
		font-size: 40rpx;
		/* padding: 10px; */
		margin-bottom: 40rpx;
	}
</style>
