import { apiBindingDistId } from '@/api/app'
import { getUserCenter } from '@/api/user'
import { DIST_ID, TOKEN_KEY, USER_INFO } from '@/enums/cacheEnums'
import cache from '@/utils/cache'
import { defineStore } from 'pinia'

interface UserSate {
    userInfo: Record<string, any>
    token: string | null
    temToken: string | null
    distId: number | null
}
export const useUserStore = defineStore({
    id: 'userStore',
    state: (): UserSate => ({
        userInfo: cache.get(USER_INFO) || {},
        token: cache.get(TOKEN_KEY) || null,
        temToken: null,
        distId: cache.get(DIST_ID) || null //分销id
    }),
    getters: {
        isLogin: (state) => !!state.token
    },
    actions: {
        async getUser() {
            if (this.token || this.temToken) {
                const data = await getUserCenter({
                    token: this.token || this.temToken
                })
                this.userInfo = data
                cache.set(USER_INFO, data)
            }
        },
        login(token: string) {
            this.token = token
            cache.set(TOKEN_KEY, token)
        },
        logout() {
            this.token = ''
            this.userInfo = {}
            this.distId = null
            cache.remove(TOKEN_KEY)
            cache.remove(USER_INFO)
            cache.remove(DIST_ID)
        },
        /**扫描分销码进来的用户 */
        setDistId(distId: number) {
            this.distId = distId
            cache.set(DIST_ID, distId)
        },
        /**绑定分销员id */
        async bindingDistId() {
            const params = {
                userId: this.userInfo.id,
                distributorId: this.distId
            }
            try {
                await apiBindingDistId(params)
            } catch (e) { }
        }

    }
})
