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

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

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

import { useVbenForm } from '#/adapter/form';
import { createWithdrawalApplicationWithdrawal } from '#/views/finance/withdrawal/api';

import { invalidatedForm, settlementForm } from '../config/form';

const gridApi = ref();
const type = ref(1);
const id = ref(0);

const [InvalidatedForm, InvalidatedFormApi] = useVbenForm(invalidatedForm);
const [SettlementForm, SettlementFormApi] = useVbenForm(settlementForm);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    let formApi = type.value === 1 ? InvalidatedFormApi : SettlementFormApi;
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = createWithdrawalApplicationWithdrawal;
        submitApi(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, modalType } = modalApi.getData<Record<string, any>>();
      if (values) {
        id.value = values;
      }
      if (type) {
         type.value = modalType;
      }
    }
  },
});

</script>

<template>
  <Modal class="w-[80%] h-[80%]" title="申请提现">
    <InvalidatedForm />
    <SettlementForm />
  </Modal>
</template>
