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

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

import api from '@/api/api.js'
import Position from '@/utils/position.js'

//Vuex.Store 构造器选项
const store = new Vuex.Store({
	state: {
		configList: [], //配置列表
		shop : false,
		position : {//定位信息
			latitude : 0,
			longitude : 0,
		},
		userInfo : {},//用户信息
	},
	getters: {
		// 角色 true为水洗店 false为酒店
		userShop(state){
			return state.shop
		}
	},
	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: '登录中...'
			})
			
			uni.login({
				success(res) {
					if(res.errMsg != "login:ok"){
						return
					}
					
					api('wxLogin', {
						code : res.code,
						latitude : state.position.latitude,
						longitude : state.position.longitude,
					}, 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_order/auth/wxUserInfo'
							})
						}else{
							uni.navigateBack(-1)
						}
					})
				}
			})
		},
		getUserInfo(state){
			api('getInfo', res => {
				if(res.code == 200){
					state.userInfo = res.result
				}
			})
		},
		getPosition(state){
			Position.getLocation(res => {
				console.log(res);
				state.position = res
			})
		},
	},
	actions: {},
})

export default store