import { objToUrl } from '@/libs/tools.js';
const baseUrl = getApp().globalData.baseUrl
//带Token请求
const request = (opts, hasToken) => {
	const authorization = getApp().globalData.token
	// console.log(authorization,'authorization')
	//  hasToken是否传入token，为true则不传token
	const header = {
			'Content-Type': 'application/json;charset=UTF-8'
		}
	if(!hasToken){
		header['X-AUTH-TOKEN'] = authorization
	}	
	//此token是登录成功后后台返回保存在storage中的
	let DefaultOpts = {
		url: baseUrl+opts.url,
		data: opts.data,
		method: opts.method,
		header: opts.header ? opts.header : header
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(DefaultOpts).then(
			(res) => {
				// console.log(res[1])
				// 是否超时已跳转
				let loginTimeOut = uni.getStorageSync('loginTimeOut');
				if(res[0]&&res[0].errMsg.indexOf('request:fail')>=0){
					resolve({
						status: 500,
						message: "请求网络失败"
					})
				}
				let ret = res[1]
				if(res[1].data.status){
					ret = res[1].data
				}else if(res[1].status){
					ret = res[1]
				}
				if(ret.status == '200'){
					resolve(ret)
				}else{
					if(ret.status == 401 && loginTimeOut == 'NO'){  //  未登录或登录过期
						uni.showToast({
							icon:'none',
							title: ret.message,
							duration: 5000 
						})
						setTimeout(function() {
						  const currentRoute = getRoutePath();
						  const url = `/pages/login/login?lanuch=${currentRoute.lanuch}&path=` + encodeURIComponent(currentRoute.url);
						  uni.reLaunch({ url });
						}, 1000);
						uni.setStorageSync('loginTimeOut', 'YES');
					}
					// 503
					if(ret.status == '503'){
						uni.showToast({
							icon:'none',
							title: ret.message,
							duration: 3000 
						})
					}
					resolve(ret)
				}
				resolve(ret)
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
}
function getRoutePath() {
  // eslint-disable-next-line no-undef
  const pages = getCurrentPages(); // 获取加载的页面

  const currentPage = pages[pages.length - 1]; // 获取当前页面的对象

  let url = currentPage.route; // 当前页面url

  const options = objToUrl(currentPage.options); // 如果要获取url中所带的参数可以查看options

  const lanuch = [
    'pages/index/index'
  ].includes(url);
  url = '/' + url;
  if (options.length) {
    url += '?' + options;
  }
  return {
    url,
    lanuch
  };
}

export default {
	baseUrl,
	request
}
