import wxApp from "./wecaht.min.app.js";
import request from "@/utils/http.js";
let token = null;
let requestLoginTime = 0;

// 获取token
export const getToken = async () => {
	// console.log("token-000000000000000000",getToken.promise);
	if (!token) token = uni.getStorageSync('token');
	// token格式化
	if (token && typeof token === "string") {
		token = JSON.parse(token);
	}
	// console.log("token-1111111111111",token);
	console.log("checkToken", checkToken(token));
	if (!token) {
		getToken.promise = login();
	} else if (checkToken(token)) {
		return Promise.resolve(token.token);
	} else {
		getToken.promise = refreshToken();
	}

	getToken.promise = getToken.promise
		.finally(() => {
			getToken.promise = null;
		})
		.then(r => {
			console.log("refresh", r, 'rrr');
			return setToken(r.data);
		});
	return getToken.promise;

};


// 登录
export const login = async () => {
	requestLoginTime++;
	if (requestLoginTime != 1) {
		let loginResponed = await loginPromise();
	}
	let code = await (wxApp.getWxMinAppUuerCode());
	let res = await request.post("/api/auth/login", {
		code: code,
		appid: wxApp.getWXAppId()
	});
	requestLoginTime = 0;
	return res;
};


const loginPromise = () => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve(true)
		}, 800)
	})
}


// 检测数据结果
export const checkResult = r => {
	if (!r.data.code) {
		return r.data.data;
	} else {
		return Promise.reject(r);
	}
};

// 刷新token
const refreshToken = () => {
	let res = request.post("/api/auth/refreshToken", {
		refreshToken: token.refreshToken,
		appid: wxApp.getWXAppId()
	});
	// console.log('refreshTokenrrrrr', res);
	return res;
};

// 检查token的有效期
const checkToken = t => {
	return new Date().getTime() < t.time;
};

// 设置token
const setToken = async t => {
	try {
		token = formatToken(t);
		uni.setStorageSync("token", token);
		return t.token;
	} catch (e) {
		console.log('token-set--errr', e);
	}

};

// 清除token  
export const clearToken = async () => {
	token = null;
	uni.removeStorageSync('token');
	console.log("clear token done");
};

// 处理token的格式
const formatToken = t => {
	t.token = "Bearer " + t.accessToken;
	t.time = ((t.expiration - 300) * 1000);
	return t;
};