import config from '@/config' import storage from '@/utils/storage' import constant from '@/utils/constant' import { login, appUserLoginByCode} from '@/api/login' import { getToken, setToken, removeToken } from '@/utils/auth' const baseUrl = config.baseUrl const user = { state: { token: getToken(), userId:storage.get(constant.userId), userName: storage.get(constant.userName), phone: storage.get(constant.phone), pd: storage.get(constant.pd), isFirstLogin:storage.get(constant.isFirstLogin), }, mutations: { SET_TOKEN: (state, token) => { state.token = token }, SET_USERID: (state, userId) => { state.userId = userId storage.set(constant.userId, userId) }, SET_USERNAME: (state, userName) => { state.userName = userName storage.set(constant.userName, userName) }, SET_PHONE: (state, phone) => { state.phone = phone storage.set(constant.phone, phone) }, SET_PD: (state, pd) => { state.pd = pd storage.set(constant.pd, pd) }, SET_IS_FIRST_LOGIN: (state, isFirstLogin) => { state.isFirstLogin = isFirstLogin storage.set(constant.isFirstLogin, isFirstLogin) }, }, actions: { // 登录 Login({ commit }, userInfo) { const phone = userInfo.phone.trim() const pd = userInfo.pd commit('SET_PD', pd) return new Promise((resolve, reject) => { login(phone, pd).then(res => { setToken(res.data.token) commit('SET_TOKEN', res.data.token) const user = res.data.user commit('SET_USERID', user.id) commit('SET_USERNAME', user.username) commit('SET_PHONE', user.phone) commit('SET_IS_FIRST_LOGIN', user.isFirstLogin) resolve(res) }).catch(error => { reject(error) }) }) }, // 验证码登录 LoginCode({ commit }, userInfo) { const phone = userInfo.phone.trim() const code = userInfo.code return new Promise((resolve, reject) => { appUserLoginByCode(phone, code).then(res => { setToken(res.data.token) commit('SET_TOKEN', res.data.token) const user = res.data.user commit('SET_USERID', user.id) commit('SET_USERNAME', user.username) commit('SET_PHONE', user.phone) commit('SET_IS_FIRST_LOGIN', user.isFirstLogin) resolve(res) }).catch(error => { reject(error) }) }) }, // 退出系统 LogOut({ commit, state }) { return new Promise((resolve, reject) => { commit('SET_TOKEN', '') removeToken() storage.clean() resolve() }) } } } export default user