<template>
  <a-modal
    v-model:visible="visible"
    title="选择试卷的问题类型"
    width="406px"
    :zIndex="1000"
    wrapClassName="mark-dialog"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form
      labelAlign="right"
      :labelCol="{ span: 6 }"
      @keydown.stop=""
      @keypress.stop=""
    >
      <a-form-item class="tw-mb-2" :required="true" label="问题类型">
        <a-select v-model:value="formModel.problemType" placeholder="类型">
          <a-select-option
            v-for="item in store.setting.problemTypes"
            :key="item.code"
            :value="item.code"
            >{{ item.name }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item
        v-if="formModel.problemType === 'OTHER'"
        class="tw-mb-2"
        label="原因"
      >
        <a-input
          v-model:value="formModel.problemRemark"
          :maxlength="32"
          placeholder="原因"
        />
      </a-form-item>
    </a-form>
  </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";
import { reactive } from "vue";

let visible = $ref(false);

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

interface FormModel {
  problemType: string;
  problemRemark: string;
}
const formModel: FormModel = reactive({
  problemType: "",
  problemRemark: "",
});

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

const handleOk = async () => {
  if (!store.currentTask) {
    void message.warn({ content: "没有可以标记的任务", duration: 5 });
    return;
  }
  if (!formModel.problemType) {
    void message.error({ content: "请选择问题类型" });
    return;
  }
  if (formModel.problemType === "OTHER" && !formModel.problemRemark) {
    void message.error({ content: "请输入原因" });
    return;
  }
  try {
    const res = await doProblemType({
      problemType: formModel.problemType,
      problemRemark:
        formModel.problemType === "OTHER" ? formModel.problemRemark : undefined,
    });
    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>
