import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		hasLogin: false,
		loginProvider: "",
		userInfo: {tplName:''},
	},
	mutations: {
		doLogin(state, payload) {
// 			console.log("====="+JSON.stringify(state));
// 			console.log("-----"+JSON.stringify(payload));
// 			console.log("pppp="+payload.userInfo);
			state.hasLogin = true;
			state.loginProvider = payload.provider;
			state.userInfo = payload.userInfo;
			
			
		},
		logout(state) {
			state.hasLogin = false
			state.userInfo = null
			
			
		},
		setOpenid(state, userInfo) {
			state.userInfo = userInfo
		}
	},
	actions: {
		// lazy loading openid
		getUserOpenId: async function ({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.userInfo) {
					resolve(state.userInfo)
				} else {
					uni.login({
						success: (data) => {
							commit('login')
							console.log(JSON.stringify(data))
							setTimeout(function () { //模拟异步请求服务器获取 openid
								const openid = '123456789'
								console.log('uni.request mock openid[' + openid + ']');
								commit('setOpenid', openid)
								resolve(openid)
							}, 1000)
						},
						fail: (err) => {
							console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
							reject(err)
						}
					})
				}
			})
		}
	}
})

export default store
