<template>
	<div
		class="psychologicalScale-index"
		v-if="topic.length"
		:style="`padding-top: ${tip?'10vw':showLeftArrow ? '34vw' : '24vw'};`"
	>
		<van-nav-bar
			title="测评"
			:border="true"
			:left-arrow="true"
			@click-left="onNavBack"
			v-if="showLeftArrow"
			style="position: fixed; left: 0; top: 0; width: 100vw; height: 10vw"
		>
			<template #left>
				<van-icon name="arrow-left" size="23" style="padding: 0" />返回
			</template>
		</van-nav-bar>
		<div class="tip" v-if="tip">
      <div class="tip-title title">{{ title }}</div>
			<div class="tip-title">测评说明：</div>
			<div class="tip-content">
				请仔细阅读每一道题，根据您自己的
				真实状态，评估最近7天内你最接近的感觉，而不只是你今天的感觉
			</div>
			<div class="tip-title">注意事项：</div>
			<div class="tip-content">
				题目共10题，选项无对错之分，不用过度思考，根据第一反应选择则可。
			</div>
			<div class="tip-content">
				该测评结果仅供参考，不能以此作相关诊断。如有疑问，请咨询专业人员。
			</div>
			<div class="button">
				<van-button
					round
					type="info"
					style="width: 100%; height: 100%"
					@click="tip = false"
					>开始测评</van-button
				>
			</div>
		</div>
		<div class="" v-else>
			<div class="top" :style="`top: ${showLeftArrow ? '10vw' : '0'};`">
				<div class="schedule">
					<div class="progress">
						<van-progress
							:percentage="
								(select.length == 0 ? 0 : select.length / topic.length) * 100
							"
							stroke-width="10px"
							color="#638ee4"
							:show-pivot="false"
							v-if="topic.length"
						></van-progress>
					</div>
					<div class="text">
						<span class="val">{{ select.length }}</span
						>/<span class="total">{{ topic.length }}</span>
					</div>
				</div>
				<div class="title">{{ title }}</div>
			</div>
			<div class="list_box">
				<div class="item" v-for="(item, index) in topic" :key="index">
					<div
						:class="[
							'label',
							{
								error:
									(isError && fromSsjl && item.Id == '6') ||
									(isError && fromSsjl && item.Id == '8') ||
									(isError && fromSsjl && item.Id == '11'),
							},
						]"
					>
						<span>{{ item.Title }}</span>
						<span>({{ item.Type }})</span>
					</div>
					<van-radio-group
						class="radio"
						v-model="item.select"
						v-if="item.Type == '单选题'"
					>
						<van-cell-group>
							<van-cell
								clickable
								v-for="(ite, idx) in item.Option"
								:key="idx"
								:title="ite.label"
								@click="onRadio(index, ite.value)"
								:title-class="[
									{
										cellTitle:
											(isError && fromSsjl && item.Id == '6') ||
											(isError && fromSsjl && item.Id == '8') ||
											(isError && fromSsjl && item.Id == '11'),
									},
								]"
							>
								<template #right-icon>
									<van-radio :name="ite.value" />
								</template>
							</van-cell>
						</van-cell-group>
					</van-radio-group>
					<van-checkbox-group class="checkbox" v-model="item.select" v-else>
						<van-cell-group>
							<van-cell
								v-for="(ite, idx) in item.Option"
								clickable
								:key="idx"
								:title="ite.label"
								@click="onCheckbox(`checkboxes${item.Id}`, idx)"
							>
								<template #right-icon>
									<van-checkbox
										:name="ite.value"
										:ref="`checkboxes${item.Id}`"
									/>
								</template>
							</van-cell>
						</van-cell-group>
					</van-checkbox-group>
				</div>
			</div>
			<div class="button">
				<van-button
					round
					type="info"
					:disabled="topic.length != select.length"
					style="width: 100%; height: 100%"
					@click="submit"
					>提交测评</van-button
				>
			</div>
		</div>
	</div>
</template>

<script>
import axios from 'axios'
import APICore from '@/api/core'

export default {
	name: 'PsychologicalScale',
	data() {
		return {
			uid: '',
			keyCode: '',
			title: '',
			tip: true,
			topic: [], //题目列表
			select: [],
			isError: null, //是否是答题错误
			fromSsjl: this.$store.getters.fromSsjl,
			showLeftArrow: false,
			isModel: false,
		}
	},
	mounted() {
		//页面标题
		window.document.title = '测评'

		//页面传参
		let params = { ...this.$route.query }

		if (params.uid) {
			this.uid = params.uid

			// 缓存从随手精灵传过来的token
			this.$store.commit('ssjlToken', params.accessToken || '')
			if (params.appType) {
				this.$store.commit('appType', params.appType)
			}
			// 缓存从随手精灵传过来的标识
			this.$store.commit('fromSsjl', params.fromSsjl)
			// 是否显示 返回标签
			if (params.showLeftArrow) {
				this.showLeftArrow = true
			}
			this.fromUrl = params.fromUrl
			console.log('fromUrl', this.fromUrl)

			// 是否从建模页过来
			if (params.isModel) {
				this.isModel = true
			}

			//初始化
			this.init()
		} else {
			this.$toast('参数错误')
		}
	},
	watch: {
		selects(val) {
			let temp = JSON.parse(val)
			let tempt = temp.filter((item) => {
				if (item.select >= 0) {
					return true
				}
			})
			this.select = tempt
		},
	},
	computed: {
		selects() {
			return JSON.stringify(this.topic)
		},
	},
	methods: {
		async init() {
			if (!this.$route.query.accessToken) {
				//  如果当前url没有 accessToken， 获取token,并且存储到本地缓存里面
				let authToken = await this.getAuth()
				this.$store.commit('ssjlToken', authToken)
			}

			let re = await this.api(
				'/api/Question/GetScaleQuestion',
				{
					method: 'GET',
					sslVerify: false,
					withCredentials: false,
					params: {
						// uid: this.uid,
						code: 'EPDS',
					},
				},
				this.$store.getters.ssjlToken
			)
			if (re.success) {
				if (
					re.response &&
					re.response.ScaleQuestionDetails &&
					re.response.ScaleQuestionDetails.length
				) {
					let code = re.response.Code
					this.title = re.response.Name
					this.keyCode = re.response.Code

					let temp = re.response.ScaleQuestionDetails

					let topic = []
					temp.forEach((item) => {
						let tempt = { ...item }
						if (!tempt.Type) {
							tempt.Type = '单选题'
						}
						let a1 = tempt.Option.split('&')
						let option = []
						for (let index = 0; index < a1.length; index++) {
							option.push({
								label: a1[index],
								value: index,
							})
						}
						tempt.Option = option
						tempt.value = ''
						topic.push(tempt)
					})

					this.topic = topic
				} else {
					this.$toast('问卷不存在')
				}
			} else {
				this.$toast(re.msg)
			}
		},
		async submit() {
			let temp = {
				uid: this.uid, //客户端系统用户id
				keyCode: this.keyCode, //问卷编号
				answer: [],
			}
			this.topic.forEach((item) => {
				temp.answer.push({
					qid: item.Id, //问卷题目编号
					value:
						typeof item.select == 'object'
							? item.select.join(',')
							: item.select, //用户所选答案的 id
				})
			})
			let re = await this.api(
				'/api/Question/ScaleRsults',
				{
					method: 'POST',
					sslVerify: false,
					withCredentials: false,
					data: temp,
				},
				this.$store.getters.ssjlToken
			)
			if (re.success && re.response) {
				this.$toast('问卷提交成功', 3000)
				this.isError = false
				setTimeout(() => {
					let fromSsjl = this.$store.getters.fromSsjl === 'true'
					if (fromSsjl) {
						// c端跳转按c端返回逻辑处理
						this.onNavBack()
					} else if (this.isModel) {
						// 建模页跳转过来的要回建模页
						this.$router.replace({
							name: 'PsychologicalModeling',
							query: {
								uid: this.uid,
							},
						})
					} else {
						this.$router.replace({
							name: 'PsychologicalScaleDetail',
							query: {
								id: re.response.Id,
								uid: this.uid,
								accessToken: this.$store.getters.ssjlToken,
								showLeftArrow: this.showLeftArrow,
							},
						})
					}
				}, 3000)
			} else {
				//this.$toast(re.msg);
				this.$dialog.confirm({
					message: re.msg,
					showCancelButton: false,
				})
				this.isError = true
			}
		},
		onRadio(index, value) {
			let temp = { ...this.topic[index] }
			temp.select = value
			this.$set(this.topic, index, temp)
		},
		onCheckbox(key, index) {
			try {
				this.$refs[`${key}`][index].toggle()
			} catch (error) {
				console.log(error)
			}
		},
		onNavBack() {
			let fromSsjl = this.$store.getters.fromSsjl === 'true'
			if (fromSsjl) {
				let baseUrl = this.fromUrl
				window.location.href = `${baseUrl}/#/${
					this.$route.query.fromMenu || 'device'
				}`
			} else {
				window.history.go(-1)
			}
		},
		// 获取b端token
		getAuth() {
			let manufactorId = '5bf13062-a41e-4d00-ba14-1101aad12650'
			let that = this
			return new Promise((resolve, reject) => {
				APICore.getAuth({ manufactorId: manufactorId }).then((res) => {
					let data = res.data
					if (data.code === 0) {
						resolve(res.data.data)
					} else {
						that.$toast.fail(`${data.message}`)
						reject('')
					}
				})
			})
		},
		api(url, config, token) {
			setTimeout(() => {
				this.$toast.loading({
					message: '',
					forbidClick: true,
					duration: 1500,
				})
			}, 100)
			let baseUrl =
				process.env.NODE_ENV === 'production'
					? 'https://dbmq.rzliot.com/auth_heart'
					: 'https://dbmq.rzliot.com/heart'
			return new Promise((res) => {
				axios({
					url: `${baseUrl}${url}`,
					...config,
					// 增加请求头部 token
					headers: {
						AccessToken: token,
					},
				})
					.then((re) => {
						if (re) {
							if (re.data) {
								console.log(re.data)
								res(re.data)
								this.$toast.clear()
								return
							}
							this.$toast(`信息获取失败-${re.status}`)
							res(true)
							this.$toast.clear()
							return
						}
						this.$toast(`信息获取失败-${url}`)
						res(true)
						this.$toast.clear()
					})
					.catch((e) => {
						this.$toast(`信息获取失败-${url}`)
						res(true)
						this.$toast.clear()
						console.log(e)
					})
			})
		},
	},
}
</script>

<style lang="scss">
.van-toast--html, .van-toast--text{
  padding: 2vw !important;
}
.van-toast--html .van-toast__text, .van-toast--text .van-toast__text{
  font-size: 3.6vw !important;
}
.psychologicalScale-index {
	width: 100vw;
	min-height: 100vh;
	box-sizing: border-box;
	font-size: 3.6vw;
	text-align: left;
	background: #f4f4f4;
	padding-bottom: 8vw;
	padding-top: 24vw;

	.van-nav-bar__content {
		height: 10vw !important;

		.van-nav-bar__left,
		.van-nav-bar__title {
			font-size: 4vw !important;
			line-height: initial !important;

			.van-icon-arrow-left {
				font-size: 4vw !important;
			}
		}
	}

  .tip{
    width: 90vw;
    margin: 0 auto;
    margin-top: 5vw;
    padding: 10vw 3vw;
    border-radius: 2vw;
    background: white;

    .tip-title{
      font-size: 4vw;
      font-weight: bold;
      margin-top: 5vw;
      margin-bottom: 5vw;
    }

     .title{
      font-size: 4.5vw;
      text-align: center;
      margin-top: 0;
    }

    .tip-content{
      font-size: 3.7vw;
      text-indent: 5vw;
      margin-bottom: 2vw;

      &:last-child{
        margin-bottom: 0;
      }
    }
    .button{
      position: fixed;
      left: 0;
      right: 0;
      bottom: 10vw;
      margin: auto;
    }
  }

	.top {
		box-sizing: border-box;
		position: fixed;
		top: 0;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 3vw;
		width: 100vw;
		height: 24vw;
		background: white;
		z-index: 99;

		.schedule {
			display: flex;
			align-items: center;

			.progress {
				width: 85%;
			}
			.text {
				width: 15%;
				font-size: 4.5vw;
				text-align: center;

				.val {
					font-size: 5vw;
					font-weight: bold;
				}
			}
		}
		.title {
			color: #638ee4;
		}
	}

	.list_box {
		width: 100%;
		margin-top: 3vw;

		.item {
			margin-top: 3vw;
			padding: 3vw;
			background: white;

			.label {
				font-size: 4vw;
				// &.error {
				// 	color: red;
				// }
			}
			.van-cell {
				line-height: initial !important;
				padding: 3vw 2vw;

				.van-cell__title {
					font-size: 3.5vw !important;

					// &.cellTitle {
					// 	color: red;
					// }
				}
				.van-radio__icon {
					height: 100% !important;

					.van-icon {
						font-size: 3.5vw !important;
					}
				}
			}
		}
	}

	.button {
		width: 75vw;
		height: 14vw;
		margin: 0 auto;
		margin-top: 8vw;

		.van-button {
			font-size: 4vw !important;
		}
		.van-button--info {
			background-color: #638ee4;
			border: 1px solid #638ee4;
		}
	}
}
</style>
