import { RouteRecordRaw } from "vue-router";
import { defineStore } from "pinia";
import { constantRoutes } from "@/router";
import { store } from "@/store";

const modules = import.meta.glob("../../views/**/**.vue");
// 不同角色，不同首页
const Layout = () => import("@/layout/school.vue");
const Admin = () => import("@/layout/admin.vue");
// 角色【后台管理员】拥有的权限路由
const schoolRoutes: RouteRecordRaw[] = JSON.parse(
  JSON.stringify([
    {
      path: "/",
      redirect: "/areaboard",
      meta: { hidden: true, name: "Home" },
    },
    {
      path: "/areaboard",
      component: "AdminIndex",
      redirect: "/areaboard/index",
      meta: { title: "数据看板", name: "Dashboard" },
      children: [
        {
          path: "index",
          component: "areaboard/index",
          meta: {
            title: "区域级数据看板",
            name: "DashboardArea",
            icon: "board",
            keepAlive: true,
            breadcrumb: false,
          },
        },
      ],
    },
  ])
);
// 角色【学校负责人】拥有的权限路由
const adminRoutes: RouteRecordRaw[] = JSON.parse(
  JSON.stringify([
    {
      path: "/",
      redirect: "/dashboard",
      meta: { hidden: true, name: "Home" },
    },
    {
      path: "/dashboard",
      component: "SchoolIndex",
      redirect: "/dashboard/index",
      meta: { title: "数据看板", name: "Dashboard" },
      children: [
        {
          path: "index",
          component: "dashboard/index",
          meta: {
            title: "数据看板",
            name: "DashboardIndex",
            icon: "board",
            keepAlive: true,
            breadcrumb: false,
          },
        },
        {
          path: "example",
          component: "dashboard/example",
          meta: {
            title: "数据看板示例",
            name: "DashboardExample",
            hidden: true,
          },
        },
      ],
    },
    {
      path: "/class",
      component: "SchoolIndex",
      redirect: "/class/index",
      meta: { title: "班级管理", name: "ClassManage" },
      children: [
        {
          path: "index",
          component: "class/index",
          meta: {
            title: "班级管理",
            name: "ClassIndex",
            icon: "class",
            keepAlive: true,
            breadcrumb: false,
          },
        },
      ],
    },
    {
      path: "/teacher",
      component: "SchoolIndex",
      redirect: "/teacher/index",
      meta: { title: "教师管理", name: "TeacherManage" },
      children: [
        {
          path: "index",
          component: "teacher/index",
          meta: {
            title: "教师管理",
            name: "TeacherIndex",
            icon: "teacher",
            keepAlive: true,
            breadcrumb: false,
          },
        },
      ],
    },
    {
      path: "/student",
      component: "SchoolIndex",
      redirect: "/student/index",
      meta: { title: "学生管理", name: "StudentManage" },
      children: [
        {
          path: "index",
          component: "student/index",
          meta: {
            title: "学生管理",
            name: "StudentIndex",
            icon: "student",
            keepAlive: true,
            breadcrumb: false,
          },
        },
        {
          path: "result",
          component: "student/result",
          meta: { title: "训练效果分析", name: "StudentResult", hidden: true },
        },
      ],
    },
    {
      path: "/equipment",
      component: "SchoolIndex",
      redirect: "/equipment/index",
      meta: { title: "设备管理", name: "EquipmentManage" },
      children: [
        {
          path: "index",
          component: "equipment/index",
          meta: {
            title: "设备管理",
            name: "EquipmentIndex",
            icon: "equipment",
            keepAlive: true,
            breadcrumb: false,
          },
        },
      ],
    },
    {
      path: "/training",
      component: "SchoolIndex",
      redirect: "/training/index",
      meta: { title: "训练管理", name: "TrainingManage" },
      children: [
        {
          path: "index",
          component: "training/index",
          meta: {
            title: "训练记录",
            name: "TrainingIndex",
            icon: "training",
            keepAlive: true,
            breadcrumb: false,
          },
        },
      ],
    },
    {
      path: "/evaluation",
      component: "SchoolIndex",
      redirect: "/evaluation/index",
      meta: { title: "测评数据看板", name: "EvaluateManage" },
      children: [
        {
          path: "index",
          component: "evaluation/index",
          meta: {
            title: "测评数据看板",
            name: "EvaluateIndex",
            icon: "evaluation",
            keepAlive: true,
            breadcrumb: false,
          },
        },
      ],
    },
  ])
);
/**
 * 递归过滤有权限的异步(动态)路由
 *
 * @param routes 接口返回的异步(动态)路由
 * @param roles 用户角色集合
 * @returns 返回用户有权限的异步(动态)路由
 */
const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const asyncRoutes: RouteRecordRaw[] = [];

  routes.forEach((route) => {
    const tmpRoute = { ...route }; // ES6扩展运算符复制新对象

    if (tmpRoute.component?.toString() == "SchoolIndex") {
      tmpRoute.component = Layout;
      console.log("SchoolIndex");
    } else if (tmpRoute.component?.toString() == "AdminIndex") {
      tmpRoute.component = Admin;
      console.log("AdminIndex");
    } else {
      const component = modules[`../../views/${tmpRoute.component}.vue`];
      if (component) {
        tmpRoute.component = component;
      } else {
        tmpRoute.component = modules[`../../views/error-page/404.vue`];
      }
    }

    if (tmpRoute.children) {
      tmpRoute.children = filterAsyncRoutes(tmpRoute.children, roles);
    }

    asyncRoutes.push(tmpRoute);
  });

  return asyncRoutes;
};

// setup
export const usePermissionStore = defineStore("permission", () => {
  // state
  const routes = ref<RouteRecordRaw[]>([]);

  // actions
  function setRoutes(newRoutes: RouteRecordRaw[]) {
    routes.value = constantRoutes.concat(newRoutes);
  }
  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes(roles: string[]) {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      // 角色【后台管理员】拥有权限
      if (roles.includes("ADMIN")) {
        // 根据角色获取有访问权限的路由
        const accessedRoutes = filterAsyncRoutes(adminRoutes, roles);
        setRoutes(accessedRoutes);
        resolve(accessedRoutes);
      }
      // 角色【学校负责人】拥有权限
      else if (roles.includes("SCHOOL")) {
        const accessedRoutes = filterAsyncRoutes(schoolRoutes, roles);
        setRoutes(accessedRoutes);
        resolve(accessedRoutes);
      } else {
        reject("没有访问权限");
      }
    });
  }
  return { routes, setRoutes, generateRoutes };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
