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

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

export const useUserStore = defineStore({
  id: '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
    },
    async logout() {
      await logout()
      this.user = null
    }
  }
})
