/*
 * @Author       : ldc 951052117@qq.com
 * @Date         : 2023-06-12 10:36:30
 * @LastEditors  : ldc 951052117@qq.com
 * @LastEditTime : 2023-08-01 14:37:22
 * @Description  : 路由总文件
 */
import { createRouter, createWebHashHistory } from 'vue-router'
import { routes, asyncRoutes } from './routes'
import { useUserStore } from '@/stores/user.js'

import { storeToRefs } from 'pinia'
import { getToken } from '@/utils/auth'

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
})

// 全局前置路由守卫
router.beforeEach(async (to, from, next) => {
  try {
    // && to.meta.isAuth
    if (getToken()) {
      if (to.path !== '/login') {
        const userStore = useUserStore()
        const { registerRouteFresh } = storeToRefs(userStore)
        // console.log(registerRouteFresh.value)
        if (registerRouteFresh.value) {
          // debugger
          const { asyncRoutes } = storeToRefs(userStore)

          userStore.updateAsyncRoutes()
          asyncRoutes.value.forEach(v => {
            router.addRoute(v)
          })
          if (from.path === '/login') {
            next({
              path: '/home',
            })
          } else {
            next({ ...to, replace: true })
          }
          userStore.updateFresh(false)
        } else {
          next()
          setRouterHistory(to,userStore)
        }
        // next({ ...to, replace: true })
      } else {
        next()
      }
    } else {
      if (to.path === '/login') {
        next()
      } else {
        next({
          path: '/login',
        })
      }
    }
  } catch (error) {
    console.log(error)
  }
  // next(); //这里是即将进入的页面是白名单的页面就直接进入
})
asyncRoutes.forEach(v => {
  router.addRoute(v)
})
export const hasPermission = (names, route) => {
  if (route.authKey) {
    return names.some(name => route.authKey === name)
  } else {
    return true
  }
}
export const filterAsyncRoutes = (routes, names) => {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(names, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, names)
      }
      res.push(tmp)
    }
  })

  return res
}
export const editRedirect = routes => {
  routes.forEach(route => {
    if (route.children && route.redirect && route.children[0]) {
      route.redirect = route.children[0].path || ''
      editRedirect(route.children)
    }
  })

  return routes
}
// 记录路由历史
const setRouterHistory = (to) => {
  const userStore = useUserStore()
	let obj = {
		title: to.meta.title,
		path: to.path,
	}
	const {routerHistory} = storeToRefs(userStore)
	routerHistory.value.push(obj);
    //map去重，避免重复记录重复路由
	let mapArr = () => {
		let map = new Map();
		for (let item of routerHistory.value) {
			if (!map.has(item.path)) {
				map.set(item.path, item);
			}
		}
		return [...map.values()];
	}
	let newArr = mapArr();

	userStore.setRouterHistory(newArr)
}
export default router
