<template>
	<view class="mg-lr-24">
		<view class="white-bg-wrap">
			<common-title :msg="'团购商品'"></common-title>
			<view class="mg-top-22">
				<view class="product-info u-f mg-top-20" @click="goDetail('/pagesC/tugou-detail/tugou-detail')">
					<view class="mg-right-10" style="flex: 1">
						<image style="width: 128rpx;height:128rpx;" :src="goodsInfo.goodsImage"></image>
					</view>
					<view class="right" style="flex: 3">
						<view class="light-black fs28 fw400 mg-bot-8">{{goodsInfo.goodsName}}</view>
						<view class="light-gray fs24 mg-bot-10">{{goodsInfo.specificationsName}}</view>
						<view class="product-price u-f u-f-jcsb mg-bot-10">
							<view class="left u-f u-f-aic">
								<view class="main-color fs28">
									<text class="fs24">￥</text>
									<text class="fw400 fw700">{{goodsInfo.groupBuyingPrice}}</text>
								</view>
							</view>
							<view class="right fs24 light-gray">
								x1
							</view>
						</view>
					</view>
				</view>
				<view class="u-f u-f-jcfs u-f-aic mg-bot-12">
					<text class="main-title-btn fs18 fw400 mg-right-48">{{goodsInfo.clusteringNum}}人可成团</text>
					<text class="fs24 main-color">倒计时：{{goodsInfo.remainingTime}}</text>
				</view>
				<view class="u-f u-f-jcfs u-f-aic">
					<view class="mg-right-24" style="flex: 2">
						<progress :percent="groupProductProgress" stroke-width="3" activeColor="#FF4502" />
					</view>
					<view class='join-group-person fs24 fw400'>已团{{goodsInfo.groupNumbered}}人</view>
				</view>
			</view>
		</view>

		<view class="white-bg-wrap mg-top-20" style="padding-top: 16rpx;">
			<view class="u-f u-f-aic u-f-jcsb light-black fs28 fw400 mg-bot-40">
				<text>团购价</text>
				<text>￥{{goodsInfo.groupBuyingPrice}}</text>
			</view>
			<view class="u-f u-f-jcsb light-black fs28 fw400 mg-bot-42" v-if="JSON.stringify(youhuiquan) !== '{}'">
				<view>优惠券</view>
				<view v-if="goodsInfo.couponList.length > 0" class="u-f u-f-jcfs u-f-aic" @click="handleShowGoodQuan">
					<text class="mg-right-6">{{youhuiquan.couponName}}</text>
					<text
						class="main-color mg-right-10">{{ youhuiquan.discountMethod == 1 ? '￥' : '' }}{{youhuiquan.discountResult}}</text>
					<image src="../.././static/common/sg_right_arrow.png" class="small-gray-right-arrow"
						:mode="'widthFix'" />
				</view>
				<view class="u-f u-f-jcfs u-f-aic" v-else>
					<text class="mg-right-6">暂无可用优惠券</text>
					<image src="../.././static/common/sg_right_arrow.png" class="small-gray-right-arrow"
						:mode="'widthFix'" />
				</view>
			</view>
			<view class="u-f u-f-jcfe u-f-aic mg-bot-42" v-else>
				<text class="fs28 fw400 light-black mg-right-8">无优惠券可用</text>
			</view>
			<view class="u-f u-f-jcfe u-f-aic fs24">
				<view class="light-black mg-right-10">已优惠</view>
				<view class="main-color mg-right-20">
					<text>￥{{youhuiInfo.couponDiscountAmount}}</text>
				</view>
				<view class="light-black">合计</view>
				<view class="mg-right-6">
					<text class="fs24">￥</text>
					<text class="fw600 fs32">{{youhuiInfo.discountedAmount}}</text>
				</view>
			</view>
		</view>

		<view class="fix-bot">
			<view class="content u-f u-f-jcsb u-f-aic">
				<view class="u-f u-f-aic u-f-fdc">
					<view class="u-f u-f-aic u-f-jcfs">
						<text class="fs24 light-black mg-right-6">实付</text>
						<view class="main-color" v-if="JSON.stringify(youhuiInfo) !== '{}'">
							<text class="fs24">￥</text>
							<text class="fs32">{{youhuiInfo.discountedAmount}}</text>
						</view>
						<view class="main-color" v-else>
							<text class="fs24">￥</text>
							<text class="fs32">{{actualPayment}}</text>
						</view>
					</view>
				</view>
				<view class="line-gradient-btn" @click="handlePay">
					立即支付
				</view>
			</view>
		</view>

		<uni-popup :position="'bottom'" :show="showModal" @click="handleHideGoodQuan">
			<view class="share-modal">
				<image class="gray-close" src="../.././static/common/gray_close.png" :mode="'widthFix'"
					@click="handleHideGoodQuan"></image>
				<view class="u-f u-f-aic u-f-jcc one-line-ellipsis mg-bot-32">
					<slot name="share-modal-title">商品券</slot>
				</view>

				<view class="mg-bot-32">
					<scroll-view scroll-y="true" style="height: 400rpx;">
						<view class="u-f u-f-jcfs u-f-aifs mg-bot-20" v-for="item in goodsInfo.couponList"
							:key="item.id">
							<view class="mg-right-10" style="flex: 1">
								<image style="width: 156rpx;height:156rpx" :src="item.couponIcon"></image>
							</view>
							<view style="flex: 3">
								<view class="u-f u-f-jcsb u-f-aic">
									<view class="u-f u-f-fdc" @click="goDetail('/pagesF/coupon-detail/coupon-detail')">
										<text class="fs28 light-black mg-bot-24">{{item.couponName}}</text>
										<text class="fs24 light-gray mg-bot-30">仅用于商城指定产品</text>
										<view class="u-f u-f-jcfs u-f-aifs">
											<text class="fs24 light-gray mg-right-12">所需等级</text>
											<text class="fs26 deep-gray">{{item.userType}}</text>
										</view>
									</view>
									<view class="u-f u-f-aic" @click="selectYouHuiQuan(item)">
										<text class="small-gradient-btn">去使用</text>
									</view>
								</view>
								<view class="light-gray fs24 mg-top-10" style="text-align: right;">
									{{item.deadline}}(含)前使用
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import commonTitle from "../.././components/common-title/common-title.vue"
	export default {
		components: {
			commonTitle
		},
		data() {
			return {
				goodsImage: '',
				goodsName: '',
				couponList: '',
				groupBuyingPrice: '',
				originalPrice: '',
				specificationsName: '',
				remainingTime: '',
				actualPayment: '',
				groupNumbered: '',
				clusteringNum: '',
				showModal: false,
				youhuiquan: {},
				youhuiInfo: {},
				goodsInfo: {},
				timer: null
			}
		},
		onLoad(options) {
			this.goodsInfo = JSON.parse(decodeURIComponent(options.data))
			this.youhuiquan = this.goodsInfo.couponList.length > 0 ? this.goodsInfo.couponList[0] : ''

			this.discountedAmount()
			this.startCountdown()
		},
		computed: {
			groupProductProgress() {
				return this.goodsInfo.groupNumbered / this.goodsInfo.clusteringNum * 100
			}
		},
		methods: {
			async shoppCartOrderDetails() {
				let res = await this.$http.get('/api/client/order/shoppCartOrderDetails?key=' + this.billId)
				let resData = res.data.data
				this.shopSureBillInfo = resData || {}
				this.youhuiquan = JSON.stringify(this.shopSureBillInfo) !== '{}' && this.shopSureBillInfo.couponList ?
					this.shopSureBillInfo.couponList[0] : {}
				this.discountedAmount()
			},
			async discountedAmount() {
				let data = {
					//goodsNum: this.goodsInfo.goodsNum,
					groupId: this.goodsInfo.groupId,
					specificationsId: this.goodsInfo.specificationsId
				}

				if (this.youhuiquan && this.youhuiquan.id) {
					data = Object.assign(data, {
						couponId: this.youhuiquan.id
					})
				}

				let res = await this.$http.post('/api/client/groupBuying/discountedAmount', data)
				let resData = res.data.data
				this.youhuiInfo = resData || {}
			},
			async placeOrder() {
				// 下单
				let data = {
					"groupId": this.goodsInfo.groupId,
					"storeId": this.goodsInfo.storeId,
					"type": 3, // 1-商品 2-会员权益 3-团购商品 4-积分商品 5-优惠券 6-投诉
					"userCarId": this.goodsInfo.userCarId,
					"goodsId": this.goodsInfo.goodsId,
					"specificationsId": this.goodsInfo.specificationsId,
					"goodsNum": this.goodsInfo.goodsNum
				}

				if (this.youhuiquan && this.youhuiquan.id) {
					data = Object.assign(data, {
						couponId: this.youhuiquan.id
					})
				}

				let res = await this.$http.post('/api/client/order/placeOrder', data)
				console.log("下单", res)
				if (res.data.code === 200) {
					console.log(res.data)
					this.orderId = res.data.data
					// 支付
					this.payMoney()
				} else {
					uni.showToast({
						title: '下单失败',
						icon: 'none'
					})
				}
			},
			async payMoney() {
				let data = {
					"orderId": this.orderId
				}
				uni.showLoading()
				let res = await this.$http.get('/api/client/lkl/pay', data)
				console.log("支付", res.data)
				let resData = res.data.data
				uni.hideLoading()
				this.wakeWxPay(resData)

				// if (res.data.code===200) {
				// 	uni.redirectTo({
				// 		url: "/pagesE/pay-success/pay-success?orderInfo="+encodeURIComponent(JSON.stringify(resData))
				// 	})
				// }
			},
			wakeWxPay(resData) {
				var app_id = resData.resp_data.acc_resp_fields.app_id
				var nonce_str = resData.resp_data.acc_resp_fields.nonce_str
				var package_word = resData.resp_data.acc_resp_fields['package']
				var partner_id = resData.resp_data.acc_resp_fields.partner_id
				var prepay_id = resData.resp_data.acc_resp_fields.prepay_id
				var time_stamp = resData.resp_data.acc_resp_fields.time_stamp
				var pay_sign = resData.resp_data.acc_resp_fields.pay_sign
				var sign_type = resData.resp_data.acc_resp_fields.sign_type

				var orderInfo = {
					appid: app_id, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
					nonceStr: nonce_str, // 随机字符串
					package: package_word, // 固定值
					partnerid: partner_id, // 微信支付商户号
					prepayid: prepay_id, // 统一下单订单号
					timeStamp: time_stamp, // 时间戳（单位：秒）
					signType: sign_type,
					paySign: pay_sign // 签名，这里用的 MD5/RSA 签名
				}

				uni.requestPayment({
					provider: "wxpay",
					appid: app_id, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
					nonceStr: nonce_str, // 随机字符串
					package: package_word, // 固定值
					partnerid: partner_id, // 微信支付商户号
					prepayid: prepay_id, // 统一下单订单号
					timeStamp: time_stamp, // 时间戳（单位：秒）
					signType: sign_type,
					paySign: pay_sign, // 签名，这里用的 MD5/RSA 签名
					success(res) {
						console.log("success", res)
						//发起订阅
						uni.redirectTo({
							url: "/pagesE/pay-success/pay-success"
						})
					},
					fail(e) {
						console.log("fail", e)
					}
				})
			},
			handlePay() {
				this.placeOrder()
			},
			enterMyGarage() {
				uni.navigateTo({
					url: "/pagesA/my-garage/my-garage"
				})
			},
			handleShowGoodQuan() {
				this.showModal = true;
			},
			handleHideGoodQuan() {
				this.showModal = false;
			},
			selectYouHuiQuan(item) {
				this.handleHideGoodQuan()
				this.youhuiquan = item
				this.discountedAmount()
			},
			// 更新所有商品的倒计时
			startCountdown() {

				this.timer = setInterval(() => {
					console.log(this.goodsInfo.remainingTime);
					// 解析剩余时间
					let timeParts = this.goodsInfo.remainingTime.split(':');
					console.log(timeParts);
					let hours = parseInt(timeParts[0], 10);
					let minutes = parseInt(timeParts[1], 10);
					let seconds = parseInt(timeParts[2], 10);

					// 如果时间还未结束
					if (hours > 0 || minutes > 0 || seconds > 0) {
						// 每秒减少1秒
						seconds -= 1;

						// 如果秒数变为负数，调整分钟和小时
						if (seconds < 0) {
							seconds = 59;
							minutes -= 1;
						}
						if (minutes < 0) {
							minutes = 59;
							hours -= 1;
						}

						// 更新倒计时
						this.goodsInfo.remainingTime = this.formatTime(hours, minutes, seconds);
					}
				}, 1000);
			},

			// 格式化时间：将小时、分钟、秒格式化为 "时:分:秒"
			formatTime(hours, minutes, seconds) {
				return `${this.padZero(hours)}:${this.padZero(minutes)}:${this.padZero(seconds)}`;
			},
			// 格式化数字，确保两位数显示
			padZero(num) {
				return num < 10 ? '0' + num : num;
			}
		}
	}
</script>

<style>
	page {
		background-color: #F9F9F9;
	}
</style>

<style lang="scss" scoped>
	.gray-down-arrow {
		width: 16rpx;
		height: 16rpx;
		// background: url(../.././static/shop/bot-arrow.png) no-repeat center center;
		background-size: 100%;
	}

	.gray-right-arrow {
		width: 16rpx;
		height: 16rpx;
		// background: url(../.././static/right-arrow.png) no-repeat center center;
		background-size: 100%;
	}

	.check {
		width: 36rpx;
		height: 36rpx;
		background-color: red;
		// background: url(../.././static/common/check.png) no-repeat center center;
		background-size: 80%;
	}

	.province {
		padding: 12rpx 20rpx;
		color: #ffffff;
		background-color: #20CF55;
		border-radius: 8rpx 0rpx 0rpx 8rpx;
		border: 1rpx solid #0087EF;
	}

	.car-num {
		padding: 12rpx 20rpx;
		color: #20CF55;
		background: #E5EEF5;
		border-radius: 0 8rpx 8rpx 0;
		border: 1rpx solid #20CF55;
	}

	.fix-bot {
		width: 100%;
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 333;

		.content {
			background-color: #ffffff;
			padding: 10rpx 24rpx;
		}
	}

	.line-gradient-btn {
		background: linear-gradient(90deg, #FF4502 0%, #FF8903 100%);
		border-radius: 41rpx 41rpx 41rpx 41rpx;
		text-align: center;
		padding: 22rpx 120rpx;
		color: #ffffff;
	}

	.wx-apply {
		width: 44rpx;
		height: 44rpx;
		// background: url(../.././static/common/wx_apply.png) no-repeat center center;
		background-size: 100%;
	}

	.product-info {
		background-color: #ffffff;
		padding: 22rpx;
		border-radius: 18rpx;

		.right {
			.product-name {
				color: #333333;
			}
		}
	}

	.main-title-btn {
		padding: 6rpx 12rpx;
		background: #FFF6F3;
		border-radius: 9rpx 4rpx 9rpx 2rpx;
		border: 1rpx solid #FFD0BF;
		color: #FF4502;
	}

	.small-gray-right-arrow {
		width: 8rpx;
		height: 16rpx;
	}

	.share-modal {
		position: relative;
		padding: 24rpx;

		.gray-close {
			position: absolute;
			right: 28rpx;
			top: 28rpx;
			width: 42rpx;
			height: 42rpx;
			// background: url(../.././static/common/gray-close.png) no-repeat center center;
			background-size: 100%;
		}

		.content-wrap {
			width: 100%;

			.inner {
				padding: 12rpx;
				border-radius: 10rpx;
				background-color: #ffffff;
				border: 10rpx solid #FF4502;
			}
		}
	}
</style>