import Vue from 'vue'
import Vuex from 'vuex'
import request from '@/common/request'

Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		hasLogin: false,
		jwt: uni.getStorageSync('jwt'),
		user: {}
	},
	// getters
	getters: {
		// 获取token值
		getJwt: state => {
			return state.jwt;
		},
		// 验证是否有token
		verifyJwt: state => {
			if (state.jwt) {
				state.hasLogin = true;
				return true
			}
			return false;
		}
	},
	mutations: {
		setJwt(state, jwt) {
			state.jwt = jwt;
			uni.setStorageSync('jwt', state.jwt);
		},
		login(state) {
			state.hasLogin = true;
			try {
				uni.setStorageSync('jwt', state.jwt);
			} catch (e) {
				// error
			}
		},
		logout(state) {
			state.hasLogin = false
			state.user = {};
			state.jwt = '';
			uni.removeStorage({
				key: 'jwt',
				success: function(res) {}
			});
		},
		setUser(state, user) {
			state.user = user
		}
	},
	actions: {
		// lazy loading openid
		getUser: async function({
			commit,
			state
		}, refresh) {
			return await new Promise((resolve, reject) => {
				if (refresh != true && state.user && Object.keys(state.user).length > 0) {
					resolve(state.user)
				} else {
					request.get("/api/user/userInfo", {}, false).then(data => {
						if (data.code == 200) {
							commit('setUser', data.data)
							resolve(data.data)
						} else {
							resolve(null)
						}
					}).catch((err) => {
						console.info(err)
						reject(err);
					});
				}
			})
		}
	}
})

export default store
