// import { Permission } from '@/store/modules/user/typing';
import type { MenuDataItem } from '@/router/typing';
import type { Action, Role } from '@/store/modules/user/typing';
import type { Ref } from 'vue';
import { computed, ref, defineAsyncComponent, watchEffect, unref } from 'vue';
import { useStore } from 'vuex';
import { intersection, toArray } from 'lodash-es';
import { useRoute } from 'vue-router';

export const filterChildRoute = (route: MenuDataItem, permissions: string[]) =>
  route.children
    ?.filter(item => {
      const hasAllow = hasAuthority(item, permissions);
      if (hasAllow && item.children && item.children.length > 0) {
        item.children = filterChildRoute(item, permissions!);
      }
      return hasAllow;
    })
    .filter(item => item);

// permissions: Permission[]
export const hasAuthority = (route: MenuDataItem, permissions: string[]) => {
  if (route.meta?.authority) {
    return permissions.some(value => {
      return route.meta?.authority?.includes(value);
    });
  }
  return true;
};

type MaybeRef<T> = T | Ref<T>;
export const useAuth = (actions: MaybeRef<Action | Action[]>) => {
  const store = useStore();
  const role = computed<Role>(() => store.getters['user/role']);
  const hasAuth = ref(false);
  const route = useRoute();
  watchEffect(() => {
    const authority =
      typeof route.meta.authority === 'string'
        ? [route.meta.authority]
        : (route.meta.authority as string[]) || [];
    const permissions = role.value?.permissions;
    const auths = toArray(unref(actions));
    if (permissions) {
      hasAuth.value = false;
      for (let i = 0; i < permissions.length; i++) {
        const p = permissions[i];
        if (!authority.includes(p.name)) continue;
        // 都是空的时候，算作有权限
        if ((p.actions && p.actions.length === 0 && auths.length === 0) || auths.length === 0) {
          hasAuth.value = true;
          break;
        }
        if (intersection(p.actions || [], auths).length) {
          hasAuth.value = true;
          break;
        }
      }
    } else {
      hasAuth.value = true;
    }
  });
  return hasAuth;
};

export const useAuthRouter = (route: string[], permissions: string[]) =>
  route
    ?.filter((item: any) => {
      const isHasAuth = hasAuth(item, permissions) || item?.extra?.isHidden;
      if (isHasAuth && item?.children && item.children.length > 0) {
        item.children = useAuthRouter(item.children, permissions);
      }
      return isHasAuth;
    })
    .filter(item => item);

export const hasAuth = (route, permissions) => {
  // RODO:关掉权限
  return true;
  // return permissions.some(value => {
  //   return route?.extra?.id == value.key;
  // });
};

export const getAuthMenu = (authData = [], pId, _arr = []) => {
  const arr = _arr;
  authData.map(item => {
    if (item.parentId == pId && (item.authType == 2 || item.authType == 3)) {
      // 当前是menu或者tab
      if (arr.indexOf(item.key) == -1) {
        arr.push(item.key);
      }
    }
    if (
      item.parentId == pId &&
      (item.authType == 3 || item.authType == 1 || item.authType == 2 || item.authType == 4)
    ) {
      // 当前是导航1或者tab3签或者 树节点 4 ,menu 2(二级menu)
      getAuthMenu(authData, item.key, arr);
    }
  });
  return arr;
};

// // 设置page-menu-link类型tabs权限
// export const getTabsAuth = data => {
//   const menuAuth = JSON.parse(window.localStorage.getItem('menuAuth') || '[]');
//   const link = data?.link || {};
//   const newLink = {};
//   let newLinksPage = [];
//   Object.keys(link)?.map(item => {
//     link[item]?.pageLinkList?.map(page => {
//       if (menuAuth.indexOf(page.uniqueKey) >= 0) {
//         newLinksPage.push(page);
//         newLink[item] = {
//           ...(link[item] || {}),
//           pageLinkList: newLinksPage,
//         };
//       }
//     });
//     newLinksPage = [];
//   });

//   return [
//     {
//       ...(data || {}),
//       link: newLink,
//     },
//     defineAsyncComponent(() => import('@/views/platform/components/Empty.vue')),
//   ];
// };

// 设置pageLinks类型
// export const getTabsPageLinksAuth = data => {
//   const menuAuth = JSON.parse(window.localStorage.getItem('menuAuth') || '[]');
//   const menuPageLinks = data?.pageLinkList?.filter(page => menuAuth.indexOf(page.uniqueKey) >= 0);

//   return [
//     {
//       ...data,
//       pageLinkList: menuPageLinks,
//     },
//     defineAsyncComponent(() => import('@/views/platform/components/Empty.vue')),
//   ];
// };
