import { BASE_URL } from '../env.js';
const request = ({ url, method, data, header }) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token');
		uni.request({
			url: url.includes('http') ? url : BASE_URL.url + url,
			method,
			data,
			header: {
				'Authorization': url == '/login' ? '' : `Bearer ${token}`
			},
			dataType: 'json',
			success: function(res) {
				if (res.data.errcode && res.data.errcode != 0) {
					wx.showToast({
						title: res.data.details || '获取失败',
						icon: 'error'
					})
				}
				if (res.data.code && res.data.code !== 200) {
					wx.showToast({
						title: res.data.msg
					})
				}
				if (res.data.code && res.data.code == 401) {
					uni.redirectTo({
						url: '/pages/login/index'
					});
				}
				resolve(res)
			},
			fail: function(err) {
				uni.showToast({
					title: "请求接口失败！"
				})
				reject(err)
			}
		});
	})
	
}
const get = async ({ url, data, header }) => {
	return await request({ url, method: 'get', data, header });
}
const post = async ({ url, data, header }) => {
	return await request({ url, method: 'post', data, header });
}
const put = async ({ url, data, header }) => {
	return await request({ url, method: 'put', data, header });
}
const del = async ({ url, data, header }) => {
	return await request({ url, method: 'delete', data, header });
}
export default { get, post, put, del };