import urlConfig from '@/config/index.js'
import checkError from "./error.js"
import { uploadOne, uploadImage} from "./upload.js"

const {
	url_config
} = urlConfig;

export {
	uploadOne,
	uploadImage
}

export default {
	request: http(),
	// 带加载框的请求
	_request: http(true)
}

function isUrl(url) {
	return /^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/.test(url)
}

export function http(showLoading, loadingText="正在加载中") {
	return function(url, method = 'GET', data = {}, type = 'form') {
		let realData = data;
		let realUrl = url
		var header = {};
		if (type == 'json') {
			header['Content-Type'] = 'application/json';
		} else if (type == 'form') {
			header['Content-Type'] = 'application/x-www-form-urlencoded';
		}
		return new Promise((resolve, reject) => {
			if (showLoading) {
				uni.showLoading({
					title: loadingText,
					mask: true
				})
			}
			uni.request({
				url: isUrl(realUrl) ? realUrl : (url_config + realUrl),
				method,
				dataType: 'json',
				header,
				data: realData,
				success: (res) => {
					if (showLoading) {
						uni.hideLoading();
					}
					if (!(res.statusCode === 200)) {
						checkError(res.statusCode, res);
						reject(res)
						return
					}
					if (res.data.code == 200) {
						resolve(res.data);
					} else {
						checkError(res.data.code, res);
						reject(res.data)
					}
				},
				fail(err) {
					if (showLoading) {
						uni.hideLoading();
					}
					uni.showToast({
						icon: 'none',
						title: err.errMsg
					})
					checkError(-1, err);
					reject(err)
				}
			});
		})
	}
}