<template>
  <home-container v-if="pageReady">
    <div class="daily-answer-container">
      <!-- 答题模式 -->
      <div v-if="mode === 'answer'" class="answer-mode">
        <div class="header">
          <div class="header-info">
            <div class="title">每日答题</div>
            <div class="progress">第 {{ currentIndex + 1 }}/{{ questions.length }} 题</div>
          </div>
          <div class="timer">
            <text class="timer-icon">⏱</text>
            <text class="timer-text">{{ formattedTime }}</text>
          </div>
        </div>

        <div v-if="currentQuestion" class="question-card">
          <div class="question-type">{{ getQuestionTypeText(currentQuestion.questionType) }}</div>
          <div class="question-content">{{ currentQuestion.questionContent }}</div>

          <div class="options">
            <div
              v-for="(option, idx) in getOptions(currentQuestion)"
              :key="idx"
              :class="['option-item', { active: isSelected(idx) }]"
              @click="selectOption(idx)">
              <div class="option-label">{{ getOptionLabel(idx) }}</div>
              <div class="option-content">{{ option }}</div>
              <div v-if="isSelected(idx)" class="option-check">✓</div>
            </div>
          </div>
        </div>

        <div class="navigation">
          <div v-if="currentIndex > 0" class="btn btn-secondary" @click="prevQuestion">上一题</div>
          <div v-if="currentIndex < questions.length - 1" class="btn btn-primary" @click="nextQuestion">下一题</div>
          <div v-if="currentIndex === questions.length - 1" class="btn btn-primary" @click="showSubmitConfirm">提交答卷</div>
        </div>

        <!-- 答题卡 -->
        <div class="answer-card">
          <div class="answer-card-title">答题卡</div>
          <div class="answer-card-grid">
            <div
              v-for="(q, idx) in questions"
              :key="idx"
              :class="[
                'answer-card-item',
                { answered: userAnswers[q.questionId] !== undefined },
                { current: idx === currentIndex }
              ]"
              @click="jumpToQuestion(idx)">
              {{ idx + 1 }}
            </div>
          </div>
        </div>
      </div>

      <!-- 结果模式 -->
      <div v-if="mode === 'result'" class="result-mode">
        <div class="result-header">
          <div class="result-score">
            <div class="score-value">{{ result.totalScore }}</div>
            <div class="score-label">总分</div>
          </div>
          <div class="result-stats">
            <div class="stat-item">
              <div class="stat-value correct">{{ result.correctCount }}</div>
              <div class="stat-label">正确</div>
            </div>
            <div class="stat-item">
              <div class="stat-value wrong">{{ result.wrongCount }}</div>
              <div class="stat-label">错误</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ result.totalCount }}</div>
              <div class="stat-label">总题数</div>
            </div>
          </div>
        </div>

        <div class="result-questions">
          <div v-for="(q, idx) in questions" :key="idx" class="result-question-item">
            <div class="result-question-header">
              <div class="question-num">第 {{ idx + 1 }} 题 ({{ getQuestionTypeText(q.questionType) }})</div>
              <div :class="['question-result', q.isCorrect ? 'correct' : 'wrong']">
                {{ q.isCorrect ? '✓ 正确' : '✗ 错误' }}
              </div>
            </div>
            <div class="question-content">{{ q.questionContent }}</div>
            <div class="question-answers">
              <div class="answer-row">
                <text class="answer-label">你的答案：</text>
                <text :class="['answer-value', q.isCorrect ? 'correct' : 'wrong']">
                  {{ formatAnswer(q.userAnswer) || '未作答' }}
                </text>
              </div>
              <div v-if="!q.isCorrect" class="answer-row">
                <text class="answer-label">正确答案：</text>
                <text class="answer-value correct">{{ formatAnswer(q.correctAnswer) }}</text>
              </div>
              <div class="answer-row">
                <text class="answer-label">得分：</text>
                <text :class="['answer-value', q.isCorrect ? 'correct' : '']">{{ q.actualScore }}/{{ q.totalScore }}分</text>
              </div>
            </div>
          </div>
        </div>

        <div class="result-footer">
          <div class="btn btn-primary" @click="backToList">返回列表</div>
        </div>
      </div>
    </div>
  </home-container>
</template>

<script>
import HomeContainer from "@/components/HomeContainer.vue";
import { startTask, submitAnswer, getTaskDetail, getRemainingTime } from "@/api/exam/dailyExam";

export default {
  components: { HomeContainer },
  data() {
    return {
      pageReady: false,
      mode: 'answer', // answer: 答题模式, result: 结果模式
      taskId: '',
      status: '', // start: 开始答题, continue: 继续答题, result: 查看结果

      questions: [],
      currentIndex: 0,
      userAnswers: {}, // { questionId: answer }

      timeLeft: 0, // 剩余时间（秒）
      timer: null,

      result: {
        totalScore: 0,
        correctCount: 0,
        wrongCount: 0,
        totalCount: 0
      }
    }
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentIndex] || null;
    },
    formattedTime() {
      const minutes = Math.floor(this.timeLeft / 60);
      const seconds = this.timeLeft % 60;
      return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
    }
  },
  onLoad(options) {
    this.taskId = options.taskId;
    this.status = options.status;

    if (this.status === 'result') {
      this.mode = 'result';
      this.loadResult();
    } else {
      this.mode = 'answer';
      this.startAnswer();
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    async startAnswer() {
      try {
        const response = await startTask(this.taskId);
        this.questions = response.data.questions || [];
        this.timeLeft = response.data.remainingTime || 0;

        // 如果是继续答题，恢复之前的答案
        this.questions.forEach(q => {
          if (q.userAnswer) {
            this.userAnswers[q.questionId] = q.userAnswer;
          }
        });

        this.startTimer();
        this.pageReady = true;
      } catch (error) {
        console.error('开始答题失败', error);
        uni.showToast({
          title: error.msg || '开始答题失败',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },

    async loadResult() {
      try {
        const response = await getTaskDetail(this.taskId);
        const task = response.task;
        const details = response.details || [];

        console.log('原始数据:', { task, details });

        this.questions = details.map(d => ({
          questionId: d.dtdQuesId,
          questionIndex: d.dtdQuestionNo,
          questionContent: d.dtdQuesContent,
          questionType: d.dtdQuesType,
          optionA: d.dtdOptionA,
          optionB: d.dtdOptionB,
          optionC: d.dtdOptionC,
          optionD: d.dtdOptionD,
          userAnswer: d.dtdUserAnswer,
          correctAnswer: d.dtdCorrectAnswer,
          isCorrect: d.dtdIsCorrect === true,
          totalScore: d.dtdScore,        // 题目总分
          actualScore: d.dtdActualScore  // 实际得分
        }));

        console.log('处理后的questions:', this.questions);

        this.result = {
          totalScore: task.dtTotalScore || 0,
          correctCount: details.filter(d => d.dtdIsCorrect === true).length,
          wrongCount: details.filter(d => d.dtdIsCorrect === false && d.dtdUserAnswer).length,
          totalCount: details.length
        };

        console.log('统计结果:', this.result);

        this.pageReady = true;
      } catch (error) {
        console.error('加载结果失败', error);
        uni.showToast({
          title: '加载结果失败',
          icon: 'none'
        });
      }
    },

    startTimer() {
      this.timer = setInterval(() => {
        if (this.timeLeft > 0) {
          this.timeLeft--;
        } else {
          clearInterval(this.timer);
          this.autoSubmit();
        }
      }, 1000);
    },

    getQuestionTypeText(type) {
      const typeMap = {
        '1': '单选题',
        '2': '多选题',
        '3': '判断题',
        'SINGLE': '单选题',
        'MULTIPLE': '多选题',
        'JUDGMENT': '判断题'
      };
      return typeMap[type] || '题目';
    },

    formatAnswer(answer) {
      if (!answer) return '';

      // 如果是数字格式 "1,2,3" 或 "1"，转换为选项字母 "A,B,C"
      if (/^\d+(,\d+)*$/.test(answer)) {
        return answer.split(',').map(num => {
          const index = parseInt(num) - 1;
          return String.fromCharCode(65 + index); // 65是'A'的ASCII码
        }).join(',');
      }

      // 如果已经是字母格式 "A" 或 "A,B,C"，直接返回
      // 但需要处理可能的格式问题（去除空格，统一大写）
      return answer.toString().toUpperCase().replace(/\s/g, '');
    },

    getOptions(question) {
      const options = [];
      if (question.optionA) options.push(question.optionA);
      if (question.optionB) options.push(question.optionB);
      if (question.optionC) options.push(question.optionC);
      if (question.optionD) options.push(question.optionD);
      return options;
    },

    getOptionLabel(index) {
      return String.fromCharCode(65 + index); // A, B, C, D
    },

    isMultipleChoice(questionType) {
      // 判断是否为多选题
      return questionType === '2' || questionType === 'MULTIPLE';
    },

    isSelected(optionIndex) {
      const answer = this.userAnswers[this.currentQuestion.questionId];
      if (!answer) return false;

      const label = this.getOptionLabel(optionIndex);
      if (this.isMultipleChoice(this.currentQuestion.questionType)) {
        // 多选题
        return answer.includes(label);
      } else {
        // 单选题或判断题
        return answer === label;
      }
    },

    selectOption(optionIndex) {
      const label = this.getOptionLabel(optionIndex);
      const questionId = this.currentQuestion.questionId;

      if (this.isMultipleChoice(this.currentQuestion.questionType)) {
        // 多选题
        let answer = this.userAnswers[questionId] || '';
        if (answer.includes(label)) {
          // 取消选择
          answer = answer.replace(label, '');
        } else {
          // 添加选择
          answer += label;
        }
        // 按字母顺序排序
        answer = answer.split('').sort().join('');
        this.$set(this.userAnswers, questionId, answer || undefined);
      } else {
        // 单选题或判断题
        this.$set(this.userAnswers, questionId, label);
      }
    },

    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--;
      }
    },

    nextQuestion() {
      if (this.currentIndex < this.questions.length - 1) {
        this.currentIndex++;
      }
    },

    jumpToQuestion(index) {
      this.currentIndex = index;
    },

    showSubmitConfirm() {
      const unanswered = this.questions.filter(q => !this.userAnswers[q.questionId]).length;
      const message = unanswered > 0
        ? `还有 ${unanswered} 题未作答，确定提交吗？`
        : '确定提交答卷吗？';

      uni.showModal({
        title: '提示',
        content: message,
        success: (res) => {
          if (res.confirm) {
            this.submitAnswers(1); // 1: 手动提交
          }
        }
      });
    },

    // 将字母答案转换为数字答案 (A→1, B→2, C→3, D→4)
    convertAnswerToNumber(answer) {
      if (!answer) return '';

      // 如果已经是数字格式，直接返回
      if (/^\d+(,\d+)*$/.test(answer)) {
        return answer;
      }

      // 将字母转换为数字
      // "A" → "1", "ABC" → "1,2,3", "B,C" → "2,3"

      // 先处理可能的逗号分隔格式
      let letters = [];
      if (answer.includes(',')) {
        // 如果有逗号，按逗号分割
        letters = answer.split(',').map(s => s.trim());
      } else {
        // 如果没有逗号，将每个字符分开（支持 "ABC" 这种格式）
        letters = answer.split('').filter(c => /[A-Za-z]/.test(c));
      }

      return letters.map(letter => {
        const charCode = letter.trim().toUpperCase().charCodeAt(0);
        return (charCode - 64).toString(); // A=65, 65-64=1
      }).join(',');
    },

    async submitAnswers(submitType) {
      try {
        console.log('原始答案:', this.userAnswers);

        const answers = this.questions.map(q => {
          const originalAnswer = this.userAnswers[q.questionId] || '';
          const convertedAnswer = this.convertAnswerToNumber(originalAnswer);

          console.log(`题目 ${q.questionId}: "${originalAnswer}" → "${convertedAnswer}"`);

          return {
            questionId: q.questionId,
            userAnswer: convertedAnswer
          };
        });

        console.log('提交的答案（转换后）:', answers);

        const response = await submitAnswer({
          taskId: this.taskId,
          answers: answers,
          submitType: submitType
        });

        uni.showToast({
          title: '提交成功',
          icon: 'success'
        });

        setTimeout(() => {
          // 跳转到结果页面
          uni.redirectTo({
            url: `/pages/daily-exam/answer/index?taskId=${this.taskId}&status=result`
          });
        }, 1500);
      } catch (error) {
        console.error('提交失败', error);
        uni.showToast({
          title: error.msg || '提交失败',
          icon: 'none'
        });
      }
    },

    autoSubmit() {
      uni.showToast({
        title: '答题时间已到，自动提交',
        icon: 'none'
      });
      setTimeout(() => {
        this.submitAnswers(2); // 2: 自动超时提交
      }, 1500);
    },

    backToList() {
      uni.navigateBack();
    }
  }
}
</script>

<style lang="scss" scoped>
.daily-answer-container {
  padding: 200rpx 0 40rpx;
}

.answer-mode {
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 16rpx;
    margin-bottom: 32rpx;

    .header-info {
      .title {
        font-size: 36rpx;
        font-weight: bold;
        color: #FFFFFF;
        margin-bottom: 8rpx;
      }

      .progress {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.8);
      }
    }

    .timer {
      display: flex;
      align-items: center;
      padding: 16rpx 24rpx;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 40rpx;

      .timer-icon {
        font-size: 28rpx;
        margin-right: 8rpx;
      }

      .timer-text {
        font-size: 28rpx;
        font-weight: bold;
        color: #FFFFFF;
      }
    }
  }

  .question-card {
    padding: 40rpx;
    background: #FFFFFF;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx 0 rgba(0, 0, 0, 0.08);
    margin-bottom: 32rpx;

    .question-type {
      display: inline-block;
      padding: 8rpx 24rpx;
      background: rgba(102, 126, 234, 0.1);
      color: #667eea;
      border-radius: 40rpx;
      font-size: 24rpx;
      margin-bottom: 24rpx;
    }

    .question-content {
      font-size: 32rpx;
      color: #333333;
      line-height: 48rpx;
      margin-bottom: 32rpx;
    }

    .options {
      .option-item {
        display: flex;
        align-items: center;
        padding: 24rpx;
        background: #F5F5F5;
        border-radius: 12rpx;
        margin-bottom: 16rpx;
        position: relative;
        border: 2rpx solid transparent;

        &.active {
          background: rgba(102, 126, 234, 0.1);
          border-color: #667eea;

          .option-label {
            background: #667eea;
            color: #FFFFFF;
          }
        }

        .option-label {
          width: 56rpx;
          height: 56rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #CCCCCC;
          color: #FFFFFF;
          border-radius: 50%;
          font-size: 28rpx;
          font-weight: bold;
          margin-right: 16rpx;
          flex-shrink: 0;
        }

        .option-content {
          flex: 1;
          font-size: 28rpx;
          color: #333333;
          line-height: 40rpx;
        }

        .option-check {
          font-size: 32rpx;
          color: #667eea;
          margin-left: 16rpx;
        }
      }
    }
  }

  .navigation {
    display: flex;
    gap: 24rpx;
    margin-bottom: 32rpx;

    .btn {
      flex: 1;
    }
  }

  .answer-card {
    padding: 32rpx;
    background: #FFFFFF;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx 0 rgba(0, 0, 0, 0.08);

    .answer-card-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 24rpx;
    }

    .answer-card-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 16rpx;

      .answer-card-item {
        aspect-ratio: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #F5F5F5;
        border-radius: 8rpx;
        font-size: 28rpx;
        color: #999999;

        &.answered {
          background: #667eea;
          color: #FFFFFF;
        }

        &.current {
          border: 2rpx solid #667eea;
        }
      }
    }
  }
}

.result-mode {
  .result-header {
    padding: 40rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 16rpx;
    margin-bottom: 32rpx;

    .result-score {
      text-align: center;
      margin-bottom: 32rpx;

      .score-value {
        font-size: 96rpx;
        font-weight: bold;
        color: #FFFFFF;
        line-height: 1;
        margin-bottom: 16rpx;
      }

      .score-label {
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.8);
      }
    }

    .result-stats {
      display: flex;
      justify-content: space-around;

      .stat-item {
        text-align: center;

        .stat-value {
          font-size: 48rpx;
          font-weight: bold;
          color: #FFFFFF;
          margin-bottom: 8rpx;

          &.correct {
            color: #4CAF50;
          }

          &.wrong {
            color: #FF5252;
          }
        }

        .stat-label {
          font-size: 24rpx;
          color: rgba(255, 255, 255, 0.8);
        }
      }
    }
  }

  .result-questions {
    .result-question-item {
      padding: 32rpx;
      background: #FFFFFF;
      border-radius: 16rpx;
      box-shadow: 0 4rpx 16rpx 0 rgba(0, 0, 0, 0.08);
      margin-bottom: 24rpx;

      .result-question-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        .question-num {
          font-size: 28rpx;
          color: #666666;
        }

        .question-result {
          font-size: 26rpx;
          padding: 8rpx 20rpx;
          border-radius: 40rpx;

          &.correct {
            background: rgba(76, 175, 80, 0.1);
            color: #4CAF50;
          }

          &.wrong {
            background: rgba(255, 82, 82, 0.1);
            color: #FF5252;
          }
        }
      }

      .question-content {
        font-size: 30rpx;
        color: #333333;
        line-height: 44rpx;
        margin-bottom: 20rpx;
      }

      .question-answers {
        .answer-row {
          font-size: 28rpx;
          line-height: 40rpx;
          margin-bottom: 8rpx;

          .answer-label {
            color: #999999;
          }

          .answer-value {
            font-weight: bold;

            &.correct {
              color: #4CAF50;
            }

            &.wrong {
              color: #FF5252;
            }
          }
        }
      }
    }
  }

  .result-footer {
    margin-top: 32rpx;
  }
}

.btn {
  padding: 24rpx 0;
  border-radius: 12rpx;
  font-size: 32rpx;
  text-align: center;
  font-weight: bold;

  &.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #FFFFFF;
  }

  &.btn-secondary {
    background: #FFFFFF;
    border: 2rpx solid #667eea;
    color: #667eea;
  }
}
</style>
