import config from '../config.js';
const getDomain = (uri, method, type) => {
	if (type && type == 'file') return config.serverUrl + '/files' + uri;
	if (type && type == 'integral') return config.serverUrl + '/point/zr/v1/api' + uri;
	if (uri.startsWith('/wechat/api')) return config.serverUrl + uri;
	else return config.serverUrl + '/point/v1/api' + uri;
}
// 获取token
const getToken = () => {
	try {
		const value = uni.getStorageSync('token');
		if (value) return value;
	} catch {}
}
export const requestBase = (uri, method, data, type) => {
	let baseUrl = getDomain(uri, method, type);
	let token = getToken();
	let header = {};
	if (token) header.token = token;
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl,
			method: method || 'GET',
			data: data || {},
			header,
			success: (res) => {
				resolve(res.data);
			},
			fail: (err) => {
				console.log(err);
				uni.showToast({
					title: '请求接口失败',
					icon: 'fail'
				})
				reject(err.data)
			}
		})
	})
}
export const requestFile = (uri, method, data, type) => {
	let baseUrl = getDomain(uri, method, type);
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseUrl,
			filePath: data,
			name: method || 'file',
			formData: {},
			success: (res) => {
				let data = JSON.parse(res.data);
				if (data.errcode != '0') {
					return uni.showToast({
						title: data.errmsg,
						icon: 'error'
					});
				}
				resolve(data);
			},
			fail: (err) => {
				let data = JSON.parse(err.data);
				uni.showToast({
					title: '请求接口失败',
					icon: 'fail'
				})
				reject(data)
			}
		});
	})
}
