import { wechatAuthLogin, mobileLogin } from '@/services/api/auth.js'
import { wxLogin } from '@/common/auth.js'
import { setStorage } from '@/common/storage.js'
import { objAssign } from '@/common/utils.js'

const state = {
    // 用户信息
    headImgUrl: '',
    mobile: '',
    nickName: '',
    openId: 'oFFip5SgfBKMHxgZLInIBTHdPGuk',
    userId: 0,
    userIdentity: -1, // 用户类型
    inviteUserId: '' // 分享者用户ID
}

const mutations = {
    SET_USER_INFO: (state, userInfo) => {
        objAssign(state, userInfo)
    },
    SET_INVITE_USER_ID: (state, id) => {
        state.inviteUserId = id
    }
}

const actions = {
    // 微信自动登录
    async wxAutoLogin({ commit }) {
        try {
            const code = await wxLogin()
            const res = await wechatAuthLogin({ code })
            const data = JSON.parse(res.data)
            commit('SET_USER_INFO', data)
            setStorage('USER_INFO', data)
            return Promise.resolve(data)
        } catch (e) {
            console.log(e)
            return Promise.reject(e)
        }
    },
    // 手机号注册登录
    async register({ commit }, resigterData) {
        try {
            const res = await mobileLogin(resigterData)
            // return Promise.resolve(data) TODO
            console.log(res)
        } catch (e) {
            console.log(e)
            return Promise.reject(e)
        }
    },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
