import type { Router } from 'vue-router';
import { NsMessage } from '/nerv-lib/component/message';
import { authorizationService } from '/nerv-base/store/modules/authorization-service';
import { appConfigStore } from '/nerv-base/store/modules/app-config';
import { Cookies } from '/nerv-lib/util/cookie';
import { setRouteChange } from '/nerv-lib/util/routeChange';

console.log(import.meta.env.VITE_PUBLIC_PATH);

export function createPermissionGuard(router: Router, whiteNameList: string[]) {
  const authorizationStore = authorizationService();
  const appConfig = appConfigStore();
  router.beforeEach(async (to, from, next) => {
    if (!appConfig.userCustomRouterGuard) {
      setRouteChange(to);
      if (to?.query?.nervsid) {
        if (to?.query?.nervsid !== Cookies.get(`${import.meta.env.VITE_PUBLIC_PATH}-nervsid`)) {
          Cookies.set(`${import.meta.env.VITE_PUBLIC_PATH}-nervsid`, to?.query?.nervsid);
          try {
            const info = await appConfig.userInfo();
            await authorizationStore.initUserResource();
            authorizationStore.initMenuResource();
            appConfig.setUserInfo(info.data);
            info.success
              ? window.sessionStorage.setItem(
                  import.meta.env.VITE_PUBLIC_PATH,
                  JSON.stringify(info.data),
                )
              : '';
          } catch (err) {
            Cookies.remove(`${import.meta.env.VITE_PUBLIC_PATH}-nervsid`);
          }
        }
      }
      if (
        !Cookies.get(`${import.meta.env.VITE_PUBLIC_PATH}-nervsid`) &&
        to.fullPath !== '/login' &&
        to.name &&
        !whiteNameList.includes(to.name as string)
      ) {
        NsMessage.error('登录信息已过期，请重新登录!', 1);
        next({ name: 'login' });
      } else {
        //  存储用户信息
        if (to.fullPath !== '/login') {
          const initUserInfo = window.sessionStorage[import.meta.env.VITE_PUBLIC_PATH];
          if (!initUserInfo && Cookies.get(`${import.meta.env.VITE_PUBLIC_PATH}-nervsid`)) {
            try {
              const info = await appConfig.userInfo();
              info.data
                ? window.sessionStorage.setItem(
                    import.meta.env.VITE_PUBLIC_PATH,
                    JSON.stringify(info.data),
                  )
                : '';
            } catch (err) {
              Cookies.remove(`${import.meta.env.VITE_PUBLIC_PATH}-nervsid`);
            }
          } else {
            if (initUserInfo) {
              const userInfo = JSON.parse(initUserInfo);
              authorizationStore.setEnterpriseName(
                !userInfo.organizationalName ? '' : userInfo.organizationalName,
              );
            }
          }
        }

        if (to.name && !whiteNameList.includes(to.name as string)) {
          if (appConfig.enablePermissions !== undefined && appConfig.enablePermissions) {
            if (authorizationStore.getInitRouterList.length === 0) {
              await authorizationStore.initUserResource();
            }

            if (
              authorizationStore.checkPermissionRouter(
                to.meta?.bindView ? to.meta?.bindView : to.name,
              )
            ) {
              next();
            } else {
              if (to.path === '/') {
                next({ name: authorizationStore.getInitRouterList[0] });
              } else {
                //  console.log(authorizationStore.getInitRouterList);
                NsMessage.error('无该页面权限！');
                next({ name: 'error403' });
              }
            }
          } else {
            next();
          }
        } else {
          next();
        }
      }
    } else {
      await appConfig.userCustomRouterGuard(
        to,
        from,
        next,
        whiteNameList,
        authorizationStore,
        appConfig,
      );
    }
  });
}
