import type { UserType, ProjectType, OrganizationType, RoleType, PermissionType } from '@/types'
import { defineStore } from 'pinia'
import { getUser, logout } 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[]
}

export const useUserStore = defineStore('user', {
  state: (): State => ({
    user: null,
    role: null,
    organization: null,
    project: null,
    roles: [],
    permissions: [],
  }),
  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()
    },
    async logout() {
      await logout()
      this.user = null
    },
  },
})
