<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    @ok="handleSubmit"
    @cancel="resetForm"
  >
    <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 {
  maintenanceRecordInfo,
  maintenanceRecordAdd,
  maintenanceRecordUpdate,
} from "@/api/basicInfo/maintenanceRecord";
import { modalSchemas } from "./maintenanceRecord.data";

defineOptions({ name: "MaintenanceRecordModal" });

const emit = defineEmits(["register", "reload"]);

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 maintenanceRecordInfo(record.id);
      await setFieldsValue(ret);
    }
    modalLoading(false);
  }
);

const [registerForm, { setFieldsValue, resetForm, validate, setProps }] = useForm({
  labelWidth: 100,
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
  schemas: modalSchemas,
});

async function handleSubmit() {
  try {
    modalLoading(true);
    const data = await validate();
    if (unref(isUpdate)) {
      await maintenanceRecordUpdate(data);
    } else {
      await maintenanceRecordAdd(data);
    }
    emit("reload");
    closeModal();
    await resetForm();
  } catch (e) {
    console.warn(e);
  } finally {
    modalLoading(false);
  }
}
</script>

<style scoped></style>
