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

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) => {
				if (res.statusCode === 401) {
					uni.removeStorageSync('token');
					uni.removeStorageSync('identifier');
					uni.showToast({
						title: '登录已过期，请重新登录',
						icon: 'none',
						duration: 2000
					});
					setTimeout(() => {
						uni.reLaunch({ url: '/pages/login/login' });
					}, 2000);
					reject(res.data);
					return;
				}

				const { code, msg, data } = res.data;

				if (code === 0 || code === 200) {
					resolve(data);
				} else {
					uni.showToast({
						title: msg || '请求失败',
						icon: 'none',
						duration: 2000
					});
					reject(res.data);
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '网络请求失败',
					icon: 'none',
					duration: 2000
				});
				reject(err);
			}
		});
	});
};

export default request;