<template>
	<div class="page" v-if="topic.length">
		<div class="top">
			<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.QId}`, idx)"
						>
							<template #right-icon>
								<van-checkbox
									:name="ite.value"
									:ref="`checkboxes${item.QId}`"
								/>
							</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>
</template>

<script>
import axios from 'axios'

export default {
	name: 'PsychologicalModeling',
	data() {
		return {
			uid: '',
			keyCode: '',
			title: '',
			topic: [], //题目列表
            select: [],
            isError: null, //是否是答题错误
            fromSsjl: this.$store.getters.fromSsjl
		}
	},
	mounted() {
		//页面标题
		window.document.title = '情绪初始化评估'

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

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

			//初始化
			this.init()
		} else {
			this.$toast('参数错误')
		}
	},
	watch: {
		selects(val) {
			let temp = JSON.parse(val)
			let tempt = temp.filter((item) => {
				if (item.select) {
					return true
				}
			})
			this.select = tempt
		},
	},
	computed: {
		selects() {
			return JSON.stringify(this.topic)
		},
	},
	methods: {
		async init() {
			let re = await this.api('/api/Question/Get', {
				method: 'GET',
				sslVerify: false,
				withCredentials: false,
				params: {
					// uid: this.uid,
				},
			}, this.$store.getters.ssjlToken)
			if (re.success) {
				if (re.response && re.response.length) {
					let temp = re.response[0]
					let code = temp.Code
					this.title = temp.Memo
					this.keyCode = temp.Code
					let re1 = await this.api('/api/Question/GetQuestion', {
						method: 'GET',
						sslVerify: false,
						withCredentials: false,
						params: {
							code: code,
						},
					}, this.$store.getters.ssjlToken)
					if (re1.success) {
						if (re1.response && re1.response.length) {
							let topic = []
							re1.response.forEach((item) => {
								let tempt = { ...item }
								let a1 = tempt.Option.split('#&')
								let option = []
								for (let index = 0; index < a1.length; index++) {
									option.push({
										label: a1[index],
										value: index + 1,
									})
								}
								tempt.Option = option
								tempt.value = ''
								topic.push(tempt)
							})
							this.topic = topic
						} else {
							this.$toast('问卷暂无题目')
						}
					} else {
						this.$toast(re1.msg)
					}
				} 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.QId, //问卷题目编号
					value:
						typeof item.select == 'object'
							? item.select.join(',')
							: item.select, //用户所选答案的 id
				})
			})
			let re = await this.api('/api/Question/Rsults', {
				method: 'POST',
				sslVerify: false,
				withCredentials: false,
				data: temp,
			}, this.$store.getters.ssjlToken)
			if (re.success) {
                this.$toast('问卷提交成功', 3000);
                this.isError = false;
				setTimeout(() => {
                    // 2023.09.25 使用此返回方法可能会导致页面返回异常,故使用路由跳转到指定页面
                    this.$router.replace({
                        name: 'PsychologicalModeling',
                        query: {
                            uid: this.uid
                        }
                    })
				}, 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)
			}
		},
		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" scoped>
.page {
	width: 100%;
	min-height: 100%;
	box-sizing: border-box;
	font-size: 3.6vw;
	text-align: left;
	background: #f4f4f4;
	padding-bottom: 8vw;
	padding-top: 24vw;

	.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 {
                .van-cell__title {
                    &.cellTitle {
                        color: red;
                    }
                }
            }
		}
	}

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

		.van-button--info {
			background-color: #638ee4;
			border: 1px solid #638ee4;
		}
	}
}
</style>
