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 : {}, //用户信息
		teamList : [],//团队列表
		authInfo : {},//实名认证信息
		position : {
			status : 0,//0正在定位中 1定位成功 2定位失败
			latitude: 39.909,
			longitude: 116.39742,
		},//定位信息
	},
	getters: {
		
	},
	mutations: {
		// 初始化配置
		initConfig(state){
			// api('getConfig', res => {
			// 	if(res.code == 200){
			// 		state.configList = res.result
			// 	}
			// })
			
			let config = ['getPrivacyPolicy', 'getUserAgreement']
			config.forEach(k => {
				api(k, res => {
					if (res.code == 200) {
						state.configList[k] = res.result
					}
				})
			})
		},
		login(state){
			uni.showLoading({
				title: '登录中...'
			})
			let self = this
			uni.login({
				success(res) {
					if(res.errMsg != "login:ok"){
						return
					}
					
					api('wxLogin', {
						code : res.code
					}, res => {
						
						uni.hideLoading()
						
						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'
							})
						}else{
							self.commit('getUserInfo')
							uni.navigateBack(-1)
						}
					})
				}
			})
		},
		logout(state){
			uni.showModal({
				title: '确认退出登录吗',
				success(r) {
					if(r.confirm){
						state.userInfo = {}
						state.role = false
						uni.removeStorageSync('token')
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}
				}
			})
		},
		getUserInfo(state){
			api('getInfo', res => {
				if(res.code == 200){
					state.userInfo = res.result
					
					if(!state.userInfo.nickName || !state.userInfo.headImage){
						uni.navigateTo({
							url: '/pages/login/wxUserInfo'
						})
					}else if(!state.userInfo.team){
						uni.navigateTo({
							url: "/pages/subPack/team/team"
						})
					}else if(!state.userInfo.auth){
						uni.navigateTo({
							url: "/pages/subPack/autonym/autonym"
						})
					}
				}
			})
		},
		getTeam(state){
			api('teamList', res => {
				if(res.code == 200){
					state.teamList = res.result
				}
			})
		},
		setAuthInfo(state, data){
			state.authInfo = data
		},
		getLocation(state){
			uni.getLocation({
				type: 'gcj02',
				success: function(res) {
					state.position.status = 1;
					state.position.longitude = res.longitude;
					state.position.latitude = res.latitude;
				},
				fail() {
					state.position.status = 2;
				}
			});
		},
	},
	actions: {},
})

export default store