import { useUserStore } from '@/store/user.js';
import { nextTick } from 'vue';
import { BASE_API_URL } from '@/settings/siteSetting.js';
import { REDIRECT_KEY } from '@/settings/enums.js';

let requestCount = 0,
	isShowingDialog = false;
const showLoading = () => {
	if (requestCount === 0) {
		uni.showLoading({ mask: true });
	}
	requestCount++;
};
//隐藏loading
const hideLoading = () => {
	requestCount--;
	if (requestCount <= 0) {
		uni.hideLoading();
	}
};

// 将对象转为 x-www-form-urlencoded 字符串（兼容小程序环境无 URLSearchParams）
function toFormUrlEncoded(obj) {
	if (obj == null || typeof obj !== 'object') return '';
	return Object.keys(obj)
		.filter((k) => obj[k] != null && obj[k] !== '')
		.map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]))
		.join('&');
}

// 获取当前页面路径以及参数
export function getCurrentPageUrlWithArgs() {
	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	const route = currentPage.route;
	const options = currentPage.options;
	let url = `/${route}?`;
	for (let key in options) {
		const value = options[key];
		url += `${key}=${value}&`;
	}
	url = url.substring(0, url.length - 1);
	return url;
}

export class Request {
	#request(config) {
		const userStore = useUserStore();
		let {
			headers = {
				'Content-Type': 'application/json;charset=UTF-8',
			},
			url,
			method, // 请求类型
			loading = true, // 是否触发 loading
			timeout = 60 * 3000, // 请求超时时间
			returnResponse = false, // 是否返回原生数据
			message = true,
			hideErrorModal = false, // 报误弹窗
			params, // 请求参数
			formUrlEncoded = false, // 是否以 application/x-www-form-urlencoded 发送
			customizeUrl = '' //自定义url
		} = config;

		const header = {
			...headers,
			Authorization: userStore.getToken
		};

		if (method.toUpperCase() === 'GET') {
			const now = Date.now();
			params = Object.assign(params || {}, { _t: now });
		}

		let data = params;
		if (formUrlEncoded && params && typeof params === 'object') {
			data = toFormUrlEncoded(params);
			header['Content-Type'] = 'application/x-www-form-urlencoded';
		}

		loading && showLoading();
		
		return new Promise((resolve, reject) => {
			uni.request({
				url: BASE_API_URL + url,
				header,
				method,
				timeout,
				data,
				dataType: 'json',
				success: async (res) => {
					const { data } = res;
					// 返回原生接口请求
					if (returnResponse) {
						resolve(res);
						return;
					}

					switch (data.code) {
						case 200:
							resolve(data.data);
							break;
						case 400:
							uni.showModal({
								title: data.msg || '系统异常，请联系管理员',
								confirmText: '确定',
								success: (res) => {
									if (res.confirm) {
									} else if (res.cancel) {
										uni.redirectTo({ url: '/pages/index/index' });
									}
								}
							});
							reject();
							break;
						default:
							if (hideErrorModal) return;
							uni.showModal({
								title: data.msg || '系统异常，请联系管理员',
								confirmText: '确定',
								success: (res) => {
									if (res.confirm) {
									} else if (res.cancel) {
										uni.redirectTo({ url: '/pages/index/index' });
									}
								}
							});
							reject();
							break;
					}
				},
				fail: async (err) => {
					uni.showToast({
						title: '网络不稳定，请稍后刷新重试',
						icon: 'none'
					});
					await nextTick();
					reject(err);
				},
				complete: () => {
					loading && hideLoading();
				}
			});
		});
	}

	get(options) {
		return this.#request({
			...options,
			method: 'GET'
		});
	}

	post(options) {
		return this.#request({
			...options,
			method: 'POST'
		});
	}

	put(options) {
		return this.#request({
			...options,
			method: 'PUT'
		});
	}

	delete(options) {
		return this.#request({
			...options,
			method: 'DELETE'
		});
	}
}

export const api = new Request();
