import { defineStore } from 'pinia'
import { asyncRouterMap, constantRouterMap } from '@/router'
import {
  generateRoutesByFrontEnd,
  generateRoutesByServer,
  flatMultiLevelRoutes
} from '@/utils/routerHelper'
import { store } from '../index'
import { cloneDeep } from 'lodash-es'
import { treeToList } from '@/utils/tree'
import { routeSort } from '@/utils/routerDeal'
import { useRouteStore } from '@/store/modules/route'

const routeStore =  useRouteStore();//使用route的pinai

export interface PermissionState {
  routers: AppRouteRecordRaw[]
  addRouters: AppRouteRecordRaw[]
  isAddRouters: boolean
  menuTabRouters: AppRouteRecordRaw[]
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routers: [],
    addRouters: [],
    isAddRouters: false,
    menuTabRouters: []
  }),
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      return this.routers
    },
    getAddRouters(): AppRouteRecordRaw[] {
      return flatMultiLevelRoutes(cloneDeep(this.addRouters))
    },
    getIsAddRouters(): boolean {
      return this.isAddRouters
    },
    getMenuTabRouters(): AppRouteRecordRaw[] {
      return this.menuTabRouters
    }
  },
  actions: {
    generateRoutes(
      type: 'server' | 'frontEnd' | 'static',
      routers?: AppCustomRouteRecordRaw[] | string[]
    ): Promise<unknown> {
      return new Promise<void>((resolve) => {
        let routerMap: AppRouteRecordRaw[] = []
        if (type === 'server') {
          // 后端过滤菜单,返回固定的数据结构
          routerMap = generateRoutesByServer(treeToList(cloneDeep(asyncRouterMap)), routers as AppCustomRouteRecordRaw[])
        } else if (type === 'frontEnd') {
          // 前端过滤菜单,根据key进行匹配
          routerMap = generateRoutesByFrontEnd(cloneDeep(asyncRouterMap), routers as string[])
        } else {
          // 直接读取静态路由表
          routerMap = cloneDeep(asyncRouterMap)
        }
        //做一个路由的过滤
        const routeTemp = routeSort(routerMap.filter(item=>item.meta.type == routeStore.getRouteType));
        
        // 动态路由，404一定要放到最后面
        this.addRouters = cloneDeep(constantRouterMap).concat(asyncRouterMap)
        // 渲染菜单的所有路由
        if(['server', 'frontEnd'].includes(type)){
          this.routers = cloneDeep(constantRouterMap).concat(routeTemp)
        } else {
          this.routers = routerMap
        }
        resolve()
      })
    },
    setIsAddRouters(state: boolean): void {
      this.isAddRouters = state
    },
    setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
      this.menuTabRouters = routers
    }
  }
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}
