import { defineStore } from 'pinia'
import { store } from '/@/store'
import { useDictStore } from './dict'
import { Storage } from '@/utils/storage'
import { TOKEN_KEY, USER_INFO_KEY } from '@/enums/cacheEnum'
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
            }

            return null
        },
        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 ['10000000001', '13000000000', '13312345678'].includes(this.getUserInfo?.phone)
        },
    },
    actions: {
        setToken(token: string) {
            this.token = token
            if (!token) {
                Storage.remove(TOKEN_KEY)
            } else {
                Storage.set(TOKEN_KEY, token)
            }
        },
        setUserInfo(info: UserInfo) {
            this.userInfo = info
            if (!info) {
                Storage.remove(USER_INFO_KEY)
            } else {
                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)

                // 清空字典数据
                const dictStore = useDictStore(store)
                dictStore.clearDict()

                this.loading = false
                uni.reLaunch({
                    url: '/pages/login/login',
                })
            }
        },
        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)
}
