<script setup name="Exam">
import TopicPractice from "../../components/Topic/TopicPractice.vue";
import { ref, onMounted } from "vue";
import { getRoute, router } 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/ShareTemplate.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 showReport = ref(false);
const showShare = 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 user_exercise_paper_id = ref(0);
const getList = async (params) => {
  if (pageParams.value.page * pageParams.value.limit >= total.value) return;
  const res = await request(
    "api/question_bank/question_reception/topic/day_practice",
    {
      ...params,
    }
  );
  total.value = res.data.total;
  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: [], // 选择的答案
        showResult: false, // 是否展示答案
        isRight: false, // 是否正确
        isImage: item.title.includes("<img"),
        ind,
      };
    })
  );
  pageParams.value.page++;
};

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

const onStar = (item) =>
  new Promise((resolve) => {
    request(
      !item.is_favorite
        ? "api/question_bank/question_reception/topic/set_favorite"
        : "api/question_bank/question_reception/topic/cancel_favorite",
      {
        id: item.id,
        chapter_id: item.chapter_id,
      }
    ).then(() => {
      item.is_favorite = item.is_favorite ? 0 : 1;
      resolve(item.is_favorite);
    });
  });

const lookReport = async (d, s) => {
  data.value = d;
  const totalTime = Time.end();
  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(() => {
  Time.start();
  const params = getRoute().params;
  title.value = params.title;
  getList(pageParams.value);
});

const a = () => {
  request("api/question_bank/question_reception/check_in/user_share_record", {
    type: 1,
  });
  showShare.value = true;
};
</script>

<template>
  <TopicPractice
    :title="title"
    :total="total"
    mode="practice"
    :topics="data"
    :user_exercise_paper_id="user_exercise_paper_id"
    @nextPage="nextPage"
    @lookReport="lookReport"
    :onStar="onStar"
    :empty="!data.length"
    text="加载中···"
    border
    v-if="!showReport && !showShare"
  />
  <Container
    bgColor="url('https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/05/7i6ROn34tZGe8QR4gaWDP1ZzyPYjqlvPgLLFRmIe.png')"
    bottomBorder
    v-else-if="!showShare && showReport"
    themeColor="#fff"
    bottomBgColor="#fff"
    title="练习报告"
  >
    <view class="reslut">
      <div class="title-r">恭 喜 完 成 考 试</div>
      <view class="card">
        <view class="card-time">
          <view>{{ submitter.totalTime?.formatTime }}</view>
          <view>学习时长</view>
        </view>
        <view class="card-time">
          <view class="red">{{ correct.rate.toFixed(2) }}%</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>
        </view>
        <view class="group">
          <view
            class="item"
            :class="{
              right: it.isRight && it.showResult,
              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="a">炫耀一下</view>
      </view>
    </template>
  </Container>
  <ShareTemplate
    :onClose="() => (showShare = false)"
    :correct="correct"
    bg="https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/05/ix4wGk9h7Fb4c3d8hjkYjJP6VsPNbZgG3uDTUzxp.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: center;
  align-items: center;
  gap: 63rpx;
  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>
