<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 * as AuthorityApi from '/@/api/system/authorityApi';
  export default defineComponent({
    name: 'MenuDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const entityId = 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) => {
        await resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        entityId.value = data?.record?.id;

        let treeData = await AuthorityApi.all({ authorityId: 0 });
        treeData = btnSelectable(treeData);
        await updateSchema({
          field: 'authorityId',
          componentProps: { treeData },
        });

        if (unref(isUpdate)) {
          await setFieldsValue({
            ...data.record,
          });
        }
      });

      const btnSelectable = (treeNodes: any) => {
        treeNodes.forEach((node) => {
          if (node.children && node.children.length > 0) {
            btnSelectable(node.children);
          }
          node['selectable'] = node.type !== 'BUTTON';
        });
        return treeNodes;
      };

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

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          const { type, keepAlive, hidden, ...rest } = values;
          const action = !unref(isUpdate) ? AuthorityApi.add : AuthorityApi.update;
          const data = !unref(isUpdate)
            ? {
                type,
                ...rest,
                keepAlive: ['DIR', 'BUTTON'].includes(type) ? false : keepAlive,
                hidden: ['BUTTON'].includes(type) ? false : hidden,
              }
            : Object.assign(
                {},
                {
                  type,
                  ...rest,
                  id: unref(entityId),
                  keepAlive: ['DIR', 'BUTTON'].includes(type) ? false : keepAlive,
                  hidden: ['BUTTON'].includes(type) ? false : hidden,
                },
              );
          await action(data);
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

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