<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 } from '/@/api/sys/menu';

  import { saveMenuApi } from '/@/api/system/menu';
  import { listToTree } from '/@/utils/menuUtil';

  import { useI18n } from '/@/hooks/web/useI18n';
  import { metaModel } from '/@/api/system/model/menuModel';

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

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });
      const { t } = useI18n(); //加载国际化

      //默认传递页面数据
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        //初始化，菜单名称为可用
        updateSchema({ field: 'title', componentProps: { disabled: false } });
        //如果是编辑操作，设置页面数据
        if (unref(isUpdate)) {
          // // 动态设置 表单值

          let menuObj: metaModel = Reflect.get(data.record, 'meta');
          Reflect.set(data.record, 'menuType', menuObj.menuType); //meta.menuType
          Reflect.set(data.record, 'title', menuObj.title); //meta.title
          Reflect.set(data.record, 'icon', menuObj.icon); //meta.icon
          Reflect.set(data.record, 'hideMenu', menuObj.hideMenu); //meta.hideMenu
          Reflect.set(data.record, 'ignoreKeepAlive', menuObj.ignoreKeepAlive); //meta.ignoreKeepAlive
          Reflect.set(data.record, 'isLink', menuObj.isLink); //meta.isLink
          Reflect.set(data.record, 'status', menuObj.status); //meta.status
          // Reflect.set(data.record, 'menuOut', menuObj.menuOut); //meta.menuOut
          // Reflect.set(data.record, 'menuSystem', menuObj.menuSystem); //meta.menuSystem
          //为表单赋值
          setFieldsValue({
            ...data.record,
          });

          //编辑模式，菜单名称为不可用
          updateSchema({ field: 'title', componentProps: { disabled: false } });
        }
        if (isUpdate.value) {
          menuId = Reflect.get(data.record, 'id');
        }
        //加载菜单
        let treeData = await getMenuList(1, 'all');
        treeData = listToTree(treeData);
        updateSchema({
          field: 'parentId',
          componentProps: { treeData },
        });
      });

      //得到页面标题
      const getTitle = computed(() =>
        !unref(isUpdate)
          ? t('routes.common.system.pageSystemTitleCreateMenu')
          : t('routes.common.system.pageSystemTitleEditMenu')
      );

      //提交按钮
      async function handleSubmit() {
        try {
          const values = await validate();

          if (values.parentId == undefined) {
            let treeData: any = await getMenuList();

            values.parentId = treeData[0].parentId;
          }
          setDrawerProps({ confirmLoading: true });
          // TODO custom api

          // 处理权限标识为null时，后台空指针
          let permissionStr: string = Reflect.get(values, 'permission');
          if (permissionStr === undefined || permissionStr === null) {
            Reflect.set(values, 'permission', ' ');
          }

          // 添加属性;
          //当前作为默认管理员操作；
          Reflect.set(values, 'type', 'SYSADMIN');
          Reflect.set(values, 'name', Reflect.get(values, 'title'));
          Reflect.set(values, 'menuSys', Reflect.get(values, 'menuSys'));
          Reflect.set(values, 'menuOut', Reflect.get(values, 'menuOut'));
          //当前选择为菜单时操作
          let menuType: string = Reflect.get(values, 'menuType');
          if (menuType === '0') {
            Reflect.set(values, 'component', 'LAYOUT');
          }
          if (isUpdate.value) {
            Reflect.set(values, 'id', menuId);
          }

          //为meta设置值
          const metaTemp: metaModel = {
            icon: Reflect.get(values, 'icon'),
            title: Reflect.get(values, 'title'),
            isLink: Reflect.get(values, 'isLink'),
            menuType: Reflect.get(values, 'menuType'),
            ignoreKeepAlive: Reflect.get(values, 'ignoreKeepAlive'), //[创建菜单，才需要]
            hideMenu: Reflect.get(values, 'hideMenu'),
            status: Reflect.get(values, 'status'),
            // menuOut: Reflect.get(values, 'menuOut'),
            // menuSystem: Reflect.get(values, 'menuSystem'),
          };
          Reflect.set(values, 'meta', metaTemp);
          // saveMenu
          await saveMenuApi(values, isUpdate.value);

          closeDrawer(); //关闭侧框
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

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