<template>
  <van-sticky>
    <van-nav-bar>
      <template #left>
        <van-icon
            name="arrow-left"
            size="18"
            @click="goBack"
        />
      </template>
      <template #title>
        <div class="question-number">
          {{ activeIndex + 1 }}/{{ questions.length }}
        </div>
      </template>
      <template #right>
        <!-- 提交按钮 -->
        <van-button @click="checkBeforeSubmit" round color="linear-gradient(to right, #18FFFF, #304FFE)"
                    style="height:30px;width: 80px" >交卷</van-button>
      </template>
    </van-nav-bar>
  </van-sticky>

  <div class="quiz-page">
    <!-- 题目内容显示 -->
    <div v-if="questions.length > 0" class="question-content">
      <!-- 题干 -->
      <p class="kong">
        <img :src="getQuestionTypeImage(currentQuestion.stemType)" class="question-type-img" alt=""/>
        {{ currentQuestion.stem }}
      </p>

      <!-- 单选题 -->
      <div v-if="currentQuestion.stemType === '1'">
        <van-radio-group v-model="userAnswers[currentQuestion.id]">
          <van-radio :name="'A'" class="kong">A.{{ currentQuestion.optionA }}</van-radio>
          <van-radio :name="'B'" class="kong">B.{{ currentQuestion.optionB }}</van-radio>
          <van-radio :name="'C'" class="kong">C.{{ currentQuestion.optionC }}</van-radio>
          <van-radio :name="'D'" class="kong" v-if="currentQuestion.optionD">D. {{ currentQuestion.optionD }}</van-radio>
          <van-radio :name="'E'" class="kong" v-if="currentQuestion.optionE">E. {{ currentQuestion.optionE }}</van-radio>
        </van-radio-group>
      </div>

      <!-- 多选题 -->
      <div v-if="currentQuestion.stemType === '2'">
        <van-checkbox-group v-model="userAnswers[currentQuestion.id]" shape="square">
          <van-checkbox :name="'A'" class="kong">A.{{ currentQuestion.optionA }}</van-checkbox>
          <van-checkbox :name="'B'" class="kong">B.{{ currentQuestion.optionB }}</van-checkbox>
          <van-checkbox :name="'C'" class="kong">C.{{ currentQuestion.optionC }}</van-checkbox>
          <van-checkbox :name="'D'" class="kong" v-if="currentQuestion.optionD">D.{{ currentQuestion.optionD }}</van-checkbox>
          <van-checkbox :name="'E'" class="kong" v-if="currentQuestion.optionE">E.{{ currentQuestion.optionE }}</van-checkbox>
        </van-checkbox-group>
      </div>

      <!-- 判断题 -->
      <div v-if="currentQuestion.stemType === '4'">
        <van-radio-group v-model="userAnswers[currentQuestion.id]">
          <van-radio :name="'A'" class="kong">A.正确</van-radio>
          <van-radio :name="'B'" class="kong">B.错误</van-radio>
        </van-radio-group>
      </div>
    </div>

    <!-- 底部固定栏 -->
    <div class="footer">
      <van-button @click="prevQuestion" :disabled="activeIndex === 0" style="height:40px;width:45%">上一题</van-button>
      <van-button @click="nextQuestion" :disabled="activeIndex === questions.length - 1" style="height:40px;width:45%">下一题</van-button>
    </div>


    <!-- 提交前确认弹窗 -->
    <van-dialog v-model:show="confirmSubmitDialog" title="确认交卷" show-cancel-button @confirm="submit">
<!--      <p v-if="hasUnanswered">{{ unansweredText }}</p>-->
<!--      <p v-else>{{ completedText }}</p>-->
      <p :class="{ 'van-dialog__message': true, 'text-center': true }">
        <span v-if="hasUnanswered">{{ unansweredText }}</span>
        <span v-else>{{ completedText }}</span>
      </p>
    </van-dialog>



    <!-- 结果弹窗 -->
    <van-popup v-model:show="showResult" position="top"  style="height: 100%">
      <div style="margin-top: 10px; margin-left: 10px; margin-bottom: 20px;">
        本次得分：{{ totalScore }}
        <!--取接口成绩-->
      </div>
      <van-divider />
      <!-- 题干 -->
      <div v-for="question in questions" :key="question.id" class="question">
        <p>
          <span v-if="question.stemType === '1'">[单选]</span>
          <span v-if="question.stemType === '2'">[多选]</span>
          <span v-if="question.stemType === '4'">[判断]</span>
          {{ question.stem }}
        </p>
        <!-- 显示提交答案 -->
        <p>
          <span :style="{ color: Array.isArray(userAnswers[question.id])
                                      ? (userAnswers[question.id].sort().join('') === question.rightAnswer ? '#007aff' : 'red')
                                      : (userAnswers[question.id] === question.rightAnswer ? '#007aff' : 'red') }">
            提交答案:{{ Array.isArray(userAnswers[question.id])
              ? userAnswers[question.id].sort().join('')
              : userAnswers[question.id] || '未作答' }}
          </span>
        </p>
        <!-- 显示正确答案 -->
        <p style="color: #007aff">
          正确答案:{{ question.rightAnswer }}
        </p>
        <div v-if="question.stemType === '1'" class="kong">
          <div >A. {{ question.optionA }}</div>
          <div>B. {{ question.optionB }}</div>
          <div >C. {{ question.optionC }}</div>
          <div v-if="question.optionD">D. {{ question.optionD }}</div>
          <div v-if="question.optionE">E. {{ question.optionE }}</div>
        </div>
        <div v-if="question.stemType === '2'" class="kong">
          <div >A. {{ question.optionA }}</div>
          <div >B. {{ question.optionB }}</div>
          <div >C. {{ question.optionC }}</div>
          <div v-if="question.optionD">D. {{ question.optionD }}</div>
          <div v-if="question.optionE">E. {{ question.optionE }}</div>
        </div>
        <div v-if="question.stemType === '4'" class="kong">
          <div >A.正确</div>
          <div >B.错误</div>
        </div>
        <van-divider />
      </div>
      <div style="margin-top: 20px; text-align: center;">
        <van-button type="primary" @click="confirmResult">确定</van-button>
      </div>
    </van-popup>




  </div>
</template>


<script setup>
import {onMounted, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import {examResult, formNew, myDefaultCourse, saveScore, sortData} from "@/api/dati";

const questions = ref([
  // {
  //   id: '1810206705229058048',
  //   stem: '1.关于生产经营单位对从业人员进行安全生产教育培训的说法，正确的是(    )',
  //   stemType: '1',
  //   optionA: '对所有从业人员都应当进行安全生产教育和培训',
  //   optionB: '对有过相似工作经验的从业人员可以不进行安全生产教育和培训',
  //   optionC: '从业人员培训不合格的应予以辞退',
  //   rightAnswer: 'A',
  //   score: 1,
  // },
  // {
  //   id: '1810206705266806784',
  //   stem: '2.关于安全生产工作机制，不正确的表述是(    )',
  //   stemType: '1',
  //   optionA: '政府负责',
  //   optionB: '职工参与',
  //   optionC: '行业自律',
  //   rightAnswer: 'A',
  //   score: 1,
  // },
  // {
  //   id: '1810206705191309312',
  //   stem: '3.安全生产责任制是生产经营单位最基本的安全制度。建立的安全生产责任制必须符合国家安全生产法律法规和(    )要求，并应适时修订',
  //   stemType: '1',
  //   optionA: '生产经营单位管理体系',
  //   optionB: '生产经营单位实际情况',
  //   optionC: '政策、方针',
  //   rightAnswer: 'C',
  //   score: 1,
  // },
  // {
  //   id: '1810206705300361216',
  //   stem: '4.生产经营单位主要负责人的职责不包括(      )',
  //   stemType: '2',
  //   optionA: '督促、检查本单位的安全生产工作及时消除生产安全事故隐患',
  //   optionB: '组织制定并实施本单位的生产安全事故应急救援预案',
  //   optionC: '及时、如实报告生产安全事故',
  //   optionD: '做好有关安全生产工作',
  //   optionE: '执行安全生产法律法规',
  //   rightAnswer: 'DE',
  //   score: 1,
  // },
  // {
  //   id: '1810206705333915648',
  //   stem: '5.安全生产教育的重要性包括(       )',
  //   stemType: '2',
  //   optionA: '普及员工的安全技术知识',
  //   optionB: '杜绝事故的发生',
  //   optionC: '提高员工安全操作技能',
  //   optionD: '改善安全管理制度',
  //   rightAnswer: 'ACD',
  //   score: 1,
  // },
  // {
  //   id: '1810206705367470080',
  //   stem: '6.班组成员要积极参加安全学习及安全培训,掌握本职工作所需的安全生产知识，提高安全生产技能,从事特种作业的不用经培训取得相应资格证书。',
  //   stemType: '4',
  //   optionA: '正确',
  //   optionB: '错误',
  //   rightAnswer: 'B',
  //   score: 1,
  // },
  // {
  //   id: '1810206705401024512',
  //   stem: '7.班组成员应该对作业中发生的险情、突发事件及时报告，组织事故初期应急处置并采取措施保护现场。',
  //   stemType: '4',
  //   optionA: '正确',
  //   optionB: '错误',
  //   rightAnswer: 'B',
  //   score: 1,
  // },
  // {
  //   id: '1810206705434578944',
  //   stem: '8.各生产单位要强化安全生产第一意识，落实安全生产主体责任，加强安全生产基础能力建设，坚决遏制一般安全生产事故的发生。',
  //   stemType: '4',
  //   optionA: '正确',
  //   optionB: '错误',
  //   rightAnswer: 'B',
  //   score: 1,
  // },
  // {
  //   id: '1810206705472327680',
  //   stem: '9.任何部门都可以负责组织对公司各部门负责人进行安全责任制培训。',
  //   stemType: '4',
  //   optionA: '正确',
  //   optionB: '错误',
  //   rightAnswer: 'B',
  //   score: 1,
  // }
]);

const userAnswers = ref({});
const activeIndex = ref(0);
const totalScore = ref(0);
const showResult = ref(false);
const router = useRouter();
const competionId = ref(0);
const courseId = ref(0);

const confirmSubmitDialog = ref(false);
const hasUnanswered = ref(false);
const unansweredText = '有题目未完成，是否确认交卷？';
const completedText = '已完成所有题目，是否确认交卷？';


// 获取当前题目
const currentQuestion = computed(() => {
  return questions.value[activeIndex.value];
});

// 获取题目类型对应的图片路径
const getQuestionTypeImage = (stemType) => {
  switch (stemType) {
    case '1': // 单选
      return require('@/assets/img/dx.svg');
    case '2': // 多选
      return require('@/assets/img/ksdx.svg');
    case '4': // 判断
      return require('@/assets/img/kspd.svg');
    default:
      return '';
  }
};

//获取试题ID
const getMyDefaultCourse = async () => {
  try {
    const res = await myDefaultCourse({
      __ajax: "json",
    });
    console.log("res777----------->", res);
    if (res) {
      const data = res; // 假设返回的数据在response.data中

      // 更新状态
      competionId.value = data.competionId;
      courseId.value = data.courseId;
      toNext2();
    }
  } catch (error) {
    console.error("出错：", error);
    showToast("获取失败，请稍后重试");
  }
  console.log("考试结果:");
};





//获取试卷
const toNext2 = async () => {
  let pdata = {
    competionId:competionId.value,
    courseId:courseId.value,
    // courseId: "1833059109359325184",
    id: "1842836805157076992",
    // courseId: courseId,
    // id: id,
    __ajax: "json",
  };

  const res = await formNew(pdata); // 使用 await 获取返回值
  console.log("res3----------->", res);
  if (res.code && res.code == 200) {
    questions.value = res.data.paparList;
    console.log(questions.value)
  }else {
    console.error(res.code + ";" + res.message);
  }


};

//返回答题首页
const goBack = () => {
  router.replace({ path: "/dailyproblem" });
};


// 切换到下一题
const nextQuestion = () => {
  if (activeIndex.value < questions.value.length - 1) {
    activeIndex.value++;
  }
};

// 切换到上一题
const prevQuestion = () => {
  if (activeIndex.value > 0) {
    activeIndex.value--;
  }
};

// 提交答卷并计算得分
const submit = async () => {
  totalScore.value = 0;
  const answers = []; // 用来存储每道题的答案

  questions.value.forEach((question) => {
    const userAnswer = userAnswers.value[question.id]; // 获取用户的答案

    let userAnswerString;
    if (Array.isArray(userAnswer)) {
      // 多选题，将数组转换为字符串
      userAnswerString = userAnswer.sort().join(''); // 排序并转换为字符串，如 "ABC"
    } else {
      // 单选题，直接是字符串
      userAnswerString = userAnswer || ''; // 如果未选择答案，则设为空字符串
    }

    // 比较用户提交的答案和正确答案
    if (userAnswerString === question.rightAnswer) {
      totalScore.value += question.score;
    }

    // 打印每道题目的用户提交的字符串答案
    console.log(`题目 ${question.id} 的提交答案为:${userAnswerString}`);

    // 将答案保存到 answers 数组中
    answers.push({
      id: question.id, // 题目 ID
      answer: userAnswerString, // 用户的答案
    });
  });
  // 显示答题结果
   showResult.value = true;

  // 打印所有用户提交的答案
  console.log('提交考试结果:', userAnswers.value);
  postSaveScore(answers);
};

//tijiao
const postSaveScore = async (answers) => {
  try {
    const res = await saveScore({
      competionId:competionId.value,
      sysId:1,
      answer:answers,
      // answer:[{
      //   id:"1842934334486548480",
      //   answer:"A"
      // }],
      __ajax: "json",
    });
    console.log("res44----------->", res);
  } catch (error) {
    console.error("出错：", error);
    showToast("获取失败，请稍后重试");
  }
  console.log("考试结果:");
};


// 确认结果并返回
const confirmResult = () => {
  showResult.value = false;
  // router.back();
  router.replace({ path: "/dailyproblem" });
};

// 检查是否所有题目都已作答
const checkBeforeSubmit = () => {
  hasUnanswered.value = questions.value.some(question => {
    const userAnswer = userAnswers.value[question.id];
    return !userAnswer || (Array.isArray(userAnswer) && userAnswer.length === 0);
  });
  confirmSubmitDialog.value = true;
};


// 在组件挂载时获取试卷
onMounted(() => {
  getMyDefaultCourse();
  // toNext2();
});

</script>






<style scoped>
.quiz-page {
  padding: 20px;
}

.question-type-img {
  width: 54px;
  height: 20px;
}

.question{
  margin-left: 20px;
  margin-right: 20px;

}


.kong {
  margin-bottom: 20px;
}


.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.van-dialog__message {
  text-align: center;
}

</style>