<script setup lang="ts">
import { ref } from 'vue';

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

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

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

import { updateTableCommentApi } from '../api';

defineOptions({
  name: 'EditTableCommentModal',
});

const [Form, formApi] = useVbenForm({
  wrapperClass: 'grid-cols-12',
  commonConfig: {
    formItemClass: 'col-span-12',
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'Textarea',
      fieldName: 'comment',
      label: '表注释',
      formItemClass: 'col-span-12',
      componentProps: {
        rows: 4,
        placeholder: '请输入表注释',
      },
    },
  ],
  showDefaultActions: false,
});

const tableName = ref('');
const reloadCallback = ref<(() => void) | null>(null);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const valid = await formApi.validate();
    if (valid.valid) {
      const values = await formApi.getValues();
      modalApi.setState({ loading: true, confirmLoading: true });
      try {
        await updateTableCommentApi({
          table_name: tableName.value,
          comment: values.comment || '',
        });
        message.success('更新成功');
        reloadCallback.value?.();
        modalApi.close();
      } catch (error: any) {
        message.error(error.message || '更新失败');
      } finally {
        modalApi.setState({ loading: false, confirmLoading: false });
      }
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<{
        tableName: string;
        comment: string;
        reload: () => void;
      }>();
      if (data) {
        tableName.value = data.tableName;
        reloadCallback.value = data.reload;
        formApi.setValues({ comment: data.comment || '' });
      }
    }
  },
});
</script>

<template>
  <Modal title="编辑表注释" class="w-[500px]">
    <Form />
  </Modal>
</template>
