const BASE_URL = 'http://127.0.0.1:8080';

const CLIENT_ID = 'e48ac397bff4f031b14d6e671eee49c3';

let isRedirectingToLogin = false;

function getToken() {
	return uni.getStorageSync('token') || '';
}

function redirectToLogin() {
	if (isRedirectingToLogin) return;
	isRedirectingToLogin = true;
	uni.showToast({ title: '登录已失效，请重新登录', icon: 'none', duration: 1500 });
	setTimeout(() => {
		isRedirectingToLogin = false;
		uni.reLaunch({ url: '/pages/login/index' });
	}, 1500);
}

function request(options = {}) {
	const { url, method = 'GET', data = {}, params = {}, header = {} } = options;

	const token = getToken();
	const headers = {
		'Content-Type': 'application/json',
		'clientid': CLIENT_ID,
		'Authorization': 'Bearer ' + token,
		...header
	};

	let requestData = data;
	let requestUrl = BASE_URL + url;

	if (method.toUpperCase() === 'GET') {
		const allParams = { ...params, ...data };
		const paramString = Object.keys(allParams)
			.filter(key => allParams[key] !== undefined && allParams[key] !== null && allParams[key] !== '')
			.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(allParams[key])}`)
			.join('&');
		if (paramString) {
			requestUrl += (requestUrl.includes('?') ? '&' : '?') + paramString;
		}
		requestData = {};
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: requestUrl,
			method,
			data: requestData,
			header: headers,
			success(res) {
				const { code, msg, data, total, rows } = res.data;

				if (code === 200) {
					const result = {};
					if (data !== undefined) result.data = data;
					if (total !== undefined) result.total = total;
					if (rows !== undefined) result.rows = rows;
					resolve(result);
				} else if (code === 401) {
					redirectToLogin();
					reject('登录已失效');
				} else if (code === 500) {
					reject(msg);
				} else {
					reject(msg || '请求失败');
				}
			},
			fail(err) {
				const message = err.errMsg || '网络请求失败';
				uni.showToast({ title: message, icon: 'none' });
				reject(message);
			}
		});
	});
}

export default request;
