<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 { createAdminNoticeType, updateAdminNoticeType } from '../api';
import { modalFormProps } from '../config/form';

const isUpdate = ref(false);
const gridApi = ref();
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 ? updateAdminNoticeType : createAdminNoticeType;
      await api(values);
      message.success('保存成功');
      gridApi.value?.query?.();
      gridApi.value?.reload?.();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (!isOpen) {
      formApi.resetForm();
      return;
    }
    const { values, update } = modalApi.getData<Record<string, any>>() || {};
    isUpdate.value = !!update;
    // 编辑时锁定 code，避免业务硬编码失效
    formApi.updateSchema([
      {
        fieldName: 'code',
        componentProps: { disabled: !!update },
      },
    ]);
    if (values && update) {
      formApi.setValues({ ...values });
    } else {
      formApi.resetForm();
      formApi.setValues({ sort: 0, status: 1, color: 'sky', icon: '', cover_url: '' });
    }
  },
});
</script>
<template>
  <Modal :title="`${isUpdate ? '编辑' : '新增'}消息类型`" class="w-[560px]">
    <Form />
  </Modal>
</template>
