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: {
		token:uni.getStorageSync('token') || '',
		configList: {}, //配置列表
		userInfo : uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : {}, //用户信息
		riceInfo : {},//用户相关信息
		category : [],//分类信息
		payOrderProduct : [],//支付订单中的商品
	},
	getters: {
		userInfo:state => state.userInfo,
		isLogin:state=>state.token?true:false
	},
	mutations: {
		// 初始化配置
		initConfig(state){
			api('getConfig', res => {
				if(res.code == 200){
					res.result.forEach(n => {
						state.configList[n.keyName] = n.keyContent
					})
				}
			})
			
			// let config = ['getPrivacyPolicy', 'getUserAgreement']
			// config.forEach(k => {
			// 	api(k, res => {
			// 		if (res.code == 200) {
			// 			state.configList[k] = res.result
			// 		}
			// 	})
			// })
		},
		login(state,commit){
			uni.showLoading({
				title: '登录中...'
			})
			uni.login({
				success(res) {
					if(res.errMsg != "login:ok"){
						return
					}
					
					let data = {
						code : res.code
					}
					
					if(uni.getStorageSync('shareId')){
						data.shareId = uni.getStorageSync('shareId')
					}
					
					api('wxLogin', data, res => {
						
						uni.hideLoading()
						
						if(res.code != 200){
							return
						}
						state.userInfo = res.result.userInfo
						state.token = res.result.token
						uni.setStorageSync('token', res.result.token)
						if(!state.userInfo.nickName || !state.userInfo.headImage){
							uni.navigateTo({
								url: '/pages_login/wxUserInfo'
							})
						}else{
							uni.switchTab({
								url:'/pages/index/index'
							})
						}
					})
				}
			})
		},
		getUserInfo(state){
			api('getInfo', res => {
				if(res.code == 200){
					uni.setStorageSync('userInfo',JSON.stringify(res.result))
					state.userInfo = res.result
				}
			})
		},
		getRiceInfo(state){
			api('getRiceInfo', {
				token : uni.getStorageSync('token') || ''
			},res => {
				if(res.code == 200){
					state.riceInfo = res.result
				}
			})
		},
		// 退出登录
		logout(state){
			state.userInfo = {}
			state.role = false
			state.token = ""
			uni.removeStorageSync('token')
		},
		// 查询分类接口
		getCategoryList(state){
			api('getCategoryList', res => {
				if(res.code == 200){
					state.category = res.result
				}
			})
		},
		// 设置支付订单中的商品
		setPayOrderProduct(state, data){
			state.payOrderProduct = data
		},
	},
	actions: {},
})

export default store