import { login, logout } from '@/api/module/user'
import { LoginData } from '@/api/types'
import { request } from '@/api/request'
import { clearToken, setToken } from '@/utils/auth'
import { removeRouteListener } from '@/utils/route-listener'
import { defineStore } from 'pinia'
import SafeStorage, { AppStorageKey } from "@/utils/safeStorage";
import useAppStore from '../app'
import { UserState } from './types'

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    name: undefined,
    avatar: undefined,
    job: undefined,
    organization: undefined,
    location: undefined,
    email: undefined,
    introduction: undefined,
    personalWebsite: undefined,
    jobName: undefined,
    organizationName: undefined,
    locationName: undefined,
    phone: undefined,
    registrationDate: undefined,
    accountId: undefined,
    certification: undefined,
    role: '',
    userInfo: SafeStorage.get(AppStorageKey.USER_INFO)
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state }
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user'
        resolve(this.role)
      })
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial)
    },

    // Reset user's information
    resetInfo() {
      this.$reset()
    },

    // Get user's information
    async info() {
      // const res = await request.post('/rbac2/v1/user/info') as any
      // request 拦截器已经返回 response.data，所以 res 就是用户信息
      // this.setInfo(res.data || res)
    },

    // Login
    async login(loginForm: LoginData) {
      try {
        const { code, details } = await login(loginForm as any) as any
        if (code === 0 && details?.token) {
          setToken(details.token)
          SafeStorage.set(AppStorageKey.USER_INFO, details)
          this.userInfo = details
        } else {
          throw new Error('登录失败')
        }
      } catch (err) {
        clearToken()
        throw err
      }
    },
    logoutCallBack() {
      const appStore = useAppStore()
      this.resetInfo()
      clearToken()
      removeRouteListener()
      appStore.clearServerMenu()
      SafeStorage.clearAppStorage()
    },
    // Logout
    async logout() {
      try {
        // await logout()
      } finally {
        this.logoutCallBack()
      }
    },
  },
})

export default useUserStore
