<template>
	<van-sticky>
		<van-nav-bar title="考试结果" />
	</van-sticky>
	<van-overlay :show="overlayloading">
		<div class="wrapper">
			<van-loading color="#0094ff"> 加载中... </van-loading>
		</div>
	</van-overlay>

	<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
		<van-list v-model:loading="loading" :finished="finished" finished-text="没有更多" @load="onLoad" class="listDiv">
			<van-cell v-for="(result, index) in list" :key="index"@click="goToLvzhi(result.id,result.totalScore )">
				<template #title>
					 {{ result.questionName }}
				</template>
				<template #label>
					<!-- <div class="labeldiv">
            {{ result.result == 1 ? "通过" : "未通过" }}
          </div> -->
					<div class="labeldiv">分数:{{ result.totalScore }}</div>
					<!-- <div class="labeldiv">合格分数: {{ result.qualifiedScore }}</div> -->
					<div class="labeldiv">考试时间: {{ result.submitTime }} </div>
				</template>
			</van-cell>
		</van-list>
	</van-pull-refresh>
  <!-- 结果弹窗 -->
  <van-popup v-model:show="showResult" position="top" style="height: 100%">
    <van-sticky>
      <van-nav-bar title="答题结果" />
    </van-sticky>
    <div style="
          margin-top: 10px;
          margin-left: 20px;
          margin-bottom: 20px;
          font-weight: bold;
        ">
      本次得分：{{ totalScore }}
      <!--取接口成绩-->
    </div>
    <van-divider />
    <!-- 题干 -->
    <div v-for="question in questions" :key="question.id" class="question">
      <p>
        <span v-if="question.category === '单选'">[单选]</span>
        <span v-if="question.category === '多选'">[多选]</span>
        <span v-if="question.category === '判断'">[判断]</span>
        {{ question.stem }}
      </p>
      <!-- 显示提交答案 -->
      <p>
					<span :style="{
              color: Array.isArray(userAnswers[question.id])
                ? userAnswers[question.id].sort().join('') ===
                  question.answer
                  ? '#007aff'
                  : 'red'
                : userAnswers[question.id] === question.answer
                ? '#007aff'
                : 'red',
            }">
						提交答案:{{
              Array.isArray(userAnswers[question.id])
                ? userAnswers[question.id].sort().join("")
                : userAnswers[question.id] || "未作答"
            }}
					</span>
      </p>
      <!-- 显示正确答案 -->
      <p style="color: #007aff">正确答案:{{ question.answer }}</p>
      <div v-if="question.category === '单选'" 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.category === '多选'" 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.category === '判断'" class="kong">
        <div>A.正确</div>
        <div>B.错误</div>
      </div>
      <van-divider />
    </div>
    <div style="margin-top: 20px; text-align: center; margin-bottom: 20px">
      <van-button class="questionBtn" type="primary" @click="confirmResult">确定</van-button>
    </div>
  </van-popup>
</template>

<script setup>
	import {
		onMounted,
		reactive,
		getCurrentInstance,
		ref
	} from "vue";
	import {
		showConfirmDialog,
		showSuccessToast,
		showFailToast,
		showDialog
	} from 'vant';
	import {
		useRoute
	} from "vue-router";
	import "@/assets/custom.less";
	const {
		proxy
	} = getCurrentInstance()
	const route = useRoute();
  const userAnswers = reactive({});

  const questions = ref([]);
  //获取试卷

  const courseId=ref('')
  const totalScore1=ref('')
  const showResult=ref(false)
const goToLvzhi = (id,totalScore) => {
    courseId.value=id
  totalScore1.value=totalScore
  showResult.value=true
  getForm()

}
const confirmResult = () => {
  showResult.value=false
}
  const getForm = async () => {
    const url = '/sgsafe/ExamLine/query';
    const query = {
      headId: courseId.value // ✅ 不需要用 ref 包裹临时对象
    };
    const param = {
      params: JSON.stringify(query)
    };
    try {
      const res = await proxy.$axios.post(url, param);
      if (res.data.code === 0) {
        questions.value = res.data.data;

        // ✅ 修复点2：清空 reactive 对象（不能用 .value）
        for (const key in userAnswers) {
          delete userAnswers[key];
        }

        // ✅ 修复点3：直接赋值，不要 .value！
        res.data.data.forEach(q => {
          userAnswers[q.id] = q.userAnswer; // 假设后端字段名为 userAnswer
        });
      } else {
        console.log('操作失败!' + res.data.msg);
      }
    } catch (error) {
      console.log('请求出错:', error);
    }
  };




	const overlayloading = ref(false);

	let userId = route.query.userId;
	if (userId == '' || userId == 'undefined') userId = localStorage.getItem('userId')
	const pageSize = ref(10);
	const pageNo = ref(1);

	const list = ref([]);
	const loading = ref(false);
	const finished = ref(false);
	const refreshing = ref(false);

	const total = ref(0)
	const resultData = ref([])
	const queryFetch = async () => {
		const url = '/sgsafe/ExamHead/queryMYfinNotListH5'
		const fetchData = ref({
			userId: userId,
      status1:'2'
		})
		const param = {
			page: pageNo.value,
			rows: pageSize.value,
			params: JSON.stringify(fetchData.value)
		};
		try {
			const res = await proxy.$axios.post(url, param);
			if (res.data.code === 0) {
				total.value = res.data.data.total
				resultData.value = res.data.data.records
			} else {
				finished.value = true;
				showFailToast("获取考试结果失败");
			}
		} catch (error) {
			showFailToast("请求出错：" + error);
		}
	};
	const onLoad = async () => {
		overlayloading.value = true;
		if (refreshing.value) {
			list.length = 0;
			pageNo.value = 1;
			refreshing.value = false;
		}
		try {
			await queryFetch();
			if (pageSize.value * pageNo.value < total.value) {
				list.value = [...list.value, ...resultData.value]
				pageNo.value++;
			} else {
				list.value = [...list.value, ...resultData.value]
				finished.value = true;
			}
			loading.value = false;
			overlayloading.value = false;
		} catch (error) {
			console.log(error);
			finished.value = true;
			showFailToast("获取失败");
		} finally {
			loading.value = false;
		}
	};
	const onRefresh = () => {
		finished.value = false;

		// 重新加载数据
		// 将 loading 设置为 true，表示处于加载状态
		loading.value = true;
		onLoad();
	};
  //TODO 跳转
</script>

<style scoped>
	.labeldiv {
		font-size: 14px;
	}

	/* 遮罩 */
	.wrapper {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.van-overlay {
		z-index: 2;
		background-color: rgba(0, 0, 0, 0.5);
	}
</style>