<template>
	<view class="page">
		<!-- <view class="title">
      <view class="title-left">
        <u-text :bold="true" :size="20" :lines="1" :text="examName"></u-text>
      </view>
      <view class="title-right">
        <u-button size="mini" :loading="saveLoading" text="保存"></u-button>
      </view>
    </view> -->
		<view class="form">
			<swiper class="swiper" :current="currentIndex" @change="swiperChange">
				<swiper-item class="swiper-item" v-for="(question, index) in questions" :key="question.questionId">
					<scroll-view scroll-y="true" class="scroll-Y">
						<answer-component :question="question"> </answer-component>
					</scroll-view>
					<!-- <view class="question"></view> -->
				</swiper-item>
			</swiper>
		</view>
		<u-tabbar :fixed="true" :placeholder="true" :safeAreaInsetBottom="true">
			<u-tabbar-item text="上一题" icon="play-left" @click="prevQuestion"></u-tabbar-item>
			<u-tabbar-item text="下一题" icon="play-right" @click="nextQuestion"></u-tabbar-item>
		</u-tabbar>
	</view>
</template>

<script>
	import {
		listAssignDetail,
		getAssignDetail,
		delAssignDetail,
		addAssignDetail,
		updateAssignDetail,
	} from "@/api/elder/questionnaire/assignDetail";

	import {
		listAnswer,
		getAnswer,
		delAnswer,
		addAnswer,
		updateAnswer,
	} from "@/api/elder/questionnaire/answer";

	import {
		listQuestion
	} from "@/api/elder/questionnaire/question";

	import score from "./Score.js";

	import {
		transformPostBody,
		transformRequestURL,
	} from "@/api/queryParam/index.js";

	import {
		listPaper,
		getPaper
	} from "@/api/elder/questionnaire/paper.js";

	import AnswerComponent from "./AnswerComponent.vue";
	//考卷做题页
	export default {
		components: {
			AnswerComponent,
		},
		data() {
			return {
				saveLoading: true,
				queryParams: {
					pageNum: 1,
					pageSize: 1000,
					paperId: "",
					assignDetailId: "",
				},
				answerList: [],
				currentIndex: 0,
				questions: [],
				errors: [],
				assignId: "",
				assignDetailId: "",
				paperId: "",
				questionId: "", //直接跳转到目标题目
				paperInfo: {},
			};
		},
		onLoad: function(options) {
			console.log("options edit", options);
			this.assignId = options.assignId;
			this.assignDetailId = options.assignDetailId;
			this.paperId = options.paperId;
			this.questionId = options.questionId;
		},
		onShow() {
			this.getList();
			console.log("onShow questions", this.questions);
		},
		methods: {
			getList() {
				this.loading = true;
				this.queryParams.paperId = this.paperId; //获取试卷题目
				this.queryParams.assignDetailId = this.assignDetailId; //获取之前做题答案
				listAnswer(transformRequestURL(this.queryParams)).then((response_ans) => {
					this.answerList = response_ans.rows;
					listQuestion(transformRequestURL(this.queryParams)).then(
						(response_ques) => {
							this.questions = this.buildTree(response_ques.data);
							this.loading = false;
							if (this.questionId) {
								this.questions.forEach((item, index) => {
									if (item.questionId == this.questionId) {
										this.currentIndex = index;
									}
								});
							}
						}
					);
				});
				getPaper(this.queryParams.paperId).then((res) => {
					this.paperInfo = res.data;
				});
			},
			buildTree(questions, parentId = 0) {
				let nodes = [];
				questions.forEach((item) => {
					if (item.parentQuestionid == parentId) {
						item.type = this.formartquestionType(item.questionType);
						item.hasAnswer = false; //默认没有答案
						item.rawAnswerValue = ""; //原始答案
						//通过this.answerList中的数据，将答案赋值给题目的answerValue
						item.answerValue = "";
						this.answerList.forEach((item2) => {
							if (item.questionId == item2.questionId && this.assignDetailId == item2
								.assignDetailId) {
								//多选题，将答案转化为数组
								if (item.type == "多选") {
									item.answerValue = item2.answerValue.split(",");
									item.rawAnswerValue = item2.answerValue.split(",");
								} else {
									item.rawAnswerValue = item2.answerValue;
									item.answerValue = item2.answerValue;
								}
								item.hasAnswer = true;
								item.answerId = item2.answerId;
							}
						});
						item.children = this.buildTree(questions, item.questionId); // 递归调用
						nodes.push(item);
					}
				});
				return nodes;
			},
			formartquestionType(questionType) {
				switch (questionType) {
					case "1":
						return "填空";
					case "2":
						return "单选";
					case "3":
						return "多选";
					case "0":
						return "主标题";
					case "21":
						return "只需选择";
					case "22":
						return "选择带填空";
					default:
						return "";
				}
			},
			// //将本题的答案进行提交
			// submitSignleQuestion() {
			//   console.log("this.questions");
			//   console.log(this.questions);
			//   //判断答案是否有变化
			//   if (
			//     this.questions[this.currentIndex].answerValue !=
			//     this.questions[this.currentIndex].rawAnswerValue
			//   ) {
			//     let answer = {};
			//     answer.assignId = this.assignId;
			//     answer.assignDetailId = this.assignDetailId;
			//     answer.questionId = this.questions[this.currentIndex].questionId;
			//     answer.answerValue = this.questions[this.currentIndex].answerValue;
			//     answer.answerId = this.questions[this.currentIndex].answerId;
			//     answer.paperId = this.paperId;
			//     answer.hasAnswer = this.questions[this.currentIndex].hasAnswer;
			//     console.log("answer", answer);

			//     //如果是多选题还需要将数组转化为字符串
			//     if (this.questions[this.currentIndex].type == "多选") {
			//       answer.answerValue =
			//         this.questions[this.currentIndex].answerValue.join(",");
			//     }

			//     if (answer.hasAnswer) {
			//       updateAnswer(answer).then((response) => {
			//         console.log("updateAnswer", response);
			//       });
			//     } else {
			//       addAnswer(answer).then((response) => {
			//         console.log("addAnswer", response);
			//       });
			//     }
			//   }
			// },
			//通过递归的方式提交
			submitSignleQuestion(questions) {
				questions.forEach((item) => {
					if (item.type != "主标题") {
						//判断答案是否有变化
						if (item.answerValue != item.rawAnswerValue) {
							let answer = {};
							answer.assignId = this.assignId;
							answer.assignDetailId = this.assignDetailId;
							answer.questionId = item.questionId;
							answer.answerValue = item.answerValue;
							answer.answerId = item.answerId;
							answer.paperId = this.paperId;
							answer.hasAnswer = item.hasAnswer;
							console.log("answer", answer);

							//如果是多选题还需要将数组转化为字符串
							if (item.type == "多选") {
								answer.answerValue = item.answerValue.join(",");
							}

							if (answer.hasAnswer) {
								updateAnswer(answer).then((response) => {
									console.log("updateAnswer", response);
								});
							} else {
								addAnswer(answer).then((response) => {
									console.log("addAnswer", response);
								});
							}
						}
					}
					if (item.children.length > 0) {
						this.submitSignleQuestion(item.children);
					}
				});
			},
			//上一题
			prevQuestion() {
				this.submitSignleQuestion([this.questions[this.currentIndex]]);
				if (this.currentIndex > 0) {
					this.currentIndex--;
				}
			},
			//下一题
			nextQuestion() {
				this.submitSignleQuestion([this.questions[this.currentIndex]]);
				if (this.currentIndex < this.questions.length - 1) {
					this.currentIndex++;
				} else {
					//已经是最后一题，对试卷进行提交
					this.submitPaper();
				}
			},
			//提交试卷
			submitPaper() {
				console.log("submitPaper");
				//校验是否所有题目都回答完整（必答题都有回答：required==1）,如果找到有未回答的题目，获取其索引用于跳转到该题目
				let requiredIndex = -1;
				for (let i = 0; i < this.questions.length; i++) {
					if (
						this.questions[i].required == "1" &&
						!this.questions[i].answerValue
					) {
						requiredIndex = i;
						break;
					}
				}
				if (requiredIndex == -1) {
					//判断是否需要自动评分，如果需要，调用自动评分接口
					this.autoScore();
					//更新该考卷状态为已完成:updateAssignDetail
					let assignDetail = {};
					assignDetail.assignDetailId = this.assignDetailId;
					assignDetail.status = "1";
					updateAssignDetail(assignDetail).then((response) => {
						console.log("updateAssignDetail", response);
						this.$tab.navigateTo(
							"/pages/WenJuanDiaoCha/Detail/index?assignId=" + this.assignId
						);
					});
				} else {
					uni.showToast({
						title: "该题为必答,请填写",
						icon: "none",
					});
					this.currentIndex = requiredIndex;
				}
			},
			//自动评分
			autoScore() {
				//调用自动评分接口
				console.log(
					"自动评分的题目",
					this.questions.filter((item) => item.spare1 == 1)
				);
				console.log("自动评分的规则", this.paperInfo.spare2);
				//如果该考卷是自动评分（spare1==1），那就需要给每个题目进行评分，统计并显示总分
				//通过anserdetailId获取该考卷
				try {
					// let scoreObj = this.questions
					// 	.map((item) => {
					// 		value: item.answerValue,
					// 		rule: item.spare2
					// 	});
					let scoreObj ={}
					const result = score(scoreObj);
					console.log("自动评分的结果", result);

					//更新该考卷的总分
					updateAssignDetail({
						assignDetailId: this.assignDetailId,
						value: result.value,
						level: result.level,
					}).then((response) => {
						console.log("updateAssignDetail", response);
					});

				} catch (error) {
					console.error(error);
				}
			},
			swiperChange({
				detail: {
					current
				}
			}) {
				this.currentIndex = current;
				console.log("this.currentIndex", this.currentIndex);
			},
			submitForm() {},
			checkboxChange(n, question) {
				console.log("change", n);
				console.log("question", question);
			},
			groupChange(n) {
				console.log("groupChange", n);
			},
			radioChange(n) {
				console.log("radioChange", n);
			},
		},
	};
</script>

<style scoped>
	.page {
		background-color: white;
		/* padding: 20rpx; */
		/* height: 100%; */
		/* height: 100vh; */
	}

	.form {
		/* height: 1200rpx; */
		/* overflow: scroll; */
		/* 高度为全屏减去标题和底部按钮的高度 */
		height: calc(100vh - 110rpx);
		/* border: 2px solid #fd00cf; */
	}

	/* .title {
  text-align: center;
  font-size: 50rpx;
  margin-bottom: 20rpx;
  font-weight: 600;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-left {
  flex: 1;
}

.title-right {
  margin-left: 10px;
} */
	.scroll-Y {
		height: 100%;
		/* overflow: hidden; */
		/* border: 2px solid red; */
	}

	.swiper {
		height: 100%;
		/* overflow: hidden; */
		/* border: 2px solid red; */
	}

	.swiper-item {
		/* display: flex;
		align-items: center;
		justify-content: center; */
	}
</style>