<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 {
  passApplicationApi,
  refuseApplicationApi,
} from '#/views/finance/withdrawal-audit/api';

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

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

const [WithdrawalAuditForm, WithdrawalAuditFormApi] =
  useVbenForm(withdrawalAudit);

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

<template>
  <Modal :title="`提现审核【${type === 1 ? '拒绝' : '通过'}】`" class="w-[30%]">
    <WithdrawalAuditForm />
  </Modal>
</template>
