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

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

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

//Vuex.Store 构造器选项
const store = new Vuex.Store({
	state: {
		configList: {}, //配置列表
		shop : false,//身份判断如果不需要，可以删除
		userInfo : {}, //用户信息
		commonQuestion: {},
	},
	getters: {
		// 角色 true为水洗店 false为酒店 ： 身份判断如果不需要，可以删除
		userShop(state){
			return state.shop
		}
	},
	mutations: {
		// 初始化配置
		async initConfig(state){
			const records = (await fetch('getConfig'))?.records
			const configList = {
				...state.configList,
			}

			records.forEach(n => {
				configList[n.paramCode] = n.paramImage || n.paramText || n.paramTextarea;
			});

			state.configList = configList

			uni.$emit('initConfig', state.configList)
			
		},
		// 微信登录
		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: '确认退出登录吗',
				success(r) {
					if(r.confirm){
						state.userInfo = {}
						state.role = false
						uni.removeStorageSync('token')
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}
				}
			})
		},
		setCommonQuestion(state, data) {
			state.commonQuestion = data
		},
	},
	actions: {},
})

export default store