<template>
  <BasicModal @register="registerModal" :title="title" width="640" v-bind="$attrs" destroyOnClose @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../MesXslManufacturer.data';
  import { saveOrUpdate } from '../MesXslManufacturer.api';

  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const isDetail = ref(false);

  const [registerForm, { resetFields, setFieldsValue, validate, setProps }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !data?.showFooter;
    if (unref(isUpdate)) await setFieldsValue({ ...data.record });
    else await setFieldsValue({ validStatus: '0' });
    setProps({ disabled: !data?.showFooter });
  });

  const title = computed(() =>
    !unref(isUpdate) ? '新增厂家信息' : unref(isDetail) ? '厂家信息详情' : '编辑厂家信息',
  );

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      await saveOrUpdate(values, isUpdate.value);
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
