<template>
  <a-modal
    v-model:visible="visible"
    title="选择试卷的问题类型"
    width="300px"
    :zIndex="6000"
    wrapClassName="profile-wrapper"
    @cancel="handleCancel"
  >
    <template #footer>
      <a-button key="back" @click="handleCancel">取消</a-button>
    </template>
    <table class="group-table">
      <tr>
        <th class="tw-text-left">问题类型</th>
        <th class="tw-text-right" style="padding-right: 20px">操作</th>
      </tr>
      <tr v-for="(problem, index) in store.setting.problemTypes" :key="index">
        <td>{{ problem.name }}</td>
        <td class="tw-text-right">
          <qm-button type="primary" @click="chooseProblemType(problem.id)">
            选择
          </qm-button>
        </td>
      </tr>
    </table>
  </a-modal>
</template>

<script setup lang="ts">
import { doProblemType, getStatus } from "@/api/markPage";
import { message } from "ant-design-vue";
import { store } from "@/store/store";
import EventBus from "@/plugins/eventBus";

let visible = $ref(false);

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

async function updateStatus() {
  const res = await getStatus();
  store.status = res.data;
}

const chooseProblemType = async (problemId: number) => {
  if (!store.currentTask) {
    void message.warn({ content: "没有可以标记的任务", duration: 5 });
    return;
  }
  try {
    const res = await doProblemType(problemId);
    if (res?.data.success) {
      void message.success({ content: "问题卷处理成功", duration: 3 });
      visible = false;
      store.currentTask = undefined;
      if (store.historyOpen) {
        EventBus.emit("should-reload-history");
      } else {
        store.tasks.shift();
        store.currentTask = store.tasks[0];
      }
      await updateStatus();
    } else {
      void message.error({ content: res?.data.message || "错误", duration: 5 });
    }
  } catch (error) {
    console.log("问题卷处理失败", error);
    void message.error({ content: "网络异常", duration: 5 });
    await new Promise((res) => setTimeout(res, 1500));
    window.location.reload();
  }
};

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

defineExpose({ showModal });
</script>

<style scoped>
.profile-wrapper .ant-modal-title {
  color: var(--app-main-text-color);
}
.profile-wrapper .anticon-close {
  vertical-align: text-top;
}
.group-table {
  width: 100%;

  border-collapse: separate;
  border-spacing: 0 0.5em;
}
.group-table th {
  color: var(--app-small-header-text-color);
}
.group-table tr td {
  color: var(--app-bold-text-color);
}
</style>
