import appConfig from '@/config/appConfig.js'
import { toErrPageFunc } from '@/util/toErrorPageUtil.js'
import { $payCancelBoardCast, $payEventBoardCast } from '@/http/apiManager.js'

function wechatH5Func(orderRes, payOrderInfo){
	
	
	let onBridgeReady = function () {

      // eslint-disable-next-line no-undef
      WeixinJSBridge.invoke( 'getBrandWCPayRequest', JSON.parse(orderRes.payInfo), function(res) {
		  
			payEventBoardCast(orderRes.payOrderId, res)
	  
			if (res.err_msg == "get_brand_wcpay_request:ok") {
			  // 使用以上方式判断前端返回,微信团队郑重提示：
			  //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
			  // //重定向
			  if(payOrderInfo.returnUrl){
				location.href = payOrderInfo.returnUrl;
			  }else{
				alert('支付成功！');
				// if(payOrderInfo.fun) return payOrderInfo.fun()	
				window.WeixinJSBridge.call('closeWindow')
			  }

			}
			if (res.err_msg == "get_brand_wcpay_request:cancel") {
			  // payCancel(orderRes.payOrderId)
			  alert("支付取消");
			  // return false;
			  window.WeixinJSBridge.call('closeWindow')
			}
			if (res.err_msg == "get_brand_wcpay_request:fail") {
			  alert('支付失败:' + JSON.stringify(res))
			  // return false;
			  window.WeixinJSBridge.call('closeWindow')
			}
			if (res.err_msg == "total_fee") {
			  alert('缺少参数')
			  window.WeixinJSBridge.call('closeWindow')
			}
		}
      );
    }
	
	
	if (typeof WeixinJSBridge == "undefined"){
		  if( document.addEventListener ){
			document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
		  }else if (document.attachEvent){
			document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		  }
	}else{
		onBridgeReady();
	}
}

// 支付宝内的浏览器调起支付：https://myjsapi.alipay.com/jsapi/native/trade-pay.html
function alipayH5Func(orderRes){
	// 执行事件 
	let doAlipay = function () {
      AlipayJSBridge.call("tradePay", { tradeNO: orderRes.alipayTradeNo }, function (data) {
		payEventBoardCast(orderRes.payOrderId, data)
        if ("9000" == data.resultCode) {
          // //重定向
          if(orderRes.returnUrl){
            location.href = orderRes.returnUrl;
          }else{
            alert('支付成功！');
            window.AlipayJSBridge.call('closeWebview')
          }
          //‘8000’：后台获取支付结果超时，暂时未拿到支付结果;
        // ‘6004’：支付过程中网络出错， 暂时未拿到支付结果;
        }else if("8000" == data.resultCode || "6004" == data.resultCode){ //其他
          alert(JSON.stringify(data));
          window.AlipayJSBridge.call('closeWebview')
        }else{ ///其他异常信息， 需要取消订单
		  // payCancel(orderRes.payOrderId)
          alert('用户已取消！');
          window.AlipayJSBridge.call('closeWebview')
        }
      });
    }
	if (!window.AlipayJSBridge) {
		document.addEventListener('AlipayJSBridgeReady', doAlipay, false);
	}else{
	  doAlipay();
	}
}

function wechatLiteFunc(orderRes, payOrderInfo){
	const payInfo = JSON.parse(orderRes.payInfo)
	wx.requestPayment({
		"timeStamp": payInfo.timeStamp,
		"nonceStr": payInfo.nonceStr,
		"package": payInfo.package,
		"signType": payInfo.signType,
		"paySign": payInfo.paySign,
		"success": function(res){			
		if(appConfig.redPacketIsOpen){
			setTimeout(() => {
			   uni.navigateTo({
			   	url: '/pages/paySuccess/redSuccess?payOrderId=' + orderRes.payOrderId
			   })
			}, 1000)			
			return false;
		}
		if(payOrderInfo.fun) return payOrderInfo.fun()	
			uni.navigateTo({
				url: '/pages/paySuccess/paySuccess?amount=' + payOrderInfo.amount + '&payOrderId=' + orderRes.payOrderId
			})
		},
		"fail": function(res){
			if(res.errMsg == 'requestPayment:fail cancel') {
				// payCancel(orderRes.payOrderId)
				// toErrPageFunc('取消支付')
		      return uni.showToast({title: '取消支付',icon:'none'})
			}else {
				toErrPageFunc(res.errMsg)
			}
		},
		"complete": (res) => {
			payEventBoardCast(orderRes.payOrderId, res)
		}
	})
}

function alipayLiteFunc(orderRes, payOrderInfo){
	my.tradePay({
		tradeNO: orderRes.alipayTradeNo,
		success: (res) => {
			if(res.resultCode == 9000) {
				if(payOrderInfo.fun) return payOrderInfo.fun()	
				uni.navigateTo({
					url: '/pages/paySuccess/paySuccess?amount=' + payOrderInfo.amount
				})
			}else if(res.resultCode == 6001) {
				// payCancel(orderRes.payOrderId)
				// toErrPageFunc('取消支付')
		      return uni.showToast({title: '取消支付',icon:'none'})
			}else if(res.resultCode == 4000) {
				// toErrPageFunc('订单处理失败')
		      return uni.showToast({title: '订单处理失败',icon:'none'})
			}else if(res.resultCode == 4) {
				toErrPageFunc('无权限调用')
			}else {
				toErrPageFunc(JSON.stringify(res))
			}
		},
		fail: (res) => {
			toErrPageFunc(JSON.stringify(res))
		},
		complete: (res) => {
			payEventBoardCast(orderRes.payOrderId, res)
		}
	});
}

function ysfpayH5Func(orderRes){
	window.location.href = orderRes.redirectUrl
}


function payCancel(payOrderId) {
	$payCancelBoardCast(payOrderId).then(() => {
		console.log("取消支付")
	})
}

function payEventBoardCast(payOrderId, resData) {
	$payEventBoardCast(payOrderId, resData)
}


export default () => {
	
	let result = {}
	result[appConfig.PAGE_TYPE_ENUM.WECHAT_H5] = wechatH5Func;
	result[appConfig.PAGE_TYPE_ENUM.ALIPAY_H5] = alipayH5Func;
	result[appConfig.PAGE_TYPE_ENUM.WECHAT_LITE] = wechatLiteFunc;
	result[appConfig.PAGE_TYPE_ENUM.ALIPAY_LITE] = alipayLiteFunc;
	result[appConfig.PAGE_TYPE_ENUM.YSFPAY_H5] = ysfpayH5Func;

	return result;	
}