import { objToUrl } from '@/libs/tools.js';
const baseUrl = getApp().globalData.baseUrl
import store from '@/store/index.js'
//带Token请求
const request = (opts, hasToken) => {
	const authorization = getApp().globalData.token
	const changeOrg = getApp().globalData.changeOrg
	const curVer = getApp().globalData.version
	console.log(changeOrg, !hasToken,'changeOrg')
	//  hasToken是否传入token，为true则不传token
	const header = {
			'Version': curVer.version?curVer.version.replace(/\./g,''):''
		}
	if(!hasToken || changeOrg){
		header['access-token'] = authorization || ''
	}
    if(changeOrg){
		header['access-org'] = changeOrg || ''
	}
	//此token是登录成功后后台返回保存在storage中的
	let DefaultOpts = {
		url: baseUrl+opts.url,
		data: opts.data,
		method: opts.method,
		header: opts.header ? opts.header : header
	}
	console.log(DefaultOpts)
	let promise = new Promise(function(resolve, reject) {
		uni.request(DefaultOpts).then(
			(res) => {
				console.log(res)
				// 是否超时已跳转
				let loginTimeOut = uni.getStorageSync('loginTimeOut');
				if(res[0]&&res[0].errMsg.indexOf('request:fail')>=0){
					uni.showToast({
						icon:'none',
						title: '网络请求失败,请检查网络连接情况',
						mask: true,
						duration: 4000 
					})
					resolve({
						status: 6000,
						message: "网络请求失败"
					})
				}
				let ret = res[1]
				if(!ret.status){
					ret.status = ret.statusCode
				}
				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' || ret.status == '1099'){  //  未登录或登录过期
					   uni.showToast({
					   	icon:'none',
					   	title: '登录已过期,请重新登录',
					   	duration: 5000 
					   })
					   store.state.vuex_token = ''
					   setTimeout(function() {
					   	const url = `/pages/login/login`
					   	uni.redirectTo({ url })
					   }, 1000)
					}
					else{
						console.log(opts.url,'opts.url')
						if(ret.status == 500){
							if(
							opts.url.indexOf("shelfReplenish/detail/outScan")<0&&
							opts.url.indexOf("shelfReplenish/detail/queryByProductQrCode")<0&&
							opts.url.indexOf("shelfStockCheck/confirm")<0){
								uni.showToast({
									icon:'none',
									title: ret.message,
									mask: true,
									duration: 4000 
								})
							}
						}
					}
					resolve(ret)
				}
				// ret.status = ret.statusCode  // mock数据结构改造
				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
}
