<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  createDeliveryWarehouse,
  updateDeliveryWarehouse,
} from '#/views/system/delivery-warehouse/api';
import { modalFormProps } from '#/views/system/delivery-warehouse/config/form';

const isUpdate = ref(false);
const gridApi = ref();

const [Form, formApi] = useVbenForm(modalFormProps);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = isUpdate.value
          ? updateDeliveryWarehouse
          : createDeliveryWarehouse;
        submitApi(values)
          .then(() => {
            message.success('保存成功');
            // 优先 query，兼容部分页面挂的 reload
            gridApi.value?.query?.() ?? gridApi.value?.reload?.();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen) {
      const { values, update } = modalApi.getData<Record<string, any>>() || {};
      isUpdate.value = !!update;
      // 新建时清空表单，避免残留编辑态的 id/证照
      formApi.resetForm();
      if (values) {
        formApi.setValues(values);
      }
    }
  },
});
</script>
<template>
  <Modal
    :title="`${isUpdate === true ? '编辑' : '新增'}配送仓库`"
    class="w-[720px]"
  >
    <Form />
  </Modal>
</template>
