import {
  fetchUser,
  fetchUserMeta,
  postLogin,
  postLogout,
  setToken,
  delToken,
  fetchUserRoleOptions
} from '@/api'
import { transformNames } from './roles'
import { defineStore } from 'pinia'

import type { User, UserMeta, LoginState } from '@/api'
import { RoutesName } from '@/router'
import { ui18n } from '@/lang'

export const LeastMenus = [RoutesName.projects, RoutesName.login]

const defState = {
  current: {
    nickname: ui18n.t('sys.unLoginName'),
    phone: '',
    email: '',
    avatar: 'https://4dkk.4dage.com/head/18819272208/head_1662022947583.png'
  } as User,
  meta: {
    projectCount: 0,
    projectFileCount: 0,
    projectSceneCount: 0,
    projectOverCount: 0
  } as UserMeta,
  roleMenus: LeastMenus
}

const userRolesStorage = localStorage.getItem('user-roles')
if (userRolesStorage) {
  try {
    defState.roleMenus = JSON.parse(userRolesStorage)
  } catch {}
}

export const useUserStore = defineStore('user', {
  state: () => defState,
  actions: {
    async fetchRoles() {
      const options = await fetchUserRoleOptions()
      this.roleMenus = Array.from(
        new Set([...LeastMenus, ...transformNames(options)])
      )
      localStorage.setItem('user-roles', JSON.stringify(this.roleMenus))
    },
    async fetchUser() {
      this.current = await fetchUser()
      await this.fetchRoles()
    },
    async fetchMeta() {
      this.meta = await fetchUserMeta()
    },
    fetch() {
      return Promise.all([this.fetchUser(), this.fetchMeta()])
    },
    async login(state: LoginState) {
      const { token, user } = await postLogin({
        phone: state.phone,
        password: state.password
      })
      this.current = user
      setToken(token)
      await this.fetchRoles()
    },
    async logout() {
      await postLogout()
      this.$state = defState
      delToken()
    }
  }
})
