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 : {}, //用户信息
		role : '0', // 当前角色：0-用户/泵司，1-企业，2-员工，3-区域管理员
		roleOptions: [
			{ value: '0', label: '用户/泵司' },
			{ value: '1', label: '企业用户' },
			{ value: '2', label: '员工' },
			{ value: '3', label: '区域管理员' }
		],
	},
	getters: {
		// 获取当前角色文本
		currentRoleText: (state) => {
			const role = state.roleOptions.find(r => r.value === state.role);
			return role ? role.label : '用户/泵司';
		},
		// 获取角色选项
		getRoleOptions: (state) => {
			return state.roleOptions;
		}
	},
	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
				}
			})
		},
		// 切换角色
		switchRole(state, roleValue) {
			state.role = roleValue;
			uni.setStorageSync('role', roleValue);
			// 触发全局事件通知角色变更
			uni.$emit('roleChanged', roleValue);
		},
		// 初始化角色
		initRole(state) {
			const savedRole = uni.getStorageSync('role');
			if (savedRole) {
				state.role = savedRole;
			}
		},
		// 退出登录
		logout(state){
			uni.showModal({
				title: '确认退出登录吗',
				success(r) {
					if(r.confirm){
						state.userInfo = {}
						state.role = '0'
						uni.removeStorageSync('token')
						uni.removeStorageSync('role')
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}
				}
			})
		},
	},
	actions: {},
})

export default store