<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="50%" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import { getMenuList, addMenu, editMenu, addButton, editButton } from '@/api/demo/system';

  defineOptions({ name: 'MenuDrawer' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
    const treeData = await getMenuList();
    updateSchema({
      field: 'parentId',
      componentProps: { treeData },
    });
    updateSchema({
      field: 'moduleId',
      componentProps: { treeData },
    });
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      // TODO custom api
      if (values.type == '1') {
        delete values.type
        // 新增菜单
        if (!unref(isUpdate)) {
          const data = await addMenu(values);
        } else {
          const data = await editMenu(values);
        }
        closeDrawer();
        emit('success');
      } else {
        // 新增按钮
        delete values.type
        if (!unref(isUpdate)) {
          const data = await addButton(values);
        } else {
          const data = await editButton(values);
        }
        closeDrawer();
        emit('success');
      }

    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>