<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { DictApi } from '#/api/system/dict/dict';

import { computed, ref } from 'vue';

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

import { useVbenForm } from '#/adapter/form';
import { apiAdd, apiUpdate } from '#/api/system/dict/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

const emit = defineEmits<{
  success: [];
}>();
const formData = ref<DictApi.Dict>();

const formSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    fieldName: 'dictName',
    label: '字典名称',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'dictType',
    label: '字典类型',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'description',
    label: '描述',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'remark',
    label: '备注',
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 90,
  },
  schema: formSchema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const data = modalApi.getData<DictApi.Dict>();
    if (data) {
      formData.value = data;
      await formApi.setValues(formData.value);
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    modalApi.lock();
    const data = await formApi.getValues<DictApi.Dict>();
    try {
      await (formData.value?.id
        ? apiUpdate({ id: formData.value.id, ...data })
        : apiAdd(data));
      resetInitialized();
      emit('success');
      modalApi.close();
    } finally {
      modalApi.unlock();
    }
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

const getModalTitle = computed(() =>
  formData.value?.id ? '修改字典类型' : '新增字典类型',
);
</script>
<template>
  <BasicModal :title="getModalTitle">
    <BasicForm class="mx-4" />
  </BasicModal>
</template>
