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

import jwt from '@/utils/js_sdk/t-jwt/jwt.js';
import uuid from "@/utils/uuid.modified.js";
// Vue3: Store is already migrated to use createStore from Vuex 4.x
// Direct state access (store.state.xxx) is still valid in Vuex 4.x
import store from "../store";


let isNavigateTo = false

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({});


	/* if (!isNavigateTo) {
		isNavigateTo = true
		// 防抖处理跳转
		// #ifdef MP-WEIXIN || MP-HARMONY
		uni.navigateTo({
			url: "/pages/login/index",
		});
		// #endif
		// #ifndef MP-WEIXIN || MP-HARMONY
		uni.navigateTo({
			url: "/pages/passport/login",
		});
		//  #endif
	} */
}

let http = new Request();


/**
 * 创建uuid方法
 */
const createUuid = () => {
	if (!storage.getUuid()) {
		storage.setUuid(uuid.v4());
		console.log("uuid", storage.getUuid());
	}
}


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

http.interceptors.request.use(
	(config) => {
		/* 请求之前拦截器。可以使用async await 做异步操作 */
		let accessToken = storage.getAccessToken();
		if(storage.getInviter()){
			config.header.inviter = storage.getInviter();
		}
		
		console.log("请求前处理");
		if (accessToken) {
			/**
			 * 使用JWT解析
			 * 小于当前时间将当前token清除
			 */
			const decodeJwt = jwt(accessToken);
			const timing = new Date().getTime() / 1000
			if (decodeJwt.exp <= timing) {
				accessToken = ""
				storage.setAccessToken('')
			}
			

			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;
			config.header.Authorization  = 'Bearer '+accessToken;


		}
		createUuid();
		config.header = {
			...config.header,
			uuid: storage.getUuid()
		};
		return config;
	},
	(config) => {
		return Promise.reject(config);
	}
);


// 是否正在刷新的标记
let isRefreshing = false;
//重试队列
let requests = [];
// 必须使用异步函数，注意
http.interceptors.response.use(
	async (response) => {
		isNavigateTo = false;
		uni.showLoading() ? uni.hideLoading() : '';
		let token = storage.getAccessToken();
		console.log("请求后的处理",response);
		// token存在但401，说明过期了
		if ((token && response.statusCode === 401) || response.data.status === 401) {
			console.log('token过期或无效，跳转登录', token);
			cleanStorage(); // 清理缓存中的token、用户信息等
			uni.showToast({
				title: '登录已过期，请重新登录',
				icon: 'none',
				duration: 2000,
				complete: () => {
					setTimeout(() => {
						uni.navigateTo({
						  url: '/pages/login/index'
						}); // 跳转登录页
					}, 2000);
				}
			});
			return Promise.reject('登录状态过期');
		}

		// 未登录也跳转
		if ((!token && !storage.getAccessToken() && response.statusCode === 401) || response.data.code === 401 || response.data.code === 403) {
			console.log('无token，跳转登录');
			cleanStorage();
			uni.showToast({
				title: `请先登录${storage.getAccessToken()}`,
				icon: 'none',
				duration: 2000,
				complete: () => {
					setTimeout(() => {
						uni.navigateTo({
						  url: '/pages/login/index'
						});
					}, 2000);
				}
			});
			return Promise.reject('未登录');
		}

		// 请求成功但业务失败
		if (
			(response.statusCode === 200 && !response.data.success) ||
			response.statusCode === 400
		) {
			if (response.data.message) {
				uni.showToast({
					title: response.data.message,
					icon: "none",
					duration: 1500,
					success: () => { store.state.isShowToast = true; },
					fail: () => { store.state.isShowToast = false; },
					complete: () => { store.state.isShowToast = false; }
				});
			}
		}

		return response;
	},
	(error) => {
		return Promise.reject(error);
	}
);


export {
	http
};

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