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

function initUserState() {
    const state = {
        // 用户信息
        headImgUrl: '',
        mobile: '',
        nickName: '',
        openId: '',
        userId: 0,
        userIdentity: -1, // 用户类型
        inviteUserId: '', // 分享者用户ID
        accessToken: '', // token
    }
    const userInfo = getStorage('USER_INFO')
    if (userInfo) {
        Object.assign(state, userInfo)
    }
    const accessToken = getStorage('ACCESS_TOKEN')
    if (accessToken) {
        state.accessToken = accessToken
    }
    return state
}

const state = initUserState()

console.log(state)

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

const actions = {
    // 微信自动登录
    async wxAutoLogin({ commit, state, dispatch }) {
        try {
            const code = await wxLogin() // 获取微信code
            const res = await wechatAuthLogin({ code }) // 微信自动登录
            const data = JSON.parse(res.data)
            commit('SET_USER_INFO', data)
            setStorage('USER_INFO', data)
            dispatch('getAccessToken') // 获取token
        } catch (e) {
            console.log(e)
        }
    },
    // 手机号注册登录
    async register({ commit }, resigterData) {
        try {
            const res = await mobileLogin(resigterData)
            const data = JSON.parse(res.data)
            commit('SET_USER_INFO', data)
            setStorage('USER_INFO', data)
        } catch (e) {
            console.log(e)
        }
    },
    // 获取accessToken
    async getAccessToken({ commit }) {
        try {
            const res = await getAccessToken()
            commit('SET_ACCESS_TOKEN', res.data)
            setStorage('ACCESS_TOKEN', res.data)
        } catch (e) {
            console.log(e)
        }
    }
}

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