let baseUrl = window.location.origin //稳定版本环境  
let UrlReg = /^http:\/\/.*/i
let UrlReg2 = /^https:\/\/.*/i
if (process.env.NODE_ENV === 'development') {
	console.log('开发环境');
	// baseUrl = 'https://dev-az-order-api.xiaopay.net/insure-order';
} else {
	// baseUrl = 'https://dev-az-order-api.xiaopay.net/insure-orders';
}

function uploadFile(params) {
	var _this = this,
		url = params.url,
		filePath = params.filePath,
		name = params.name ? params.name : 'file',
		data = params.data;
	console.log('uploadFile', params)
	//fileType	String	见平台差异说明	文件类型，image/video/audio
	uni.uploadFile({
		url: url, //仅为示例，非真实的接口地址
		filePath: filePath,
		name: name,
		formData: data,
		success: (uploadFileRes) => {
			if (params.success) {
				console.log("uploadFile成功", uploadFileRes)
				params.success(uploadFileRes)
			}
		}
	});
}

function downloadFile(params) {
	uni.downloadFile({
		url: 'https://www.example.com/file/test', //仅为示例，并非真实的资源
		success: (res) => {
			if (res.statusCode === 200) {
				console.log('下载成功');
			}
		}
	});
}




/**
 * 方法说明
 * @url 请求地址
 * @method 请求方式
 * @dataType 请求类型
 * @data 参数
 * @header {参数类型} 额外头部信息
 * @return {返回值类型} 返回值说明
 * 
 */
function request(params, data) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: (UrlReg.test(params.url) || UrlReg2.test(params.url)) ? params.url : baseUrl + params
				.url,
			method: params.method,
			dataType: params.dataType,
			data,
			header: Object.assign({
				"Content-Type": "application/json;charset=utf-8",
			}, params.header),
			success: function(res) {
				resolve(res)
			},
			fail: function(fail) {
				reject({
					message: fail.errMsg
				})
			}
		});
	})

}

/**
 * 方法说明
 * @url 请求地址
 * @parms 参数
 * @header {参数类型} 额外头部信息
 * @return {返回值类型} 返回值说明
 * 
 */
function postRequest(params, data = {}) {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: params.Ltitle ? params.Ltitle : "加载中...",
			mask: true
		});
		try {
			//登录错误提示
			let duration;
			if (params.url == '/user/login/pwd') {
				duration = 20000
			} else {
				duration = 3000
			}
			//token
			let personalInfo = uni.getStorageSync("personalInfo");
			params.header = Object.assign({
				seesionID: personalInfo.seesionID || '',
				sessionid: personalInfo.seesionID || '',
				token: personalInfo.seesionID || '',
				wechattype: 1
			}, params.header);
			data = Object.assign({
				seesionID: personalInfo.seesionID || '',
				sessionid: personalInfo.seesionID || '',
				token: personalInfo.seesionID || '',
				wechattype: 1
			}, data)
			params.method = "POST";
			params.dataType = "JSON"
			if (!params.url) {
				uni.showToast({
					icon: "none",
					title: "url不能为空",
					duration
				})
				uni.hideLoading();
				reject("url不能为空")
			}
			request(params, data).then(reslt => {
				try {
					reslt.data = JSON.parse(reslt.data)
				} catch (e) {
					reslt.data = reslt.data
					//TODO handle the exception
				}
				uni.hideLoading();
				resolve(reslt.data)
			}).catch(e => {
				uni.hideLoading();
				reject(e)
			})
		} catch (e) {
			console.log(e);
			uni.hideLoading();
			reject(e.message)
			//TODO handle the exception
		}
	})
}

/**
 * 方法说明
 * @url 请求地址
 * @parms 参数
 * @header {参数类型} 额外头部信息
 * @return {返回值类型} 返回值说明
 * 
 */
function getRequest(params, data) {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: params.Ltitle ? params.Ltitle : "加载中...",
			mask: true
		});
		try {
			//token
			let personalInfo = uni.getStorageSync("personalInfo");
			params.header = Object.assign({
				seesionID: personalInfo.seesionID || '',
				sessionid: personalInfo.seesionID || '',
				token: personalInfo.seesionID || '',
				wechattype: 1
			}, params.header);
			data = Object.assign({
				seesionID: personalInfo.seesionID || '',
				sessionid: personalInfo.seesionID || '',
				token: personalInfo.seesionID || '',
				wechattype: 1
			}, data)
			params.method = "GET";
			params.dataType = "JSON"
			if (!params.url) {
				uni.showToast({
					icon: "none",
					title: "url不能为空",
					duration: 3000
				})
				uni.hideLoading();
				reject("url不能为空")
			}
			request(params, data).then(reslt => {
				try {
					reslt.data = JSON.parse(reslt.data)
				} catch (e) {
					reslt.data = reslt.data
					//TODO handle the exception
				}
				uni.hideLoading();
				resolve(reslt.data)
			}).catch(e => {
				uni.hideLoading();
				reject(e.message)
			})
		} catch (e) {
			console.log(e);
			uni.hideLoading();
			reject(e.message)
			//TODO handle the exception
		}
	})
}

/**
 * 方法说明
 * @url 请求地址
 * @parms 参数
 * @header {参数类型} 额外头部信息
 * @return {返回值类型} 返回值说明
 * 
 */

async function Login(params, data) {
	try {
		await uni.showLoading({
			title: params.Ltitle ? params.Ltitle : "加载中...",
			mask: true
		});
		params.method = "POST";
		params.dataType = "JSON"
		if (!params.url) {
			await uni.showToast({
				icon: "none",
				title: "url不能为空",
				duration: 3000
			})
			await uni.hideLoading();
			throw Error("url不能为空")
		}

		//获取验证码
		let [err, reslt] = await request(params, data);
		try {
			reslt.data = JSON.parse(reslt.data)
		} catch (e) {
			reslt.data = reslt.data
			//TODO handle the exception
		}
		if (err) {
			await uni.showToast({
				icon: "none",
				title: JSON.stringify(err),
				duration: 3000
			})
			await uni.hideLoading();
			throw Error(JSON.stringify(err))
		}
		if (reslt.data.code != 1000) {
			await uni.showToast({
				icon: "none",
				title: reslt.data.message,
				duration: 3000
			})
			await uni.hideLoading();
			throw Error(reslt.data.message)
		}
		//获取token 用户信息
		let [LoginErr, LoginInfo] = await request({
			method: "POST",
			url: '/user/login/to_login'
		}, {
			phone: reslt.data.data.phone,
			verifyCode: reslt.data.data.verifyCode
		});
		try {
			reslt.data = JSON.parse(reslt.data)
		} catch (e) {
			reslt.data = reslt.data
			//TODO handle the exception
		}
		if (LoginErr) {
			await uni.showToast({
				icon: "none",
				title: JSON.stringify(LoginErr),
				duration: 3000
			})
			await uni.hideLoading();
			throw Error(JSON.stringify(LoginErr))
		}
		if (LoginInfo.data.code != 200) {
			await uni.showToast({
				icon: "none",
				title: LoginInfo.data.message,
				duration: 3000
			})
			await uni.hideLoading();
			throw Error(LoginInfo.data.message)
		}
		//缓存用户信息
		uni.setStorageSync("token", LoginInfo.data.data.token)
		uni.setStorageSync("userId", LoginInfo.data.data.userId)
		await uni.hideLoading();
		return true
	} catch (e) {
		console.log(e);
		await uni.hideLoading();
		throw Error(e)
		//TODO handle the exception
	}
}



module.exports = {
	post: postRequest,
	get: getRequest,
	upload: uploadFile,
	download: downloadFile,
	Login,
	//接口地址
	baseUrl
}