import { defineStore, createPinia } from 'pinia'
import { GlobalState } from './interface/index'
import { Menu_User_List } from '@/api/role/index'
import { User_Info } from '@/api/user/index'
import { isEmptyObject } from '@/utils/common'
import { User_Dept_List, User_Post_List } from '@/api/user/index'
import { flatMenuListGet, AddRouterMeta } from '@/utils/common'

export const GlobalStore = defineStore({
  id: 'GlobalState',
  state: (): GlobalState => ({
    loading: false,
    isCollapse: false,
    breadcrumb: [],
    userInfo: JSON.parse(localStorage.getItem('User_info') as any) || {},
    UserDeptList: [],
    UserPostList: [],
    User_tokey: localStorage.getItem('User_tokey') || '',
    path: '',
    MenuList: [],
    allBreadcrumbList: [],
    flatMenu: []
  }),
  getters: {
    GET_User_tokey: state => state.User_tokey,
    GET_Dept_List: state => state.UserDeptList,
    GET_isCollapse: state => state.isCollapse,
    GET_Breadcrumb: state => state.breadcrumb,
    GET_User_Info: state => state.userInfo,
    GET_Menu_List: state => state.MenuList,
    GET_Flat_Menu: state => state.flatMenu
  },
  actions: {
    SET_User_Tokey(payload: string) {
      if (typeof payload === 'string') {
        this.User_tokey = payload
      }
    },
    SET_isCollapse() {
      this.isCollapse = !this.isCollapse
    },
    SET_Breadcrumb(payload: string[]) {
      let map = payload.map(item => {
        return item.replace('/', '')
      })
      this.breadcrumb = map
    },
    SET_User_Info(payload: any) {
      this.userInfo = payload
    },
    SET_Path(payload: string) {
      this.path = payload
    },
    SET_Flat_Menu(payload: any) {
      this.flatMenu = payload
    },
    async SET_User_Dept_List() {
      const res: any = await User_Dept_List()
      this.UserDeptList = res.Data
    },
    async SET_User_Post_List() {
      const res = await User_Post_List()
      console.log(res)
    },
    async SET_UserInfo() {
      // 如果以及有用户数据，则不请求
      if (isEmptyObject(this.GET_User_Info)) return
      const res: any = await User_Info({ User_tokey: this.GET_User_tokey })
      if (res.Code === 200) {
        this.SET_User_Info(res.Data)
        localStorage.setItem('User_info', JSON.stringify(res.Data))
      }
    },
    async SET_Menu_User_List() {
      const res: any = await Menu_User_List({ User_tokey: this.GET_User_tokey })
      if (res.Code === 200) {
        this.MenuList = res.Data.Data // 保存所有菜单
        this.allBreadcrumbList = AddRouterMeta(res.Data.Data) // 扩展菜单属性
        this.SET_Flat_Menu(flatMenuListGet(this.allBreadcrumbList)) // 接收扁平化菜单
      }
    }
  }
})

const pinia = createPinia()

export default pinia
