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

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

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

import { useFormOptions, useVbenForm } from '#/adapter';
import { DictionaryApi } from '#/api';

import { useSchema } from './data.config';

defineOptions({
  name: 'UserEdit',
});
const emit = defineEmits(['success']);
const modelRef = ref<Record<string, any>>({});
const isUpdate = ref(true);

const [Form, { validate, setValues, getValues }] = useVbenForm(
  useFormOptions({
    schema: useSchema(),
  }),
);

const [Modal, { close, setState, getData }] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    close();
  },
  onConfirm: async () => {
    try {
      const { valid } = await validate();
      if (valid) {
        const values = await getValues();
        setState({ confirmLoading: true });
        const postParams = unref(modelRef);
        Object.assign(postParams, values);
        await (unref(isUpdate)
          ? DictionaryApi.editItemDetail(postParams as DictionaryApi.RecordItem)
          : DictionaryApi.addItemDetail(
              postParams as DictionaryApi.BasicRecordItem,
            ));
        message.success('操作成功');

        close();
        emit('success');
      }
    } finally {
      setState({ confirmLoading: false });
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      setState({ loading: true });
      const data = getData<Record<string, any>>();
      isUpdate.value = !!data.isUpdate;
      modelRef.value = { ...data.baseData };
      setState({ title: unref(isUpdate) ? '编辑字典项' : '新增字典项' });

      if (unref(isUpdate)) {
        const entity = await DictionaryApi.getItemDetail(data.baseData.id);
        modelRef.value = { ...entity };
        setValues(entity);
      }
      setState({ loading: false });
    }
  },
  title: '新增字典项',
});

onMounted(async () => {});
</script>
<template>
  <Modal class="w-[1000px]">
    <Form />
  </Modal>
</template>
