<template>
  <view class="page">
    <view class="title">{{ paperInfo.paperName }}</view>
    <view class="form">
      <u-col span="12">
        <u-empty v-if="questions.length == 0" mode="list"></u-empty>
        <u-collapse @open="Open" @change="change" @close="close">
          <u-collapse-item
            v-for="(item, index) in questions"
            :key="index"
            :duration="150"
            :name="questions.questionId"
            :disabled="item.answerValue == null || item.answerValue == ''"
            :isLink="!(item.answerValue == null || item.answerValue == '')"
          >
            <!-- :disabled="item.answerValue == null || item.answerValue == ''" -->
            <!-- :isLink="!(item.answerValue == null || item.answerValue == '')" -->

            <!-- 左侧标签和中间题目 -->
            <view slot="title" class="u-slot-title">
              <u-tag
                v-if="item.type == '填空'"
                text="填空题"
                plain
                size="mini"
                type="success"
              >
              </u-tag>
              <u-tag
                v-else-if="item.type == '单选'"
                text="单选题"
                plain
                size="mini"
                type="warning"
              >
              </u-tag>
              <u-tag
                v-else-if="item.type == '多选'"
                text="多选题"
                plain
                size="mini"
              >
              </u-tag>
              <text class="u-cell-text">{{ item.questionName }}</text>
            </view>

            <!-- 右侧内容 -->
            <view
              v-if="item.answerValue == null || item.answerValue == ''"
              slot="value"
              class="u-slot-value"
            >
              <u-tag
                text="未作答"
                @click="handle_tag_click(item)"
                plain
                size="mini"
                type="error"
              ></u-tag>
            </view>

            <view v-else slot="value" class="u-slot-value">
              <text>{{ formartAnswerArray(item.answerValue) }}</text>
            </view>

            <!-- 展开内容 -->
            <view v-if="item.type == '填空'">
              <u--textarea
                v-model="item.answerValue"
                placeholder="请输入答案"
                :height="150"
                count
                :disabled="editEnable"
              ></u--textarea>
            </view>
            <view v-else-if="item.type == '单选'">
              <u-radio-group
                size="20"
                iconSize="20"
                v-model="item.answerValue"
                placement="column"
                :disabled="editEnable"
              >
                <u-radio
                  labelSize="20"
                  :customStyle="{ marginBottom: '25rpx' }"
                  v-for="(childrenItem, index) in item.children"
                  :key="index"
                  :label="childrenItem.questionName"
                  :name="childrenItem.questionName"
                  @change="radioChange"
                >
                </u-radio>
              </u-radio-group>
            </view>
            <view v-else-if="item.type == '多选'">
              <u-checkbox-group
                v-model="item.answerValue"
                placement="column"
                :disabled="editEnable"
              >
                <u-checkbox
                  size="20"
                  labelSize="20"
                  iconSize="20"
                  :customStyle="{ marginBottom: '25rpx' }"
                  v-for="(childrenItem, index) in item.children"
                  :key="index"
                  :label="childrenItem.questionName"
                  :name="childrenItem.questionName"
                >
                </u-checkbox>
              </u-checkbox-group>
            </view>
            <view v-if="item.type == '主标题'">
              <answer-component :showRoot="false" :question="item"> </answer-component>
            </view>
          </u-collapse-item>
        </u-collapse>
      </u-col>
    </view>

     <u-tabbar :fixed="true" :placeholder="true" :safeAreaInsetBottom="true">
      <u-tabbar-item
        text="开始答题"
        @click="handle_Answer_click"
      ></u-tabbar-item>
    </u-tabbar>


    <!-- <view class="submit-button">
      <u-button size="large" @click="handle_Answer_click">开始答题</u-button>
    </view> -->
  </view>
</template>

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

import {
  listAnswer,
  getAnswer,
  delAnswer,
  addAnswer,
  updateAnswer,
} from "@/api/elder/questionnaire/answer";
import {
  listAssign,
  getAssign,
  delAssign,
  addAssign,
  updateAssign,
} from "@/api/elder/questionnaire/assign";

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

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

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

		onShow,
		onHide,
		onReady
	} from '@dcloudio/uni-app'
	import {
		computed,
		ref,
		reactive,
		onMounted
	} from 'vue';
//考卷预览页
	let editEnable = ref(false)//是否可编辑
	let defaultOpenAll = ref(false)
	let loading = ref(false)
	let assignId = ref(null)
	let assignDetailId = ref(null)
	let paperId = ref(null)
	let paperInfo = reactive({})
	let form = reactive({
        respondent: "",
        answers: [],
     })
	 let queryParams = reactive({
        pageNum: 1,
        pageSize: 1000,
        paperId: null,
      })
      // 表单查询参数
	  let queryParamsForm = reactive({})
	  let currentIndex = ref(0)
	  let questions = ref([])
	  let answerList = ref(null)

  let openIndex = computed(() => {
  	if (defaultOpenAll.value) {
  	  return Array.from(
  	    {
  	      length: questions.value.length,
  	    },
  	    (v, k) => k
  	  );
  	}
  	return [];
  });
  onLoad((options) => {
	assignId.value = options.assignId;
	assignDetailId.value = options.assignDetailId;
  })
  onShow(() => {
	  getList()
  })
    function getList() {
      loading.value = true;
      //获取题目，先通过assignDetailId获取paperId
      getAssignDetail(assignDetailId.value).then((response) => {
        console.log("getAssignDetail", response);
        paperId.value = response.data.paperId;
        queryParams.paperId = paperId.value; //获取试卷题目
        queryParams.assignDetailId = assignDetailId.value; //获取之前做题答案
        getPaper(queryParams.paperId).then((res) => {
          paperInfo = res.data;
        });
        listAnswer(transformRequestURL(queryParams)).then(
          (response_ans) => {
            console.log("listAnswer", response_ans);
            answerList.value = response_ans.rows;
            listQuestion(transformRequestURL(queryParams)).then(
              (response_ques) => {
                questions.value = buildTree(response_ques.data);
                //将主标题类型的题目，递归获取其子题目中（首个非主标题类型的题目）的答案
                questions.value.forEach((item, index) => {
                  if (item.type == "主标题") {
                    let children = item.children;
                    let answerValue = "";
                    for (let i = 0; i < children.length; i++) {
                      if (children[i].type != "主标题") {
                        answerValue = children[i].answerValue;
                        break;
                      }
                    }
                    item.answerValue = answerValue;
                  }
                });

                loading.value = false;
                if (questionId.value) {
                  questions.value.forEach((item, index) => {
                    if (item.questionId == questionId.value) {
                      currentIndex.value = index;
                    }
                  });
                }
              }
            );
          }
        );
      });
    }
   function buildTree(questions, parentId = 0) {
      let nodes = [];
      questions.forEach((item) => {
        if (item.parentQuestionid == parentId) {
          item.type = formartquestionType(item.questionType);
          item.hasAnswer = false; //默认没有答案
          item.rawAnswerValue = ""; //原始答案
          //通过this.answerList中的数据，将答案赋值给题目的answerValue
          item.answerValue = "";
          answerList.value.forEach((item2) => {
            if (item.questionId == item2.questionId &&  assignDetailId.value  == 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 = buildTree(questions, item.questionId); // 递归调用
          nodes.push(item);
        }
      });
      return nodes;
    }
    function handle_tag_click(item) {
      console.log("handle_tag_click", item);
      //   this.currentIndex = this.questions.findIndex((n) => n.questionId == item.questionId);
      //跳转到答题页面
      // this.$tab.navigateTo(
      //   "/pages/WenJuanDiaoCha/Answer/edit?assignId=" +
      //     this.assignId +
      //     "&assignDetailId=" +
      //     this.assignDetailId +
      //     "&paperId=" +
      //     this.paperId +
      //     "&questionId=" +
      //     item.questionId
      // );
    }
    function Open(e) {
      console.log("open", e);
    }
    function close(e) {
      console.log("close", e);
    }
    function change(e) {
      console.log("change", e);
    }
    //将数组结果转化为答案
    function formartAnswerArray(answerValue) {
      //如果是数组，将数组转化为字符串
      //   console.log("formartAnswerArray", typeof(answerValue) == 'object',typeof(answerValue) == Object);
      if (Array.isArray(answerValue)) {
        return answerValue.join(",");
      } else {
        return answerValue;
      }
    }
    //转化questionType
    function formartquestionType(questionType) {
      switch (questionType) {
        case "1":
          return "填空";
        case "2":
          return "单选";
        case "3":
          return "多选";
        case "0":
          return "主标题";
        case "21":
          return "只需选择";
        case "22":
          return "选择带填空";
        default:
          return "";
      }
    }

    function handleInput(item) {
      return false;
    }
    function prevQuestion() {
      if (currentIndex.value > 0) {
        currentIndex.value--
      }
    }
   function nextQuestion() {
      if (currentIndex.value < questions.value.length - 1) {
        currentIndex.value++
      }
    }
    function swiperChange({ detail: { current } }) {
      currentIndex.value = current;
    }
   function submitForm() {
      this.errors = [];
      // 表单校验
      // for (let i = 0; i < this.questions.length; i++) {
      //   const field = `answers.${i}`;
      //   this.$refs.form.validateField(field, (error) => {
      //     this.errors[i] = error ? error[0].message : "";
      //   });
      // }
      // // 判断是否所有题目都回答完整
      // const isComplete = this.errors.every((error) => !error);
      // if (isComplete) {
      //   console.log(this.form);
      // } else {
      //   uni.showToast({
      //     title: "请填写完整问卷",
      //     icon: "none",
      //   });
      // }
    }
   function  checkboxChange(n) {
      console.log("change", n);
    }
    function groupChange(n) {
      console.log("groupChange", n);
    }
    function radioChange(n) {
      console.log("radioChange", n);
    }
   function handel_cell_click() {}
   function handle_Answer_click() {
      //跳转页面，将考卷ID，答案
      // this.$tab.navigateTo(
      //   "/pages/WenJuanDiaoCha/Answer/edit?assignId=" +
      //     this.assignId +
      //     "&assignDetailId=" +
      //     this.assignDetailId +
      //     "&paperId=" +
      //     this.paperId
      // );
  }
</script>

<style scoped>
::v-deep .u-cell__body {
  background-color: white;
}

.u-slot-title {
  display: flex;
  align-items: center;
}

.u-cell-text {
  margin: 6rpx;
  max-width: 90%;
  

  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.u-slot-value {
  max-width: 30%;
  white-space: nowrap;
  /* 禁止换行 */
  overflow: hidden;
  /* 隐藏溢出内容 */
  text-overflow: ellipsis;
  /* 使用省略号表示溢出内容 */
}

.page {
  height: 100%;
}

.title {
  text-align: center;
  font-size: 45rpx;

  position: sticky; /* 添加粘性定位 */
  top: 5rpx; /* 粘性定位在屏幕顶部 */
  background-color: white;
  z-index: 9999;

  /* font-size: 60rpx; */
  /* text-align: left; */
  margin: 5rpx 10rpx 5rpx 5rpx;
  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; /* 添加圆角效果 */
}

.form {
  height: calc(100% - 100rpx);
  overflow: hidden;
}

.submit-button {
  display: flex;
  justify-content: center;
  margin-top: 20rpx;

  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 9999;
  /* 保证在最上层 */
}
</style>