<script setup lang="ts">
import { onMounted, ref } from 'vue'

import { useRoute } from 'vue-router'

import { examPaperDetail } from '@/api/exam'
import { getAnswerResult } from '@/api/exam/answer'
import { getParticipantById } from '@/api/exam/participant'

const route = useRoute()
const examId = Number(route.query.id || 0)
const pid = Number(route.query.pid || 0)

const participantInfo = ref<any>({})

// 考试信息
const examInfo = ref<any>({})
// 答题信息
const answerInfo = ref<any>([])

// onMounted(() => {
//   getParticipantById(pid).then((res: any) => {
//     participantInfo.value = res || {}
//   })
// })

// 计算用时
function calculateExamTime() {
  if (!participantInfo.value.startTime || !participantInfo.value.submitTime) {
    return '-'
  }
  const startTime = new Date(participantInfo.value.startTime).getTime()
  const submitTime = new Date(participantInfo.value.submitTime).getTime()
  const duration = (submitTime - startTime) / 60_000 // 转换为分钟
  return `${duration.toFixed(2)} 分钟`
}

// 数据处理工具函数
// 解析JSON字符串，处理异常
function parseJson(str: string) {
  if (!str)
    return []
  try {
    return JSON.parse(str)
  }
  catch (error) {
    console.error('解析JSON失败:', error)
    return []
  }
}

// 根据paperQuestionId获取答题信息
function getAnswerByPaperQuestionId(paperQuestionId: number) {
  return (
    answerInfo.value.find(
      (item: any) => item.paperQuestionId === paperQuestionId,
    ) || {}
  )
}
// 获取题目类型中文名称
function getQuestionTypeName(type: string) {
  const typeMap: any = {
    single_choice: '单选题',
    multiple_choice: '多选题',
    judgment: '判断题',
    fill_blank: '填空题',
    essay: '简答题',
  }
  return typeMap[type] || type
}

// 按大题索引分组题目
function getQuestionsByBigIndex() {
  if (!examInfo.value?.paper?.questions)
    return []

  const grouped: any = {}
  examInfo.value.paper.questions.forEach((question: any) => {
    if (!grouped[question.bigQuestionIndex]) {
      grouped[question.bigQuestionIndex] = []
    }
    grouped[question.bigQuestionIndex].push(question)
  })

  // 转换为数组并按索引排序
  return Object.keys(grouped)
    .sort((a, b) => Number(a) - Number(b))
    .map(key => grouped[key])
}

async function init() {
  // 并发请求接口获取数据
  const [examInfoRes, participantRes, answerRes]: any = await Promise.all([
    examPaperDetail(examId),
    getParticipantById(pid),
    getAnswerResult(examId),
  ])
  examInfo.value = examInfoRes.data || {}
  if (examInfo.value?.paper?.bigQuestionNames) {
    examInfo.value.paper.bigQuestionNames = JSON.parse(
      examInfo.value.paper.bigQuestionNames,
    )
  }
  participantInfo.value = participantRes.data || {}
  answerInfo.value = answerRes.data || {}
}

onMounted(async () => {
  await init()
})

// const list = ref([
//   {
//     type: 'single',
//     title: '第一题单选题(本题分值1分)',
//     score: 1,
//     list: [
//       {
//         title: '这是本题的题目，请选择',
//         answer: [
//           {
//             title: 'A.答案1',
//             isRight: true,
//           },
//           {
//             title: 'B.答案2',
//             isRight: false,
//           },
//           {
//             title: 'B.答案3',
//             isRight: '',
//           },
//           {
//             title: 'B.答案4',
//             isRight: '',
//           },
//         ],
//         AnswerExplanation:
//           '解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析',
//       },
//       {
//         title: '这是本题的题目，请选择',
//         answer: [
//           {
//             title: 'A.答案1',
//             isRight: '',
//           },
//           {
//             title: 'B.答案2',
//             isRight: true,
//           },
//           {
//             title: 'B.答案3',
//             isRight: '',
//           },
//           {
//             title: 'B.答案4',
//             isRight: false,
//           },
//         ],
//         AnswerExplanation:
//           '解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析',
//       },
//     ],
//   },
//   {
//     type: 'single',
//     title: '第二题多选题(本题分值1分)',
//     score: 1,
//     list: [
//       {
//         title: '这是本题的题目，请选择',
//         answer: [
//           {
//             title: 'A.答案1',
//             isRight: true,
//           },
//           {
//             title: 'B.答案2',
//             isRight: true,
//           },
//           {
//             title: 'B.答案3',
//             isRight: true,
//           },
//           {
//             title: 'B.答案4',
//             isRight: false,
//           },
//         ],
//         AnswerExplanation:
//           '解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析',
//       },
//       {
//         title: '这是本题的题目，请选择',
//         answer: [
//           {
//             title: 'A.答案1',
//             isRight: false,
//           },
//           {
//             title: 'B.答案2',
//             isRight: true,
//           },
//           {
//             title: 'B.答案3',
//             isRight: false,
//           },
//           {
//             title: 'B.答案4',
//             isRight: true,
//           },
//         ],
//         AnswerExplanation:
//           '解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析',
//       },
//     ],
//   },
//   {
//     type: 'single',
//     title: '第三题判断题(本题分值1分)',
//     score: 1,
//     list: [
//       {
//         title: '这是本题的题目，请选择',
//         answer: [
//           {
//             title: 'A.答案1',
//             isRight: true,
//           },
//           {
//             title: 'B.答案2',
//             isRight: false,
//           },
//         ],
//         AnswerExplanation:
//           '解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析',
//       },
//       {
//         title: '这是本题的题目，请选择',
//         answer: [
//           {
//             title: 'A.答案1',
//             isRight: false,
//           },
//           {
//             title: 'B.答案2',
//             isRight: true,
//           },
//         ],
//         AnswerExplanation:
//           '解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析',
//       },
//     ],
//   },
//   {
//     type: 'single',
//     title: '第四题填空题(本题分值1分)',
//     score: 1,
//     list: [
//       {
//         title: '1.这是本题的题目(),(),()',
//         answer: [
//           {
//             title: 'A.填空',
//             answertext: '考生输入的答案1',
//             isRight: true,
//           },
//           {
//             title: 'B.填空',
//             answertext: '考生输入的答案2',
//             isRight: true,
//           },
//           {
//             title: 'C.填空',
//             answertext: '考生输入的答案3',
//             isRight: false,
//           },
//         ],
//         AnswerExplanation:
//           '解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析',
//       },
//       {
//         title: '2.这是本题的题目(),(),()',
//         answer: [
//           {
//             title: 'A.填空',
//             answertext: '考生输入的答案1',
//             isRight: true,
//           },
//           {
//             title: 'B.填空',
//             answertext: '考生输入的答案2',
//             isRight: false,
//           },
//         ],
//         AnswerExplanation:
//           '解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析',
//       },
//     ],
//   },
//   {
//     type: 'single',
//     title: '第五题简答题(本题分值1分)',
//     score: 1,
//     list: [
//       {
//         title: '1.这是本题的题目。',
//         answer: [
//           {
//             title: '这是一个简答题',
//             answertext:
//               '考生输入的答案考生输入的答案考生输入的答案考生输入的答案考生输入的答案考生输入的答案',
//             Correctanswer: '正确答案正确答案正确答案正确答案正确答案正确答案',
//             isRight: true,
//           },
//         ],
//         AnswerExplanation:
//           '解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析解析',
//       },
//     ],
//   },
// ]) as any
</script>

<template>
  <view class="knowledgebase_exam_explanation">
    <view class="knowledgebase_exam_explanation_title">
      {{ examInfo.examName || '' }}
    </view>
    <view class="knowledgebase_exam_explanation_content">
      <view class="knowledgebase_exam_explanation_content_title">
        考试说明
      </view>
      <view class="knowledgebase_exam_explanation_content_text">
        {{ examInfo.remark || '' }}
      </view>
    </view>
    <view class="knowledgebase_exam_explanation_float">
      <view class="knowledgebase_exam_explanation_float_title">
        考试总分
        <span class="knowledgebase_exam_explanation_float_title_score">{{ examInfo.totalScore || 0 }}分</span>
      </view>
      <view class="knowledgebase_exam_explanation_float_title">
        及格分数
        <span class="knowledgebase_exam_explanation_float_title_score">{{ examInfo.passScore }}分</span>
      </view>
      <view class="knowledgebase_exam_explanation_float_title">
        考试时长
        <span class="knowledgebase_exam_explanation_float_title_score">{{ examInfo.examDuration }}分钟</span>
      </view>
      <view class="knowledgebase_exam_explanation_float_title">
        考生得分
        <span
          class="knowledgebase_exam_explanation_float_title_score"
          style="color: #215acd"
        >{{ participantInfo.score || 0 }}分</span>
      </view>
      <view class="knowledgebase_exam_explanation_float_title">
        考试结果
        <span
          v-if="participantInfo.score >= examInfo.passScore"
          class="knowledgebase_exam_explanation_float_title_score"
          style="color: #38b865"
        >及格</span>
        <span
          v-else
          class="knowledgebase_exam_explanation_float_title_score"
          style="color: #eb5e12"
        >不及格</span>
      </view>
    </view>
    <view class="AnswerDetails">
      <view class="AnswerDetails_title">
        答题详情
      </view>
      <view
        v-for="(bigQuestion, bigIndex) in examInfo?.paper?.bigQuestionNames"
        :key="bigIndex" class="AnswerDetails_content"
      >
        <view class="AnswerDetails_content_box">
          <view class="AnswerDetails_content_title">
            {{ bigQuestion.name }}(本题分值{{ bigQuestion.score }}分)
          </view>
          <view
            v-for="(question, questionIndex) in getQuestionsByBigIndex()[
              +bigIndex
            ] || []"
            :key="question.id"
            class="AnswerDetails_content_item"
          >
            <view class="Thisquestiontitle">
              <view class="AnswerDetails_content_item_title">
                {{ +questionIndex + 1 }}.
                <span v-html="question.info.questionContent" />（{{
                  getQuestionTypeName(question.questionType)
                }}，{{ question.smallQuestionScore }}分）
              </view>
              <view
                v-if="
                  ['single_choice', 'multiple_choice', 'judgment'].includes(
                    question.questionType,
                  )
                " class="AnswerDetails_content_item_answer"
              >
                <text
                  v-for="(option, optionIndex) in parseJson(
                    question.info.options,
                  )"
                  :key="optionIndex"
                  :style="
                    getAnswerByPaperQuestionId(question.id).isCorrect === 1
                      ? 'color: #38B865'
                      : getAnswerByPaperQuestionId(question.id).isCorrect === 0
                        ? 'color: #EB5E12'
                        : ''
                  "
                >
                  <text>
                    {{ String.fromCharCode(65 + +optionIndex) }}.
                    <span v-html="option" />
                  </text>
                  <wd-icon
                    v-if="
                      getAnswerByPaperQuestionId(question.id).isCorrect === 1
                    "
                    style="
                      color: #38b865;
                      text-align: center;
                      margin-left: 20rpx;
                    "
                    name="check-circle-filled"
                    size="16px"
                  />
                  <wd-icon
                    v-else
                    style="
                      color: #eb5e12;
                      text-align: center;
                      margin-left: 20rpx;
                    "
                    name="close-circle-filled"
                    size="16px"
                  />
                </text>
              </view>
              <view
                v-else-if="question.questionType === 'fill_blank'"
                class="AnswerDetails_content_item_answer"
              >
                <text
                  v-for="(option, optionIndex) in parseJson(
                    getAnswerByPaperQuestionId(question.id).userAnswer
                      || '[]',
                  )"
                  :key="optionIndex"
                  :style="
                    getAnswerByPaperQuestionId(question.id).isCorrect === 1
                      ? 'color: #38B865'
                      : getAnswerByPaperQuestionId(question.id).isCorrect === 0
                        ? 'color: #EB5E12'
                        : ''
                  "
                >
                  <text>
                    {{ option }}
                  </text>
                  <wd-icon
                    v-if="
                      getAnswerByPaperQuestionId(question.id).isCorrect === 1
                    "
                    style="
                      color: #38b865;
                      text-align: center;
                      margin-left: 20rpx;
                    "
                    name="check-circle-filled"
                    size="16px"
                  />
                  <wd-icon
                    v-else
                    style="
                      color: #eb5e12;
                      text-align: center;
                      margin-left: 20rpx;
                    "
                    name="close-circle-filled"
                    size="16px"
                  />
                </text>
              </view>
              <view
                v-else-if="question.questionType === 'essay'"
                class="AnswerDetails_content_item_answer"
              >
                <text
                  :style="
                    getAnswerByPaperQuestionId(question.id).isCorrect === 1
                      ? 'color: #38B865'
                      : getAnswerByPaperQuestionId(question.id).isCorrect === 0
                        ? 'color: #EB5E12'
                        : ''
                  "
                >
                  <text>
                    {{ getAnswerByPaperQuestionId(question.id).userAnswer
                      || '未作答' }}
                  </text>
                  <wd-icon
                    v-if="
                      getAnswerByPaperQuestionId(question.id).isCorrect === 1
                    "
                    style="
                      color: #38b865;
                      text-align: center;
                      margin-left: 20rpx;
                    "
                    name="check-circle-filled"
                    size="16px"
                  />
                  <wd-icon
                    v-else
                    style="
                      color: #eb5e12;
                      text-align: center;
                      margin-left: 20rpx;
                    "
                    name="close-circle-filled"
                    size="16px"
                  />
                </text>
              </view>
            </view>
            <!-- 答案解析 -->
            <view class="AnswerExplanation_box">
              <view class="Correctanswer" style="margin-bottom: 48rpx">
                <text class="Correctanswer_title">正确答案 : </text>
                <!-- <text
                  v-for="values in items?.answer.filter((a) => a.isRight)"
                  v-if="value.title.includes('简答题')"
                  :key="values.title"
                  class="Correctanswer_title Content"
                >
                  {{ `${values.Correctanswer};` }}
                </text> -->
                <text
                  v-if="
                    ['single_choice', 'multiple_choice', 'judgment', 'fill_blank'].includes(
                      question.questionType,
                    )
                  "
                  class="Correctanswer_title Content"
                >
                  <span
                    v-html="
                      parseJson(question.info.correctAnswer || '[]')
                        .map((idx: number) => String.fromCharCode(65 + idx))
                        .join('、')
                    "
                  />
                </text>
                <text
                  v-else
                  class="Correctanswer_title Content"
                >
                  <span
                    v-html="question.info.correctAnswer || '无'"
                  />
                </text>
              </view>
              <view class="AnswerExplanation">
                <view class="Correctanswer_title" style="margin-bottom: 32rpx">
                  答案解析:
                </view>
                <text class="Correctanswer_Content">
                  <span
                    v-html="question.info.answerAnalysis || '暂无解析'"
                  />
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
html,
body {
  overflow: hidden;
}
.knowledgebase_exam_explanation {
  height: calc(100vh - 88rpx);
  display: flex;
  flex-direction: column;
  padding: 24rpx;
  box-sizing: border-box;
}
.knowledgebase_exam_explanation_title {
  font-family: Alibaba PuHuiTi 2;
  font-weight: 500;
  font-style: 65 Medium;
  font-size: 48rpx;
  leading-trim: NONE;
  line-height: 48rpx;
  letter-spacing: 0px;
  color: #31373d;
}
.knowledgebase_exam_explanation_content {
  margin-top: 80rpx;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 32rpx;
  .knowledgebase_exam_explanation_content_title {
    font-weight: 500;
    font-style: 65 Medium;
    font-size: 36rpx;
    leading-trim: NONE;
    letter-spacing: 0px;
    color: #31373d;
  }
  .knowledgebase_exam_explanation_content_text {
    font-weight: 400;
    font-style: 55 Regular;
    font-size: 28rpx;
    line-height: 48rpx;
    letter-spacing: 0px;
    color: #4e5969;
  }
}
.knowledgebase_exam_explanation_float {
  margin-top: 48rpx;
  margin-bottom: 48rpx;
  border-top: 1rpx solid #eeeeee;
  border-bottom: 1rpx solid #eeeeee;
  padding-top: 48rpx;
  padding-bottom: 48rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 32rpx;
  .knowledgebase_exam_explanation_float_title {
    font-weight: 400;
    font-style: 55 Regular;
    font-size: 28rpx;
    letter-spacing: 0px;
    color: #4e5969;
    .knowledgebase_exam_explanation_float_title_score {
      margin-left: 48rpx;
      color: #31373d;
    }
  }
}
.AnswerDetails {
  flex: 1;
  overflow-y: auto;
  .AnswerDetails_title {
    font-weight: 500;
    font-style: 65 Medium;
    font-size: 36rpx;
    leading-trim: NONE;
    letter-spacing: 0px;
    color: #31373d;
    margin-bottom: 48rpx;
  }
  .AnswerDetails_content {
    // width: 100%;
    // display: flex;
    // flex-direction: column;
    // gap: 24rpx;
    margin-bottom: 24rpx;
    .AnswerDetails_content_box {
      display: flex;
      flex-direction: column;
      gap: 24rpx;
    }
    .AnswerDetails_content_title {
      width: 100%;
      height: 96rpx;
      background-color: #f7f9fa;
      padding-left: 32rpx;
      box-sizing: border-box;
      line-height: 88rpx;

      font-weight: 500;
      font-size: 32rpx;
      color: #31373d;
    }
    .AnswerDetails_content_item {
      box-sizing: border-box;
      padding: 32rpx;
      width: 100%;
      background-color: #f7f9fa;
      .Thisquestiontitle {
        border-bottom: 1rpx solid #e6e8eb;
        box-sizing: border-box;
        padding-bottom: 48rpx;
        margin-bottom: 48rpx;
        .AnswerDetails_content_item_title {
          margin-bottom: 48rpx;
          font-weight: 400;
          font-size: 32rpx;
          color: #31373d;
        }
        .AnswerDetails_content_item_answer {
          display: flex;
          flex-direction: column;
          gap: 52rpx;

          font-weight: 400;
          font-size: 28rpx;
          color: #31373d;
        }
      }
      .AnswerExplanation_box {
        .Correctanswer_title {
          font-weight: 400;
          font-size: 28rpx;
          color: #31373d;
        }
        .Content {
          color: #38b865;
          margin-right: 10rpx;
        }
        .Correctanswer_Content {
          font-weight: 400;
          font-size: 32rpx;
          color: #4e5969;
          line-height: 56rpx;
        }
      }
    }
  }
}
</style>
