var core = getApp().globalData.requirejs("core"),
	foxui = getApp().globalData.requirejs("foxui"),
	that
let chectOrderTask = {},
	mockLoadingText = {}
export default {
	data() {
		return {
			icons: getApp().globalData.requirejs("icons"),
			success: false,
			successData: {},
			coupon: false,
			options: "",
			list: "",
			order: "",
			ordervirtual: "",
			ordervirtualtype: "",
			alidata: {},
			isSubPay: false,
			isOnPaying: false,
			onPayingProgress: 99,
			shop: 0
		};
	},

	components: {},
	props: {},
	onLoad: function (option) {
		that = this
		onPayingProgress()
		if (option && option.id) {
			that.init(option);
		} else {
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('acceptDataFromOfflinePay', function (data) {
				that.init(data.order);
			})
		}

	},
	onShow: function () { },
	onHide: function () {

	},
	onUnload: function () {
		that.checkUserCancelPay()
		clearTimeout(chectOrderTask)
		clearTimeout(mockLoadingText)
	},
	methods: {
		init: function (option) {
			that.setData({
				options: option
			})
			// 先获取订单是否是直接全部使用金豆抵扣的
			if (that.options.status == 3) {
				// 已经用金豆或者储值卡完全抵扣
				that.allUseCreditPay(that.options)
			} else {
				// 如果是公众号支付
				if (that.options.ish5wechat == 'yes') {
					// 如果是公众号登录
					that.getH5WechatPay({
						outTradeNo: that.options['ordersn'],
						payAmount: that.options['offline_price'],
						orderName: '扫码付款-' + that.options['merch_name'],
					});
				}
				that.doPayment()
			}
		},
		get_list: function () {
			let typeJsonData = {}
			//#ifdef MP-WEIXIN
			typeJsonData = {
				'currentTarget': {
					'dataset': {
						'type': 'wechat'
					}
				}
			};
			//#endif
			let alipayJsonData = {
				'currentTarget': {
					'dataset': {
						'type': 'alipay'
					}
				}
			}
			//#ifdef MP-ALIPAY
			typeJsonData = alipayJsonData
			//#endif	
			let h5Pla = getApp().globalData.util.getH5Platform()
			if (h5Pla == "H5-ALIPAY") {
				typeJsonData = alipayJsonData
			}
			let payRequestData = JSON.parse(JSON.stringify(that.options))
			console.log("payRequestData::::",payRequestData)
			payRequestData['s'] = 'App.Order_Pay.submit'
			uni.showLoading({
				title: '支付中...',
				mask: true
			})
			// 创建订单
			getApp().globalData.request(payRequestData).then(payRes => {
				uni.hideLoading()
				let subRes = payRes.data.data
				

				if ("SUCCESS" == subRes.result_code) {
					that.setData({
						list: subRes.data
					})
					// 直接发起支付
					that.callPayWin(typeJsonData)
				} else {
					uni.hideToast()
					uni.showModal({
						title: "提示",
						content: subRes.err_code_des,
						showCancel: false
					})
				}
			})
		},
		doPayment: function () {
			uni.showToast({
				title: "支付中...",
				icon: "loading",
				duration: getApp().globalData.config.timeout,
			})
			that.get_list()
		},
		// 调起支付
		callPayWin: function (payTypeQuery) {
			console.log("payTypeQuery",payTypeQuery)
			// 1.取消支付提醒逻辑
			that.isSubPay = true
			that.isOnPaying = true
			var payType = core.pdata(payTypeQuery).type,
				_this = this;
				console.log("payType",payType)
			if (payType == 'alipay' || "wechat" == payType) {
				// 微信小程序支付
				let payinfo = {}
				if (payType == 'alipay') {
					var trade_no=that.list.alipay['data']["trade_no"];
					that.list.alipay['data']["trade_no"]=trade_no.slice(2); //去掉前2位
					payinfo = {
						provider: 'alipay',
						orderInfo: that.list.alipay['data']["trade_no"]
					}					
				} else {
					payinfo = that.list.wechat['data']					
				}
				core.pay(payinfo, function (payinfoRes) {					
					let isPaySuccess = false
					if (
						// #ifdef MP-ALIPAY||MP-WEIXIN
						"requestPayment:ok" == payinfoRes.errMsg &&
						//#endif 
						1
					) {
						if (payType == "alipay") {
							// isPaySuccess = true					
							if (payinfoRes.resultCode == "9000") {
								isPaySuccess = true
							}
						} else if (payType == "wechat") {
							isPaySuccess = true
						}
					}					
					if (isPaySuccess) {
						uni.showLoading({
							title: '支付中',
							mask: true
						})
						setTimeout(function () {
							_this.finishPay(payType)
						}, 100)
					} else {
						that.isOnPaying = false
						that.checkUserCancelPay()
					}
				}, function () {
					console.log("支付失败")
					// 支付失败
					that.checkUserCancelPay()
				}) 
			} else if ("cash" == payType) {
				core.confirm("确认要使用货到付款吗?", function () {
					_this.finishPay(payType);
				}, function () { })
			} else if ("credit" == payType) {
				core.confirm("确认要支付吗?", function () {
					_this.finishPay(payType)
				}, function () { })
			}
		},

		finishPay: function (typeQuery, ordersn, showloading = true, loadingText = "支付中...", payComHideLoading = true) {
			this.isSubPay = false
			let payRequestData = {
				s: 'App.Order_Pay.complete',
				id: that.options.id,
				ordersn: ordersn
			}
			// 创建订单
			getApp().globalData.request(payRequestData).then(payRes => {
				uni.hideLoading()
				let subRes = payRes.data.data
				if ("SUCCESS" == subRes.result_code) {
					// 兼容平安银行,等待支付回调
					if (1642409719 == subRes.err_code) {
						chectOrderTask = setTimeout(function () {
							if (that.isOnPaying) {
								that.finishPay(typeQuery, ordersn, true, loadingText, false)
							}
						}, 290);
					} else if (0 != subRes.err_code) {
						that.isOnPaying = false
						foxui.toast(that, subRes.err_code_des)
					} else {
						that.isOnPaying = false
						setTimeout(function () {
							uni.hideLoading()
						}, 800)
						that.setData({
							order: subRes.data
						});
						that.showPoPSuccessPay(subRes.data)
					}
				} else {
					uni.hideToast()
					uni.showModal({
						title: "提示",
						content: subRes.err_code_des,
						showCancel: false
					})
				}
			})
		},

		/**
		 * 显示付款成功通知 */
		showPoPSuccessPay: function (order) {
			uni.setStorage({
				key: 'pay_complete_success_order_data',
				data: order,
				success: (result) => {
					uni.reLaunch({
						url: '/pages/order_sub/pay/complete_show/index'
					})
				}
			})
		},

		// 直接支付完成的情况,全部使用金豆抵扣 
		allUseCreditPay: function (order) {
			uni.hideLoading()
			that.showPoPSuccessPay(order)
		},

		// H5 公众号支付
		getH5WechatPay: function (wechatH5PayData) {
			uni.request({
				url: 'https://yld.angyakeji.com/www/src/tools/wechat/pay/jsapi.php',
				data: {
					outTradeNo: wechatH5PayData['outTradeNo'],
					payAmount: wechatH5PayData['payAmount'],
					orderName: wechatH5PayData['orderName'],
					openid: uni.getStorageSync('userInfo').openid,
				},
				header: {
					// 'custom-header': 'hello' //自定义请求头信息
				},
				success: (res) => {
					if (res.data) {
						callpay(res.data);
					} else {
						uni.showModal({
							title: '提示',
							content: '网络异常,编号2020092101'
						});
					}
				}
			})

			function jsApiCall(jsApiParameters) {
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest',
					jsApiParameters,
					function (res) {
						if (res.err_msg == 'get_brand_wcpay_request:ok') {
							// alert('支付成功！');
							that.finishPay('wechat', {});
						} else {
							alert('支付失败：' + res.err_code + res.err_desc + res.err_msg);
							uni.navigateBack();
						}
					}
				);
			}

			function callpay(jsApiParameters) {
				if (typeof WeixinJSBridge == "undefined") {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', jsApiCall);
						document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
					}
				} else {
					jsApiCall(jsApiParameters);
				}
			}
		},
		shopFun: function (t) {
			0 == core.pdata(t).id ? this.setData({
				shop: 1
			}) : this.setData({
				shop: 0
			});
		},
		phone: function (t) {
			core.phone(t);
		},
		closecoupon: function () {
			this.setData({
				coupon: false
			});
		},
		checkUserCancelPay: function () {
			that.isOnPaying = false
			if (that.isSubPay) {
				getApp().globalData.request({
					s: 'Order_CheckPay.isPay',
					id: that.options.id
				}).then(res => { });
				that.isSubPay = false;
			}
		},
	}
}

function onPayingProgress() {
	setInterval(function () {
		if (that.onPayingProgress >= 90) {
			that.onPayingProgress = 0
		} else {
			that.onPayingProgress += 40
		}
	}, 1000)
}
