import type { UserType, ProjectType, OrganizationType, RoleType, PermissionType } from '@/types'
import { defineStore } from 'pinia'
import { getUser, logout, checkDataStatus, getAuth } from '@/api/base'
import { useMapStore } from '@/stores/map'

// 角色信息(1学员；5教师; 6管理员)
interface Role {
  id: 1 | 5 | 6
  name: string
}
interface State {
  user: UserType | null
  role: Role | null
  project: ProjectType | null
  organization: OrganizationType | null
  roles: RoleType[]
  permissions: PermissionType[]
  status: any
  menus: Menu[]
}

interface Menu {
  id: number
  name: string
  pid: number
}

export const useUserStore = defineStore({
  id: 'user',
  state: (): State => ({
    user: null,
    role: null,
    organization: null,
    project: null,
    roles: [],
    permissions: [],
    status: {},
    menus: [],
  }),
  getters: {
    isLogin: (state) => !!state.user,
  },
  actions: {
    async getUser() {
      const res = await getUser()
      const { info, role } = res.data
      const { organization, project, roles = [], permissions = [] } = res.data.permissions || {}
      this.user = info
      this.role = role
      this.organization = organization
      this.project = project
      this.roles = roles
      this.permissions = permissions
      await useMapStore().getMapList()
      await checkDataStatus().then((res) => {
        this.status = res.data
      })
      await getAuth().then((res) => {
        this.menus = res.data.items || []
      })
    },
    async logout() {
      await logout()
      this.user = null
    },
  },
})
