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

const app = getApp()

function doRequest(url, method = 'GET', data, header = {}) {
	//安全白名单判断
	if (config.noSecuritys.indexOf(url) == -1 && !getToken()) {
		removeToken();
		wx.redirectTo({
			url: '../login/login',
		});
	}
	wx.showLoading({
		mask: true,
		title: url == config.noSecuritys[1] ? '登录中' : '加载中'
	})
	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()
				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()
				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 request(options) {
	if(options.method=='get' && options.params){
		options.url = options.url+"?"+options.params;
	}
	return doRequest(options.url, options.method, options.data, options.header)
}