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

Vue.use(Vuex); //vue的插件机制

import api from '@/api/api.js'

//Vuex.Store 构造器选项
const store = new Vuex.Store({
	state: {
		configList: {}, //配置对象
		userInfo : {},
	},
	getters: {},
	mutations: {
		// 初始化配置
		initConfig(state) {
			let config = ['preferential', 'wx']
			config.forEach(k => {
				api('getConfig', {
					keyValue : k
				}, res => {
					if (res.code == 200) {
						state.configList[k] = res.result
					}
				})
			})
		},
		login(state) {
			uni.login({
				success(res) {
					if (res.errMsg != "login:ok") {
						return
					}
					api('loginLogin', {
						code: res.code
					}, res => {
						if (res.code != 200) {
							return
						}

						state.userInfo = res.result.userInfo
						uni.setStorageSync('token', res.result.token)

						if (!state.userInfo.nickName || !state.userInfo.headImage) {
							uni.navigateTo({
								url: '/pages/login/wxUserInfo'
							})
						}
					})
				},
				fail(err) {
					console.error(err)
				}
			})
		},
		getUserInfo(state) {
			api('infoGetInfo', res => {
				if(res.code == 200){
					state.userInfo = res.result
				}
			})
		},
	},
	actions: {},
})

export default store