import type { Router } from 'vue-router';

import { authorizationService } from '/nerv-lib/paas/store/modules/authorization-service';
import { loginService } from '/nerv-lib/paas/store/modules/login-service';

import { NsMessage } from '/nerv-lib/component/message';
import { CatalogConfigService } from '/nerv-lib/paas/store/modules/catalog-config';
import { routerConfig } from '/nerv-lib/paas/config/router.config';
import { appConfigStore } from '/nerv-base/store/modules/app-config';
import { identity, isArray } from 'lodash-es';
export function createPermissionGuard(router: Router, whiteNameList: string[]) {
  const authService = authorizationService();
  const user = loginService();
  const catalogConfig = CatalogConfigService();
  const appConfig = appConfigStore();

  router.beforeEach(async (to) => {
    // const regionStr = localStorage.getItem('region');
    // if (regionStr && !to.fullPath.includes('region=')) {
    //   const region = JSON.parse(regionStr);
    //   to.query.region = region?.value;
    //   const urlArray = to.fullPath.split('?');
    //   if (urlArray.length === 2 && urlArray[1]) {
    //     to.path = `${to.path}&region=${region?.value}`;
    //     to.fullPath = `${to.fullPath}&region=${region?.value}`;
    //   } else {
    //     to.path = `${to.path}?region=${region?.value}`;
    //     to.fullPath = `${to.fullPath}?region=${region?.value}`;
    //   }
    // }

    if (!appConfig.pagePermission) {
      return true;
    }
  

    let catalogs;
    if (to.name && !whiteNameList.includes(to.name as string)) {
      if (!user.isLogin()) {
        await router.push({ name: 'login' });
        // routerConfig.login();
        return false;
      } else {
        await user.checkUserInfo();
        await authService.checkAuthMap();
        catalogs = await catalogConfig.getCatalogs();
      }

      if (
        authService.checkPermission(
          to.meta?.app ? to.meta?.app : (to.matched[0].name as string),
          to.meta?.bindView ? to.meta?.bindView : (to.name as string),
        )
      ) {
        return true;
      } else {
        // redirect(to, catalogs);
        // NsMessage.error('无该页面权限!');
        return false;
      }
    }
    return true;
  });

  /** 针对从产品与服务点击某项目图标应跳转到第一个有权限的菜单场景,
   * 从非vue项目点击进去,含有层级菜单项目获取的第一个有权限的菜单有误,需要在此处重定向,待非vue项目重新装过最新lib版本,即可去除*/
  function redirect(to: any, catalogs: any) {
    const moduleName = to.meta?.app ? to.meta?.app : (to.matched[0].name as string);
    let target = null;
    for (const catalog of catalogs) {
      const items = catalog['items'];
      if (isArray(items) && items.length > 0) {
        for (const item of items) {
          if (item['name'] == moduleName) {
            target = item;
            break;
          }
        }
      }
      if (target) {
        break;
      }
    }
    if (target && target['url']) {
      window.location.replace(target['url']);
    }
  }
}