import Vue from 'vue'
import Vuex from 'vuex'
import {
	loginByOpenid
} from '@/api/index'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		token: uni.getStorageSync("token") || '',
		userInfo: {},
	},
	mutations: {
		setToken(state, token) {
			state.token = token;
			uni.setStorageSync("token", token)
		},
		setUserInfo(state, userInfo) {
			console.log(userInfo);
			state.token = userInfo.openId;
			uni.setStorageSync("token", userInfo.openId);
			state.userInfo = userInfo;
		},
	},
	actions: {
		async getUserInfo({
			commit,
			state
		}) {
			if(!state.token) {
				return
			}
			const res = await loginByOpenid({openid: state.token})
			if(res.success) {
				commit('setUserInfo', res.data);
			} else {
				commit('setToken', '')
			}
		}
	}
})

export default store
