// 用户数据模块
import http from '@/common/request/index'
import store from '@/common/store'
import tools from '@/common/utils/tools'
import wechat from '@/common/wechat/wechat'
import share from '@/common/share'

const state = {
	token: uni.getStorageSync("token") || "",
	isLogin: uni.getStorageSync("isLogin") || false, // 是否登陆
	userInfo: uni.getStorageSync("userInfo") || {}, // 用户信息
	userData: {}, //用户其他相关数据
	subscribeMessageIdsMap: [], //小程序订阅消息模板ids
	authType: '', // smsLogin:手机号登录注册, accountLogin:密码登录, forgotPwd:忘记密码, changePwd:修改密码, bindMobile:绑定手机号
	tabbarList: []
}

const getters = {
	token: state => state.token,
	isLogin: state => state.isLogin,
	userInfo: state => state.userInfo,
	authType: state => state.authType,
	userData: state => state.userData,
	tabbarList: state => state.tabbarList,
	subscribeMessageIdsMap: state => state.subscribeMessageIdsMap
}

const actions = {
	// 获取用户信息
	getUserInfo({
		commit,
		dispatch,
		getters,
		state
	}, token = '') {
		return new Promise((resolve, reject) => {
			console.log(token);
			token && uni.setStorageSync('token', token);
			http('user.info').then(res => {
					// console.log(res);
					if (res.code === 0) {
						let lastLoginStatus = getters.isLogin;
						commit('userInfo', res.data);
						commit('isLogin', true);
						!lastLoginStatus && share.setShareInfo();
						// 存在分享信息 添加分享记录
						let spm = uni.getStorageSync('spm');
						if (spm) {
							http('commission.addTeam', {
								spm: spm
							});
							uni.removeStorageSync('spm');
						}
						resolve(res.data)
					}
				}).then(() => {
					// uni.showModal({
					// 	title:'提示',
					// 	content:'账号已被锁定，请联系管理员',
					// 	showCancel:false,
					// 	confirmText:'确定',
					// 	confirmColor:'#00e699'
					// })
					// 只有在登录的时候请求购物车信息，订单信息，获取登录信息之后。
					// token && dispatch('getCartList');
					// console.log('sss');
					// dispatch('tabbarInit');
					token && dispatch('getUserData');
					// dispatch('getMember');
				})
				.catch(e => {
					reject(e)
				})
		})
	},
	// 用户其他相关信息
	getUserData({
		commit
	}) {
		return new Promise((resolve, reject) => {
			http('user.userData').then(res => {
				commit('USER_DATA', res.data);
				resolve(res)
			}).catch(e => {
				reject(e)
			})
		})
	},

	// 自动登录
	async autoLogin({
		getters,
		dispatch
	}) {
		// console.log('s')
		if (getters.initWechat?.autologin && !getters.isLogin) { // 微信开启自动登录 并且当前未登录，进入自动登录流程
			let token = '';
			// #ifdef H5
			// wechat.login();
			// #endif
			// #ifdef MP-WEIXIN
			token = await wechat.getWxMiniProgramSessionKey(true);
			// #endif
			token && await dispatch('getUserInfo', token);
		} else if (getters.isLogin) { // 已经登录，直接获取用户信息
			await dispatch('getUserInfo');
		}
		share.setShareInfo();
		// 初始化小程序session_key
		// #ifdef MP-WEIXIN
		if (!getters.initWechat?.autologin) {
			await wechat.getWxMiniProgramSessionKey(false);
		}
		// #endif
	},

	// 退出登录
	logout({
		commit,
		dispatch
	}) {
		uni.getStorageSync('token');
		commit('token', "");
		uni.removeStorageSync('chatSessionId');
		commit('isLogin', false);
		commit('userInfo', {});
		commit('USER_DATA', {});
		// 重置全局分享信息
		share.setShareInfo();
	},

	// 获取订阅消息模板ids;
	getMessageIds({
		commit,
		state
	}) {
		http('conf.getGroupConf', {
			group: 'system.notification'
		}).then(res => {
			commit('formatMessage', res.data)
			Promise.resolve(res.data)
		}).catch(e => {
			Promise.reject(e)
		})

	},
}

const mutations = {
	token(state, payload) {
		state.token = payload;
		uni.setStorageSync("token", payload);
	},
	// 登录态
	isLogin(state, data) {
		state.isLogin = data;
		uni.setStorageSync('isLogin', data);
	},
	// 用户信息
	userInfo(state, data) {
		state.userInfo = data;
		uni.setStorageSync("userInfo", data);
	},
	// 小程序订阅消息模板ids
	MESSAGE_IDS(state, data) {
		state.subscribeMessageIds = data;
	},
	USER_DATA(state, data) {
		state.userData = data;
		uni.setStorageSync("userData", data);
	},
	AUTH_TYPE(state, data) {
		data ? uni.hideTabBar() : uni.showTabBar();
		state.authType = data;
	},
	// 订阅消息
	subscribeMessage(state, type) {
		let arr = state.subscribeMessageIdsMap[type];
		arr.length && uni.requestSubscribeMessage({
			tmplIds: arr,
			success: (res) => {
				// console.log(res);
			},
			fail: (err) => {
				// console.log(err);
			}

		});
	},

	// 解析订阅消息数据
	formatMessage(state, messageIdsObj) {
		// 各场景下用到的订阅模板
		let typeMap = {
			'unread_msg': ['pay_suc', 'examine_result', 'company_examine'],
			// 'order':['pay_suc','recommend','new_video']
		}
		let idsMap = {}
		Object.keys(typeMap).forEach(key => {
			idsMap[key] = []
			typeMap[key].forEach(item => {
				idsMap[key].push(messageIdsObj[item])
			})
		})
		state.subscribeMessageIdsMap = idsMap
	},
}



export default {
	state,
	mutations,
	actions,
	getters
}