<template>
  <a-modal v-model:open="visible" :width="424" style="top: 10vh" @ok="confirm">
    <template #title> 重置 </template>

    <my-quote class="m-b-16px" :message="quoteContent" type="error"></my-quote>

    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ style: { width: '110px' } }"
    >
      <a-form-item name="password" label="管理员密码">
        <a-input
          v-model:value="formData.password"
          placeholder="请输入"
        ></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import type { UnwrapRef } from "vue";
import { message } from "ant-design-vue";

import useModal from "@/hooks/useModal";
import { useUserStore } from "@/store";
import { reviewTaskReset, reviewTaskResetStatus } from "@/ap/review";
import { SubjectItem } from "@/ap/types/base";
import useLoop from "@/hooks/useLoop";

defineOptions({
  name: "ResetConfirmDialog",
});

/* modal */
const { visible, open, close } = useModal();
defineExpose({ open, close });

const props = defineProps<{
  subject: SubjectItem | null;
}>();

const emit = defineEmits(["confirm"]);

const userStore = useUserStore();

const quoteContent = computed(() => {
  return `将重置${userStore.curExam.name}${
    props.subject?.subjectCode || ""
  }的复核校验任务，请输入当前管理员密码`;
});

const formRef = ref();
const formData: UnwrapRef<{ password: string }> = reactive({
  password: "",
});
const rules: FormRules<"password"> = {
  password: [
    {
      required: true,
      message: "请输入",
      trigger: "change",
    },
  ],
};

/* confirm */
const { start: startLoopSync, stop: stopLoopSync } = useLoop(checkStatus, 1000);

async function checkStatus() {
  const res = await reviewTaskResetStatus({
    examId: userStore.curExam.id,
    subjectCode: props.subject?.subjectCode || "",
  }).catch(() => {});
  if (res) {
    if (!res.synching) {
      stopLoopSync();
      message.success("操作成功！");
      emit("confirm");
      close();
    }
  } else {
    stopLoopSync();
    message.error("操作错误，请重新尝试！");
  }
}

async function confirm() {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;

  const res = await reviewTaskReset({
    examId: userStore.curExam.id,
    subjectCode: props.subject?.subjectCode || "",
    password: formData.password,
  }).catch(() => false);
  if (!res) return;

  startLoopSync();
}
</script>
