<script setup name="Exam">
import TopicExam from "../../components/Topic/TopicExam.vue";
import { ref, onMounted } from "vue";
import { getRoute } from "../../utils/router";
import { request } from "../../utils/request";
import { useTimeStore } from "@/store/time";
import Container from "../../components/Container/Container.vue";
import ShareTemplate from "../../components/ShareTemplate/ShareTemplateExam.vue";

const Time = useTimeStore();

const TopicMapList = ["A", "B", "C", "D", "E"];

const title = ref("");
const total = ref(100000);
const correct = ref({
  rate: 0, // 正确率
  error: 0, // 错误数
  right: 0, // 正确数
  not: 0, // 未答题
  total: 0, // 总题数
});
const useTime = ref(null);

const showReport = ref(false);
const showShare = ref(false);
const isEnd = ref(false);
const submitter = ref({
  closeText: "直接退出",
  context: "您本次答题还未提交， 确定要退出答题吗？",
  isEndQuestion: false,
  text: "提交查看",
  totalTime: {
    formatTime: "00:00",
    totalTime: 0,
  },
});

const pageParams = ref({
  page: 1,
  limit: 999,
});
const data = ref([]);
const real_topic_id = ref(0);

const getList = async (params = {}) => {
  if (pageParams.value.page * pageParams.value.limit >= total.value) return;
  const { catalogue_id, id } = getRoute().params;
  if (!catalogue_id) {
    const t = await request(
      "api/question_bank/question_reception/real_topic/set_user_new_paper",
      {
        catalogue_id: getRoute().params.id,
      }
    );
    real_topic_id.value = t.data;
  } else {
    real_topic_id.value = id;
  }

  const res = await request(
    "api/question_bank/question_reception/real_topic/get_real_topic",
    {
      ...params,
      catalogue_id: catalogue_id || getRoute().params.id,
      user_real_paper_id: real_topic_id.value,
    }
  );
  total.value = res.data.total;
  correct.value.not = total.value;
  data.value.push(
    ...res.data.data.map((item, ind) => {
      let questions = [];
      const ans = item.correct_answer.split(",");
      const ansList = [];
      for (let i = 0; i < item.question_count; i++) {
        const current = TopicMapList[i];
        if (ans.includes(current)) {
          ansList.push({
            label: current,
            value: i,
          });
        }
        const v =
          item[`select_${current.toLowerCase()}`].replace(/<br\s*\/?>/g, "") ||
          "";
        questions.push({
          label: v,
          value: current,
          checked: false,
          index: i,
        });
      }

      return {
        ...item,
        questions, // 题目
        ansList, // 正确答案
        selectAns: !item.user_answer ? [] : item.user_answer.split(","), // 选择的答案
        showResult: !!catalogue_id, // 是否展示答案
        isRight: !!item.is_correct, // 是否正确
        isImage: item.title.includes("<img"),
        ind,
      };
    })
  );
  if (catalogue_id) {
    useTime.value = res.data.use_time_str;
    lookReport(data.value, submitter.value);
  }
};

const nextPage = (e) => {
  if (pageParams.value.page * pageParams.value.limit - e.index - 1 !== 1)
    return;
  getList(pageParams.value);
};

const lookReport = async (d, s) => {
  data.value = d;
  const totalTime = Time.end();
  isEnd.value = true;
  // 提交试卷
  if (!getRoute().params.catalogue_id) {
    await request(
      "api/question_bank/question_reception/real_topic/user_submit_real_paper",
      {
        user_real_paper_id: real_topic_id.value,
        catalogue_id: getRoute().params.id,
        use_time: totalTime.totalTime,
        use_time_str: totalTime.formatTime,
      }
    );
  }
  showReport.value = true;
  submitter.value = {
    ...s,
    totalTime,
  };
  const r = data.value.filter((item) => item.isRight).length;
  const n = data.value.filter((item) => !item.selectAns.length).length;
  correct.value = {
    rate: (r / total.value) * 100,
    right: r,
    error: total.value - r - n,
    not: n,
    total: total.value,
  };
};

onMounted(async () => {
  const params = getRoute().params;
  title.value = params.title;
  if (params.catalogue_id) {
    showReport.value = true;
  }
  await getList(pageParams.value);
  Time.start();
});
</script>

<template>
  <TopicExam
    :title="title"
    :total="total"
    mode="practice"
    :isEnd="isEnd"
    :topics="data"
    @nextPage="nextPage"
    @lookReport="lookReport"
    :real_topic_id="real_topic_id"
    :empty="!data.length"
    border
    v-if="!showReport && !showShare"
    text="加载中···"
  />
  <Container
    bgColor="url('https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/05/7i6ROn34tZGe8QR4gaWDP1ZzyPYjqlvPgLLFRmIe.png')"
    bottomBorder
    v-else-if="!showShare && showReport"
    bottomBgColor="#fff"
    title="练习报告"
  >
    <view class="reslut">
      <div class="title-r">恭 喜 完 成 本 课</div>
      <view class="card">
        <view class="card-time">
          <view>{{
            useTime !== null
              ? useTime
              : submitter.totalTime?.formatTime
          }}</view>
          <view>学习时长</view>
        </view>
        <view class="card-time">
          <view class="red">{{ correct.rate.toFixed(2) }}%</view>
          <view>正确率</view>
        </view>
        <view class="card-time">
          <view class="red">{{ correct.right }}</view>
          <view>获得分数</view>
        </view>
      </view>
      <view class="template">
        <view class="header">
          <view>答题卡</view>
          <view class="right-error">
            <view class="right">答对({{ correct.right }})</view>
            <view class="error">答错({{ correct.error }})</view>
            <view class="not">未作({{ correct.not }})</view>
          </view>
        </view>
        <view class="group">
          <view
            class="item"
            :class="{
              right: it.isRight && it.showResult && it.selectAns.length,
              error: !it.isRight && it.showResult && it.selectAns.length,
            }"
            v-for="(it, index) in data"
            :key="it.id"
            >{{ index + 1 }}</view
          >
        </view>
      </view>
    </view>
    <template #footer>
      <view class="footer">
        <view class="button plain" @click="showReport = false">答题解析</view>
        <view class="button" @click="showShare = true">炫耀一下</view>
      </view>
    </template>
  </Container>
  <ShareTemplate
    :onClose="() => (showShare = false)"
    :correct="correct"
    bg="https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/05/BxBKVS1eV1xaSylWq3i2UjE5VmiJfrfVT7Cc98m3.png"
    v-else
  />
</template>

<style lang="scss" scoped>
@import "@/uni.scss";
.template {
  padding: 15rpx;
  border-radius: 24rpx;
  background-color: #f8f9fb;
}
.red {
  color: #ff4444;
}

.title-r {
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  font-size: 50rpx;
  color: #002fa7;
}
.card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 50rpx;
  background-color: #f8f9fb;
  border-radius: 24rpx;
  &-time {
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 28rpx;
    color: #999999;
    display: flex;
    flex-direction: column;
    gap: 10rpx;
    align-items: center;
  }
}

.reslut {
  margin: 0 32rpx;
  padding: 24rpx;
  font-family: PingFang SC, PingFang SC;
  font-weight: 500;
  font-size: 28rpx;
  color: #333333;
  background: #fff;
  border-radius: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .right-error {
      display: flex;
      gap: 20rpx;
      font-weight: 400;
      font-size: 20rpx;
      color: #333333;
      @mixin type($color) {
        display: flex;
        align-items: center;
        gap: 10rpx;
        &::before {
          content: "";
          width: 16rpx;
          height: 16rpx;
          border-radius: 50%;
          display: block;
          background: $color;
        }
      }
      .right {
        @include type($success);
      }
      .error {
        @include type($error);
      }
      .not {
        @include type($default);
      }
    }
  }

  .group {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    gap: 20rpx;
    margin-top: 20rpx;

    .item {
      width: 72rpx;
      height: 72rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: $default;
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 28rpx;
      color: #ffffff;
    }
    .item.right {
      background: $success;
    }
    .item.error {
      background: $error;
    }
  }
}

.footer {
  display: flex;
  gap: 20rpx;
  align-items: center;
  padding-top: 20rpx;
}
</style>
