import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import { defineStore } from 'pinia'
import { RouteRecordRaw } from 'vue-router'
import useUserStore from './user'
import { separateAndCreateRoutes } from '@/utils/routerUtil'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

const usePermissionStore = defineStore('permission', {
  state: (): {
    routes: RouteRecordRaw[]
    addRoutes: RouteRecordRaw[]
    defaultRoutes: RouteRecordRaw[]
    topbarRouters: RouteRecordRaw[]
    sidebarRouters: RouteRecordRaw[]
  } => ({
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
  }),
  actions: {
    setRoutes(routes: RouteRecordRaw[]) {
      this.addRoutes = routes
      this.routes = constantRoutes.concat(routes)
    },
    setDefaultRoutes(routes: RouteRecordRaw[]) {
      this.defaultRoutes = constantRoutes.concat(routes)
    },
    setTopbarRoutes(routes: RouteRecordRaw[]) {
      this.topbarRouters = routes
    },
    setSidebarRouters(routes: RouteRecordRaw[]) {
      this.sidebarRouters = routes
    },
    generateRoutes(routes?: RouteRecordRaw[]) {
      return new Promise((resolve) => {
        // 1.向后端请求路由数据
        getRouters().then(({ Data, Status }) => {
          const { menus, buttonsAuth, sidebarRoutes, rewriteRoutes, defaultRoutes } = separateAndCreateRoutes(Data.Data)

          // 2.1 添加按钮权限
          useUserStore().permissions = buttonsAuth
          // 2.2 添加（基于用户权限动态）的固定菜单
          if (dynamicRoutes.length)
            dynamicRoutes.forEach((route) => {
              router.addRoute(route)
            })
          // 3 添加后端请求的数据路由
          this.setRoutes(rewriteRoutes)
          // 合并公共路由 并成一个完整的路由
          this.setSidebarRouters(constantRoutes.concat(sidebarRoutes))
          this.setDefaultRoutes(sidebarRoutes)
          this.setTopbarRoutes(defaultRoutes)
          resolve(rewriteRoutes)
        })
      })
    },
  },
})

export default usePermissionStore
