import { App } from 'vue'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { RedirectRoute } from '@/router/base'
import { PageEnum } from '@/enums/pageEnum'
import { createRouterGuards } from './router-guards'
import routes from './modules/dashboard'
import { AesEncryption } from '@/utils/cipher'
import { isArray, isNull, isUndefined } from 'lodash-es'
import type { LocationQuery, LocationQueryRaw, LocationQueryValue } from 'vue-router'
const aes = new AesEncryption()
const routeModuleList: RouteRecordRaw[] = [...routes]
function sortRoute(a: any, b: any) {
  return (a.meta?.sort || 0) - (b.meta?.sort || 0)
}
/**
 *
 * @description 加密:反序列化字符串参数
 */
export function stringifyQuery(obj: LocationQueryRaw): string {
  if (!obj) return ''
  const result = Object.keys(obj)
    .map((key) => {
      const value = obj[key]
      if (isUndefined(value)) return ''
      if (isNull(value)) return key
      if (isArray(value)) {
        const resArray: string[] = []
        value.forEach((item) => {
          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 = 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
}

routeModuleList.sort(sortRoute)

export const RootRoute: RouteRecordRaw = {
  path: '/',
  name: 'Root',
  redirect: PageEnum.BASE_HOME,
  meta: {
    title: 'Root'
  }
}

export const LoginRoute: RouteRecordRaw = {
  path: '/login',
  name: 'Login',
  component: () => import('@/views/login/index.vue'),
  meta: {
    title: '登录'
  }
}

//需要验证权限
export const asyncRoutes = []

//普通路由 无需验证权限
export const constantRouter: any[] = [LoginRoute, RootRoute, RedirectRoute, ...routeModuleList]

const router = createRouter({
  history: createWebHashHistory(''),
  routes: constantRouter,
  strict: true,
  stringifyQuery,
  parseQuery,
  scrollBehavior: () => ({ left: 0, top: 0 })
})
/**
 * 
 // stringifyQuery, // 序列化query参数
  // parseQuery,
 */
export function setupRouter(app: App) {
  app.use(router)
  // 创建路由守卫
  createRouterGuards(router, app)
}

export default router
