import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
import { userBreadStore } from '@/store/bread'
import { user, loginShow } from '~/store/index'
import { init } from 'echarts'
const isAdmin = user.value?.user_role_id === '69';
document.title = '桐乡互联网学校'


const modules: Record<string, { default: RouteRecordRaw }> = import.meta.glob('./routes/**/*.ts', { eager: true })
console.log('modules : ', modules)
export const constantRoutes: RouteRecordRaw[] = []
export const asyncRoutes: RouteRecordRaw[] = []
export const frontRoutes: RouteRecordRaw[] = []
Object.keys(modules).forEach((path) => {
  const arr = path.split('/');
  const filename = arr[arr.length - 1]
  if (filename?.startsWith('_'))
    constantRoutes.push(modules[path].default)
  else if (path.indexOf('./routes/manage') != -1) {
    asyncRoutes.push(modules[path].default)
  } else
    frontRoutes.push(modules[path].default)
})

console.log('constantRoutes :>> ', constantRoutes)
console.log('asyncRoutes :>> ', asyncRoutes)
console.log('frontRoutes :>> ', frontRoutes)

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...constantRoutes, ...frontRoutes, { path: '/', redirect: { name: 'home' } }],
})

let hasRoleData: any = [];
if (user.value?.user_role_id_ext_now && String(user.value.user_role_id_ext_now) != '0') {
  let { code, data } = await request({ url: "/txwx/user_role/detail", data: { tur_id: user.value?.user_role_id_ext_now, M5jxrcL: "" } });
  if (code == 1) {
    if (data.one_info.tur_role_menu) {
      hasRoleData = data.one_info.tur_role_menu.split(",");
    }
    init1();
  }
} else if (isAdmin) {
  init1();
}

function init1() {
  const filteredRoutesMap: any = {}
  // 维护路由树结构
  const RoutesTreeRelationMap: any = {}
  // const leafRouteMap: any = {}
  function initRoutesTreeRelation(routes: RouteRecordRaw[], parent: string[]) {
    routes.forEach(route => {
      RoutesTreeRelationMap[route.name] = {
        parent,
        children: route.children === undefined ? undefined : initRoutesTreeRelation(route.children, [...parent, route.name])
      }
      if (route.children === undefined) {
        if (hasRoleData.indexOf(route.name) != -1) {
          filteredRoutesMap[route.name] = true
          RoutesTreeRelationMap[route.name].parent.forEach((k: string) => filteredRoutesMap[k] = true)
        }
      }
    })
  }
  initRoutesTreeRelation(asyncRoutes, [])

  function handleFilterRoutes<R extends RouteRecordRaw[]>(routes: R): R {
    const res: any = []
    routes.forEach((route) => {
      const tmp = { ...route }
      if (filteredRoutesMap[tmp.name]) {
        if (tmp.children) {
          tmp.children = handleFilterRoutes(tmp.children)
        }
        res.push(tmp)
      }
    })
    return res
  }

  const routes = (isAdmin ? asyncRoutes : handleFilterRoutes(asyncRoutes as RouteRecordRaw[])).sort((a, b) => a.meta.sort - b.meta.sort)
  let $routes: any = [];
  if (routes[0]) {
    $routes = routes.concat([
      {
        path: '/manage',
        name: 'back',
        redirect: { name: routes[0].name }
      }
    ])
  }
  sessionStorage.setItem('routes', JSON.stringify(routes))
  $routes.forEach((filteredRoute: RouteRecordRaw) => router.addRoute(filteredRoute as RouteRecordRaw))
}

router.addRoute({
  path: '/:pathMatch(.*)',
  redirect: '/noSet',
})

export default router

// export const asyncFilteredRoutes = asyncRoutes
// asyncFilteredRoutes.forEach((route) => {
//   router.addRoute(route)
// })

router.beforeEach((to, from) => {
  // const breadStore = userBreadStore();
  // if (breadStore.breadTitle != "") {
  //   to.meta.title = breadStore.breadTitle;

  //   to.matched.map(item => {
  //     if (item.name == to.name) {
  //       item.meta.title = to.meta.title;
  //     }
  //   })
  // }

  console.groupCollapsed(`%c${from.name?.toString()} => ${to.name?.toString()}`, 'color:#0ff')
  console.log(`%c${from.meta.title} => ${to.meta.title}`, 'color:#0cc')
  console.groupEnd()

  if (user.value.token)
    return true
  if (!user.value?.token && to.meta.login === true) {
    loginShow.value = true;
    return false
  }
})
