<template>
  <home-container v-if="pageReady">
    <div class="header-title">
      <div class="title">{{ exName }}</div>
      <div class="sub-title">测试时间：{{ exTime }}分钟 总分：{{ totalScore }}分</div>

      <question-done v-if="status === 'done'" ref="QuestionDone" />
      <question-card v-else ref="QuestionCard" :ex-time="exTime" :answer-list="answerList" @chooseAnswer="chooseAnswer"
        @currentQuestion="cur => currentQuestion = cur" @submit="handleSubmit" />

      <div v-if="status !== 'done'" class="question-card">
        <div class="title">
          答题卡
          <div class="right-question-card">
            <div class="question-status">
              <div class="question-status-item done">
                已答
              </div>
              <div class="question-status-item current">
                当前
              </div>
              <div class="question-status-item">
                未答
              </div>
            </div>
          </div>
        </div>

        <div v-if="status !== 'done'" class="question-num">
          <div v-for="(num, idx) in questionCount" :class="{
            done: currentQuestion > idx,
            current: currentQuestion === idx
          }" class="question-num-item" @click="goToQuestion(idx)">
            <div class="question-num-item-title">
              {{ idx + 1 }}
            </div>
          </div>
        </div>
      </div>

      <div v-if="status === 'done'" class="question-card">
        <div class="title">
          答题卡
          <div class="right-question-card">
            <div class="question-status">
              <div class="question-status-item done">
                正确
              </div>
              <div class="question-status-item mistake">
                错误
              </div>
              <div class="question-status-item">
                未答
              </div>
            </div>
          </div>
        </div>

        <div v-if="status === 'done'" class="question-num">
          <div v-for="(num, idx) in answeringSituation" :class="{
            done: num.eroCorrectStatus == 'ALL_CORRECT' && num.eroCorrectStatus != 'NOT_FILLED',
            mistake: num.eroCorrectStatus != 'ALL_CORRECT' && (num.eroCorrectStatus == 'PART_CORRECT'||num.eroCorrectStatus == 'INCORRECT') &&  num.eroCorrectStatus != 'NOT_FILLED'
          }" class="question-num-item" @click="goToResult(num)">
            <div class="question-num-item-title">
              {{ idx + 1 }}
            </div>
          </div>
        </div>
      </div>

      <div v-if="resultShow" class="question-card">
        <question-result ref="QuestionResult" :answer-list="answerList" />
      </div>


    </div>


  </home-container>
</template>
<script>
import HomeContainer from "@/components/HomeContainer.vue";
import QuestionCard from "@/pages/exam/components/question-card.vue";
import QuestionDone from "@/pages/exam/components/question-done.vue";
import QuestionResult from "@/pages/exam/components/question-result.vue";
import { getExamIntro } from "@/api/exam/exam"
import { applyExam } from "@/api/exam/exam"
import { submitExam } from "@/api/exam/exam"
import { getExam } from "@/api/exam/exam"
import { getToken } from '@/utils/auth'



export default {
  components: { QuestionDone, QuestionCard, HomeContainer, QuestionResult, },
  data() {
    return {
      pageReady: false,   // 新增

      resultDetail: [],
      answeringSituation: [],
      exName: '',
      exTime: '40',
      totalScore: '',
      questionCount: 0,
      answerList: [
      ],
      currentQuestion: 1,
      status: 'done',
      resultShow: false,
      options: [],
      exId: '',
      erId: '',
      erExamTime: 10,
    }
  },
  onLoad(options) {
 

    this.status = options.status
    const id = options.id;
    const erId = options.erId;
    this.exTime = options.exTime;
    //    console.log("this.status",this.status)
    // if(this.status === 'done'){
    //   uni.navigateTo({
    //     url: '/pages/exam-list/index'
    //   })
    // }
    if (erId && erId !== 'null' && erId !== 'undefined') {
      this.exId = id;
      this.erId = erId;
      this.showExDetail()
    } else {
      this.initData(id)
    }
  },
  methods: {
    chooseAnswer(ops) {
      this.options = ops;
    },
    async handleSubmit(leftTimeSec = 0) {
      try {
        console.log("leftTimeSec",leftTimeSec)
        
        // 转换options格式为后端期望的格式
        const formattedOptions = this.formatOptionsForBackend(this.options);
        
        await submitExam({ "clientType": "client_type_kg_app", "exId": this.exId, "erId": this.erId, "erExamTime": leftTimeSec, "options": formattedOptions });
        const response = await getExam({ "erId": this.erId, "clientType": "client_type_kg_app" });
        this.status = 'done'
        this.answeringSituation = response.model.question

        const exData = {
          "erRate": response.model.erCorrect,
          "erScore": response.model.erScore,
          "erExamTime": response.model.erExamTime,
          "erCorrect": response.model.erCorrect,
          "erBingoCount": response.model.erBingoCount, //正确的
          "erIncorrectCount": response.model.erIncorrectCount, //错误的
          "erNotFilledCount":response.model.erNotFilledCount //未作答
        };
        this.$nextTick(() => {
          if (this.$refs.QuestionDone) {
            this.$refs.QuestionDone.initDone(exData); // 调用子组件的 nextQuestion 方法
          } else {
            setTimeout(() => {
              this.$refs.QuestionDone?.initDone(exData);
            }, 1000);
          }
        });
      } finally {
        this.pageReady = true;      // 关键：放开渲染
      }
    },
    // 格式化options为后端期望的格式
    formatOptionsForBackend(options) {
      if (!options || !Array.isArray(options)) return [];
      
      const result = [];
      
      options.forEach((option, index) => {
        if (Array.isArray(option)) {
          // 多选题：将数组中的每个选项转换为单独的对象
          option.forEach(opt => {
            result.push({
              quId: opt.quId,
              eroConnNo: opt.eroConnNo,
              eroSort: opt.eroSort
            });
          });
        } else if (option && typeof option === 'object') {
          // 单选题：直接添加对象
          result.push({
            quId: option.quId,
            eroConnNo: option.eroConnNo,
            eroSort: option.eroSort
          });
        }
      });
      
      return result;
    },
    async showExDetail() {
      try {
        
        // await submitExam({ "clientType": "client_type_kg_app", "exId": this.exId, "erId": this.erId, "erExamTime": this.erExamTime, "options": this.options });
        const response = await getExam({ "erId": this.erId, "clientType": "client_type_kg_app" });
        this.status = 'done'
        this.answeringSituation = response.model.question
        this.totalScore = response.model.erTpTotalScore

        const exData = {
          "erRate": response.model.erCorrect,
          "erScore": response.model.erScore,
          "erExamTime": response.model.erExamTime,
          "erCorrect": response.model.erCorrect,
          "erBingoCount": response.model.erBingoCount, //正确的
          "erIncorrectCount": response.model.erIncorrectCount, //错误的
          "erNotFilledCount":response.model.erNotFilledCount //未作答
        };
        this.$nextTick(() => {
          if (this.$refs.QuestionDone) {
            this.$refs.QuestionDone.initDone(exData); // 调用子组件的 nextQuestion 方法
          } else {
            setTimeout(() => {
              this.$refs.QuestionDone?.initDone(exData);
            }, 1000);
          }
        });
      } finally {
        this.pageReady = true;      // 关键：放开渲染
      }



      // this.status = 'done'
    },
    goToQuestion(idx) {
      this.currentQuestion = idx;

      this.$nextTick(() => {
        if (this.$refs.QuestionCard) {
          this.$refs.QuestionCard.selectQuestion(idx); // 调用子组件的 nextQuestion 方法
        } else {
          console.error('子组件未正确引用');
        }
      });



    },
    async initData(id) {
      try {
        const response = await getExamIntro({ "id": id, "clientType": "client_type_kg_app" });
        this.exName = response.model.exName,
          this.exTime = response.model.exExamTime / 60
        this.totalScore = response.model.totalScore,
          this.questionCount = response.model.questionCount
      } catch (error) {
        console.error('获取测试记录失败', error);
      }
      try {
        const response = await applyExam({ "id": id, "pcId": "h5", "clientType": "client_type_kg_app" })
        const quTypeMap = {
          SINGLE: '单选',
          MULTIPLE: '多选',
          JUDGMENT: '判断',
          FILL_BLANK: '填空',
          CONNECTION: '连线'
        };
        this.answerList = response.model.question.map(item => ({
          exExamTime: response.model.exExamTime,
          quId: item.quId,
          quType: quTypeMap[item.quType],
          exName: response.model.exName,
          title: item.quContent,
          answer: item.options.map(option => ({
            quId: item.quId,
            num: option.sort,
            content: option.qoOption
          }))

        }));
        this.erId = response.model.erId;
        this.exId = response.model.exId


      } finally {
        this.pageReady = true;      // 关键：放开渲染
      }

    },
    goToResult(result) {
      const quTypeMap = {
        SINGLE: '单选',
        MULTIPLE: '多选',
        JUDGMENT: '判断',
        FILL_BLANK: '填空',
        CONNECTION: '连线'
      };
      this.resultDetail = {
        quType: quTypeMap[result.eroQuType],
        title: result.eroQuContent,
        eroTpqSort: result.eroTpqSort,
        answer: result.option

      };
      this.$nextTick(() => {
        if (this.$refs.QuestionResult) {
          this.$refs.QuestionResult.initResult(this.resultDetail); // 调用子组件的 nextQuestion 方法
        } else {
          setTimeout(() => {
            this.$refs.QuestionResult?.initResult(this.resultDetail);
          }, 1000);
        }
      });
      this.resultShow = true;

    }
  },
}
</script>

<style lang="scss" scoped>
.header-title {
  padding: 40rpx 0 20rpx 20rpx;
  z-index: 2;
  position: relative;

  &:after {
    content: "";
    position: absolute;
    z-index: 2;
    top: 0;
    right: 0;
    width: 220rpx;
    height: 500rpx;
    background-image: url("../../static/images/exam.png");
    background-repeat: no-repeat;
    background-size: 220rpx;
    background-position: right 40rpx;
  }

  .title {
    font-weight: 400;
    font-size: 40rpx;
    color: #FFFFFF;
    line-height: 56rpx;
  }

  .sub-title {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.9);
    line-height: 40rpx;
    padding-bottom: 56rpx;
  }
}


.question-card {
  padding: 40rpx;
  background: #FFFFFF;
  box-shadow: 0 8rpx 32rpx 0 rgba(0, 0, 0, 0.1);
  border-radius: 32rpx;
  margin-top: 66rpx;

  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 36rpx;
    color: #222222;
    line-height: 42rpx;
    margin-bottom: 48rpx;
  }

  .question-status {
    display: flex;
    align-items: center;
    gap: 32rpx;

    .question-status-item {
      font-size: 26rpx;
      color: #666666;
      line-height: 30rpx;
      padding-left: 36rpx;
      position: relative;

      &:after {
        content: "";
        width: 24rpx;
        height: 24rpx;
        border-radius: 8rpx;
        border: 2rpx solid #C5C5C5;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
      }

      &.done {
        &:after {
          border-color: #5F88F8;
          background: #5F88F8;
        }
      }

      &.current {
        &:after {
          border-color: #D5E1FF;
          background: #D5E1FF;
        }
      }

      &.mistake {
        &:after {
          border-color: #fe0303;
          background: #fe0303;
        }
      }
    }
  }

  .question-num {
    display: flex;
    align-items: center;
    flex-flow: wrap;
    gap: 28rpx;

    .question-num-item {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 64rpx;
      height: 64rpx;
      background: #FFFEFD;
      border-radius: 80rpx;
      border: 2rpx solid #D6D6D6;
      font-size: 28rpx;
      color: #C4C4C4;

      &.done {
        background: linear-gradient(135deg, #6E9BFC 0%, #496CF4 100%);
        color: #FFFFFF;
      }

      &.current {
        background: #D5E1FF;
        color: #2A70D1;
      }

      &.mistake {
        border-color: #fe0303;
        background: #fe0303;

      }
    }
  }
}
</style>