<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 { sendDeliveryWarehouseOrder } from '#/views/system/delivery-warehouse-order/api';
import { modalFormProps } from '#/views/system/delivery-warehouse-order/config/form';

const gridApi = ref();
const orderNo = 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 });
        sendDeliveryWarehouseOrder(values)
          .then(() => {
            message.success('发货成功');
            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 } = modalApi.getData<Record<string, any>>();
      if (values) {
        orderNo.value = values.order_no;
        formApi.setValues(values);
      }
    }
  },
});
</script>
<template>
  <Modal :title="`订单：【 ${orderNo} 】发货`" class="w-[80%] md:w-[50%] lg:w-[30%] h-[60%]">
    <Form />
  </Modal>
</template>
