<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 { modalFormProps } from '../config/form';

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

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();
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = createWithdrawalApplicationWithdrawal;
        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);
      }
    }
  },
});

const setAmount = (amount: number) => {
  formApi.setValues({ amount });
};
</script>

<template>
  <Modal class="w-[30%]" title="申请提现">
    <Form />
    <div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
      <Button type="primary" @click="setAmount(1000)"> 1000 </Button>
      <Button type="primary" @click="setAmount(3000)"> 3000 </Button>
      <Button type="primary" @click="setAmount(5000)"> 5000 </Button>
      <Button type="primary" @click="setAmount(10000)"> 10000 </Button>
      <Button type="primary" @click="setAmount(30000)"> 30000 </Button>
      <Button type="primary" @click="setAmount(50000)"> 50000 </Button>
      <Button type="primary" @click="setAmount(100000)"> 100000 </Button>
      <Button type="primary" @click="setAmount(maxAmount.value)">
        全部提现
      </Button>
    </div>
  </Modal>
</template>
