<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 { saveCard } from '#/views/system/admin/api';

import { modalCardFormProps } from '../config/form';

const gridApi = ref();
const showCard = ref();
const maxAmount = ref(0);

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

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 = saveCard;
        submitApi(values)
          .then(() => {
            message.success('保存成功');
            // gridApi.value?.reload();
            showCard.value();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    showCard.value = isOpen ? modalApi.getData()?.showCard : null;
    if (isOpen) {
      const { values, balance } = modalApi.getData<Record<string, any>>();
      if (values) {
        maxAmount.value = balance;
        formApi.setValues(values);
      }
    }
  },
});
</script>

<template>
  <Modal class="w-[30%]" title="编辑银行卡账户">
    <Form />
  </Modal>
</template>
