import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import { RouteRecordDetailRaw } from './routes.d';
import { app_ready, app_routes } from '~/store/app';
import request from '~/utils/request';
import { user } from '~/store/user';
const isAdmin = user.user_role_id === '69'
document.title = "桐艺云校后台管理"
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      component: () => import("~/layout/loading/index.vue")
    },
    // {
    //   path: '/routes',
    //   name: '-ROUTES',
    //   props: true,
    //   meta: {
    //     hidden: false,
    //     sort: -1,
    //     title: "组织机构与权限"
    //   },
    //   component: () => import("~/router/routes.vue")
    // }
  ]
})

// function hasPermission(route: RouteRecordDetailRaw, role: string) {
//   if (Array.isArray(route?.meta?.roles)) {
//     return route.meta.roles.includes(role)
//   } else {
//     return true
//   }
// }

// function handleFilterRoutes<R extends RouteRecordDetailRaw[]>(routes: R, role: string): R {
//   const res: any = []
//   routes.forEach((route) => {
//     const tmp = { ...route }
//     if (hasPermission(tmp, role)) {
//       if (tmp.children) {
//         tmp.children = handleFilterRoutes(tmp.children, role)
//       }
//       res.push(tmp)
//     }
//   })
//   return res
// }

// 自动引入routes下所有路由，无需再手动
// 适用于vite 2版本，不可用于vite 3
const modules = import.meta.globEager('./routes/*.ts')
const importRoutes: RouteRecordDetailRaw[] = Object.values(modules).reduce((previous, module) => { return previous.concat(module.default) }, []) as RouteRecordDetailRaw[]

await request({
  url: '/user/org_menu/setting',
  data: {
    cpm_id: '90000',
    dept_id: user.dept_id,
    keyname: "cmu_name"
  }
}).then(setting => {
  const requestRoutes = setting.data.cmu_name ?? {}
  // console.log('requestRoutes :>> ', requestRoutes);
  const requestRoutesKeyMap: any = {}
  Object.keys(requestRoutes).forEach(k => {
    const val = requestRoutes[k]
    if (val?.split(',')?.includes('show')) { requestRoutesKeyMap[k] = true }
  })
  // console.log('requestRoutesKeyMap :>> ', requestRoutesKeyMap);

  const filteredRoutesMap: any = {}
  // 维护路由树结构
  const RoutesTreeRelationMap: any = {}
  // const leafRouteMap: any = {}
  function initRoutesTreeRelation(routes: RouteRecordDetailRaw[], parent: string[]) {
    routes.forEach(route => {
      RoutesTreeRelationMap[route.name] = {
        parent,
        children: route.children === undefined ? undefined : initRoutesTreeRelation(route.children, [...parent, route.name])
      }
      if (route.children === undefined) {
        // leafRouteMap[route.name] = true
        if (requestRoutesKeyMap[route.name]) {
          filteredRoutesMap[route.name] = true
          RoutesTreeRelationMap[route.name].parent.forEach((k: string) => filteredRoutesMap[k] = true)
        }
      }
    })
  }
  initRoutesTreeRelation(importRoutes, [])
  // console.log('filteredRoutesMap :>> ', filteredRoutesMap);
  // export const RoutesCheck: any = {}
  function handleFilterRoutes<R extends RouteRecordDetailRaw[]>(routes: R): R {
    const res: any = []
    routes.forEach((route) => {
      const tmp = { ...route }
      // console.log('route :>> ', route, filteredRoutesMap[tmp.name]);

      if (filteredRoutesMap[tmp.name]) {
        if (!isAdmin) {
          tmp.meta.checkList = requestRoutes[tmp.name]?.split(',')
        }
        // RoutesCheck[tmp.name] = tmp.meta.checkList
        if (tmp.children) {
          tmp.children = handleFilterRoutes(tmp.children)
        }
        res.push(tmp)
      }
      // else if(!tmp?.meta?.checkList){
      //   if (tmp.children) {
      //     tmp.children = handleFilterRoutes(tmp.children)
      //   }
      //   res.push(tmp)
      // }
    })
    return res
  }

  const routes = (isAdmin ? importRoutes : handleFilterRoutes(importRoutes as RouteRecordDetailRaw[])).sort((a, b) => a.meta.sort - b.meta.sort)
  sessionStorage.setItem('routes', JSON.stringify(routes))
  routes.forEach(filteredRoute => router.addRoute(filteredRoute as RouteRecordRaw))
  console.log('sessionStorage :>> ', routes);
  app_ready.value = true
  app_routes.value = (routes as RouteRecordDetailRaw[])
})

export default router


router.beforeEach((to, from) => {
  if (to?.name) {
    sessionStorage.setItem('toRouteName', to.name as string)
    console.log('to.name :>> ', to.name);
  }
  console.groupCollapsed(`%c${from.name?.toString()} => ${to.name?.toString()}`, 'color:#0ff');
  console.log(`%c${from.meta.title} => ${to.meta.title}`, 'color:#0cc');
  console.log(`%c${from} => ${to}`, 'color:#011');
  console.groupEnd();
})
