//定义路由

const routers = {
	'Login': '/pagesA/login/login',
	'Home': '/pages/home/home',
	'Order': '/pages/order/order',
	'Mine': '/pages/mine/mine',
	'SelectAccount': '/pagesA/selectAccount/selectAccount',
	'GoodsDetail': '/pagesA/goods/goods',
	'SubmitOrder': '/pagesA/submitOrder/submitOrder',
	'GoodSkuList': '/pagesA/GoodSkuList/GoodSkuList',
	'IntegralDetail': '/pagesA/integralDetail/integralDetail',
	'Setting': '/pagesA/setting/setting',
	'VertifyPhone': '/pagesA/VertifyPhone/VertifyPhone',
	'SetPwd': '/pagesA/SetPwd/SetPwd',
	'OrderDetail': '/pagesA/orderDetail/orderDetail',
	'Coupon': '/pagesA/coupon/coupon',
	'AlertToLogin': '/pagesA/AlertToLogin/AlertToLogin',
	'Agreement': '/pagesA/agreement/agreement',
	'WebView': '/pagesA/webView/webView'
}

export function push(routerName, params, events) {
	let param = '?'
	if (params && (typeof params == 'object')) {
		for (let key of Object.keys(params)) {
		  let value = params[key];
		  param = param + key + '=' + value + '&'
		}
	}
	let url = routers[routerName] + param
	console.log(url);
	if (routerName === 'Home' || routerName === 'Order' || routerName === 'Mine') {
		uni.switchTab({
			url:url
		})
		return
	}
	uni.navigateTo({
		url:url,
		events:events,
		fail(err) {
			console.error(err)
		}
	})
}

export function pop() {
	uni.navigateBack({})
}

export function replaceTo(routerName, params) {
	let param = '?'
	if (params && (typeof params === 'object')) {
		for (let key of Object.keys(params)) {
		  let value = params[key];
		  param = param + key + '=' + value + '&'
		}
	}
	let url = routers[routerName] + param
	if (routerName === 'Home' || routerName === 'Order' || routerName === 'Mine') {
		console.log('pop')
		uni.switchTab({
			url:url
		})
		return
	}
	console.log('pop')
	uni.redirectTo({
		url:url
	})
}

export function goLandPage (url) {
	let pageUrl = url
	let routerName = url
	if (url.indexOf('?')>-1) {
		let arr = url.split('?')
		routerName = arr[0]
		let goodsType = getQueryVariable(url,'type')
		if (routerName=='goodDetail' && goodsType==100) {
			// 电商商品
			routerName = 'goodDetail'
		} else if (routerName=='goodDetail' && goodsType==200) {
			// 本地生活商品
			routerName = 'localLifeGoodDetail'
		}
		pageUrl = routers[routerName] + '?' + arr[1]
	}
	if (routerName === 'Home' || routerName === 'Mine' || routerName === 'Order') {
		uni.switchTab({
			url:pageUrl
		})
		return
	}
	uni.navigateTo({
		url:pageUrl
	})
}

export function getQueryVariable (url, key) {
  if (url.indexOf('?') === -1) {
    return null
  }
  let vars = url.split('?')
  let keyValues = vars[1].split('&')
  for (let i = 0; i < keyValues.length; i++) {
    let pair = keyValues[i].split('=')
    if (pair[0] === key) {
      return pair[1]
    }
  }
  return null
}

export default {
	push: push,
	pop: pop,
	replaceTo: replaceTo,
	goLandPage: goLandPage,
	getQueryVariable: getQueryVariable
}
