import { BASE_URL } from './env.js';

const showErrorToast = (message) => {
	uni.showToast({
		title: message || '请求失败，请稍后重试',
		icon: 'none',
		duration: 2000
	});
};

const request = (options) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token') || '';

		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: {
				'Content-Type': 'application/json',
				'Authorization': token ? `Bearer ${token}` : '',
				...options.header
			},
			success: (res) => {
				const responseData = res.data || {};
				const { code, msg, data } = responseData;

				if (res.statusCode === 401) {
					uni.removeStorageSync('token');
					uni.removeStorageSync('identifier');
					showErrorToast(msg || '登录已过期，请重新登录');
					setTimeout(() => {
						uni.reLaunch({ url: '/pages/login/login' });
					}, 2000);
					reject(responseData);
					return;
				}

				if (code === 0) {
					resolve(data);
					return;
				}

				if (options.showError !== false) {
					showErrorToast(msg);
				}
				reject(responseData);
			},
			fail: (err) => {
				showErrorToast('网络请求失败');
				reject(err);
			}
		});
	});
};

export default request;
