import { App } from 'vue';
import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
  LocationQuery,
  LocationQueryRaw,
  LocationQueryValue,
  Router
} from 'vue-router';
import { constantRoutes } from './routes/index';
import { AesEncryption } from '@/utils/cipher';
import { createRouterGuards } from './router-guards';
const aes = new AesEncryption();

/** Used as references for various `Number` constants. */
const MAX_SAFE_INTEGER = 9007199254740991;
function isLength(value: any) {
  return (
    typeof value === 'number' &&
    value > -1 &&
    value % 1 == 0 &&
    value <= MAX_SAFE_INTEGER
  );
}
function isUndefined(value: any) {
  return value === undefined;
}
function isArray(value: any) {
  return value != null && typeof value !== 'function' && isLength(value.length);
}
function isNull(value: any) {
  return value === null;
}
/**
 *
 * @description 加密:反序列化字符串参数
 */
export function stringifyQuery(obj: LocationQueryRaw): string {
  if (!obj) return '';
  const result = Object.keys(obj)
    .map(key => {
      const value: any = obj[key];
      if (isUndefined(value)) return '';
      if (isNull(value)) return key;
      if (Array.isArray(value)) {
        const resArray: string[] = [];
        value.forEach((item: string) => {
          if (isUndefined(item)) return;
          if (isNull(item)) {
            resArray.push(key);
          } else {
            resArray.push(key + '=' + item);
          }
        });
        return resArray.join('&');
      }
      return `${key}=${value}`;
    })
    .filter(x => x.length > 0)
    .join('&');
  return result ? `?${aes.encryptByAES(result)}` : '';
}

/**
 *
 * @description 解密:反序列化字符串参数
 */
export function parseQuery(query: string): LocationQuery {
  const res: LocationQuery = {};
  query = query.trim().replace(/^(\?|#|&)/, '');
  if (!query) return res;
  query = aes.decryptByAES(query);
  query.split('&').forEach(param => {
    const parts = param.replace(/\+/g, ' ').split('=');
    const key: any = parts.shift();
    const val = parts.length > 0 ? parts.join('=') : null;
    if (!isUndefined(key)) {
      if (isUndefined(res[key])) {
        res[key] = val;
      } else if (isArray(res[key])) {
        (res[key] as LocationQueryValue[]).push(val);
      } else {
        res[key] = [res[key] as LocationQueryValue, val];
      }
    }
  });
  return res;
}

const router: Router = createRouter({
  history: createWebHashHistory('/classroom'),
  routes: [...constantRoutes],
  stringifyQuery,
  parseQuery,
  scrollBehavior: () => ({ top: 0 })
});

export function setupRouter(app: App) {
  app.use(router);
  // 创建路由守卫
  createRouterGuards(router);
}

export default router;
