<template>
  <BasicModal v-bind="$attrs" :title="title" @register="registerInnerModal" :width="800">
    <template #footer>
      <div v-if="isUpdate !== 3">
        <a-button type="default" @click="handleCancle">取消</a-button>
        <a-button type="primary" @click="handleSubmit">确认</a-button>
      </div>
    </template>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
import { BasicModal, useModalInner } from "@/components/Modal";
import { BasicForm, useForm } from "@/components/Form";
import { computed, ref, unref } from "vue";
import {
  faultMessageInfo,
  faultMessageAdd,
  faultMessageUpdate,
} from "@/api/statusCheck/fault";
import { modalSchemas } from "./faultMessage.data";
import { convertNumberToString } from "@/utils/tool";

defineOptions({ name: "FaultMessageModal" });

const emit = defineEmits(["register", "reload"]);
const showFooter = ref<boolean>(true);
const isUpdate = ref<number>(1);
const title = computed<string>(() => {
  return isUpdate.value === 1
    ? "编辑故障消息;"
    : isUpdate.value === 2
    ? "新增故障消息;"
    : "查看故障消息;";
});

const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
  async (data: { record?: Recordable; update: number }) => {
    modalLoading(true);
    const { record, update } = data;
    isUpdate.value = update;
    if (isUpdate.value === 3) {
      setProps({ disabled: true });
    } else {
      setProps({ disabled: false });
    }
    if ((update === 1 || update === 3) && record) {
      const ret = await faultMessageInfo(record.id);
      ret.source = convertNumberToString(ret.source);
      await setFieldsValue(ret);
      if (update === 3) {
        clearValidate();
      }
    }
    modalLoading(false);
  }
);

const [
  registerForm,
  { setFieldsValue, resetForm, validate, setProps, clearValidate },
] = useForm({
  labelWidth: 100,
  showActionButtonGroup: false,
  baseColProps: { span: 12 },
  schemas: modalSchemas,
});
function handleCancle() {
  closeModal();
  resetForm();
}
async function handleSubmit() {
  try {
    modalLoading(true);
    const data = await validate();
    if (isUpdate.value === 1) {
      await faultMessageUpdate(data);
    } else {
      await faultMessageAdd(data);
    }
    emit("reload");
    closeModal();
    await resetForm();
  } catch (e) {
    console.warn(e);
  } finally {
    modalLoading(false);
  }
}
</script>

<style scoped></style>
