import config from '../config'
import {
	getToken,
	removeToken
} from './auth'

const app = getApp()

function doRequest(url, method = 'GET', data, header = {}) {
	//安全白名单判断
	if(url.indexOf("/wxApi/")<0){
		if (config.noSecuritys.indexOf(url) == -1 && !getToken()) {
			removeToken();
			wx.redirectTo({
				url: '../login/login',
			});
		}
	}
	//POST请求设置数据来源为小程序...
	if(method=='post' || method=='POST'){
		data.dataSource = "1";
		wx.showLoading({
			mask: true,
			title: url == config.noSecuritys[1] ? '登录中' : '正在处理'
		})
		app.securityLoading();
	}
	return new Promise((resolve, reject) => {
		wx.request({
			url: config.baseUrl + url,
			method: method,
			data: data,
			header: {
				'content-type': 'application/json',
				'Authorization': 'Bearer ' + getToken(),
				...header
			},
			timeout: config.timeOut,
			success: function (res) {
				wx.hideLoading({success: (res) => {}});
				const code = res.data.code || 200
				if (code === 401) {
					removeToken();
					wx.redirectTo({
						url: '../login/login',
					});
				} else if (code === 500 || code === 403) {
					app.toast(res.data.msg);
					setTimeout(() => {
						resolve(res.data);
					}, 800)
				} else {
					resolve(res.data);
				}
			},
			fail: function (error) {
				wx.hideLoading({success: (res) => {}});
				app.toast(error);
				reject(error);
			}
		})
	})
}

/**
 * 这里考虑上传异步问题,封装为同步
 */
export function syncFileUpload(file) {
	if (!getToken()) {
		removeToken();
		wx.redirectTo({
			url: '../login/index',
		});
	}
	wx.showLoading({
		mask: true,
		title: '正在上传资源'
	})
	return new Promise((resolve, reject) => {
		wx.uploadFile({
			url: config.baseUrl + '/common/upload', // 上传的服务器接口地址
			filePath: file,
			header: {
				"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
				'Authorization': 'Bearer ' + getToken()
			},
			name: "file", //上传的所需字段,后端提供
			formData: {},
			success: (res) => {
				// 上传完成操作
				wx.hideLoading()
				let resJson = JSON.parse(res.data)
				const code = resJson.code || 200
				if (code === 401) {
					removeToken();
					wx.redirectTo({
						url: '../login/index',
					});
				} else if (code === 500 || code === 403) {
					app.toast(resJson.msg);
					setTimeout(() => {
						resolve(resJson);
					}, 800)
					resolve(resJson);
				} else {
					resolve(resJson);
				}
			},
			fail: (error) => {
				wx.hideLoading()
				//上传失败:修改pedding为reject
				app.toast("网络出错,上传失败")
				reject(error)
			}
		});
	})
}

/**
 * 这里考虑上传异步问题,封装为同步
 */
export function securityFileUpload(file) {
	wx.showLoading({
		mask: true,
		title: '正在上传资源'
	})
	return new Promise((resolve, reject) => {
		wx.uploadFile({
			url: config.baseUrl + '/file/NoSecurity/upload', // 上传的服务器接口地址
			filePath: file,
			header: {
				"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
			},
			name: "file", //上传的所需字段,后端提供
			success: (res) => {
				// 上传完成操作
				wx.hideLoading()
				let resJson = JSON.parse(res.data)
				const code = resJson.code || 200
				if (code != 200) {
					app.toast(resJson.msg);
					setTimeout(() => {
						resolve(resJson);
					}, 800)
					resolve(resJson);
				} else {
					resolve(resJson);
				}
			},
			fail: (error) => {
				wx.hideLoading()
				//上传失败:修改pedding为reject
				app.toast("网络出错,上传失败")
				reject(error)
			}
		});
	})
}

/**
 * 签名文件上传
 * 支持裁剪
 * 支持压缩
 * @param {*} file 
 */
export function securitySignFileUpload(file) {
	wx.showLoading({
		mask: true,
		title: '正在上传签名'
	})
	return new Promise((resolve, reject) => {
		wx.uploadFile({
			url: config.baseUrl + '/file/NoSecurity/signUpload', // 上传的服务器接口地址
			filePath: file,
			header: {
				"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
			},
			name: "file", //上传的所需字段,后端提供
			success: (res) => {
				// 上传完成操作
				wx.hideLoading()
				let resJson = JSON.parse(res.data)
				const code = resJson.code || 200
				if (code != 200) {
					app.toast(resJson.msg);
					setTimeout(() => {
						resolve(resJson);
					}, 800)
					resolve(resJson);
				} else {
					resolve(resJson);
				}
			},
			fail: (error) => {
				wx.hideLoading()
				//上传失败:修改pedding为reject
				app.toast("网络出错,上传失败")
				reject(error)
			}
		});
	})
}

export function request(options) {
	if(options.method=='get' && options.params){
		options.url = options.url+"?"+options.params;
	}
	return doRequest(options.url, options.method, options.data, options.header)
}