var siteinfo = require('../../siteinfo.js'); //require这个js模块  
module.exports = function(a) {
	console.log('request 接收参数',a)
	let header = {
		'Content-Type': 'application/json',
	}
	if (a.header) {
		header = a.header
	}
	let data = a.data || (a.data = {}),
		method = a.method || "POST",
		hide = a.hide || "",
		is_agent = a.is_agent || '',
		str = a.url,
		showLoading = a.showLoading ? false : true;
	// return
 
	if (str.indexOf("Smdcshop") == -1 || str.indexOf("Litepay") == -1) {
		if (a.superid) {
			data.super_id = data.superid;
		} else {
			if (siteinfo.super_id) {
				if (str != "funeng/scan") {
					data.super_id = siteinfo.super_id;
				}
			}
		}
	}
	showLoading && uni.showLoading({
		title: '加载中...',
		mask: true
	})
	return request(str, is_agent, method, data, header, hide)
}

var host = siteinfo.siteroot + '/index.php?s=/';

function request(url, is_agent, method, data, header, hide) {

	var controller = is_agent == 'admin' ? 'admin/' : is_agent == 'member' ? 'member/' : is_agent == 'agent' ?
		'agent/' : is_agent == 'server' ?
		'server/' : is_agent == 'carcode' ?
		'carcode/' : 'api/';

	return new Promise((resolve, reject) => {
		uni.request({
			data,
			method,
			header,
			url: host + controller + url,
			timeout: 60000,
			success: (res) => {
				uni.hideLoading();
				if (res.data.code === '200' || res.data.code === 200) {
					resolve(res.data);
				} else if (res.data.code == '100' || res.data.code == '400' || res.data.code ==
					400) {
						
					if (!hide) {
						setTimeout(() => {
							_show_error(1, res.data.message)
						}, 200)
					}

					reject(res.data)
				} else if (res.data.code === 1003) {
					uni.showModal({
						title: '提示',
						content: res.data.message,
						showCancel: false,
						confirmText: "去激活",
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: "/pages/jihuo/jihuo"
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
				} else {
					if (res.data.code == 1002 || res.data.message == '缺少token') {
						uni.reLaunch({
							url: "/pages/login/login"
						})
						return;
					}
					if (res.data.code == '300') {
						uni.showModal({
							title: '提示',
							content: res.data.message,
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: "/pages/recharge/recharge"
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						})
						return;
					}
					reject(res.data);
					reject(res);
				}
			},
			fail: err => {
				uni.hideLoading();
				console.log(err.errMsg)
				_show_error(0, "");
				reject(err)
			},
			complete: res => {
				uni.hideLoading();
			}
		})
	})
}

function _show_error(error_code, msg) {
	let title = error_code == 1 ? msg : "网络开小差啦,请稍后再试";
	uni.showToast({
		title: title,
		icon: 'none',
		duration: 2000
	})
}
