import { defineStore } from 'pinia'
import { store } from '/@/store'
import { Storage } from '@/utils/storage'
import { TOKEN_KEY, USER_INFO_KEY } from '@/enums/cacheEnum'
import Navigate from '@/utils/page/navigate'
import * as API from '/@/api/model/userInfo'

export interface UserInfo {
    id: string
    phone: string
    avatar: string
    realname: string
}

interface UserState {
    userInfo: Nullable<UserInfo>
    token?: string
    loading?: boolean
}

export const useUserStore = defineStore({
    id: 'app-user',
    state: (): UserState => ({
        token: null,
        userInfo: null,
        loading: false,
    }),
    getters: {
        getToken(): Nullable<string> {
            if (this.token) {
                return this.token
            }

            const token = Storage.get(TOKEN_KEY)
            if (token) {
                this.token = token
                return token
            }
        },
        getUserInfo(): Nullable<UserInfo> {
            if (this.userInfo) {
                return this.userInfo
            }

            const info = Storage.get(USER_INFO_KEY)
            if (info) {
                const userInfo = JSON.parse(info) as UserInfo
                this.userInfo = userInfo
                return userInfo
            }

            return null
        },
        /**
         * @returns 是否为审核账号
         */
        isAuditMode(): boolean {
            return this.getUserInfo?.phone === '10000000001'
        },
    },
    actions: {
        setToken(token: string) {
            this.token = token
            Storage.set(TOKEN_KEY, token)
        },
        setUserInfo(info: UserInfo) {
            this.userInfo = info
            Storage.set(USER_INFO_KEY, info ? JSON.stringify(info) : null)
        },
        async logout() {
            if (this.loading) {
                return
            }

            this.loading = true
            try {
                await API.logout()
            } finally {
                this.setToken(null)
                this.setUserInfo(null)
                await Navigate.to('/pages/login/login')
                this.loading = false
            }
        },
        async refreshUserInfo() {
            if (this.loading) {
                return
            }

            this.loading = true
            try {
                const userInfo = await API.getUserInfo()
                this.setUserInfo(userInfo)
            } finally {
                this.loading = false
            }
        },
    },
})

// Need to be used outside the setup
export function useUserStoreWithOut() {
    return useUserStore(store)
}
