import { defineStore } from 'pinia'
import { store } from '/@/store'
import { getAuthCache, setAuthCache } from '@/utils/auth'
import { TOKEN_KEY, USER_INFO_KEY } from '@/enums/cacheEnum'
import type { defs } from '@/api/services'
import Navigate from '@/utils/page/navigate'

export type UserInfo = Partial<defs.UserInfo>

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 = getAuthCache(TOKEN_KEY)
            if (token) {
                this.token = token
                return token
            }
        },
        getUserInfo(): Nullable<UserInfo> {
            if (this.userInfo) {
                return this.userInfo
            }

            const info = getAuthCache(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?.mobile === '10000000001'
        },
    },
    actions: {
        setToken(token: string) {
            this.token = token
            setAuthCache(TOKEN_KEY, token)
        },
        setUserInfo(info: UserInfo) {
            this.userInfo = info
            setAuthCache(USER_INFO_KEY, info ? JSON.stringify(info) : null)
        },
        async logout() {
            if (this.loading) {
                return
            }

            this.loading = true
            try {
                await API.auth.logout.request()
            } 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.userView.getUserInfo.request()
                this.setUserInfo(userInfo)
            } finally {
                this.loading = false
            }
        },
    },
})

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