import { defineStore } from 'pinia'
import { AuthState } from '@/stores/interface'
import { getFlatMenuList } from '@/utils'

export const useAuthStore = defineStore({
  id: 'auth',
  state: (): AuthState => ({
    // 按钮权限列表
    authButtonList: [],
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    menuSign: '',
    // 当前激活菜单的菜单ID，后端判断用来做数据权限
    activeMenuId: '',
    // 菜单权限中所以菜单的name集合
    routeNameMap: {},
    // 面包屑数据
    breadcrumbList: []
  }),
  getters: {
    // 按钮权限列表
    authButtonListGet: (state): string[] => state.authButtonList,
    // 菜单权限列表 ==> 去除掉按钮权限级别后的菜单
    authMenuListGet: (state): Menu.MenuOptions[] => {
      // 筛选过的菜单（去除了按钮层级的菜单）
      let menuTree: Menu.MenuOptions[] = JSON.parse(JSON.stringify(state.authMenuList))
      for (let item of menuTree) {
        if (item.children && item.children.length) {
          for (let childItem of item.children) {
            if (childItem.children) {
              delete childItem.children
            }
          }
        }
      }
      return menuTree
    },
    // 扁平化菜单，用于菜单搜索
    flatMenuListGet(): Menu.MenuOptions[] {
      return getFlatMenuList(this.authMenuListGet)
    }
  },
  actions: {
    // 设置可访问按钮数据
    async setAuthButtonList(data: string[]) {
      this.authButtonList = data
    },
    // 设置可访问菜单数据
    async setAuthMenuList(data: Menu.MenuOptions[]) {
      this.authMenuList = data
    },
    // 设置当前页面的路由name
    async setMenuSign(name: string) {
      this.menuSign = name
    },
    // 设置激活当前激活菜单ID
    async setActiveMenuId(id: string) {
      this.activeMenuId = id
    },
    // 用户菜单权限的name集合
    setRouteNameMap(menuTree: any[]) {
      let data: { [key: string]: boolean } = {}
      for (let item of menuTree) {
        data[item.menuSign] = true
        if (item.children && item.children.length > 0) {
          for (let child of item.children) {
            data[child.menuSign] = true
          }
        }
      }
      this.routeNameMap = data
    },
    // 设置面包屑数据
    setBreadcrumb(data: any[]) {
      this.breadcrumbList = data
    }
  }
})
