<!-- 统一收银台支付 -->

<template>
	<view class="page">
		<view class="pay-price">
			<view class="price">
				<text class="unit">￥</text>
				<view v-if="fromType == 'order'">
					<numberScroll :num='payPriceShow' color="#E93323" width='30' height='50' fontSize='50'></numberScroll>
				</view>
				<view v-else>
					<numberScroll :num='orderData.price' color="#E93323" width='30' height='50' fontSize='50'></numberScroll>
				</view>
			</view>
			<view class="count-down">
				支付剩余时间：
				<countDown :is-day="false" :tip-text="' '" :day-text="' '" :hour-text="' : '" :minute-text="' : '" :second-text="' '" :datatime="invalidTime"></countDown>
			</view>
		</view>
		<view class="payment">
			<view class="title">
				支付方式
			</view>
			<view class="item acea-row row-between-wrapper" v-for="(item,index) in cartArr" :key="index"
				v-show='item.payStatus' @click="payType(item.number || 0, item.value, index)">
				<view class="left acea-row row-between-wrapper">
					<image class="iconfont" src="https://imgs.agrimedia.cn/shop/shop-icon.png"
						style="width: 50rpx; height: 50rpx;"></image>
					<view class="text">
						<view class="name">{{item.name}}</view>
						<view class="info" v-if="item.value == 'yue'">
							{{item.title}} <span class="money">￥{{ item.number }}</span>
						</view>
						<view class="info" v-else>{{item.title}}</view>
					</view>
				</view>
				<image style="width: 31rpx;height: 31rpx; margin-top: 10rpx"
					src="https://imgs.agrimedia.cn/shop/select_icon-red.png"></image>
			</view>
		</view>
		<view class="btn">
			<view class="button acea-row row-center-wrapper" @click='goPay(number, paytype)'>确认支付</view>
			<view class="wait-pay" @click="waitPay">暂不支付</view>
		</view>
		<view v-show="false" v-html="formContent"></view>
	</view>
	</view>
</template>

<script>
	import countDown from '@/components/countDown';
	import numberScroll from '@/components/numberScroll.vue';
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';
	import {
		getCashierOrder,
		orderPay
	} from '@/api/order.js';
	import {
		basicConfig
	} from '@/api/public.js';

	export default {
		components: {
			countDown,
			numberScroll
		},
		props: {
			orderId: {
				type: String,
				default: ''
			},
			fromType: {
				type: String,
				default: ''
			},
			// 怡亚通支付参数
			dat: {
				type: Object,
				default: {}
			},
			// 点餐订单参数
			orderData: {
				type: Object,
				default: {}
			},
			tabIndex: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				//支付方式
				cartArr: [{
					"name": '微信支付',
					"icon": "icon-weixin2",
					value: 'middle_pay',
					title: '使用微信快捷支付',
					payStatus: 1,
				}],
				active: 0,
				payPrice: 0,
				payPriceShow: 0,
				payPostage: 0,
				offlinePostage: false,
				invalidTime: 0,
				initIn: false,
				jumpData: {
					orderId: '',
					msg: ''
				},
				formContent: '',
				oid: 0,
				number: ''
			}
		},
		watch: {
			cartArr: {
				handler(newV, oldValue) {
					let newPayList = [];
					newV.forEach((item, index) => {
						if (item.payStatus) {
							item.index = index;
							newPayList.push(item)
						}
					});
					this.$nextTick(e => {
						this.active = newPayList[0].index;
						this.paytype = newPayList[0].value;
					})

				},
				immediate: true,
				deep: true
			}
		},
		onLoad() {
			if (typeof window.WeixinJSBridge === "undefined") {
				if (document.addEventListener) {
					document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady.bind(this), false);
				} else if (document.attachEvent) {
					document.attachEvent('WeixinJSBridgeReady', onBridgeReady.bind(this));
					document.attachEvent('onWeixinJSBridgeReady', onBridgeReady.bind(this));
				}
			} else {
				onBridgeReady.call(this);
			}
		},
		methods: {
			getBasicConfig() {
				basicConfig().then(res => {
					//微信支付是否开启
					this.cartArr[0].payStatus = res.data.pay_weixin_open || 0
					//支付宝是否开启
					this.cartArr[1].payStatus = res.data.ali_pay_status || 0;
					//#ifdef MP
					this.cartArr[1].payStatus = 0;
					//#endif
					//余额支付是否开启
					this.cartArr[2].payStatus = res.data.yue_pay_status
					if (res.data.offline_pay_status) {
						this.cartArr[3].payStatus = 1
					} else {
						this.cartArr[3].payStatus = 0
					}
					//好友代付是否开启
					this.cartArr[4].payStatus = res.data.friend_pay_status || 0;
					this.getCashierOrder()
				}).catch(err => {
					uni.hideLoading();
					console.log(err)
				})
			},
			getCashierOrder() {
				uni.showLoading({
					title: `创建订单中`
				});
				getCashierOrder(this.orderId, this.fromType).then(res => {
					this.payPrice = this.payPriceShow = res.data.pay_price
					this.payPostage = res.data.pay_postage
					this.offlinePostage = res.data.offline_postage
					this.invalidTime = res.data.invalid_time
					this.cartArr[2].number = res.data.now_money;
					this.number = Number(res.data.now_money) || 0;
					this.oid = res.data.oid
					uni.hideLoading();
				}).catch(err => {
					uni.hideLoading();
					console.log(err)
				})
			},
			payType(number, paytype, index) {
				this.active = index;
				this.paytype = paytype;
				this.number = number;
				if (this.offlinePostage) {
					if (paytype == 'offline') {
						this.payPriceShow = this.$util.$h.Sub(this.payPrice, this.payPostage);
					} else {
						this.payPriceShow = this.payPrice;
					}

				}
			},
			formpost(url, postData) {
				let tempform = document.createElement("form");
				tempform.action = url;
				tempform.method = "post";
				tempform.target = "_self";
				tempform.style.display = "none";
				for (let x in postData) {
					let opt = document.createElement("input");
					opt.name = x;
					opt.value = postData[x];
					tempform.appendChild(opt);
				}
				document.body.appendChild(tempform);
				this.$nextTick(e => {
					tempform.submit();
				})
			},
			
			waitPay() {
				window.location.href = `${HTTP_REQUEST_URL}/JXH5/pages/goods/order_list/index?activeInd=1`
			},

			goPay(number, paytype) {
				let that = this;
				uni.showLoading({
					title: `支付中`
				});
				
				// 检查环境
				const ua = window.navigator.userAgent.toLowerCase();
				const isWechat = ua.includes('micromessenger');
				const isH5 = typeof window !== 'undefined';
				
				if (!isH5 || !isWechat) {
					uni.hideLoading();
					uni.showToast({
						title: '请在微信浏览器中使用微信支付功能',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				
				
				// 支付参数直接支付
				if (this.dat.prePay?.appId || this.dat.appId) {
					let jsConfig = that.dat.prePay || that.dat
					const onBridgeReady = () => {
						window.WeixinJSBridge.invoke(
							'getBrandWCPayRequest', {
								'appId': jsConfig.appId,
								'timeStamp': jsConfig.timeStamp || jsConfig.timestamp,
								'nonceStr': jsConfig.nonceStr,
								'package': jsConfig.package,
								'signType': jsConfig.signType,
								'paySign': jsConfig.paySign,
								'redirect_url': 'www.baidu.com',
							}, (res) => {
								const isSuccess = res.err_msg === 'get_brand_wcpay_request:ok';
								uni.hideLoading();
								uni.showToast({
									title: isSuccess ? "支付完成" : "取消支付",
									icon: isSuccess ? 'success' : 'none',
									duration: 2000,
								});
								
								setTimeout(() => {
									window.location.href = `${HTTP_REQUEST_URL}/JXH5/pages/goods/order_list/index`
								}, 2000);
							}
						);
					};
					
					if (typeof window.WeixinJSBridge === "undefined") {
						if (document.addEventListener) {
							document.addEventListener('WeixinJSBridgeReady', onBridgeReady.bind(this), false);
						} else if (document.attachEvent) {
							document.attachEvent('WeixinJSBridgeReady', onBridgeReady.bind(this));
							document.attachEvent('onWeixinJSBridgeReady', onBridgeReady.bind(this));
						}
					} else {
						onBridgeReady.call(this);
					}
					return
				};
				
				
				// 电商下单支付
				orderPay({
					uni: that.orderId,
					paytype: paytype,
					type: that.friendPay ? 1 : 0,
					quitUrl: location.port ? location.protocol + '//' + location.hostname + ':' + location
						.port +
						'/pages/goods/order_details/index?order_id=' + this.orderId : location.protocol +
						'//' + location.hostname +
						'/pages/goods/order_details/index?order_id=' + this.orderId
				}).then(res => {
					let status = res.data.status,
						orderId = res.data.result.order_id,
						jsConfig = res.data.result.jsConfig
						
						// 必须通过下单操作才算是0元支付,所以回调里执行跳转操作
						if (Number(this.payPriceShow) == 0) {
							window.location.href = `${HTTP_REQUEST_URL}/JXH5/pages/goods/order_list/index?activeInd=${this.tabIndex}`
							return
						};
					switch (status) {
						case 'MIDDLE_PAY':
						case 'WECHAT_PAY':
							// 微信支付处理
							if (!jsConfig) {
								uni.showToast({
									title: '支付参数错误',
									icon: 'none'
								});
								uni.hideLoading();
								return;
							}
							const onBridgeReady = () => {
								window.WeixinJSBridge.invoke(
									'getBrandWCPayRequest', {
										'appId': jsConfig.appId,
										'timeStamp': jsConfig.timeStamp,
										'nonceStr': jsConfig.nonceStr,
										'package': jsConfig.package,
										'signType': jsConfig.signType,
										'paySign': jsConfig.paySign,
										'redirect_url': 'www.baidu.com',
									}, (res) => {
										const isSuccess = res.err_msg === 'get_brand_wcpay_request:ok';
										uni.hideLoading();
										uni.showToast({
											title: isSuccess ? "支付完成" : "取消支付",
											icon: isSuccess ? 'success' : 'none',
											duration: 2000,
										});
										
										setTimeout(() => {
											window.location.href = `${HTTP_REQUEST_URL}/JXH5/pages/goods/order_list/index?activeInd=${this.tabIndex}`
										}, 2000);
									}
								);
							};
							
							if (typeof window.WeixinJSBridge === "undefined") {
								if (document.addEventListener) {
									document.addEventListener('WeixinJSBridgeReady', onBridgeReady.bind(this), false);
								} else if (document.attachEvent) {
									document.attachEvent('WeixinJSBridgeReady', onBridgeReady.bind(this));
									document.attachEvent('onWeixinJSBridgeReady', onBridgeReady.bind(this));
								}
							} else {
								onBridgeReady.call(this);
							}
					}

				}).catch(err => {
					// 弹出提示需要登录
					uni.hideLoading();
					setTimeout(() => {
						window.location.href = `${HTTP_REQUEST_URL}/JXH5/pages/goods/order_list/index`
					}, 2000);
				})
			},
			
			// 自定义时长
			getTime() {
				this.invalidTime = this.getTimestampAfter(15);
			},
			
			getTimestampAfter(val) {
				const now = Math.floor(Date.now() / 1000); // 转换为秒级
				return now + (val * 60);
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #F5F5F5;
	}

	.page {
		.pay-price {
			display: flex;
			justify-content: center;
			flex-direction: column;
			align-items: center;
			padding: 50rpx 0 40rpx 0;

			.price {
				color: #E93323;
				margin-bottom: 20rpx;
				display: flex;
				align-items: flex-end;

				.unit {
					font-size: 34rpx;
					font-weight: 500;
					line-height: 41rpx;
				}

				.num {
					font-size: 50rpx;
					font-weight: 600;
				}
			}

			.count-down {
				display: flex;
				align-items: center;
				background-color: #fff;
				padding: 8rpx 28rpx;
				border-radius: 40rpx;
				font-size: 24rpx;
				color: #E93323;

				.time {
					margin-top: 0 !important;
				}

				.red {
					margin: 0 !important;
				}
			}
		}

		.payment {
			width: 690rpx;
			border-radius: 14rpx 14rpx;
			background-color: #fff;
			z-index: 999;
			margin: 0 30rpx;

			.title {
				color: #000;
				font-weight: 800;
				font-size: 30rpx;
				padding: 30rpx 0 0 30rpx;
				margin-bottom: 30rpx;
			}

			.payMoney {
				font-size: 28rpx;
				color: #333333;
				text-align: center;
				margin-top: 50rpx;

				.font-color {
					margin-left: 10rpx;

					.money {
						font-size: 40rpx;
					}
				}
			}


		}

		.payment.on {
			transform: translate3d(0, 0, 0);
		}

		.icon-xuanzhong11 {
			color: #E93323 !important;
		}

		.payment .item {
			border-bottom: 1rpx solid #eee;
			height: 100rpx;
			margin-left: 30rpx;
			padding-right: 30rpx;
			display: flex;
			padding-bottom: 20rpx;
			align-items: center;
		}

		.payment .item:last-child {
			border-bottom: none;
		}

		.payment .item .left {
			display: flex;
			align-items: center;
			flex: 1;
		}

		.payment .item .left .text {
			flex: 1;
		}

		.payment .item .left .text .name {
			font-size: 30rpx;
			color: #333;
		}

		.payment .item .left .text .info {
			font-size: 22rpx;
			color: #999;
		}

		.payment .item .left .text .info .money {
			color: #ff9900;
		}

		.payment .item .left .iconfont {
			font-size: 50rpx;
			color: #09bb07;
			margin-right: 28rpx;
		}

		.payment .item .left .iconfont.icon-zhifubao {
			color: #00aaea;
		}

		.payment .item .left .iconfont.icon-yuezhifu {
			color: #ff9900;
		}

		.payment .item .left .iconfont.icon-yuezhifu1 {
			color: #eb6623;
		}

		.payment .item .left .iconfont.icon-tonglianzhifu1 {
			color: #305fd8;
		}

		.payment .item .iconfont {
			font-size: 40rpx;
			color: #ccc;
		}

		.icon-haoyoudaizhifu {
			color: #F34C3E !important;
		}

		.btn {
			position: fixed;
			left: 30rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			bottom: 30rpx;
			bottom: calc(30rpx + constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
			bottom: calc(30rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
		}

		.wait-pay {
			color: #aaa;
			font-size: 24rpx;
			padding-top: 20rpx;
		}

		.button {
			width: 690rpx;
			height: 90rpx;
			border-radius: 45rpx;
			color: #FFFFFF;
			background-color: #E93323;
			line-height: 90rpx;
			text-align: center;
		}
	}
</style>