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

  import { getMenuList, saveMenuApi, updateMenuApi } from '/@/api/system/system';
  import { makeMenuTree, TreeMenuNode } from '/@/utils/treeUtils';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';

  export default defineComponent({
    name: 'MenuDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const tData = ref<TreeMenuNode[]>([]);
      const menuId = ref(0);

      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)) {
          console.log('data.record', data.record.menuId);
          menuId.value = data.record.menuId;
          setFieldsValue({
            ...data.record,
          });
        }
        tData.value = (await getMenuList()) as any as TreeMenuNode[];
        const treeData = makeMenuTree(tData.value);
        updateSchema({
          field: 'parentId',
          componentProps: {
            treeData,
          },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));
      const { createMessage } = useMessage();
      const { t } = useI18n();
      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);
          values.parentId ??= 0;
          const parent = tData.value.find((i) => i.menuId === values.parentId);
          if (values.type === 0) {
            values.component = 'LAYOUT';
          }
          if (values.type === 2 && parent && parent.type !== 1) {
            createMessage.error(t('routes.system.buttonMenuWaring'));
            return;
          }

          if (!unref(isUpdate)) {
            await saveMenuApi(values);
          } else {
            values.menuId = menuId.value;
            await updateMenuApi(values);
          }

          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
