<template>
  <view class="question">
    <view v-if="showRoot">
      <view v-if="isRoot" class="question-title-root">{{
        question.questionName
      }}</view>
      <view v-else class="question-title">{{ question.questionName }}</view>
    </view>

    <view class="question-content">
      <view>
        <view v-if="question.type == '填空'">
          <!-- <textarea v-model="question.answerValue" placeholder="请输入答案" @blur="bindTextAreaBlur"
									auto-height :focus="true" :adjust-position="false">
								</textarea> -->
          <u--textarea
            v-model="question.answerValue"
            placeholder="请输入内容"
          ></u--textarea>
        </view>
        <view v-else-if="question.type == '单选'">
          <u-radio-group
            size="35"
            iconSize="30"
            v-model="question.answerValue"
            placement="column"
            @change="groupChange"
          >
            <u-radio
              labelSize="20"
              :customStyle="{ marginBottom: '55rpx' }"
              v-for="(childrenItem, index) in question.children"
              :key="index"
              :label="childrenItem.questionName"
              :name="childrenItem.questionName"
              @change="radioChange"
            >
            </u-radio>
          </u-radio-group>
        </view>
        <view v-else-if="question.type == '多选'">
          <u-checkbox-group
            v-model="question.answerValue"
            placement="column"
            @change="checkboxChange($event, question)"
          >
            <u-checkbox
              size="20"
              labelSize="20"
              iconSize="30"
              :customStyle="{ marginBottom: '55rpx' }"
              v-for="(childrenItem, index) in question.children"
              :key="index"
              :label="childrenItem.questionName"
              :name="childrenItem.questionName"
            >
            </u-checkbox>
          </u-checkbox-group>
        </view>
        <view v-else-if="question.type == '主标题'">
          <view
            v-for="childrenItem in question.children"
            :key="childrenItem.questionId"
            class="question-children"
          >
            <!-- {{ childrenItem.questionName }} -->
            <AnswerComponent :isRoot="false" :question="childrenItem" />
          </view>
          <!-- v-if="question.children && question.children.length > 0" -->
        </view>
      </view>
    </view>
  </view>
</template>

<script>
//考卷做题页
export default {
  name: "AnswerComponent",
  props: {
    question: {
      type: Object,
      required: true,
    },
    isRoot: {
      type: Boolean,
      default: true,
    },
    showRoot: {
      type: Boolean,
      default: true,
    },
  },
  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) {
              //多选题，将答案转化为数组
              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);
          });
        }
      }
    },
    //上一题
    prevQuestion() {
      this.submitSignleQuestion();
      if (this.currentIndex > 0) {
        this.currentIndex--;
      }
    },
    //下一题
    nextQuestion() {
      this.submitSignleQuestion();
      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），那就需要给每个题目进行评分，统计并显示总分
      try {
        const result = score(value, ruleName);
        console.log("自动评分的结果", result);
      } 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>
.question {
}

.question-title-root {
  position: sticky; /* 添加粘性定位 */
  top: 0; /* 粘性定位在屏幕顶部 */
  background-color: white;

  font-size: 50rpx;
  text-align: left;
  margin: 0rpx 10rpx 20rpx 10rpx;
  padding: 5px;

  font-weight: 600;
  border: 1px solid #e8e8e8; /* 添加边框 */
  box-shadow: 3px 3px 6px rgba(0, 0, 0, 0.16); /* 添加阴影效果 */
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); /* 添加文字阴影效果 */
  border-radius: 5px; /* 添加圆角效果 */
}

.question-title {
  background-color: white;

  font-size: 40rpx;
  text-align: left;
  margin: 0rpx 10rpx 20rpx 10rpx;
  /* font-weight: 500; */
  border-radius: 5px;
  padding: 5px;
  border: 1px solid #e8e8e8; /* 添加边框 */
  box-shadow: 0px 1px 6px rgba(0, 0, 0, 0.16);
  /* text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); 添加文字阴影效果 */
}

.question-content {
  /* width: 100%;
  flex: 1;
  overflow: scroll; */
}

.question-children {
  display: flex;
  flex-direction: column;
  /* 靠上集中 */
  align-items: flex-start;
}
</style>