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

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

import { useFormOptions, useVbenForm } from '#/adapter';
import { CmsSiteMenuApi } 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, formApi] = useVbenForm(
  useFormOptions({
    commonConfig: {
      colon: true,
      formItemClass: 'col-span-2 md:col-span-1',
    },
    schema: [],
    wrapperClass: 'grid-cols-2 gap-x-4',
  }),
);

const [Drawer, { close, getData, lock, unlock }] = useVbenDrawer({
  closeOnClickModal: false,
  destroyOnClose: true,
  onCancel() {
    close();
  },
  onConfirm: async () => {
    try {
      const { valid } = await formApi.validate();
      if (!valid) return;

      const values = await formApi.getValues();
      lock();
      const postParams = unref(modelRef);

      Object.assign(postParams, values);

      await (unref(isUpdate)
        ? CmsSiteMenuApi.editDetail(postParams as CmsSiteMenuApi.RecordItem)
        : CmsSiteMenuApi.addDetail(
            postParams as CmsSiteMenuApi.BasicRecordItem,
          ));
      alert('操作成功');

      emit('success');
      close();
    } finally {
      unlock();
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      // lock();
      const data = getData<Record<string, any>>();
      isUpdate.value = !!data.isUpdate;
      modelRef.value = { ...data.baseData };

      const schema = useSchema({ siteId: data.baseData.siteId });
      formApi.setState({ schema });

      if (unref(isUpdate)) {
        const entity = await CmsSiteMenuApi.getDetail(data.baseData.id);
        modelRef.value = { ...entity };

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

        await formApi.setValues(formatData);
        // unlock();
      }
    }
  },
});

const getTitle = computed(() => (unref(isUpdate) ? '编辑菜单' : '新增菜单'));
</script>
<template>
  <Drawer class="w-[1000px]" :title="getTitle">
    <Form />
  </Drawer>
</template>
