<script lang="ts" setup>
import type { Notice } from '#/api/system/notice/model';

import { defineEmits, ref } from 'vue';

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

import {
  addNotice,
  detailNotice,
  updateNotice,
} from '#/api/system/notice/notice';

import { modalFormSchema } from './config-data';

const emit = defineEmits<{ reload: [] }>();

const [Form, formApi] = useVbenForm({
  commonConfig: {
    formItemClass: 'col-span-2',
  },
  layout: 'vertical',
  showDefaultActions: false,
  schema: modalFormSchema(),
  wrapperClass: 'grid-cols-2',
});
const isUpdateRef = ref<boolean>(false);
const [Modal, modalApi] = useVbenModal({
  centered: true,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      this.loading = true;
      const { noticeId, isUpdate } = modalApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate) {
        const noticeData = await detailNotice(noticeId);
        await formApi.setValues(noticeData);
      }
    } catch (error) {
      console.error(error);
    } finally {
      this.loading = false;
    }
  },
  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues<Notice>();
      isUpdateRef.value ? await updateNotice(data) : await addNotice(data);
      emit('reload');
      await modalApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
  onClosed() {
    formApi.resetForm();
  },
});
</script>
<template>
  <Modal :title="isUpdateRef ? '编辑' : '新增'" class="w-[800px]">
    <Form />
  </Modal>
</template>
