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&&authorization){
		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,'pppp')
				if(res[0]&&res[0].errMsg.indexOf('request:fail')>=0){
					resolve({
						status: 6000,
						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'){
						uni.showToast({
							icon:'none',
							title: ret.message,
							mask: true
						})
					}
					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
}
