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: {}, //配置列表
		shop : false,//身份判断如果不需要，可以删除
		userInfo : {}, //用户信息
		payOrderProduct: [], //支付订单中的商品applyServiceProduct
		applyServiceProduct: [], // 售后服务商品
		addressInfo: null,
	},
	getters: {
		// 角色 true为水洗店 false为酒店 ： 身份判断如果不需要，可以删除
		userShop(state){
			return state.shop
		}
	},
	mutations: {
		// 初始化配置
		initConfig(state){
			api('getConfig', res => {
				const configList = {
					...state.configList,
				}
				if (res.code == 200) {
					res.result.forEach(n => {
						configList[n.keyName] = n.keyContent;
						configList[n.keyName + '_keyValue'] = n.keyValue;
					});
				}
				state.configList = configList
				uni.$emit('initConfig', state.configList)
			})
			
			// 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
					}, 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
				}
			})
		},
		// 退出登录
		logout(state){
			uni.showModal({
				title: '退出登录',
				content: '确认要退出登录吗',
				cancelColor: '#393939',
				confirmColor: '#7451DE',
				success(r) {
					if(r.confirm){
						state.userInfo = {}
						state.role = false
						uni.removeStorageSync('token')
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}
				}
			})
		},
		addCart(state, data) {
			// todo: fetch

			console.log('addCart', data)

		},
		setAddressInfo(state, data) {
			state.addressInfo = data
		},
		// 设置支付订单中的商品
		setPayOrderProduct(state, data) {
			state.payOrderProduct = data
		},
		createOrder(state, data) {
			
			state.payOrderProduct = data

			// todo: create order

			uni.navigateTo({
				url: '/pages_order/order/orderConfirm/index'
			})
		},
		setApplyServiceProduct(state, data) {
			state.applyServiceProduct = data
		},
	},
	actions: {},
})

export default store