<template>
  <a-modal
    v-model:visible="visible"
    title="切换分组"
    :zIndex="6000"
    centered
    width="700px"
    wrapClassName="mark-dialog"
  >
    <table class="table">
      <tr>
        <th>分组号</th>
        <th>试题</th>
        <th>进度</th>
        <th>操作</th>
      </tr>
      <tr
        v-for="(group, index) in store.groups"
        :key="index"
        :class="isCurrentGroup(group.groupNumber) && 'is-current'"
      >
        <td>{{ group.groupNumber }}</td>
        <td>{{ group.groupQuestions }}</td>
        <td>{{ progress(group.totalCount, group.markedCount) }}%</td>
        <td>
          <a-button
            :disabled="isCurrentGroup(group.groupNumber)"
            type="text"
            class="btn-primary"
            @click="chooseGroup(group.groupNumber)"
          >
            选择
          </a-button>
        </td>
      </tr>
    </table>
    <template #footer>
      <a-button class="btn-cancel" @click="handleCancel">取消</a-button>
    </template>
  </a-modal>
</template>
<script setup lang="ts">
import { getGroup } from "@/api/markPage";
// import { message } from "ant-design-vue";
import { onUpdated } from "vue";
import { store } from "@/store/store";
import vls from "@/utils/storage";
import { clearMarkTask } from "@/api/markPage";

let visible = $ref(false);

onUpdated(async () => {
  if (visible) {
    const groups = await getGroup();
    store.groups = groups.data;
  }
});

const showModal = () => {
  visible = true;
};

const progress = (totalCount: number, markedCount: number) => {
  if (totalCount <= 0) return 0;
  let p = markedCount / totalCount;
  if (p < 0.01 && markedCount >= 1) p = 0.01;
  p = Math.floor(p * 100);
  return p;
};

const isCurrentGroup = (groupNumber: number) => {
  return groupNumber === store.setting.groupNumber;
};

const chooseGroup = async (groupNumber: number) => {
  await clearMarkTask();
  const markinfo = vls.get("mark", {});
  vls.set("mark", { ...markinfo, groupNumber });
  window.location.reload();
};

const handleCancel = () => {
  visible = false;
};

defineExpose({ showModal });
</script>
