import * as types from '../mutation-types.js'
import auth from '../../service/auth'
import common from '../../common/js/common'

const _userInfo = common.castEval(localStorage.getItem('USERINFO') || '{}')

const state = {
    userInfo: _userInfo || {},
    uid: '',
    token: ''
}

// getters
const getters = {
    getUserInfo(state) {
        console.log('state.userInfo', state.userInfo)
        return state.userInfo
    }
}

// actions
const actions = {
    setUserInfo({ commit }, userInfo) {
        commit(types.SET_USER_INFO, userInfo)
    },
    setUid({ commit }, uid) {
        commit(types.SET_UID, uid)
    },
    setToken({ commit }, token) {
        commit(types.SET_TOKEN, token)
    },
    removeUserInfo({ commit }) {
        commit(types.REMOVE_USER_INFO)
    },
    login({ commit }, userInfo) {
        commit(types.SET_USER_INFO, userInfo.user)
        commit(types.SET_UID, userInfo.uid)
        commit(types.SET_TOKEN, userInfo.token)

        console.log('login...')
        // console.log('login...', userInfo)
        if (auth.getUserType() === auth.TYPE_BIZ || auth.getUserType() === auth.TYPE_PERSON_BIZ) {
            auth.setBiz(userInfo.biz)
        } else {
            auth.removeBiz()
        }

        auth.setUser(userInfo.user)
        auth.setToken(userInfo.token)
    },
    // remove token
    logout({ commit }) {
        console.log('logout...')
        return new Promise(resolve => {
            commit(types.REMOVE_USER_INFO)
            auth.removeUser()
            auth.removeToken()
            resolve()
        })
    }
}

// mutations
const mutations = {
    SET_USER_INFO(state, userInfo) {
        state.userInfo = userInfo
    },
    REMOVE_USER_INFO(state) {
        state.userInfo = {}
        state.uid = ''
        state.token = ''
    },
    SET_UID(state, uid) {
        state.uid = uid
    },
    SET_TOKEN(state, token) {
        state.token = token
    }
}

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