import Request from "@/lib/request/index.js";
import {
	refreshTokenFn
} from "@/api/login.js";
import storage from "@/utils/storage.js";
import {
	md5
} from "@/utils/md5.js";
import Foundation from "@/utils/Foundation.js";
import api from "@/config/api.js";

import uuid from "@/utils/uuid.modified.js";

import {
	clearIm
} from "@/utils/handleim.js";



function cleanStorage() {
	uni.showToast({
		title: "你的登录状态已过期，请重新登录",
		icon: "none",
		duration: 1500,
	});
	if (uni.showLoading()) {
		uni.hideLoading();
	}

	storage.setHasLogin(false);
	storage.setAccessToken("");
	storage.setRefreshToken("");
	storage.setUuid("");
	storage.setUserInfo({});
	// 清理vlog信息
	storage.setVlogToken("");
	storage.setVlogUserInfo(null);
	// 清除初始化数据内容
	storage.setRefreshVlogIndex("1"); //需要刷新
	// 退出im登录
	clearIm()

	// 获取当前页面栈
	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	const currentRoute = currentPage.route;
	// 防抖处理跳转
	// #ifdef MP-WEIXIN
	if (currentRoute !== 'pages/passport/wechatMPLogin') {
		uni.navigateTo({
			url: "/pages/passport/wechatMPLogin"
		});
	}
	// #endif
	// #ifndef MP-WEIXIN
	if (currentRoute !== 'pages/passport/login') {
		uni.navigateTo({
			url: "/pages/passport/login"
		});
	}
	//  #endif
}

let http = new Request();

http.setConfig((config) => {
	// 没有uuid创建
	if (!storage.getUuid()) {
		storage.setUuid("wzj666");
	}

	/* 设置全局配置 */
	config.baseURL = api.buyer;
	config.header = {
		...config.header,
	};
	config.validateStatus = (statusCode) => {
		// 不论什么状态,统一在正确中处理
		return true;
	};
	return config;
});

http.interceptors.request.use(
	(config) => {
		/* 请求之前拦截器。可以使用async await 做异步操作 */
		let accessToken = storage.getAccessToken();

		if (accessToken) {
			const nonce = Foundation.randomString(6);
			const timestamp = parseInt(new Date().getTime() / 1000);
			const sign = md5(nonce + timestamp + accessToken);
			const _params = {
				nonce,
				timestamp,
				sign,
			};
			let params = config.params || {};
			params = {
				...params,
				..._params,
			};

			config.params = params;
			config.header.accessToken = accessToken;
		}
		// 配置vlog所需参数
		let vlogToken = storage.getVlogToken();
		let vlogId = storage.getVlogUserInfo();
		if (vlogToken) {
			config.header.headerUserToken = vlogToken;
			config.header.headerUserId = vlogId.id;
		}
		config.header = {
			...config.header,
			uuid: "wzj666",
		};
		return config;
	},
	(config) => {
		return Promise.reject(config);
	}
);

// 是否正在刷新的标记
let isRefreshing = false;
//重试队列
let requests = [];
// 必须使用异步函数，注意
http.interceptors.response.use(
	async (response) => {
			console.log(response)
			/* 请求之后拦截器。可以使用async await 做异步操作  */
			// token存在并且token过期

			/**
			 * 后续进来的请求，此时异步获取token时isRefreshing一定为true
			 * 那么也就代表此时token一定是过期状态，响应码也一定为403
			 * 也就会去清理缓存
			 * 所以会导致页面多次刷新到登录页
			 */

			// if (isRefreshing && response.statusCode === 403) {
			// 	cleanStorage();
			// 	isRefreshing = false;
			// }

			let token = storage.getAccessToken();
			if(response.statusCode === 408){
				cleanStorage();
			}
			if (
				(token && response.statusCode === 403) ||
				(token && response.data.status === 403)
			) {
				console.log('去刷tk1')
				if (!isRefreshing) {
					isRefreshing = true;
					console.log('去刷tk2')
					//调用刷新token的接口
					return refreshTokenFn(storage.getRefreshToken())
						.then((res) => {
							let {
								accessToken,
								refreshToken
							} = res.data.result;
							storage.setAccessToken(accessToken);
							storage.setRefreshToken(refreshToken);

							response.header.accessToken = `${accessToken}`;
							// token 刷新后将数组的方法重新执行
							requests.forEach((cb) => cb(accessToken));
							requests = []; // 重新请求完清空
							return http.request(response.config);
						})
						.catch((err) => {
							console.log('刷新token失败刷新token失败刷新token失败刷新token失败刷新token失败刷新token失败')
							console.log(err);
							cleanStorage();
							return Promise.reject(err);
						})
						.finally(() => {
							isRefreshing = false;
						});
				} else {
					// 返回未执行 resolve 的 Promise
					return new Promise((resolve) => {
						// 用函数形式将 resolve 存入，等待刷新后再执行 
						requests.push((token) => {
							// 刷新token后传入新的token
							response.header.accessToken = `${token}`;
							resolve(http.request(response.config));
						});
					});
				}

				// 这是没有token的情况
			} else if (
				(!token && response.statusCode === 403) ||
				response.data.code === 403
			) {
				console.log('没有token的情况');
				cleanStorage();

				// 如果当前状态码为正常但是success为不正常时
			} else if (
				(response.statusCode == 200 && !response.data.success) ||
				response.statusCode == 400
			) {
				if (response.data.message) {
					uni.showToast({
						// title: response.data.message,
						title: "请重试",
						icon: "none",
						duration: 1500,
					});
				}
			} else if (response.data.code == 502) {
				cleanStorage();
			}
			return response;
		},
		(error) => {
			return error;
		}
);

export {
	http
};

export const Method = {
	GET: "GET",
	POST: "POST",
	PUT: "PUT",
	DELETE: "DELETE",
};