<script lang="ts" setup>
/**
 * 拒绝审核原因弹窗
 * 支持 gridApi.reload/query 或自定义 onSuccess 回调（详情内审方场景）
 */
import { ref } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';

import { modalFormProps } from '../config/form';
import { rejectApi } from '#/views/pharmacist/audit-prescription/api';

const isUpdate = ref(false);
const gridApi = ref();
const onSuccess = ref<(() => void) | null>(null);

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 });
        rejectApi(values)
          .then(() => {
            message.success('拒绝成功');
            gridApi.value?.reload?.();
            gridApi.value?.query?.();
            onSuccess.value?.();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      gridApi.value = null;
      onSuccess.value = null;
      return;
    }
    const data = modalApi.getData<Record<string, any>>() || {};
    gridApi.value = data.gridApi ?? null;
    onSuccess.value =
      typeof data.onSuccess === 'function' ? data.onSuccess : null;
    const { values, update } = data;
    if (values) {
      isUpdate.value = update;
      formApi.setValues({
        id: values,
      });
    }
  },
});
</script>
<template>
  <Modal title="拒绝审核" class="w-[80%] md:w-[50%] lg:w-[30%] h-[60%]">
    <Form />
  </Modal>
</template>
