<template>
	<view class="top_footer">
		<template v-if="hasDiscount">
			<view class="pay_price">
				<!-- <view class='pay_price_y'>优惠价</view> -->
				<view class="pay_price_p">￥{{price}}</view>
				<view class="pro_tag"><text style="margin: 6rpx 5rpx 0 0;">优惠后:</text><text
						class="price">￥{{promotionPrice}}</text></view>
			</view>
			<view style="display: flex;justify-content: center; align-items: center; margin: 20rpx 0;">
				<!-- <view class="people_sy"> 本次优惠剩余名额：{{residueNum}} </view> -->
				<view class="people_sy_time">
					<!-- <uni-countdown :show-day="false" :hour="testHour" :minute="testMinute" :second="testSecond" /> -->
					<text>优惠倒计时：</text><uni-countdown :show-day="true" background-color="#FF9D41" color="#ffffff"
						:start="start" :hour="testHour" :minute="testMinute" :second="testSecond" />
				</view>
			</view>
		</template>
		<view class="pay_btn_lg" @click="payHandle">
			{{hasDiscount? promotionPrice : price}}元解锁专属测试报告
		</view>
	</view>
	<uni-popup ref="popup" type="center">
		<view class="pay_dialog">
			<view class="btn_area">
				<image style="margin-right: 89rpx;" @click="completeHandle"
					src="https://test.jue-ming.com:8849/api/show?filePath=./webo/EQtest/paymentPage/complete_btn.png"
					mode="widthFix"></image>
				<image @click="uncompleteHandle"
					src="https://test.jue-ming.com:8849/api/show?filePath=./webo/EQtest/paymentPage/uncomplete_btn.png"
					mode="widthFix"></image>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import {
		timestampFormatter
	} from '../../utils/util.js'
	export default {
		data() {
			return {
				orderNo: '',
				orderInfo: {},
				peopleNum: 0,
				residueNum: 0, // 剩余名额
				price: 0, // 正常价格
				promotionPrice: 0, // 优惠价格
				promotionEndTime: 0, // 结束时间（时间戳）
				testHour: 0, // 时
				testMinute: 0, // 分
				testSecond: 0, // 秒
				start: false
			}
		},
		onLoad(options) {
			if (options.orderNo) {
				this.orderNo = options.orderNo;
				setTimeout(() => {
					this.payEnsure();
				}, 200)
			}
			this.orderInfo = uni.getStorageSync('orderInfo');
			this.getPeople();
			this.queryPromotion();
		},
		computed: {
			// 是否有折扣
			hasDiscount() {
				let timeSpan = new Date().getTime();
				let endTime = this.promotionEndTime - timeSpan;
				return this.residueNum > 0 && endTime > 0
			}
		},
		methods: {
			payHandle() {
				// #ifdef H5
				this.getH5Pay();
				// #endif
				// #ifdef MP-TOUTIAO
				this.createOrder();
				// #endif
			},
			// 检查订单支付状态
			checkOrder() {
				let _this = this;
				_this.$request
					.get({
						url: `api/wx-pay/queryOrder/${_this.orderNo}`,
						loadingTip: "加载中...",
						data: {},
					})
					.then((res) => {
						uni.hideLoading();
						let resultInfo = JSON.parse(res.data.body)
						if (resultInfo.trade_state === 'SUCCESS') {
							uni.navigateTo({
								url: `/newScale/Charm/testResult?resultId=${this.orderInfo.resultId}&messageShare=1`
							});
						} else {
							return;
						}
					});
			},
			// 拉起微信支付
			getH5Pay(params) {
				let _this = this;
				_this.$request
					.get({
						url: `api/orderInfo/queryOrderByResultIdAndUserId/${this.orderInfo.userId}/${this.orderInfo.resultId}`,
						loadingTip: "加载中...",
						data: {},
					})
					.then((res) => {
						uni.hideLoading();
						if (res.data && res.data.orderStatus === '支付成功') {
							uni.navigateTo({
								url: `/newScale/Charm/testResult?resultId=${this.orderInfo.resultId}&messageShare=1`
							});
						} else {
							// _this.orderInfo.total = _this.hasDiscount ? _this.promotionPrice : _this.price;
							_this.$request
								.post({
									url: "api/wx-pay/h5Pay",
									loadingTip: "加载中...",
									data: _this.orderInfo
								})
								.then((res) => {
									let redirect_url = encodeURI(
										`http://hnhong-duo.com/webo/newScale/Charm/paymentPage?orderNo=${res.data.orderNo}`
									)
									window.location.href = `${res.data.codeUrl}&redirect_url=${redirect_url}`;
								});
						}
					});
			},
			createOrder() {
				let _this = this;
				let params = {
					resultId: _this.orderInfo.resultId,
					subject: _this.orderInfo.description,
					body: _this.orderInfo.description,
					total_amount: _this.orderInfo.total * 100,
					msgPage: "",
				}
				_this.$request
					.post({
						url: "api/douyin/createOrder",
						loadingTip: "加载中...",
						data: params
					})
					.then((res) => {
						_this.orderNo = res.data.orderNo;
						let imageUrl = 'https://test.jue-ming.com:8849/api/show?filePath=./webo/EQtest/banner1.png';
						_this.payToutiao(
							res.data.orderId,
							res.data.orderToken,
							res.data.orderNo
						);
					});
			},
			payToutiao(orderId, orderToken, orderNo) {
				let _this = this;
				tt.pay({
					orderInfo: {
						order_id: orderId,
						order_token: orderToken,
					},
					service: 5,
					success: (response) => {
						_this.timer = setInterval(() => {
							_this.getQueryOrder(orderNo);
						}, 1000);
					},
					fail: (err) => {
						uni.showToast({
							icon: "none",
							name: "支付失败",
						});
					},
				});
			},
			// 订单状态
			getQueryOrder(orderNo) {
				let _this = this;
				_this.$request
					.get({
						url: `api/douyin/queryOrder/${orderNo}`,
						loadingTip: "加载中...",
						data: {},
					})
					.then((res) => {
						if (res.code == "200") {
							if (res.data.statusCode == "SUCCESS") {
								let imageUrl =
									'https://test.jue-ming.com:8849/api/show?filePath=./webo/EQtest/banner1.png';
								uni.navigateTo({
									url: `/newScale/Charm/testResult?resultId=${_this.orderInfo.resultId}&messageShare=1`
								});

								clearInterval(_this.timer);
								uni.showToast({
									title: "支付成功",
								});
							} else if (res.data.statusCode == "CLOSED") {
								// console.log("订单支付回调成功===========CLOSED》", _this.trade_state_closed );
							} else {
								clearInterval(_this.timer);
								// console.log("订单支付回调成功CLOSED===========》", _this.trade_state_closed);
							}
						} else {
							uni.showToast({
								title: "支付失败",
							});
						}
					});
			},
			// 查询测试人数
			getPeople() {
				let _this = this;
				_this.$request
					.get({
						url: "record/countByFlag?flag=20210804164957",
						loadingTip: "加载中..."
					})
					.then((res) => {
						_this.peopleNum = res.data + 57000
					});
			},
			payEnsure() {
				// console.log(11111)
				this.$refs.popup.open();
			},
			uncompleteHandle() {
				this.$refs.popup.close();
			},
			completeHandle() {
				uni.showLoading({
					title: ''
				});
				this.checkOrder();
			},
			// 查询优惠信息
			queryPromotion() {
				let _this = this;
				_this.$request
					.get({
						url: `api/promotionInfo/queryPromotionDetail/${this.orderInfo.productId}`,
						loadingTip: "加载中...",
						data: {},
					})
					.then((res) => {
						this.residueNum = res.data.residueNum
						this.price = res.data.price;
						this.promotionPrice = res.data.promotionPrice;
						this.promotionEndTime = new Date(res.data.promotionEndTime).getTime()
						this.getDhms();
						uni.hideLoading();
					});
			},
			// 获取天时分秒
			getDhms() {
				let timeSpan = this.promotionEndTime - new Date().getTime();
				let time = timestampFormatter(timeSpan);
				this.testHour = time.h;
				this.testMinute = time.m;
				this.testSecond = time.s;
				this.start = true;
			}
		}
	}
</script>

<style>
</style>