let baseUrl = process.env. VUE_APP_BASE_URL
import store from '@/store/index.js'
/**
 * 请求前置方法，可拦截请求
 * @param {Object} data 请求数据
 */
function before(data){
	let option = data
	let header = {}
	//带入token
	if(store.getters.token){
		header.authorization = 'Bearer ' + store.getters.token
	}
	//带入baseurl
	option.url = baseUrl + option.url
	return {
		...option,
		header,
		allow: true //是否允许
	}
}

/**
 * 请求后置方法
 * @param {Object} data 返回数据
 * @param {Object} resolve
 */
function after(data, resolve){
	let res = data
	
	
	
	resolve(res.data)
}

/**
 * 请求后置方法(出错时)
 * @param {Object} data 返回的数据
 * @param {Object} reject
 */
function error(data, reject){
	let err= data
	

	
	reject(err)
}

/**
 * 普通请求
 * @param {Object} data 发起请求的数据结构，详见https://uniapp.dcloud.net.cn/api/request/request.html
 */
export const request = (data) => {
	let option = before(data)
	if(option.allow){
		return new Promise((resolve, reject) => {
			uni.request({
				...option,
				success: (res) => {
					after(res, resolve)
				},
				fail: (err) => {
					error(err, reject)
				}
			})
		})
	}else{
		return new Promise((resolve, reject) => {
			reject(option)
		})
	}
}

/**
 * 请求体中带有文件的请求
 * @param {Object} data 发起请求的数据结构，详见https://uniapp.dcloud.net.cn/api/request/network-file.html
 * @param {Object} data.formData 参数放这里！！，不是data里！！
 */
export const formdata = (data) => {
	let option = before(data)
	if(option.allow){
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				filePath:'formdata',
				name:'formdata',
				...option,
				success: (res) => {
					after(res, resolve)
				},
				fail: (err) => {
					error(err, reject)
				}
			})
		})
	}else{
		return new Promise((resolve, reject) => {
			reject(option)
		})
	}
}

/**
 * 文件上传请求
 * @param {Object} data 发起请求的数据结构，详见https://uniapp.dcloud.net.cn/api/request/network-file.html
 */
export const upload = (data) => {
	let option = before(data)
	if(option.allow){
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				...option,
				success: (res) => {
					after(res, resolve)
				},
				fail: (err) => {
					error(err, reject)
				}
			})
		})
	}else{
		return new Promise((resolve, reject) => {
			reject(option)
		})
	}
}

/**
 * 文件下载请求
 * @param {Object} data 发起请求的数据结构，详见https://uniapp.dcloud.net.cn/api/request/network-file.html
 */
export const download = (data) => {
	let option = before(data)
	if(option.allow){
		return new Promise((resolve, reject) => {
			uni.downloadFile({
				...option,
				success: (res) => {
					after(res, resolve)
				},
				fail: (err) => {
					error(err, reject)
				}
			})
		})
	}else{
		return new Promise((resolve, reject) => {
			reject(option)
		})
	}
}