<template>
	<view>
		<view class="AggOrdListBox">
			<view class="visaList row" v-for="(item,index) in g" :key="index" @click="goDetails(item)"
				:class="[item.orderStatus==4?'active':'']">
				<view class="visaListL">
					<image v-if="item.goodsPic&&item.goodsPic!=''" mode="aspectFill" :src="item.goodsPic" />
					<image v-else mode="aspectFill"
						src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/defaultHotelImg.png" />
					<text class="visaListLText">
						{{ item.goodTypeEnum.desc }}
					</text>
				</view>
				<view class="visaListR col column">
					<view class="visaListTitle">{{ item.goodsName }}</view>
					<view class="visaListText row">
					</view>
					<view class="col"></view>
					<view class="visaListNum row">
						<view class="visaListNumR">
							<text style="font-size: 20rpx;">{{ item.currencyCode?item.currencyCode:'CNY' }}</text>
							<text class="price-Num">
								{{parseFloat(item.totalPrice-item.preferentialPrice).toFixed(2)}}
							</text>
							<text class="price-stuff" style="font-size: 20rpx;color: rgba(164, 164, 164, 1)"></text>
						</view>
						<view class="visaListNumL row items-center">
							<!-- #ifdef MP-DI -->
							<template v-if="item.orderStatus!=5">
								{{ item.orderStatusInfo.desc }}
							</template>
							<template v-else>{{ item.afterSalesOrderStatusStr }}</template>
							<!-- #endif -->
							<!-- #ifdef MP-AG -->
							{{ item.orderStatusInfo.desc }}
							<!-- {{ item.orderStatusStr=='取消'?'已取消':item.orderStatusStr }}-->
							<!-- #endif -->
						</view>
					</view>
					<view class="row">
						<view class="col"></view>
						<!-- #ifdef MP-DI -->
						<view class="jz_Zailai" @click.stop="" style="width: 110rpx;">
							客服
							<button class="AggOrdListH-RBut" open-type="contact" show-message-card="true"></button>
						</view>
						<!-- #endif -->
						<view class="row">
							<!-- #ifdef MP-DI -->
							<template v-if="item.goodsType==9">
								<view v-if="item.orderStatus==1||item.orderStatus==2" class="jz_Zailai"
									style="width: 110rpx;margin-left: 10rpx;" @click.stop="cancelHotelOrder(item)">取消
								</view>
							</template>
							<template v-else>
								<view v-if="item.orderStatus==1||item.orderStatus==2" class="jz_Zailai"
									style="width: 110rpx;margin-left: 10rpx;" @click.stop="goCancelZK(item)">取消</view>
							</template>
							<view v-if="item.orderStatus==1" class="jz_Zailai jz_ZailaiZF"
								style="margin-left: 10rpx;" 
								:style="{'width':!item.remainingSeconds?'150rpx':'auto'}"
								:class="[item.remainingSeconds?'active':'']"
								@click.stop="submitGetCodeByOrderNo(item)">
								立即支付
								<!--<text v-if="item.remainingSeconds" style="margin-left: 10rpx;"> 剩余：{{ formatTime(item.remainingSeconds) }}</text> -->
							</view>
							<view v-if="item.orderStatus!=1" style="margin-left: 10rpx;" class="jz_Zailai"
								@click.stop="AnotherOrder(item)">再来一单</view>
							<!-- #endif -->
							<!-- #ifdef MP-AG -->
						
							<view v-if="item.goodsType==7&&(item.orderStatus==1||item.orderStatus==2)" class="jz_Zailai"
								style="width: 110rpx;margin-left: 10rpx;" @click.stop="cancelHotelOrder(item)">取消</view>
							<view v-if="item.goodsType!=7&&item.income == 0&&item.orderStatus==1" class="jz_Zailai"
								style="width: 110rpx;margin-left: 10rpx;" @click.stop="goCancel(item)">取消</view>
							<view v-if="item.goodsType==7&&item.orderStatus==1" class="jz_Zailai jz_ZailaiZF"
								style="margin-left: 10rpx;" 
								:style="{'width':!item.remainingSeconds?'150rpx':'auto'}"
								:class="[item.remainingSeconds?'active':'']"
								@click.stop="submitGetCodeByOrderNo(item)">
								立即支付 
								<!--<text v-if="item.remainingSeconds" style="margin-left: 10rpx;"> 剩余：{{ formatTime(item.remainingSeconds) }}</text>-->
							</view>
							<view v-else class="jz_Zailai" style="margin-left: 10rpx;" @click.stop="AnotherOrder(item)">
								再来一单</view>
								<!-- #endif -->
						</view>
					</view>
				</view>
			</view>
		</view>
		<cancelPrompt v-if="showModal" 
		:showModal="showModal" 
		@cancel="cancelModal" 
		@success="cancelSuccess" type="1"
			:orderNo="currentData.orderNo"
			:CancelPolicy="CancelPolicy"></cancelPrompt>
	</view>
</template>
<script>
	import cancelPrompt from "@/components/cancelPrompt/cancelPrompt.vue";
	export default {
		props: ['orders'],
		components: {
			cancelPrompt
		},
		data() {
			return {
				g: [],
				submitCancel: false,
				submit: false,
				orderInfo: null,
				showModal: false,
				currentData: null,
				b2b_user: null,
				CancelPolicy: null,
				timers: {}, // 存储定时器对象
      			checkInterval: null // 全局检查间隔
			}
		},
		watch: {
			orders: {
				handler(newVal, oldVal) {
					this.g = JSON.parse(JSON.stringify(newVal))
					this.g.forEach(x => {
						let goodsTypeHotel = 0
						// #ifdef MP-DI
							goodsTypeHotel = x.goodsType==9?1:0
						// #endif
						// #ifdef MP-AG
							goodsTypeHotel = x.goodsType==7?1:0
						// #endif
						if(x.orderStatus!=1) x.isExpired = true
						if (x.orderStatus==1&&goodsTypeHotel>0) {
							const now = Date.now();
							// const customStr = '2025-05-12 14:43:00'
							const customStr = x.createTimeStr
							const [date, time] = customStr.split(' ')
							const [year, month, day] = date.split('-')
							const [hours, minutes, seconds] = time.split(':')
							const parsedDate = new Date(year, month-1, day, hours, minutes, seconds)
							x.orderTime = parsedDate.getTime()
							const diff = x.orderTime + 5 * 60 * 1000 - now; // 5分钟倒计时
							let remainingSeconds = Math.max(diff, 0); // 确保不出现负数
							x.remainingSeconds = Math.floor(remainingSeconds/1000)
							// console.log("支付倒计时",x.remainingSeconds)
							if(x.remainingSeconds) this.initCountdown(x)
						}	
					});
				},
				deep: true,
			}
		},
		beforeDestroy() {
			// 清除所有定时器
			// Object.values(this.timers).forEach(timer => clearInterval(timer))
			// clearInterval(this.checkInterval)
  		},
		onShow(){
			
		},
		mounted() {
			this.b2b_user = uni.getStorageSync("b2b_user")
			// 全局定时检查（防止极端情况下定时器失效）
			this.checkInterval = setInterval(() => {
				this.checkExpiredOrders()
			}, 60000) // 每分钟检查一次
		},
		methods: {
			// 时间格式化
			formatTime(seconds) {
				const mins = Math.floor(seconds / 60)
				const secs = seconds % 60
				return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
			},
			initCountdown(order) {
				// return
				const timer = setInterval(() => {
					if(order.remainingSeconds>0){
						order.remainingSeconds--
					}else {
						if(order.isExpired) return clearInterval(null)
						order.isExpired = true
						this.submitCancel = true
						let cancelMsg = {
							OrderNo: order.OrderNo,
							ErpOrderId: order.erpOrderId,
							OrderTypeStr: "Hotel", //订单类型为酒店
							ConfirmID: "",
							Amount: 0,
						};
						order.orderStatus = 4
						this.cancelOrder(cancelMsg,1)
						clearInterval(null)
						this.timers[order.erpOrderId] = null
					}
				}, 1000)
				this.timers[order.erpOrderId] = timer
			},
			// 检查过期订单
			checkExpiredOrders() {
				const now = Date.now()
				this.g.forEach(order => {
					let goodsTypeHotel = 0
					// #ifdef MP-DI
						goodsTypeHotel = order.goodsType==9?1:0
					// #endif
					// #ifdef MP-AG
						goodsTypeHotel = order.goodsType==7?1:0
					// #endif
					if (order.orderStatus === 1 &&goodsTypeHotel>0&& 
						now - order.orderTime > 300000) { // 5分钟超时
						this.submitCancel = true
						let cancelMsg = {
							OrderNo: order.OrderNo,
							ErpOrderId: order.erpOrderId,
							OrderTypeStr: "Hotel", //订单类型为酒店
							ConfirmID: "",
							Amount: 0,
						};
						order.orderStatus = 4
						this.cancelOrder(cancelMsg,1)
					}
				})
			},
			cancelSuccess() {
				this.$emit('research', 5)
			},
			//取消酒店订单
			cancelHotelOrder(item) {
				var that = this;
				if (this.submitCancel) return
				this.submitCancel = true;
				var cancelMsg = {
					OrderNo: item.directOrderNo, //注意这是直客表的订单流水号
					ErpOrderId: item.erpOrderId, //这是第三方订单表的Id
					OrderTypeStr: "Hotel", //订单类型为酒店
					ConfirmID: "",
					Amount:0,
				};
				wx.showModal({
					title: '提示',
					content: '确定取消订单？',
					success: (tip) => {
						if (tip.confirm) {
							that.submitCancel = true
							//待付款-直接取消
							if (item.orderStatus == 1) {
								that.cancelOrder(cancelMsg)
							}
							//已付款，可能会有取消费用
							else if (item.orderStatus == 2) {
								var didaMsg = {
									BookingID: item.thirdOrderNo
								}
								that.apipost("dmc_post_GetDiDaBookingCancel", didaMsg, (res) => {
										if (res.resultCode == 1) {
											var tempData = res.data;
											if (tempData) {
												cancelMsg.ConfirmID = tempData.ConfirmID;
												cancelMsg.Amount=tempData.Amount;
												//有取消费用
												if (tempData.Amount && tempData.Amount > 0) {
													var tipmsg = "取消订单将收取【" + tempData.Amount +
														"】取消费用，是否确认取消订单?"
													wx.showModal({
														title: '提示',
														content: tipmsg,
														success: (tip) => {
															if (tip.confirm) {
																that.submitCancel = true;
																that.cancelOrder(cancelMsg);
															}
														}
													})
												}
												//无取消费用
												else {
													that.cancelOrder(cancelMsg);
												}
											}
										}
									},
									(err) => {
										uni.showToast({
											title: err.message,
											icon: "none",
										});
										that.submitCancel = false
									})
							}
						}
					}
				})
			},
			cancelOrder(postMsg,type) {
				if(type) return this.$emit('research');
				this.apipost(
					"post_CancelThirdHotelOrder", postMsg,
					(res) => {
						if (res.resultCode == 1) {
							uni.showToast({
								title: "操作成功",
								icon: "success",
							});
							this.$emit('research');
						}
					},
					(err) => {
						uni.showToast({
							title: err.message,
							icon: "none",
						});
						this.submitCancel = false
					}
				);
			},
			//调用支付
			submitGetCodeByOrderNo(item) {
				console.log("item", item)
				let mallUserInfo = uni.getStorageSync("mall_UserInfo");
				uni.showLoading({
					title: "请稍等片刻...",
				})
				if (this.submit || this.submitCancel) return;
				this.submit = true
				this.apipost("GetCodeByOrderNo_post", {
					OrderNo: item.directOrderNo?item.directOrderNo:item.orderNo,
					OpenId: mallUserInfo.OpenId,
					MallBaseId: mallUserInfo.MallBaseId
				}, (res) => {
					if (res.resultCode == 1) {
						this.orderInfo = JSON.parse(res.data.sPayInfo)
						this.goPayHandler(item);
					}
				}, e => {
					uni.hideLoading()
					uni.showToast({
						title: '无法发起支付，请稍后',
						icon: 'none',
						duration: 3000
					})
					this.submit = false
				});
			},
			goPayHandler(item) {
				let that = this;
				uni.requestPayment({
					provider: "wxpay",
					timeStamp: this.orderInfo.timeStamp,
					nonceStr: this.orderInfo.nonceStr,
					package: this.orderInfo.package,
					signType: this.orderInfo.signType,
					paySign: this.orderInfo.sign,
					success: function(res) {
						that.submit = false;
						uni.hideLoading()
						uni.showToast({
							title: "支付成功",
						});
						that.cancelSuccess();
					},
					fail: function(err) {
						that.submit = false;
						uni.hideLoading()
						uni.showToast({
							title: "支付失败",
							icon: "none",
						});
					},
				});
			},
			goPaySuccess(item) {
				let isFrom = null
				if (item.goodsType > 0 && item.goodsType < 4) { //线路
					isFrom = 1
				} else if (item.goodsType > 3 && item.goodsType < 8) { //景点门票

				} else if (item.goodsType > 7 && item.goodsType < 12) { //酒店住宿
					isFrom = 5
				} else if (item.goodsType > 11 && item.goodsType < 15) { //目的地用车

				} else if (item.goodsType == 15) { //签证
					isFrom = 3
				} else if (item.goodsType == 16) { //机票
					isFrom = 4
				}
				if (isFrom) {
					setTimeout(() => {
						uni.redirectTo({
							url: "/pages/jiuzhai/paysuccess?PreferPrice=" +
								(item.totalPrice - item.preferentialPrice).toFixed(2) +
								"&isFrom=" + isFrom,
						});
					}, 100);
				}
			},
			// 再来一单
			AnotherOrder(item) {
				let url = ''
				// #ifdef MP-DI
				if (item.goodsType > 0 && item.goodsType < 4) { //线路
					const pts = ['', 2, 0, 1]
					const productType = pts[item.goodsType]
					url = `jiuzhai/jz_Line?teamType=${productType}`
				} else if (item.goodsType > 3 && item.goodsType < 8) { //景点门票

				} else if (item.goodsType > 7 && item.goodsType < 12) { //酒店住宿

				} else if (item.goodsType > 11 && item.goodsType < 15) { //目的地用车
					url = "bus/index"
				} else if (item.goodsType == 15) { //签证
					url = "visa/visaList"
				} else if (item.goodsType == 16) { //机票
					url = "airTicket/airIndex"
				}
				// #endif
				// #ifdef MP-AG
				if (item.goodsType == 2) { //线路
					const pts = ['', 2, 0, 1]
					const productType = pts[item.goodsType]
					url = `jiuzhai/jz_Line?teamType=${productType}`
				} else if (item.goodsType == 4) { //景点门票

				} else if (item.goodsType == 3) { //酒店住宿

				} else if (item.goodsType == 7) { //道旅酒店住宿
					url = "hotel/list"
				} else if (item.goodsType == 5) { //目的地用车
					url = "bus/index"
				} else if (item.goodsType == 6) { //签证
					url = "visa/visaList"
				} else if (item.goodsType == 1) { //机票
					url = "airTicket/airIndex"
				}
				// #endif
				if (url) {
					uni.navigateTo({
						url: `/pages/${url}`,
					});
				}
			},
			// 详情
			goDetails(item) {
				let url = null
				let msg = null
				// #ifdef MP-DI
				msg = `OrderNo=${item.orderNo}`
				if (item.goodsType > 0 && item.goodsType < 4) url = `jiuzhai/jz_SureOrder?` //线路
				else if (item.goodsType > 3 && item.goodsType < 8) { //景点门票
				} else if (item.goodsType > 7 && item.goodsType < 12) { //酒店住宿
					msg = `orderId=` + item.erpOrderId
					url = `hotel/orderdetails?`;
				} else if (item.goodsType > 11 && item.goodsType < 15) { //目的地用车
					msg = `orderId=` + item.erpOrderId
					url = `bus/orderdetails?`;
				} else if (item.goodsType == 15) url = `visa/visa_SureOrder?` //签证  
				else if (item.goodsType == 16) url = `airTicket/airTicketOrderDetail?` //机票
				// #endif
				// #ifdef MP-AG
				msg = `orderId=${item.erpOrderId}`
				if (item.goodsType == 2) url = `jiuzhai/jz_SureOrder?` //线路
				else if (item.goodsType == 4) { //景点门票
				} else if (item.goodsType == 3) { //酒店住宿

				} else if (item.goodsType == 7) { //道旅酒店住宿
					url = `hotel/orderdetails?`;
				} else if (item.goodsType == 5) { //目的地用车
					let phone = `SalePhone=${item.SalePhone}&`
					url = `bus/orderdetails?`;
					if(item.SalePhone) url+=phone
				} else if (item.goodsType == 6) url = `visa/visa_SureOrder?` //签证  
				else if (item.goodsType == 1) { //机票
					url = `airTicket/airTicketOrderDetail?`
					msg = `id=${item.erpOrderId}`
				}
				// #endif
				if (url) {
					let path = `/pages/${url}${msg}`
					uni.navigateTo({
						url: path,
					});
				}
			},
			//取消订单(同行订单取消)
			goCancel(item) {
				let that = this
				if (this.submit || this.submitCancel) return
				wx.showModal({
					title: '提示',
					content: '确定取消订单？',
					success: (tip) => {
						if (tip.confirm) {
							that.submitCancel = true
							that.apipost(
								"b2b_get_GetB2BAllCancelOrder", {
									ID: item.erpOrderId,
									OrderTypeStr: item.goodsType,
								},
								(res) => {
									that.submitCancel = false
									if (res.resultCode == 1) {
										uni.showToast({
											title: "操作成功",
											icon: "success",
										});
										that.$emit('research');
									}
								},
								(err) => {
									that.submitCancel = false
									uni.showToast({
										title: err.message,
										icon: "none",
									})
								}
							);
						}
					}
				})
			},
			cancelModal() {
				this.showModal = false
			},
			//直客订单取消
			goCancelZK(item) {
				if (item.orderStatus == 2) {
					if(item.goodsType==12||item.goodsType==13||item.goodsType==14){
						this.initData(item.goodsId)
					}else{
						this.CancelPolicy = null	
					}
					this.currentData = item
					return this.showModal = true
				}
				let that = this
				if (this.submit || this.submitCancel) return
				wx.showModal({
					title: '提示',
					content: '确定取消订单？',
					success: (tip) => {
						if (tip.confirm) {
							that.submitCancel = true
							that.apipost(
								"GetCancelOrder_post", {
									OrderNo: item.orderNo,
								},
								(res) => {
									that.submitCancel = false
									if (res.resultCode == 1) {
										uni.showToast({
											title: "操作成功",
											icon: "success",
										});
										that.$emit('research');
									}
								},
								(err) => {
									uni.showToast({
										title: err.message,
										icon: "none",
									});
									that.submitCancel = false
								}
							);
						}
					}
				})
			},
			initData(ProductId) {
				this.apipost(
				"CarSingle_post_GetTYCarSingleProductInfo",{
					ProductId: ProductId,
				},
				res => {
					if (res.resultCode == 1) {
						this.CancelPolicy = res.data.CancelPolicy!=''?res.data.CancelPolicy:'暂无'
					}
				});
			},
		}
	}
</script>
<style lang="scss" scoped>
	@import url("@/asset/css/flex.css");

	.AggOrdListBox {
		padding: 0 36rpx;
	}

	.AggOrdList {
		border-radius: 18rpx;
		background: #fff;
		padding: 20rpx 30rpx;
		margin-bottom: 20rpx;
	}

	.AggOrdListH {
		font-size: 22rpx;
		color: #080A09;
	}

	.AggOrdListH-left text {
		color: #e91e63;
		background: rgba(234, 32, 100, .2);
		border-radius: 10rpx;
		display: block;
		padding: 2rpx 10rpx;
	}

	.AggOrdListH-RBBox {
		display: block;
		color: #1d1d1d;
		position: relative;
	}

	.AggOrdListH-RS {
		color: #9e9e9e;
		margin-left: 40rpx;
	}

	.AggOrdListH-RBut {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 1;
		opacity: 0;
	}

	.AggOrdListH-RBut {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 1;
		opacity: 0;
	}

	.jz_Zailai {
		border-radius: 16px;
		width: 150rpx;
		height: 60rpx;
		text-align: center;
		color: #111111;
		line-height: 60rpx;
		font-size: 24rpx;
		position: relative;
		border: 1rpx solid rgba(164, 164, 164, .3);
	}
	.jz_Zailai.active{
		padding: 0 20rpx;
	}
	.jz_Zailai.jz_ZailaiZF {
		color: #B99846;
		border: 1rpx solid #B99846;
	}

	.jz_ZailaiZX img {
		position: relative;
		top: 10rpx;
	}

	.visaList {
		padding: 30rpx;
		margin-bottom: 20rpx;
		background: #fff;
		overflow: hidden;
		border-radius: 14rpx;
	}

	.visaListL {
		width: 161rpx;
		height: 190rpx;
		overflow: hidden;
		margin-right: 19rpx;
		position: relative;
		border-radius: 14rpx;
	}

	.visaListL image {
		width: 100%;
		height: 100%;
		border-radius: 14rpx;
	}

	.visaListTitle {
		font-weight: bold;
		font-size: 28rpx;
		color: #111111;
		word-break: break-all;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		margin-bottom: 10rpx;
	}

	.visaListText text {
		background-color: rgba(226, 194, 122, .3);
		color: #B99846;
		margin-right: 16rpx;
		white-space: nowrap;
		border-radius: 6rpx;
		padding: 5rpx 9rpx;
		font-size: 20rpx;
	}

	.visaListNum {
		justify-content: space-between;
		align-items: center;
	}

	.visaListNumL text {
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 20rpx;
		color: #080A09;
		margin-left: 10rpx;
	}

	.visaListNum {
		margin-bottom: 15rpx;
	}

	.visaListNumR {
		color: rgba(255, 49, 102, 1);
	}

	.price-Num {
		font-size: 34rpx;
		margin-left: 5rpx;
		font-weight: bold;
	}

	.uDropdownText text {
		color: #444;
	}

	.uDropdownText.active text {
		color: #B99846;
		font-weight: bold;
	}

	.visaListLText {
		position: absolute;
		left: 0;
		top: 0;
		border-radius: 14rpx 0rpx 14rpx 0rpx;
		background: #B99846;
		padding: 4rpx 9rpx;
		font-size: 20rpx;
		color: #fff;
	}

	.visaList.active .visaListTitle,
	.visaList.active .visaListNumR,
	.visaList.active .visaListNumL {
		color: #CBCBCB;
	}

	.visaList.active .visaListLText {
		background: #CBCBCB;
	}

	.visaList.active .visaListL image {
		// filter: grayscale(100%); 
	}
</style>