// 用户数据模块
import http from '@/shopro/request/index'
import api from "@/shopro/request/index";
const state = {
	sessionkey: uni.getStorageSync("sessionkey") || "",
	userInfo: {}
	// token:""
}

const getters = {
	token: state => state.token,
	userInfo: state => state.userInfo
}

const actions = {
	/***获取用户信息
		无token 走获取用户信息接口。
		有token 走校验authcheck信息
	 */

	async getUserInfo({
		dispatch,
		commit,
		state
	}, code) {
		return new Promise((resolve, reject) => {
			let sessionStatus = false;
			uni.checkSession({ //校验session
				success(res) {
					if (res.errMsg === "checkSession:ok") sessionStatus = true;
				},
				complete() {
					let mallId = '106975910000477'
					uni.setStorageSync("mallId", mallId)
					if (uni.getStorageSync("sessionKey") && sessionStatus) {
						resolve(uni.getStorageSync("sessionKey"));
					} else {
						uni.login({
							success: function(info) {
								console.log("获取手机号======")
								console.log(info)
								let code = info.code;
								http('user.getHomePage', {
									code: code,
									mallId: mallId
								}).then(res => {
									if (!res.code) {
										let { sessionkey } = res.data
										uni.setStorageSync("sessionKey", sessionkey)
										commit('userInfo', res.data);
										let token = encodeURI(JSON.stringify(res.data))
										uni.setStorageSync("token", token)
										dispatch('authCheck')
										resolve(res)
									}
								})
							}
						})
					}
				}
			})
		})
	},
	// 校验接口过期
	authCheck({
		commit,
		dispatch,
		state
	}) {
		return new Promise((resolve, reject) => {
			let token = uni.getStorageSync('token');
			let mallId = uni.getStorageSync('mallId');
			if(token) {
				state.userInfo = JSON.parse(decodeURI(token))
				uni.setStorageSync("sessionKey",state.userInfo.sessionKey)
			}
			api("user.authCheck", {
				mallId: mallId
			}).then(res => {
				let data = res.data;
				if (res.code === 0) {
					resolve(res.code)
				} else if (res.code == 1001) {
					dispatch('getUserInfo')
				} else {
					reject(res.code)
				}
			});
		})
	},
	// // 获取用户信息
	// geAauthorizeWeRun({
	// 	commit,
	// 	dispatch,
	// 	getters,
	// 	state
	// }) {
	// 	//解密微信运动
	// 	uni.getWeRunData({
	// 		success: function(res) {
	// 			console.log(res)
	// 			wRunEncryptedData.encryptedData = res.encryptedData
	// 			wRunEncryptedData.iv = res.iv
	// 		}
	// 	})
	// },
}
const mutations = {
	token(state, payload) {
		state.token = payload;
		uni.setStorageSync("token", payload);
	},
	USER_INFO(state, info) {
		 commit("userInfo", info);
	}
}
export default {
	state,
	mutations,
	actions,
	getters
}
