<template>
  <a-modal
    title="切换分组"
    v-model:visible="visible"
    :zIndex="6000"
    wrapClassName="profile-wrapper"
  >
    <table class="group-table">
      <tr>
        <th style="padding-left: 15px">分组号</th>
        <th>分组名</th>
        <th>进度</th>
        <td class="tw-text-right" style="padding-right: 15px">操作</td>
      </tr>
      <tr
        v-for="(group, index) in store.groups"
        :key="index"
        :class="isCurrentGroup(group.number) && 'current-group'"
      >
        <td style="padding-left: 15px">{{ group.number }}</td>
        <td>{{ group.title }}</td>
        <td>{{ progress(group.totalCount, group.markedCount) }}%</td>
        <td class="tw-text-right">
          <qm-button
            :disabled="isCurrentGroup(group.number)"
            type="primary"
            @click="chooseGroup(group.markerId)"
          >
            选择
          </qm-button>
        </td>
      </tr>
    </table>
    <template #footer>
      <a-button key="back" @click="handleCancel">取消</a-button>
    </template>
  </a-modal>
</template>
<script setup lang="ts">
import { doSwitchGroup, getGroups } from "@/api/markPage";
import { message } from "ant-design-vue";
import { onUpdated } from "vue";
import { store } from "@/store/store";

let visible = $ref(false);

onUpdated(async () => {
  if (visible) {
    const groups = await getGroups();
    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 (markerId: number) => {
  const res = await doSwitchGroup(markerId)
    .then((res) => {
      // 切换分组相当于刷新页面，此时之前的所有的状态消失，即task/markResult不存在了
      if (res.data.success) {
        const body = document.querySelector("body");
        if (body) body.innerHTML = "重新加载中...";
        return new Promise((resolve) => setTimeout(() => resolve(true), 300));
      } else {
        message.error({ content: res.data.message || "错误", duration: 5 });
        return false;
      }
    })
    .then((res) => {
      if (res) {
        window.location.reload();
      }
    });
};

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

defineExpose({ showModal });
</script>

<style scoped>
.group-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 0.5em;
}

.current-group {
  background-color: #f2f7ff;
}
</style>
<style>
.profile-wrapper .ant-modal-title {
  color: var(--app-main-text-color);
}
.profile-wrapper .anticon-close {
  vertical-align: text-top;
}
.profile-wrapper .ant-modal-body {
  color: var(--app-bold-text-color);
}
.profile-wrapper .ant-modal-body th {
  color: var(--app-small-header-text-color);
}
</style>
