let isToLoginSend = false;
var requestTask = null
var elabprojectname = ''
var elabsystem = ''
var elabEnvironment = ''
export const myRequest = (options) => {
	if (!options.hasOwnProperty("showLoading")) {
		var localDate = uni.getStorageSync('loadingStamp') || 0
		var date = new Date().getTime()
		if (date - localDate > 2000) {
			uni.setStorageSync('loadingStamp', date)
			uni.showLoading({
				mask: true,
				title: "正在加载中"
			})
		}
	}
	let token = getApp().globalData.token;
	if (token) {
		options.token = token
	} else {
		options.token = null
	}
	let BASE_URL = getApp().globalData.BASE_URL;
	var plat = getApp().globalData.platform
	if (plat == 'android') {
		elabprojectname = 'com.elab.damai'
		elabsystem = '1'
		elabEnvironment = '2'
	} else if (plat == 'ios') {
		elabprojectname = 'com.elab.damai'
		elabsystem = '1'
		elabEnvironment = '1'
	} else {
		elabprojectname = '大麦数字营销'
		elabsystem = '3'
		elabEnvironment = '4'
	}

	// console.log("param", JSON.stringify(options.data) + "token:" + options.token + ":url = " + BASE_URL + options.url)
	return new Promise((resolve, reject) => {
		let userInfo = uni.getStorageSync('userInfo');
		if (!userInfo) {
			var pages = getCurrentPages()
			var currentPage = pages[pages.length - 1]
			var url = currentPage.route
			if (url.indexOf('loginPage/index') == -1) {
				uni.redirectTo({
					url: '/pages/loginPage/index'
				})
				reject()
			}
		}
		requestTask = uni.request({
			url: BASE_URL + options.url,
			method: options.method || "POST",
			data: options.data || {},
			header: {
				'token': options.token || null,
				'elabprojectname': elabprojectname,
				'elabsystem': elabsystem,
				'elabEnvironment': elabEnvironment
			},
			success: res => {

				// console.log("token", options.token)
				// console.log("返回参数：", res);
				if (res.statusCode == 401) { //登出
					uni.removeStorage({
						key: 'userInfo',
					})
					getApp().globalData.token = "";
					uni.removeStorageSync('selectedData');
					uni.removeStorageSync('selecedProject');
					if (!isToLoginSend) {
						isToLoginSend = true;
						uni.reLaunch({
							url: "../loginPage/index",
							success() {
								setTimeout(() => {
									isToLoginSend = false;
								}, 1000)
							}
						})
						uni.showToast({
							title: "您的账号在别处登录，请重新登录",
							icon: "none",
							duration: 3000
						})
					}
					ekanfang.logout();
					return
				}
				uni.hideLoading()
				resolve(res)
			},
			fail: (err) => {
				uni.hideLoading()
				uni.hideNavigationBarLoading();
				uni.stopPullDownRefresh();
				reject(err)
			}
		})
	})
}
