<script lang="ts" setup>
/**
 * 平台仓库列表：银行卡报备弹窗
 * 复用仓侧报备表单与 API，提交时带当前行 warehouse_id
 */
import { ref } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';
import {
  getDeliveryWarehouseBankCardDetail,
  reportDeliveryWarehouseBankCard,
} from '#/views/system/delivery-warehouse-bank-card/api';
import { reportFormProps } from '#/views/system/delivery-warehouse-bank-card/config/form';

const warehouseId = ref(0);
const warehouseName = ref('');
const gridApi = ref();

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

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const result = await formApi.validate();
    if (!result.valid) {
      return;
    }
    const values = await formApi.getValues();
    modalApi.setState({ loading: true, confirmLoading: true });
    try {
      await reportDeliveryWarehouseBankCard({
        ...values,
        warehouse_id: warehouseId.value,
      });
      message.success('银行卡报备已提交');
      gridApi.value?.query?.() ?? gridApi.value?.reload?.();
      modalApi.close();
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    const data = modalApi.getData<Record<string, any>>() || {};
    warehouseId.value = Number(data.warehouse_id || data.values?.id || 0);
    warehouseName.value = data.warehouse_name || data.values?.name || '';
    gridApi.value = data.gridApi;
    formApi.resetForm();
    formApi.setValues({ warehouse_id: warehouseId.value });
    // 有历史草稿或主体镜像时预填，方便驳回后重提
    try {
      const detail = await getDeliveryWarehouseBankCardDetail({
        warehouse_id: warehouseId.value,
      });
      if (detail) {
        formApi.setValues({
          warehouse_id: warehouseId.value,
          bank_user_name: detail.bank_user_name,
          bank_card: detail.bank_card,
          bank_name: detail.bank_name,
          bank_account_type: detail.bank_account_type || 2,
          bank_no: detail.bank_no,
          cert_no: detail.cert_no,
          attachment: detail.attachment,
        });
      }
    } catch {
      // 未报备时 detail 可能为空，忽略即可
    }
  },
});
</script>
<template>
  <Modal
    :title="`银行卡报备${warehouseName ? ` - ${warehouseName}` : ''}`"
    class="w-[520px]"
  >
    <Form />
  </Modal>
</template>
