<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 {
  invalidatedApi,
  settlementApi,
} from '#/views/finance/monthly-payment/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 () => {
    const 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 = type.value === 1 ? invalidatedApi : settlementApi;
        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 { modalType, id } = modalApi.getData<Record<string, any>>();
      if (modalType) {
        type.value = modalType;
      }
      if (id && type.value === 1) {
        InvalidatedFormApi.setValues({
          id,
        });
      }
    }
  },
});
</script>

<template>
  <Modal :title="type === 1 ? '作废订单' : '结算订单'" class="w-[30%]">
    <InvalidatedForm v-if="type === 1" />
    <SettlementForm v-else />
  </Modal>
</template>
