<template>
  <a-modal
    v-model:open="visible"
    :width="450"
    style="top: 10vh"
    :confirm-loading="loading"
    @ok="confirm"
  >
    <template #title> 设置扫描点代码 </template>

    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ style: { width: '110px' } }"
    >
      <a-form-item name="scanSite" label="扫描点代码">
        <a-input
          v-model:value="formData.scanSite"
          placeholder="请输入"
        ></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

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

import useLoading from "@/hooks/useLoading";
import useModal from "@/hooks/useModal";
import { objAssign, objModifyAssign } from "@/utils/tool";
import { markSiteSetParams } from "@/ap/types/resultExport";

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

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

const defaultFormData = {
  examId: 0,
  scanSite: "",
};

const props = defineProps<{
  rowData: markSiteSetParams;
}>();
const emit = defineEmits(["modified"]);

const formRef = ref();
const formData: UnwrapRef<markSiteSetParams> = reactive({
  ...defaultFormData,
});
const rules: FormRules<keyof markSiteSetParams> = {
  scanSite: [
    {
      required: true,
      message: "请输入",
      trigger: "change",
    },
    {
      max: 30,
      message: "不能超过30字符",
      trigger: "change",
    },
  ],
};

/* confirm */
const { loading, setLoading } = useLoading();
async function confirm() {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;

  setLoading(true);
  const datas = objAssign(formData, {});
  const res = await markSiteCodeSet(datas).catch(() => false);
  setLoading(false);
  if (!res) return;
  message.success("保存成功！");
  emit("modified", datas);
  close();
}

watch(
  () => visible.value,
  (val) => {
    if (val) {
      modalOpenHandle();
    }
  },
  {
    immediate: true,
  }
);

/* init modal */
function modalOpenHandle() {
  objModifyAssign(formData, props.rowData);
}
</script>
