<!-- 支付结果页面 -->
<template>
		<!-- result:{{result}} -->
		<view class="pay-result-box ss-flex-col ss-row-center ss-col-center">
			<!-- 信息展示 -->
			<view class="pay-waiting ss-m-b-30" v-if="payResult === 'waiting'" />
			<image class="pay-img ss-m-b-30" v-if="payResult === 'success'"
				:src="sheep.$url.static('/static/images/order_pay_success.gif')" />
			<image class="pay-img ss-m-b-30" v-if="['failed', 'closed'].includes(payResult)"
				:src="sheep.$url.static('/static/images/order_paty_fail.gif')" />
			<view class="tip-text ss-m-b-30" v-if="payResult === 'success'">{{ t('order.payment_successful') }}</view>
			<view class="tip-text ss-m-b-30" v-if="payResult === 'failed'">{{ t('order.payment_failed') }}</view>
			<view class="tip-text ss-m-b-30" v-if="payResult === 'closed'">{{ t('order.order_closed') }}</view>
			<view class="tip-text ss-m-b-30" v-if="payResult === 'waiting'">{{ t('order.checking_payment_result') }}</view>
			<view class="pay-total-num ss-flex" v-if="payResult === 'success'">
				<view>¥{{ fen2yuan(state.orderInfo.price) }}</view>
			</view>
			<!-- 操作区 -->
			<view class="btn-box ss-flex ss-row-center ss-m-t-50">
				<button class="back-btn ss-reset-button" @tap="goBack">
					{{ t('order.return_home') }}
				</button>
				<!-- <button class="check-btn ss-reset-button" v-if="payResult === 'failed'" @tap="
            sheep.$router.redirect('/pages/pay/index', { id: state.id, orderType: state.orderType })
          ">
					{{ t('order.retry_payment') }}
				</button> -->
				<button class="check-btn ss-reset-button" v-if="payResult === 'success' && !isTopUp" @tap="goOrderList">
					{{ t('order.view_order') }}
				</button>
				<button class="check-btn ss-reset-button" v-if="payResult === 'success' && isTopUp" @tap="goWallet">
					{{ t('order.view_wallet') }}
				</button>
				<!-- TODO 非繁人:拼团接入 -->
				<!-- <button class="check-btn ss-reset-button" v-if="payResult === 'success' && state.tradeOrder.type === 3"
					@tap="sheep.$router.redirect('/pages/activity/groupon/order')">
					{{ t('order.my_group_buying') }}
				</button> -->
			</view>
			<!-- TODO 非繁人:订阅 -->
			<!-- #ifdef MP -->
			<!-- <view class="subscribe-box ss-flex ss-m-t-44">
				<image class="subscribe-img" :src="sheep.$url.static('/static/images/cargo.png')" />
				<view class="subscribe-title ss-m-r-48 ss-m-l-16">{{ t('order.get_realtime_shipping_info') }}</view>
				<view class="subscribe-start" @tap="subscribeMessage">{{ t('order.subscribe_now') }}</view>
			</view> -->
			<!-- #endif -->
		</view>

</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
		computed,
		watchEffect
	} from 'vue';
	import axios from 'axios';
	import 'https://wx.gtimg.com/pay_h5/goldplan/js/jgoldplan-1.0.0.js';
	import {
		onLoad,
		onHide,
		onShow
	} from '@dcloudio/uni-app';
	import {
		isEmpty
	} from 'lodash';
	import sheep from '@/sheep';
	import PayOrderApi from '@/sheep/api/pay/order';
	import {
		fen2yuan
	} from '../../sheep/hooks/useGoods';
	import OrderApi from '@/sheep/api/trade/order';
	import {
		showWalletModal,
		colseWalletModal
	} from '@/sheep/hooks/useModal';
	import { t } from '@/locale'
	const order = ref({});
	const result = ref({});
	const url = ref('https://payapp.weixin.qq.com');



	// 获取地址栏字段
	const getQueryVal = () => {
		const queryStr = window.location.href.split("?")[1]; // 地址栏字符串
		const strArr = queryStr.split('&');
		if (strArr.length) {
			strArr.forEach((val) => {
				const subStrArr = val.split('=');
				result.value[subStrArr[0]] = subStrArr[1];
			});
		}
	};

	// 用于展示商家小票
	const showCustomPage = () => {
		console.log("showCustomPage")
		const customData = JSON.stringify({
			action: 'onIframeReady',
			displayStyle: 'SHOW_CUSTOM_PAGE',
			// height: 900
		});
		parent.postMessage(customData, url.value);
	};
	const state = reactive({
		id: 0, // 支付单号
		orderType: 'goods', // 订单类型
		result: 'unpaid', // 支付状态
		orderInfo: {}, // 支付订单信息
		tradeOrder: {}, // 商品订单信息,只有在 orderType 为 goods 才会请求。目的:【我的拼团】按钮的展示
		counter: 0, // 获取结果次数
	});
	// 支付结果 result => payResult
	const payResult = computed(() => {
		if (state.result === 'unpaid') {
			return 'waiting';
		}
		if (state.result === 'paid') {
			return 'success';
		}
		if (state.result === 'failed') {
			return 'failed';
		}
		if (state.result === 'closed') {
			return 'closed';
		}
	});
	// 是否充值消费分订单
	const isTopUp = computed(() => {
		return result.value.out_trade_no.includes("top-up") ;
	});
	// 获得订单信息
	async function getOrderInfo(payOrderNo) {
		state.counter++;
		// 1. 加载订单信息
		const {
			data,
			code
		} = await PayOrderApi.getFuYouPayOrderByStatus(payOrderNo);
		if (code === 0) {
			state.orderInfo = data;
			if (!state.orderInfo || state.orderInfo.status === 30) {
				// 支付关闭
				state.result = 'closed';
				return;
			}
			if (state.orderInfo.status !== 0) {
				// 非待支付,可能是已支付,可能是已退款
				state.result = 'paid';
				// #ifdef MP
				subscribeMessage();
				// #endif
				// 特殊:获得商品订单信息
				// if (state.orderType === 'goods') {
				// 	const {
				// 		data,
				// 		code
				// 	} = await PayOrderApi.getByStatus2(state.orderInfo.merchantOrderId);
				// 	if (code === 0) {
				// 		state.tradeOrder = data;
				// 	}
				// }
				return;
			}
		}
		// 2.1 情况三一:未支付,且轮询次数小于三次,则继续轮询
		if (state.counter < 3 && state.result === 'unpaid') {
			setTimeout(() => {
				getOrderInfo(payOrderNo);
			}, 1500);
		}
		// 2.2 情况二:超过三次检测才判断为支付失败
		if (state.counter >= 3) {
			state.result = 'failed';
		}
	}
	// onShow(() => {
	// 	if (isEmpty(state.orderInfo)) {
	// 		return;
	// 	}
	// 	getOrderInfo(state.id);
	// });
	
	// onHide(() => {
	// 	state.result = 'unpaid';
	// 	state.counter = 0;
	// });
	// 组件挂载后执行
	onMounted(async () => {
		await showCustomPage();
		await getQueryVal();
		await getOrderInfo(result.value.out_trade_no);
		// if (!result.value.out_trade_no) {
		// 	parent.alert('没有订单号,请联系管理员!');
		// } else {
		// 	queryOrderInfo();
		// }
	
	});


	// 返回首页
	const goBack = () => {
		const mchData = {
			action: 'jumpOut',
			jumpOutUrl: `${location.origin}/#/pages/index/index?points=${state.orderInfo.jf}&socialStatus=${state.orderInfo.sj}`
		};
		console.log(mchData.jumpOutUrl)
		const postData = JSON.stringify(mchData);
		parent.postMessage(postData, url.value);
	};
	// 跳转到订单
	const goOrderList = () => {
		console.log(state.orderInfo)
		const mchData = {
			action: 'jumpOut',
			jumpOutUrl: `${location.origin}/#/pages/order/list?type=2&points=${state.orderInfo.jf}&socialStatus=${state.orderInfo.sj}`
		};
		console.log(mchData.jumpOutUrl)
		const postData = JSON.stringify(mchData);
		parent.postMessage(postData, url.value);
	};
	const goWallet = () => {
		const mchData = {
			action: 'jumpOut',
			jumpOutUrl: `${location.origin}/#/pages/user/wallet/score`
		};
		const postData = JSON.stringify(mchData);
		parent.postMessage(postData, url.value);
	}
</script>

<style lang="scss" scoped>
	@keyframes rotation {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.score-img {
		width: 36rpx;
		height: 36rpx;
		margin: 0 4rpx;
	}
	
	.pay-result-box {
		// padding: 60rpx 0;
		height:100vh;
		background:#fff;
		.pay-waiting {
			margin-top: 20rpx;
			width: 60rpx;
			height: 60rpx;
			border: 10rpx solid rgb(233, 231, 231);
			border-bottom-color: rgb(204, 204, 204);
			border-radius: 50%;
			display: inline-block;
			// -webkit-animation: rotation 1s linear infinite;
			animation: rotation 1s linear infinite;
		}

		.pay-img {
			width: 130rpx;
			height: 130rpx;
		}

		.tip-text {
			font-size: 30rpx;
			font-weight: bold;
			color: #333333;
		}

		.pay-total-num {
			font-size: 36rpx;
			font-weight: 500;
			color: #333333;
			font-family: OPPOSANS;
		}

		.btn-box {
			width: 100%;

			.back-btn {
				width: 190rpx;
				height: 70rpx;
				font-size: 28rpx;
				border: 2rpx solid #dfdfdf;
				border-radius: 35rpx;
				font-weight: 400;
				color: #595959;
			}

			.check-btn {
				width: 190rpx;
				height: 70rpx;
				font-size: 28rpx;
				border: 2rpx solid #dfdfdf;
				border-radius: 35rpx;
				font-weight: 400;
				color: #595959;
				margin-left: 32rpx;
			}
		}

		.subscribe-box {
			.subscribe-img {
				width: 44rpx;
				height: 44rpx;
			}

			.subscribe-title {
				font-weight: 500;
				font-size: 32rpx;
				line-height: 36rpx;
				color: #434343;
			}

			.subscribe-start {
				color: var(--ui-BG-Main);
				font-weight: 700;
				font-size: 32rpx;
				line-height: 36rpx;
			}
		}
	}
</style>