import storage from '@/utils/storage'
import constant from '@/utils/constant'
import {
	getInfo,
	login,
	logout
} from '@/api/login'
import {
	getIsLogin,
	getToken,
	removeToken,
	setIsLogin,
	setToken
} from '@/utils/auth'
import {
	currentUrl
} from '@/utils/getUrl'
import {
	wxLogin
} from "../../api/system/user";
import {
	getbaseInfo
} from "@/api/home.js"

const baseUrl = currentUrl
const user = {
	state: {
		accessToken: uni.getStorageSync("token") || "",
		userInfo: uni.getStorageSync("baseInfo") ? JSON.parse(uni.getStorageSync("baseInfo")) : {}
	},

	mutations: {
		// 设置token
		setAccessToken(state, token) {
			state.accessToken = token;
		},

		// 设置用户信息
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo;
		}
	},

	actions: {
		login(context, loading) {
			
			let success = function(){}
			let error = function(){}
			let promise = new Promise((s, e) => {
				success = s
				error = e
			})
			
			uni.login({
				success: (res) => {
					const code = res.code
					
					if(loading){
						uni.showLoading({
							mask : true
						});
					}
					
					wxLogin({
						code
					}).then(res => {
						if (res.code === 200) {
							uni.setStorageSync("token", res.data.token)
							uni.setStorageSync("baseInfo", JSON.stringify(res.data.userInfo))
							context.commit('setAccessToken', res.data.token);
							context.commit('setUserInfo', res.data.userInfo);
							setIsLogin(true);
							uni.hideLoading();
							success(res)
							
							// if(loading){
								if (!res.data.userInfo.userName || !res.data.userInfo.userImage || !
									res.data.userInfo.userTelephone) {
									uni.navigateTo({
										url: "/pages/login/wxUserInfo"
									})
								} else {
									uni.navigateBack(-1)
								}
							// }
							
						}
					})
				}
			})
			
			return promise
		},

		// 已登录的情况下调用接口获取用户信息，保证用户信息的实时更新
		async getUserInfo({
			commit,
			state
		}) {
			if (getIsLogin() && state.userInfo.userId) {
				const response = await getbaseInfo(state.userInfo.userId);
				if (response.code == 200) {
					commit("setUserInfo", response.data);
					uni.setStorageSync("baseInfo", JSON.stringify(response.data))
				}
			}
		}
	}
}

export default user