import { defineStore, createPinia } from 'pinia'
import { GlobalState, DepotType, NoticeType } 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 } from '@/api/user/index'
import { User_News_List } from '@/api/user/index'
import { flatMenuListGet, AddRouterMeta, getAllBreadcrumbList } from '@/utils/common'
import { Storehouse_Depot_List } from '@/api/storehouse/index'

export const GlobalStore = defineStore({
  id: 'GlobalState',
  state: (): GlobalState => ({
    isloading: false,
    isCollapse: false,
    breadcrumb: [],
    depotList: [], //仓库列表
    userInfo: JSON.parse(sessionStorage.getItem('User_info') as any) || {},
    UserDeptList: [],
    UserPostList: [],
    User_tokey: sessionStorage.getItem('User_tokey') || '',
    path: '',
    MenuList: [], // 保存原始菜单
    allBreadcrumbList: [], // 用作面包屑
    expandMenuList: [], // 扩展菜单属性
    flatMenu: [], // 扁平化的数组
    noticeTotal: 0,
    noticePage: 1,
    noticeList: []
  }),
  getters: {
    GET_isloading: state => state.isloading,
    GET_User_tokey: state => state.User_tokey,
    GET_Dept_List: state => state.UserDeptList,
    GET_isCollapse: state => state.isCollapse,
    GET_Breadcrumb: state => state.breadcrumb,
    GET_depotList: state => state.depotList,
    GET_User_Info: state => state.userInfo,
    GET_Menu_List: state => state.MenuList,
    GET_Flat_Menu: state => state.flatMenu,
    GET_AllBreadcrumbList: state => state.allBreadcrumbList
  },
  actions: {
    SET_isloading(payload: boolean) {
      if (typeof payload === 'boolean') {
        this.isloading = payload
      }
    },
    SET_User_Tokey(payload: string) {
      if (typeof payload === 'string') {
        this.User_tokey = payload
      }
    },
    SET_isCollapse() {
      this.isCollapse = !this.isCollapse
    },
    SET_depotList(list: DepotType[]) {
      this.depotList = [...list]
    },
    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
    },
    SET_NoticeList(list: NoticeType[], clear?: boolean) {
      if (Array.isArray(list)) {
        if (clear) this.noticeList = list
        else this.noticeList.push(...list)
      }
    },
    SET_NoticeTotal(num: number) {
      this.noticeTotal = num
    },
    SET_NoticePage(page?: number) {
      if (page) return (this.noticePage = page)
      this.noticePage++
    },
    async SET_User_Dept_List() {
      const res: any = await User_Dept_List()
      this.UserDeptList = res.Data
    },
    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)
        sessionStorage.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.expandMenuList = AddRouterMeta(res.Data.Data) // 扩展菜单属性
        // 添加上首页
        this.expandMenuList.unshift({
          Children: null,
          Id: 0,
          T_State: 1,
          T_permission: '/home',
          component: '/home/Home',
          meta: { icon: 'HomeFilled', title: '首页', isKeepAlive: true },
          name: 'home',
          path: '/home'
        })
        // 侧边栏
        this.SET_Flat_Menu(flatMenuListGet(this.expandMenuList)) // 接收扁平化菜单
        // 面包屑
        this.allBreadcrumbList = getAllBreadcrumbList(this.expandMenuList)
      }
    },
    /**
     * 获取消息通知
     */
    async SET_User_News_List(tag?: number) {
      const params = {
        User_tokey: this.User_tokey,
        T_Tag: tag,
        page: this.noticePage,
        page_z: 10
      }
      const res: any = await User_News_List(params)
      setTimeout(() => {
        this.SET_NoticeList(res.Data.Data)
      }, 100)
      this.SET_NoticeTotal(res.Data.Num)
    },
    /**
     * 获取仓库列表
     */
    async SET_Storehouse_Depot_List() {
      if (this.depotList.length) return
      const res: any = await Storehouse_Depot_List({ User_tokey: this.GET_User_tokey, page: 1, page_z: 999 })
      this.SET_depotList(res.Data.Data)
    }
  }
})

const pinia = createPinia()

export default pinia
