<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 { sendOrder } from '#/views/business/order/product-order/api';
import { modalFormProps } from '#/views/business/order/product-order/config/form';



const isUpdate = ref(false);
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();
        // 仅提交合法非负整数 warehouse_id；脏值不传，由后端按角色默认平台包 0
        const wid = Number(values.warehouse_id);
        const payload: Record<string, any> = { ...values };
        if (Number.isFinite(wid) && wid >= 0 && String(values.warehouse_id) !== '[object Object]') {
          payload.warehouse_id = wid;
        } else {
          delete payload.warehouse_id;
        }
        modalApi.setState({ loading: true, confirmLoading: true });
        sendOrder(payload)
          .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, update } = modalApi.getData<Record<string, any>>() || {};
      // 先重置，避免上次发货残留的 warehouse_id
      formApi.resetForm();
      if (values) {
        orderNo.value = values.order_no;
        isUpdate.value = update;
        formApi.setValues(values);
      }
    }
  },
});
</script>
<template>
  <Modal :title="`订单：【 ${orderNo} 】发货`" class="w-[80%] md:w-[50%] lg:w-[30%] h-[60%]">
    <Form />
  </Modal>
</template>
