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

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

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

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

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

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

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

const [Drawer, { close, setState, getData }] = useVbenDrawer({
  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)
          ? MenuApi.editDetail(postParams as MenuApi.RecordItem)
          : MenuApi.addDetail(postParams as MenuApi.BasicRecordItem));
        message.success('操作成功');

        close();
        emit('success');
      }
    } catch {
      message.error('操作失败');
    } 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 MenuApi.getDetail(data.baseData.id);
        modelRef.value = { ...entity };

        const formatData: any = { ...entity };

        setValues(formatData);
      }
      setState({ loading: false });
    }
  },
  title: '新增菜单',
});

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