<template>
	<view class="m-content">
		<public-module></public-module>
		<view class="m-top-order-btn-group">
			<view class="m-top-btn m-btn-all" :class="{ active: activeButton == '' }" @click="setActive('')">
				<image class="m-top-ico m-btn-all-ico" src="../static/img/order_all.svg" alt="" />
				全部订单
			</view>
			<view class="m-top-btn m-btn-waitPay" :class="{ active: activeButton === '1' }" @click="setActive('1')">
				<image class="m-top-ico m-btn-waitPay-ico" src="../static/img/order_pending-payment-.svg" alt="" />
				待支付
			</view>
			<view class="m-top-btn m-btn-overPay" :class="{ active: activeButton == '2' }" @click="setActive('2')">
				<image class="m-top-ico m-btn-overPay-ico" src="../static/img/order_paid.svg" alt="" />
				已支付
			</view>
			<view class="m-top-btn m-btn-backPay" :class="{ active: activeButton == '3' }" @click="setActive('3')">
				<image class="m-top-ico m-btn-backPay-ico" src="../static/img/order_refund.svg" alt="" />
				退款/售后
			</view>
		</view>

		<view class="m-list-box m-order-list">
			<mescroll-body top="140" :topbar="true" :safearea="true" ref="mescrollRef" @init="mescrollInit" :down="downOption"
				@down="downCallback" @up="upCallback">
				<view class="m-card-list">
					<view class="m-card" v-for="item in list" @click.stop="goDetails(item)">
						<view class="m-card-title">
							<view class="m-title-code-box">
								<img class="m-img" src="../static/img/order_number.svg" alt="" />
								<view class="m-title-middle">订单编号:{{ item.orderNumber }}</view>
							</view>
							<view
								:class="['m-ticket-status', 'm-tag-no-border', item.orderStatus == 3 ? 'm-tag-no-border-blue' : 'm-tag-no-border-red']">
								{{ item.orderStatusLabel }}
							</view>
						</view>
						<view class="m-card-content">
							<view class="m-ticket-item">
								<view class="m-ticket-inf">

									<view class="m-ticket-name">
										<view>{{ item.ticketList[0].ticketname }}</view>
										<view class="m-ticket-status">
											{{ item.ticketList[0].ticketStatusName ? item.ticketList[0].ticketStatusName : '暂无' }}
										</view>

									</view>
									<view class="m-ticket-info">
										<view class="mm-box">
											<view class="m-ticket-price">销售价:¥{{ item.ticketList[0].settlementAmount }}
											</view>
											<view class="m-ticket-nums">X{{ item.ticketList[0].ticketNums }}</view>
										</view>

										<view class="m-ticket-ticketPOV">使用有效期:{{
											parseTime(item.ticketList[0].startdate, '{y}-{m}-{d}') }}至{{
											parseTime(item.ticketList[0].enddate, '{y}-{m}-{d}') }}</view>
									</view>
								</view>
							</view>
							<view class="transition-button" v-if="!item.show && item.ticketList.length > 1"
								@click.stop="handle(['fade', 'slide-top'], item)">
								展开更多信息
								<uni-icons custom-prefix="iconfont" type="icon-z-arrowDown" size="15"></uni-icons>
							</view>
							<uni-transition ref="ani" :mode-class="modeClass" :styles="styles" :show="item.show">
								<view class="m-ticket-item" v-for="items in item.ticketList.slice(1, item.ticketList.length)">
									<view class="m-ticket-inf">
										<!-- <view class="m-ticket-img-box">
											<image class="m-ticket-img" :src="items.ticketCoverImg" mode=""></image>
										</view> -->
										<view class="m-ticket-name">
											<view>{{ items.ticketname }}</view>
											<view class="m-ticket-status">
												{{ items.ticketStatusName ? items.ticketStatusName : '暂无' }}
											</view>

										</view>
										<view class="m-ticket-info">
											<view class="mm-box">
												<view class="m-ticket-price">销售价:¥{{ items.settlementAmount }}</view>
												<view class="m-ticket-nums">X{{ items.ticketNums }}</view>
											</view>
											<view class="m-ticket-ticketPOV">使用有效期:{{
												parseTime(items.startdate, '{y}-{m}-{d}') }}至{{
												parseTime(items.enddate, '{y}-{m}-{d}') }}</view>
										</view>
									</view>
								</view>
								<view class="transition-button" v-if="item.show" @click.stop="handle(['fade', 'slide-top'], item)">
									收起
									<uni-icons custom-prefix="iconfont" type="icon-z-arrowUp" size="15"></uni-icons>
								</view>
							</uni-transition>
						</view>
						<view class="m-card-feet">
							<view class="m-order-nums-price">¥{{ item.settlementAmount }}</view>
							<view class="m-feet-count">
								<uni-countdown v-if="item.orderStatus == 1" :show-day="false" :show-hour="false"
									:minute="item.countdownMinute" :second="item.countdownSecond" @timeup="timeup" />
								<view class="m-btn-box">
									<button size="mini" class="m-prime" @click.stop="cancelOrder(item.orderNumber)"
										v-if="item.orderStatus == 1">取消订单</button>
									<!--这里走支付流程-->
									<button size="mini" class="m-prime" @click.stop="goPay(item)" v-if="item.orderStatus == 1">支付</button>
									<!--这里走退款流程-->
									<button size="mini" class="m-prime" @click.stop="refund(item)"
										v-if="item.canAbove == true">申请退款</button>
									<!--这里跳转到预定页面-->
									<!-- <button size="mini" class="m-prime-line" @click.stop="bookAgain"
										v-if="item.orderStatus == 4 || item.orderStatus == 3">再次预定</button> -->
									<!--这里跳转到申请发票页面-->

									<button size="mini" class="m-prime" v-if="item.orderStatus == 4"
										@click.stop="delOrder(item.id)">删除</button>
								</view>
							</view>
						</view>
					</view>
				</view>
			</mescroll-body>
		</view>
		<uni-popup mask-background-color="rgba(0,0,0,0.2)" class="m-refund-pop" ref="refundPopup" type="center"
			border-radius="10px 10px 0 0">
			<view class="m-pop-content">
				<view class="m-pop-title">申请退款</view>
				<view class="m-pop-middle">
					<view class="m-middle-list">
						<view class="m-middle-list-item">
							<view class="m-item-label">退款清单</view>
							<view class="m-item-value-box">
								<view class="m-item-value m-item-value-item" v-for="item in orderInfo.ticketList">
									<span class="ticket-name">{{item.ticketname }}</span>
									<span class="ticket-num">*{{item.ticketNums}}张</span>
								</view>
							</view>
						</view>
						<view class="m-middle-list-item">
							<view class="m-item-label">支付方式</view>
							<view class="m-item-value">微信支付</view>
						</view>
						<view class="m-middle-list-item">
							<view class="m-item-label">退款金额</view>
							<view class="m-item-value">￥{{ orderInfo.payAmount }}</view>
						</view>
					</view>
					<view class="m-middle-remark">退款金额原路返回</view>
				</view>
				<view class="m-pop-feet">
					<button class="m-prime-line" @click="closeBackMoney" size="mini">取消</button>
					<button class="m-prime" @click="backMoney" size="mini">确认退款</button>
				</view>
			</view>
		</uni-popup>
		<u-popup :show="isPayPopup" mode="bottom" @close="isPayPopup = false" round="10">
			<f-pay :show-title="false" :show="isPayPopup" :order="orderInfo" :payMoney="orderInfo.settlementAmount"
				:tradeNo="orderInfo.orderNumber" @payResult="payResult"></f-pay>
		</u-popup>
	</view>
</template>

<script>
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js';
import uPopup from "../components/uview-ui/components/u-popup/u-popup.vue";
import uniTransition from "../components/uni-transition/components/uni-transition/uni-transition.vue"
import fPay from "../components/f-pay/f-pay";
import { parseTime } from "@/common/util";
export default {
	mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
	components: {
		fPay, uPopup, uniTransition
	},
	data() {
		return {
			orderInfo: null,
			activeButton: '', // 初始状态下没有活动的按钮
			show: false, // 控制显示状态的布尔值
			modeClass: 'fade', // 控制显示模式的类名
			isPayPopup: false,
			tradeNo: '16fw61cqew6464wdc', //支付单号
			downOption: {
				auto: false //是否在初始化后,自动执行downCallback; 默认true
			},
			testMinute: 30,
			timeupSecond: 0,
			list: [], //商品数据

		};
	},
	onShow() {
		this.judgeLogin()
		this.upCallback()
	},
	mounted() {
	},
	methods: {
		//支付结果
		payResult(data) {
			console.log(data);
			if (data.payStatus == 1) {
				uni.showToast({ title: '支付成功', icon: 'none' });
				this.isPayPopup = false
				this.upCallback()
			} else {
				uni.showToast({ title: '支付失败', icon: 'none' });
			}
			//uni.showToast({title: data.detail.errMsg,icon:'none'});
		},
		async startCountdownForAllOrders(val) {
			val.forEach(item => {
				if (item.orderStatus == 1) {
					this.startCountdown(item);
				}
			});
		},
		startCountdown(item) {
			const orderTime = new Date(item.orderTime);
			const targetTime = new Date(orderTime.getTime() + 30 * 60 * 1000); // 订单时间加30分钟

			this.calculateCountdown(item, targetTime);
		},
		calculateCountdown(item, targetTime) {
			const interval = setInterval(() => {
				const now = new Date();
				const diff = targetTime - now;

				if (diff <= 0) {
					clearInterval(interval);
					item.countdownMinute = 0;
					item.countdownSecond = 0;
					this.timeup(item);
				} else {
					item.countdownMinute = Math.floor(diff / 1000 / 60);
					item.countdownSecond = Math.floor((diff / 1000) % 60);
				}
			}, 1000);
		},
		timeup(item) {
			console.log('时间到！', item);
			// 处理时间到后的逻辑
		},
		closeBackMoney() {
			this.$refs.refundPopup.close();
			this.upCallback()
		},
		//退款接口
		backMoney() {
			let httpData = {
				id: this.orderInfo.belongingPayOrderId,
				ticketId: 0,
			};
			if (this.orderInfo.qmxOrderNumber == null) {
				this.$Request
					.put(this.$config.refund, httpData, null, null, false, true).then(res => {
						this.$refs.refundPopup.close();
						if (res.data != null) {
							uni.showToast({
								title: '退款已提交',
								icon: 'none',
								mask: false
							})
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								mask: false
							})
						}
						setTimeout(() => {
							this.upCallback()
						}, 1000)
					}).catch(err => {
						console.log(err)
					})
			} else {
				this.$Request
					.put(this.$config.refundWeChat, httpData, null, null, false, true).then(res => {
						this.$refs.refundPopup.close();
						if (res.data != null) {
							uni.showToast({
								title: '退款已提交',
								icon: 'none',
								mask: false
							})
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								mask: false
							})
						}
						setTimeout(() => {
							this.upCallback()
						}, 1000)
					}).catch(err => {
						console.log(err)
					})
			}

		},
		//支付
		goPay(val) {
			console.log(val)
			this.orderInfo = val
			this.isPayPopup = true

		},
		parseTime(val, par) {
			return parseTime(val, par)
		},
		setActive(button) {
			uni.showLoading({
				title: '加载中...',
				mask: true
			})
			this.activeButton = button; // 更新活动的按钮
			this.upCallback()
		},
		// 计算订单总价
		handelPrice(value) {
			let price = 0;
			value.forEach((item) => {
				if (item.ticketStatus == 1) {
					price += item.ticketPrice;
				}
			});
			return price.toFixed(2);
		},
		// 切换显示状态和模式
		handle(type, item) {
			item.show = !item.show
			this.modeClass = type;
		},
		imageErr(value) {
			// 处理图片错误
			console.log(value);
		},
		/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
		upCallback(page) {
			//联网加载数据
			if (page) {
				this.loadData(page.num);

			} else {
				this.loadData(1);
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300 // 动画时长，单位 ms
				});
			}
		},
		// 下拉刷新
		loadData(pageNo) {
			let that = this
			const userInfo = uni.getStorageSync("userInfo");
			const extConfig = uni.getAccountInfoSync().miniProgram;
			let appId = extConfig.appId

			let httpData = {
				openid: userInfo.openid,
				appid: appId,
				orderStatus: this.activeButton == 3 ? '' : this.activeButton,
				orderStatusTwo: this.activeButton == 3 ? 4 : '',
				pageNo: pageNo,
				pageSize: 10
			};
			this.$Request
				.get(this.$config.getOrderList, httpData, null, null, false, false)
				.then((res) => {
					console.log(res)
					uni.stopPullDownRefresh();
					// 为每个 item 添加 show 属性
					const listWithShow = res.data.list.map(item => {
						item.show = false; // 或者根据你的需求设置 show 的值
						return item;
					});
					listWithShow.forEach(item => {

						const index = item.ticketList.findIndex(ele => ele.ticketStatus == '1' && ele.refundRules != 1);
						if (index != -1) {
							item.canAbove = true
						} else {
							item.canAbove = false; // 根据需求设置
						}
					})
					console.log(listWithShow, 'item.ticketListKKKKKK')
					this.mescroll.endByPage(listWithShow.length, res.data.total / 10); // 必传参数(当前页的数据个数, 总页数)

					if (pageNo == 1) {
						this.list = listWithShow;
					} else {
						this.list = this.list.concat(listWithShow);
					}
					that.$forceUpdate();
					console.log(this.list);

					// this.startCountdownForAllOrders(this.list);

					uni.hideLoading();
				})
				.catch(() => {
					//联网失败, 结束加载
					this.mescroll.endErr();
				});
		},
		//退款
		refund(val) {
			console.log(val, 'val')
			let payAmount = 0
			if (val && Array.isArray(val.ticketList)) {
				const filteredList = val.ticketList.filter(item => item.ticketStatus == 1);
				payAmount = filteredList.reduce((sum, item) => {
					return sum + (item.settlementAmount || 0); // 确保 settlementAmount 存在
				}, 0);
				val.ticketList = filteredList; // 更新 ticketList
			}
			this.orderInfo = val; // 赋值给 orderInfo
			this.orderInfo.payAmount = payAmount; // 赋值给 orderInfo
			console.log(this.orderInfo);

			// backOrder
			this.$refs.refundPopup.open();
		},
		//取消接口
		viewCancelOrder(orderNumber) {
			let httpData = {
				orderNumber: orderNumber,
			}
			this.$Request
				.get(this.$config.cancelOrder, httpData, null, null, false, false)
				.then((res) => {
					if (res.code == 0) {
						uni.showToast({
							title: '取消成功',
							icon: 'none'
						});
						// this.upCallback();
						this.mescroll.resetUpScroll()
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				})
		},
		//再次预定
		bookAgain() {
			uni.showModal({
				icon: 'exception',
				content: `“***门票”已下架，请返回首页选购其他门票`,
				success: function (res) {
					if (res.confirm) {
						console.log('用户点击确定');
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		//去详情
		goDetails(val) {
			if (val.id) {
				const orderInf = encodeURIComponent(JSON.stringify(val))
				uni.navigateTo({
					url: '/subPageC/order/orderDetail?id=' + val.id + '&belongId=' + val.belongingPayOrderId + '&orderInf=' + orderInf
				})
			}
		},
		//取消订单
		cancelOrder(orderNumber) {
			let this_ = this
			uni.showModal({
				icon: 'warning',
				content: `确定取消该笔订单吗`,
				success: function (res) {
					if (res.confirm) {
						this_.viewCancelOrder(orderNumber);
						console.log('用户点击确定');
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		//删除订单接口
		viewDelectOrder(id) {
			let httpData = {
				id: id,
			}
			this.$Request
				.get(this.$config.delectOrder, httpData, null, null, false, false)
				.then((res) => {
					if (res.code == 0) {
						uni.showToast({
							title: '删除成功',
							icon: 'none'
						});
						this.upCallback();
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				})
		},
		//删除订单
		delOrder(id) {
			let this_ = this
			uni.showModal({
				icon: 'warning',
				content: `确定删除该笔订单吗`,
				success: function (res) {
					if (res.confirm) {
						this_.viewDelectOrder(id);
						console.log('用户点击确定');
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.m-top-order-btn-group {
	display: flex;
	width: 95%;
	margin: 0 2.5%;
	justify-content: space-evenly;
	padding: 30rpx 0;
	font-size: 24rpx;
	text-align: center;
	align-items: center;
	position: fixed;
	top: 0;
	z-index: 9;
	background: #fff;
	border-radius: 0 0 20rpx 20rpx;

	.m-top-btn {
		width: 20%;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 10rpx 5rpx;

		.m-top-ico {
			width: 40rpx;
			height: 40rpx;
			margin-bottom: 20rpx;
		}
	}

	.active {
		position: relative;

		::before {
			content: '';
			width: 50%;
			height: 5rpx;
			position: absolute;
			bottom: 0;
			left: 50%;
			transform: translateX(-50%);
			background: linear-gradient(-90deg, #0983ff 0%, #57abff 100%);
			box-shadow: 0rpx 2rpx 6rpx 0rpx rgba(9, 131, 255, 0.35);
			border-radius: 3rpx;
		}
	}
}

.m-list-box {
	margin: 0 2.5%;
}

.m-card-list {
	.m-card {
		background: #fff;
		padding: 20rpx;
		border-radius: 15rpx;
	}

	.m-card-title {
		display: flex;
		line-height: 70rpx;
		font-size: 24rpx;
		justify-content: space-between;
		border-bottom: solid 1rpx #ddd;
		padding-bottom: 20rpx;

		.m-title-code-box {
			display: flex;
			justify-content: start;
			align-items: center;

			.m-img {
				width: 28rpx;
				height: 30rpx;
			}

			.m-title-middle {
				margin-left: 15rpx;
			}
		}
	}

	.m-card-content {
		padding: 15rpx;

		.m-ticket-item {
			padding: 15rpx;
			background-color: #eef3ff;
			border-radius: 20rpx;

			&:not(:last-child) {

				margin-bottom: 20rpx;
			}

			.m-ticket-inf {
				display: flex;
				margin: 20rpx 0;
				flex-direction: column;

				.m-ticket-name {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.m-ticket-status {
						font-family: Source Han Sans SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #999999;
					}

				}

				.m-ticket-img-box {
					width: 139rpx;
					height: 139rpx;
					margin-right: 25rpx;
					flex: none;

					.m-ticket-img {
						width: 100%;
						height: 100%;
						background: #eee;
						border-radius: 12rpx;
					}
				}

				.m-ticket-info {
					display: flex;
					flex-direction: column;

					.mm-box {
						display: flex;
						justify-content: space-between;
						align-items: center;

					}

					.m-ticket-name {
						font-family: Source Han Sans SC;
						font-weight: 500;
						font-size: 30rpx;
						color: #1b1b1b;
						width: 75%;
						margin-right: 5%;


					}

					.m-ticket-status,
					.m-ticket-price,
					.m-ticket-nums,
					.m-ticket-ticketPOV {
						font-family: Source Han Sans SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #999999;
					}


					.m-ticket-nums {
						margin-left: auto;
					}

					.m-ticket-price {
						margin: 10rpx 0;
					}
				}
			}
		}

		.transition-button {
			text-align: center;
			font-size: 28rpx;
			color: #3f3f3f;
		}
	}

	.m-card-feet {
		border-top: solid 1rpx #eee;
		padding: 25rpx;
		text-align: right;

		.m-feet-count {
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}
	}
}

::v-deep .m-refund-pop .uni-popup__wrapper {
	width: 80%;
	height: fit-content;

	.m-pop-content {
		padding: 30rpx;
		background: #fff;
		border-radius: 15rpx;
		box-shadow: 0 0 8px 2px #e0efff;

		.m-pop-title {
			text-align: center;
		}

		.m-pop-middle {
			margin: 30rpx 0;
			padding: 20rpx;
			background: #fbfbfb;
			border-radius: 15rpx;

			.m-middle-list {
				.m-middle-list-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 10rpx;
					padding-bottom: 15rpx;

					.m-item-label {
						width: 200rpx;
						color: #666;
						flex: none;
					}

					.m-item-value-box {
						display: flex;
						flex-direction: column;

						.m-item-value {
							font-size: 24rpx;
							color: #111;
						}


					}

				}
			}

			.m-middle-remark {
				text-align: center;
				margin: 20rpx 0;
			}
		}

		.m-pop-feet {
			display: flex;
			justify-content: space-around;
			align-items: center;
		}
	}

}

.m-card {
	margin-bottom: 20rpx;
}

.m-btn-box {
	width: 100%;
	align-items: center;
	justify-content: flex-end;
	margin-top: 20rpx;
}

.m-prime:not(:last-child) {
	margin-right: 20rpx;
}

.m-item-value-item {
	display: flex;
	align-items: center;
	justify-content: space-between;

	.ticket-name {
		width: 75%;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.ticket-num {
		flex: 1;
		margin-left: auto;
	}
}
</style>
