<script lang="ts" setup>
/**
 * AI 平台新增/编辑弹窗
 */
import { ref } from 'vue';

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

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

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

import { createAiPlatform, updateAiPlatform } from '../api';
import { modalFormProps } from '../config/form';

const isUpdate = ref(false);
const gridApi = ref();
const onSuccess = ref<null | (() => void)>(null);
const [Form, formApi] = useVbenForm(modalFormProps);
const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const e = await formApi.validate();
    if (!e.valid) return;
    const values = await formApi.getValues();
    modalApi.setState({ confirmLoading: true });
    try {
      const api = isUpdate.value ? updateAiPlatform : createAiPlatform;
      await api(values);
      message.success('保存成功');
      gridApi.value?.query?.();
      onSuccess.value?.();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    onSuccess.value = isOpen
      ? modalApi.getData()?.onSuccess || null
      : null;
    if (!isOpen) {
      formApi.resetForm();
      return;
    }
    const { values, update } = modalApi.getData<Record<string, any>>() || {};
    isUpdate.value = !!update;
    if (values && update) {
      formApi.setValues({ ...values });
    } else {
      formApi.resetForm();
      formApi.setValues({ sort: 0, status: 1 });
    }
  },
});
</script>
<template>
  <Modal :title="`${isUpdate ? '编辑' : '新增'}AI平台`" class="w-[640px]">
    <Form />
  </Modal>
</template>
