<template>
	<uni-popup ref="selectPopup" :safe-area="false" type="bottom">
		<view class="header-text">开场前{{ listData.earlyRefundTime || '--' }}分钟随时退</view>
		<view class="select-popup">
			<view class="pop-title">选择场次</view>
			<view class="pop-date-list">
				<scroll-view scroll-x="true" class="scroll-view_H">
					<view class="scroll-view-item" v-for="(item, index) in listData.stadiumConcertsVOList" :key="index"
						@click="sel_tab(item, index)">
						<view class="today-time">{{ item.weekDayAndDate }}</view>
						<view class="num">{{ item.noDayConcertsReservationNum || '0' }}场可订</view>
						<view class="line" v-if="deteSelIndex == index"></view>
					</view>
				</scroll-view>
			</view>
			<view class="gym-list">
				<view class="time-list">
					<view class="time-title">时间段</view>
					<block
						v-for="(concert, index) in listData?.stadiumConcertsVOList?.[0]?.concertsVOList?.[0]?.concertsDetailsVOList || []"
						:key="index">
						<view class="item-time">{{ concert.startTime }}-{{ concert.endTime }}</view>
					</block>
				</view>
				<view class="table-list">
					<scroll-view scroll-x="true" class="table-scroll">
						<view class="father-list" v-for="(conc, index) in itemList" :key="index"
							style="vertical-align: top;">
							<view class="father-title">{{ conc.sitePlaceName }}</view>
							<view class="children-list" v-for="(concert, index) in conc.concertsDetailsVOList"
								:key="index">
								<view class="item-card" :class="{ selected: isSelected(concert) }"
									@click="selectItem(conc, concert)" v-if="concert.concertStatus == 0">
									￥{{ concert.price }}
								</view>
								<view class="item-card" style="color: #AAA;" v-if="concert.concertStatus == 1">
									已选
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
			<view class="select-list" v-if="selArr.length > 0">
				<view class="select-title">已选场次</view>
				<scroll-view scroll-x="true" class="select-scroll">
					<view class="item-list" v-for="(item, index) in selArr" :key="index">
						<view class="list-box">
							<view class="list-text">
								<view class="">{{ item.time }}</view>
								<view class="">{{ item.name }}</view>
							</view>
							<view @click="deleteSelarr(item)"> <zzx-icon name="cancel" size="12"></zzx-icon></view>
						</view>
					</view>
				</scroll-view>
			</view>
			<view style="height: 200rpx;"></view>
			<view class="footer-submit">
				<view class="f-price">
					<view class="">总价</view>
					<view class="">￥{{ priceTotal.toFixed(2) }}</view>
				</view>
				<view class="f-btn" @click="submit_order">
					<button>提交订单</button>
				</view>
			</view>
		</view>
	</uni-popup>
	<view v-if="isopenDetail">
		<uni-popup ref="orderPopup" :safe-area="false" type="bottom">
			<view class="header-text">开场前{{ previewgymOrderDetail.earlyRefundTime || '--' }}分钟随时退</view>
			<view class="order-popup">
				<view class="p-header-card">
					<view class="p-school-info">
						<zzx-icon name="pay-icon1" size="16"></zzx-icon>
						<view class="name">{{ previewgymOrderDetail.storeName }}</view>
					</view>
					<view class="p-title">羽毛球场地预定</view>
					<view class="p-preset">
						<view class="preset-info" v-for="item in previewgymOrderDetail.timePeriod" :key="item.id">
							{{ item.name }}
						</view>
					</view>
				</view>
				<view class="p-price-card">
					<view class="p-price">
						<view class="text">商品总价(共{{ previewgymOrderDetail.timePeriod.length }}场)</view>
						<view class="price"><text class="mini-text">￥</text>{{ previewgymOrderDetail.subtotal.toFixed(2)
						}}</view>
					</view>
					<view class="p-subtotal">
						<text>小计</text>
						<view class="total-price"><text class="mini-text">￥</text>{{
							previewgymOrderDetail.totalPrice.toFixed(2) }}
						</view>
					</view>
				</view>
				<view class="p-phone-card">
					<view class="p-phone">
						<view class="text">手机号码</view>
						<input class="phone" type="number" v-model="displayPhone" @blur="orderDetailPhoneBlur" />
						<!-- <view class="phone" v-if="previewgymOrderDetail.mobile">{{ previewgymOrderDetail.mobile ?
							phoneHide(previewgymOrderDetail.mobile) : '' }}</view> -->
					</view>
					<view class="tips">请通话畅通，商家需要联系您确认到店时间</view>
				</view>
				<view class="p-rules-card">
					<view class="p-title">退改规则</view>
					<view class="p-text">
						每场开场前<text>{{ previewgymOrderDetail.earlyRefundTime }}分钟</text>可随时退改，之后不可退款。如您有疑问，可联系场馆。</view>
				</view>
				<view class="p-rules-card">
					<view class="p-title">温馨提示</view>
					<view class="p-text">{{ previewgymOrderDetail.reminder }}</view>
				</view>
				<view class="p-remark">
					<view class="title">备注</view>
					<input type="text" />
				</view>
				<view style="height: 200rpx;"></view>
				<view class="footer-pay">
					<button hover-class="hover-style" @click="submitOrder">
						<view class="btn-price"><text class="mini-text">￥</text>{{
							previewgymOrderDetail.totalPrice.toFixed(2) }}
						</view>
						<view class="btn-text">立即支付</view>
					</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue';
import { http } from '@/utils/http'
import { TipsUtils, phoneHide, RouterUtils, debounce } from '@/utils/util';
interface Props {
	listData?: any;
	itemList?: any;
	deteObj?: any;
	deteSelIndex?: any;
}
const props = withDefaults(defineProps<Props>(), {
	listData: [],
	itemList: [],
	deteObj: null,
	deteSelIndex: null,
});
const selectPopup = ref();
const orderPopup = ref();
const weekDayDate = ref('');
const displayPhone = computed({
	get: () => phoneHide(orderDetailPhone.value),
	set: (value: any) => { orderDetailPhone.value = value }
})
onMounted(() => {

})
const emit = defineEmits(['changess']);
// 监听 props.deteObj 或 listData 变化，设置 weekDayDate 为匹配项的 weekDayDate

watch(
	[() => props.deteObj, () => props.listData, () => props.deteSelIndex],
	([deteObj, listData, deteSelIndex]) => {
		if (
			listData &&
			Array.isArray(listData.stadiumConcertsVOList) &&
			typeof deteSelIndex === 'number' &&
			listData.stadiumConcertsVOList[deteSelIndex]
		) {
			weekDayDate.value = listData.stadiumConcertsVOList[deteSelIndex || 0].weekDayDate;
		} else if (deteObj && deteObj.dateLabel && listData && Array.isArray(listData.stadiumConcertsVOList)) {
			const match = listData.stadiumConcertsVOList.find(item => item.weekDayAndDate === deteObj.dateLabel);
			weekDayDate.value = match ? match.weekDayDate : '';
		} else {
			weekDayDate.value = '';
		}
	},
	{ immediate: true }
);

const opens = () => {
	// 打开弹窗时赋值默认日期，优先根据deteSelIndex
	if (
		props.listData &&
		Array.isArray(props.listData.stadiumConcertsVOList) &&
		typeof props.deteSelIndex === 'number' &&
		props.listData.stadiumConcertsVOList[props.deteSelIndex]
	) {
		weekDayDate.value = props.listData.stadiumConcertsVOList[props.deteSelIndex].weekDayDate;
	} else if (props.deteObj && props.deteObj.dateLabel && props.listData && Array.isArray(props.listData.stadiumConcertsVOList)) {
		const match = props.listData.stadiumConcertsVOList.find(item => item.weekDayAndDate === props.deteObj.dateLabel);
		weekDayDate.value = match ? match.weekDayDate : '';
	} else {
		weekDayDate.value = null;
	}
	nextTick(() => {
		selectPopup.value?.open();
	});
}
defineExpose({ opens })
const sel_tab = (e, i) => {
	emit('changes', e, i);
	weekDayDate.value = e.weekDayDate
}

const selArr = ref([])
const selectItem = (item1, item2) => {
	console.log(props.listData, '场次选择');
	const existingIndex = selArr.value.findIndex(item => item.id === item2.id);
	if (existingIndex !== -1) {
		selArr.value.splice(existingIndex, 1);
		return;
	}
	if (selArr.value.length >= props.listData.buyLimit) {
		return TipsUtils.tips_toast(`最多选择${props.listData.buyLimit}个场次`);
	}
	selArr.value.push({
		name: item1.sitePlaceName,
		time: item2.startTime + '-' + item2.endTime,
		price: item2.price,
		id: item2.id,
		date: weekDayDate.value // 记录选择时的日期
	});
}

const isSelected = (concert) => {
	return selArr.value.some(item => item.id === concert.id);
}

const priceTotal = computed(() => {
	return selArr.value.reduce((total, item) => {
		return total + item.price
	}, 0)
})

const deleteSelarr = (item) => {
	const index = selArr.value.findIndex(selItem => selItem.id === item.id);
	if (index !== -1) {
		selArr.value.splice(index, 1);
	}
}

const submit_order = () => {
	if (selArr.value.length < 1) {
		return TipsUtils.tips_toast('请选择场次')
	}
	get_previewOrderPlaceGymnasiumChartered()
}

const previewgymOrderDetail = ref()
const isopenDetail = ref(false)
const orderDetailPhone = ref()
const get_previewOrderPlaceGymnasiumChartered = () => {
	const result = selArr.value.map(item => item.id).join(',')
	http.get('/order/previewOrderPlaceGymnasiumChartered', { data: { rulesId: result }, loading: true }).then((res) => {
		previewgymOrderDetail.value = res.result
		orderDetailPhone.value = phoneHide(res.result.mobile)
		isopenDetail.value = true
		orderFormData.value.productIds = res.result.timePeriod.map(item => {
			// 找到 selArr 里对应的 item，取其 date
			const sel = selArr.value.find(sel => sel.id === item.id);
			return `${item.id}|${sel ? sel.date : weekDayDate.value}`;
		}).join(',')
		orderFormData.value.amount = res.result.timePeriod.length
		setTimeout(() => {
			selectPopup.value.close()
			orderPopup.value && orderPopup.value.open();
		}, 500)
	})
}

const orderDetailPhoneBlur = () => {
	http.get('/user/updateUserInfo', { data: { phone: orderDetailPhone.value }, loading: true }).then((res) => {
	})
}

// 提交订单
const orderFormData = ref({
	type: 0,
	orderType: 1,
	productIds: null,
	amount: null,
})
const orderCode = ref(null)
const orderId = ref(null)
const submitOrderImpl = () => {
	http.post('/order/createOrder', orderFormData.value, { loading: true }).then((res) => {
		orderCode.value = res.result.orderCode
		orderId.value = res.result.orderId
		paymentOrder(res.result.params)
		// getOrderQuery(res.result.orderCode, res.result.orderId)
	})
}
const paymentOrder = (payInfo: object) => {
	getOrderQuery(orderCode.value, orderId.value)
	// console.log(payInfo, '支付参数');
	// uni.requestPayment({
	// 	provider: 'wxpay',
	// 	...payInfo,
	// 	success: function (res) {
	// 		console.log('支付成功', res);
	// 		getOrderQuery(orderCode.value, orderId.value)
	// 	},
	// 	fail: function (err) {
	// 		console.log('支付失败', err);
	// 		if (err.errMsg == 'requestPayment:fail cancel') {
	// 			RouterUtils.to_page(`/pages/index/toBeUsed/index?orderId=${orderId.value}&orderType=${orderFormData.value.orderType}`)
	// 			return
	// 		}else{
	// 			RouterUtils.to_page(`/pages/index/payError/index?errMsg=${err.errMsg}`)
	// 		}
	// 		// TipsUtils.tips_toast('支付失败，请稍后重试');
	// 	}
	// });
}
const submitOrder = debounce(submitOrderImpl, 500)

// code编码 "100001支付成功";"100002查询失败"; "100003查询中 "; "100004支付失败"
const getOrderQuery = (orderCode: string, orderId: string, retryCount = 0) => {
	http.get('/order/orderQuery', { data: { orderCode: orderCode }, loading: true }).then((res) => {
		if (res.result == '100001') {
			RouterUtils.to_page(`/pages/index/toBeUsed/index?orderId=${orderId}&orderType=${orderFormData.value.orderType}`)
			selectPopup.value?.close()
			orderPopup.value?.close()
			selArr.value = []
		} else if (retryCount <= 3) {
			setTimeout(() => {
				getOrderQuery(orderCode, orderId, retryCount + 1)
			}, 1000)
		} else {
			if (res.result == '100003') {
				console.log('查询中，但已达到最大查询次数')
			} else if (res.result == '100002') {
				console.log('查询失败')
			} else if (res.result == '100004') {
				console.log('支付失败')
				TipsUtils.tips_toast('支付失败')
			}
		}
	}).catch((error) => {
		console.error('查询订单失败：', error)
		if (retryCount < 2) {
			setTimeout(() => {
				getOrderQuery(orderCode, orderId, retryCount + 1)
			}, 1000)
		}
	})
}
</script>

<style lang="less" scoped>
.header-text {
	margin: auto;
	background: linear-gradient(90deg, #C8FF0C 0%, rgba(100, 128, 6, 0) 100%);
	border-radius: 60rpx;
	width: 286rpx;
	height: 54rpx;
	text-align: center;
	line-height: 54rpx;
	font-size: 24rpx;
	color: #FFFFFF;
	margin-bottom: 20rpx;
}

.select-popup {
	background: #F6F6F6;
	border-radius: 32rpx 32rpx 0rpx 0rpx;
	max-height: 1200rpx;
	overflow: auto;

	.pop-title {
		font-weight: bold;
		font-size: 28rpx;
		color: #222222;
		padding: 20rpx;
	}

	.pop-date-list {
		border-bottom: 1rpx solid #F0F0F0;
		background: #FFFFFF;
		padding: 20rpx;
		border-radius: 24rpx;

		.scroll-view_H {
			white-space: nowrap;
			width: 100%;

			.scroll-view-item {
				display: inline-block;
				text-align: center;
				margin-right: 30rpx;

				.today-time {
					font-weight: bold;
					font-size: 28rpx;
					color: #222222;
				}

				.num {
					margin-top: 8rpx;
					font-size: 24rpx;
					color: #AAAAAA;
				}

				.line {
					margin: auto;
					width: 50rpx;
					height: 8rpx;
					background: #C8FF0C;
					transition: width 2s ease;
				}
			}
		}
	}

	.gym-list {
		display: flex;
		background: #FFFFFF;
		padding: 20rpx;

		.time-list {
			width: 180rpx;

			.time-title {
				height: 60rpx;
				line-height: 60rpx;
				text-align: center;
				font-weight: bold;
				font-size: 24rpx;
				color: #222222;
			}

			.item-time {
				margin-bottom: 20rpx;
				height: 54rpx;
				font-size: 24rpx;
				color: #222222;
				line-height: 54rpx;
			}
		}

		.table-list {
			width: 560rpx;

			.table-scroll {
				white-space: nowrap;
				width: 100%;

				.father-list {
					display: inline-block;
					margin-right: 20rpx;

					.father-title {
						height: 60rpx;
						line-height: 60rpx;
						text-align: center;
						font-weight: bold;
						font-size: 24rpx;
						color: #222222;
					}

					.children-list {
						margin-bottom: 20rpx;

						.item-card {
							width: 124rpx;
							height: 54rpx;
							background: #F6F6F6;
							border-radius: 8rpx;
							font-weight: bold;
							font-size: 24rpx;
							color: #222222;
							text-align: center;
							line-height: 54rpx;

							&.selected {
								background: #C8FF0C !important;
							}
						}
					}
				}
			}

		}
	}

	.select-list {
		padding: 20rpx;

		.select-title {
			font-weight: bold;
			font-size: 28rpx;
			color: #222222;
		}

		.select-scroll {
			white-space: nowrap;
			width: 100%;
			margin-top: 20rpx;

			.item-list {
				display: inline-block;
				padding: 20rpx;
				width: 180rpx;
				height: 60rpx;
				background: #FFFFFF;
				border-radius: 16rpx;
				margin-right: 20rpx;

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

					.list-text {
						font-weight: bold;
						font-size: 24rpx;
						color: #222222;

						&>view:last-child {
							margin-top: 8rpx;
						}
					}
				}
			}
		}
	}

	.footer-submit {
		position: fixed;
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 710rpx;
		height: 166rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -6rpx 12rpx 2rpx rgba(0, 0, 0, 0.09);
		border-radius: 32rpx 32rpx 0rpx 0rpx;
		bottom: 0;
		padding: 0 20rpx;

		.f-price {
			display: flex;
			align-items: center;
			gap: 16rpx;

			&>view:first-child {
				font-weight: bold;
				font-size: 28rpx;
				color: #222222;
			}

			&>view:last-child {
				font-weight: 800;
				font-size: 48rpx;
				color: #FB5B5B;
			}
		}

		.f-btn {
			&>button {
				width: 226rpx;
				height: 100rpx;
				background: #C8FF0C;
				border-radius: 60rpx;
				line-height: 100rpx;
				text-align: center;
				font-weight: bold;
				font-size: 32rpx;
				color: #222222;
			}

			&>button::after {
				border: none;
			}
		}
	}
}

.order-popup {
	background: #F6F6F6;
	border-radius: 32rpx 32rpx 0rpx 0rpx;
	max-height: 1200rpx;
	overflow: auto;

	.p-header-card {
		background: #fff;
		padding: 20rpx;
		margin-top: 20rpx;

		.p-school-info {
			display: flex;
			align-items: center;
			gap: 10rpx;
			font-size: 24rpx;
			color: #AAAAAA;
		}

		.p-title {
			margin-top: 20rpx;
			font-weight: bold;
			font-size: 28rpx;
			color: #222222;
		}

		.p-preset {
			font-size: 24rpx;
			color: #AAAAAA;

			.preset-info {
				margin-top: 20rpx;
			}
		}
	}

	.p-price-card {
		background: #fff;
		padding: 20rpx;
		margin-top: 20rpx;

		.p-price {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 114rpx;
			border-bottom: 1rpx solid #F0F0F0;

			.text {
				font-weight: bold;
				font-size: 28rpx;
				color: #222222;
			}

			.price {
				font-weight: 800;
				font-size: 48rpx;
				color: #222222;
			}
		}

		.p-subtotal {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			gap: 16rpx;
			margin-top: 20rpx;

			&>text:nth-child(1) {
				font-weight: bold;
				font-size: 28rpx;
				color: #222222;
			}

			.total-price {
				font-weight: 800;
				font-size: 48rpx;
				color: #FB5B5B;
			}
		}
	}

	.p-phone-card {
		background: #fff;
		padding: 20rpx;
		margin-top: 20rpx;

		.p-phone {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-weight: bold;
			font-size: 28rpx;
			color: #222222;

			.phone {
				width: 210rpx;
			}
		}

		.tips {
			margin-top: 20rpx;
			font-size: 24rpx;
			color: #AAAAAA;
		}
	}

	.p-rules-card {
		background: #fff;
		padding: 20rpx;
		margin-top: 20rpx;

		.p-title {
			font-weight: bold;
			font-size: 28rpx;
			color: #222222;
		}

		.p-text {
			margin-top: 20rpx;
			font-size: 24rpx;
			color: #AAAAAA;

			&>text {
				color: #222222;
			}
		}
	}

	.p-remark {
		display: flex;
		align-items: center;
		gap: 10rpx;
		background: #fff;
		padding: 20rpx;

		.title {
			width: 60rpx;
			font-size: 24rpx;
			color: #222222;
		}

		&>input {
			width: 690rpx;
			font-size: 24rpx;
			color: #757575;
		}
	}

	.footer-pay {
		position: fixed;
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 710rpx;
		height: 166rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -6rpx 12rpx 2rpx rgba(0, 0, 0, 0.09);
		border-radius: 32rpx 32rpx 0rpx 0rpx;
		bottom: 0;
		padding: 0 20rpx;
		z-index: 9999;

		&>button {
			width: 686rpx;
			height: 100rpx;
			background: #C8FF0C;
			border-radius: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 10rpx;

			&>button::after {
				border: none;
			}

			.btn-price {
				font-weight: 800;
				font-size: 48rpx;
				color: #222222;
			}

			.btn-text {
				font-weight: bold;
				font-size: 32rpx;
				color: #222222;
			}
		}

		.hover-style {
			color: #999999;
		}
	}
}
</style>