import url from './config.js';
const baseUrl = url.baseUrl
// 封装post请求
const postData = (url, data = {}) => {
	// uni.showLoading({
	// 	title: '加载中',
	// 	mask: false
	// });
	let _url = url;
	let _data = data;
	url = baseUrl + url;
	let token = uni.getStorageSync('token').token;
	var promise = new Promise((resolve, reject) => {
		//网络请求
		uni.request({
			url: url,
			data: data,
			method: 'POST',
			header: {
				'Authorization': token,
			},
			success: function(res) { //服务器返回数据
				console.log(8888, res)
				if (res.statusCode == 200) {
					resolve(res.data);
				} else {
					uni.showModal({
						title: '提示',
						content: '出错了',
						showCancel: false,
					});
					reject("出错了");
				}
			},
			fail: function(e) {
				uni.showModal({
					title: '提示',
					content: '网络错误，请稍后再试',
					showCancel: false,
				});
				reject('网络出错');
			}
		})
	});
	return promise;
}

const getData = (url, data = {}) => {
	// uni.showLoading({
	// 	title: '加载中',
	// 	mask: false
	// });
	// let _url = url;
	// let _data = data;
	url = baseUrl + url;
	// let token = uni.getStorageSync('token');
	// if (token) {
	// 	data.token = token;
	// }
	var promise = new Promise((resolve, reject) => {
		//网络请求
		uni.request({
			url: url,
			data: data,
			method: 'GET',
			dataType:'json',
			// header: {
			// 	'content-type': 'application/json'
			// 	// 'content-type': 'application/x-www-form-urlencoded',
			// },
			success: function(res) { //服务器返回数据

				if (res.statusCode == 200) {
					resolve(res.data);
				} else {
					uni.showModal({
						title: '提示',
						content: '出错了',
						showCancel: false,
					});
					reject("出错了");
				}
				
			},
			fail: function(e) {
				uni.showModal({
					title: '提示',
					content: '网络错误，请稍后再试',
					showCancel: false,
				});
				reject('网络出错');
			}
		})
	});
	
	return promise;
}

const logins = (url, data = {}) => {
	// uni.showLoading({
	// 	title: '加载中',
	// 	mask: false
	// });
	let _url = url;
	let _data = data;
	url = baseUrl + url;
	
	var promise = new Promise((resolve, reject) => {
		//网络请求
		uni.request({
			url: url,
			data: data,
			method: 'POST',
			header: {
				"Content-Type": "application/json"
			},
			success: function(res) { //服务器返回数据
				if (res.data.code == 200) {
					uni.setStorageSync("token",res.data.data)
					resolve(res.data.data);
				} else {
					uni.showModal({
						title: '提示',
						content: '登陆失败',
						showCancel: false,
					});
					reject("登陆失败");
				}
			},
			fail: function(e) {
				uni.showModal({
					title: '提示',
					content: '网络错误，请稍后再试',
					showCancel: false,
				});
				reject('网络出错');
			}
		})
	});
	return promise;
}

module.exports = {
	postData,
	getData,
	logins
}
