
const baseUrl = 'https://szcf.superbest.wang/API' //稳定版本环境  
let UrlReg = /^http:\/\/.*/i
let UrlReg2 = /^https:\/\/.*/i

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(fail)
			}
		});
	})

}

/**
 * 方法说明
 * @url 请求地址
 * @parms 参数
 * @header {参数类型} 额外头部信息
 * @return {返回值类型} 返回值说明
 * 
 */
function postRequest(params, data = {}) {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: params.Ltitle ? params.Ltitle : "加载中..."
		});
		try {
			//登录错误提示
			let duration;
			if(params.url == '/user/login/pwd'){
				duration = 20000
			}else{
				duration = 3000
			}
			
			//token
			let token = uni.getStorageSync("token")
			//用户id
			let userId = uni.getStorageSync("userId")
			data.userId = data.userId || userId;
			params.header = {
				"token": token || ""
			};
			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
				}
				if (reslt.data.code != 200) {
					//token失效或者错误   ----401
					//账号已在其他地方登录！  -----1006
					if (reslt.data.code == 401 || reslt.data.code == 1006) {
						uni.showToast({
							icon: "none",
							title: reslt.data.message,
							duration
						})
						uni.hideLoading();
						//401跳转登录
						uni.redirectTo({
							// url: "/pages/notecheck/notecheck?phone=13428967050",
							// url: "/pages/notecheck/notecheck",
							url: "/pages/login/login"
						})
						reject(reslt.data.message)
					}
					
					uni.showToast({
						icon: "none",
						title: reslt.data.message,
						duration
					})
					uni.hideLoading();
					reject(reslt.data.message)
				}
				console.log(reslt);
				uni.hideLoading();
				resolve(reslt.data)
			}).catch(e => {
				reject(e.message)
			})
		} 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 : "加载中..."
		});
		try {
			//token
			let token = uni.getStorageSync("token")
			//用户id
			let userId = uni.getStorageSync("userId")
			data.userId = data.userId || userId;
			params.header = {
				"token": token || ""
			};
			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
				}
				if (reslt.data.code != 200) {
					//token失效或者错误
					if (reslt.data.code == 401) {
						uni.showToast({
							icon: "none",
							title: reslt.data.message,
							duration:3000
						})
						uni.hideLoading();
						//401跳转登录
						uni.redirectTo({
							// url: "/pages/notecheck/notecheck?phone=13428967050",
							// url: "/pages/notecheck/notecheck",
							url: "/pages/login/login"
						})
						reject(reslt.data.message)
					}
					uni.showToast({
						icon: "none",
						title: reslt.data.message,
						duration:3000
					})
					uni.hideLoading();
					reject(reslt.data.message)
				}
				console.log(reslt);
				uni.hideLoading();
				resolve(reslt.data)
			}).catch(e => {
				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 : "加载中..."
		});
		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 != 200) {
			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
}
