<template>
	<view class="m-content">
		<uni-nav-bar dark :fixed="true" shadow background-color="#007AFF" status-bar left-icon="left"
			right-icon="trash-filled" @clickRight="clearCar" left-text="" title="购物车" @clickLeft="back" />

		<view class="m-ticket-box" v-if="ticketList.length > 0">
			<view class="item" v-for="(item, index) in ticketList" :key="index">
				<view class="item-title">{{ item.ticketname }}</view>
				<view class="item-date" v-if="item.datesettings == 1">
					<view class="m-date-label">使用有效期：</view>
					<view class="m-date-value">
						{{ parseArrayTime(item.usevalidityStart) }}
						至
						{{ parseArrayTime(item.usevalidityEnd) }}
					</view>
				</view>
				<!--  datesettings=='2' 日期票------------------ -->
				<view class="item-date" v-if="item.datesettings == 2">
					<view class="m-date-label">使用天数：</view>
					<view class="m-date-value">
						{{ item.effectivedays }}
						<span class="m-l-mini">天</span>
					</view>
				</view>
				<!--  datesettings=='3' 小时票------------------ -->
				<view class="item-date" v-if="item.datesettings == 3">
					<view class="m-date-label">使用时间段：</view>
					<view class="m-date-value">
						{{ item.usertimeslotStart }}
						至
						{{ item.usertimeslotEnd }}
					</view>
				</view>
				<view class="footer">
					<view class="item-price">¥{{ sumPrice(item) }}</view>
					<u-number-box :ref="'numberBox' + index" :longPress="false" class="m-number" :min="0"
						:max="getMaxValue(item)" @overlimit="overlimit" :disabledInput="true" :integer="true"
						v-model="item.num" @change="valChange($event, item, index)"></u-number-box>
				</view>
			</view>
		</view>
		<view class="m-empty" v-else>
			<u-empty mode="car" icon="http://cdn.uviewui.com/uview/empty/car.png">
			</u-empty>
		</view>
		<view class="m-botom fixed-botom">
			<view class="m-botm-left">
				<view class="m-b-l-t">
					合计：
					<span class="m-red">
						¥
						<span class="m-price">{{ priceSum }}</span>
					</span>
				</view>
				<view class="m-b-l-b">
					已选门票
					<span class="m-red">{{ ticketSum }}</span>
					张
				</view>
			</view>
			<view class="m-botm-right">
				<button class="m-prime" :disabled="couldSub" size="mini" @click="verifyAndCreateOrder">确认</button>
			</view>
		</view>
	</view>
</template>

<script>
import { parseTime, parseArrayTime } from '../../utils/ruoyi';
import { verifyAndCreateOrder } from '@/api/seal/seal.js'
export default {
	data() {
		return {
			ticketSum: 0,
			priceSum: 0,
			ticketList: [],
			orderTickets: [],
			couldSub:false
		};
	},
	onShow(params) {
		//debugger
		const allTicket = uni.getStorageSync('ALL_TICKET');
		const oldTicket = uni.getStorageSync('oldTicket')
		console.log(oldTicket)
		if (allTicket && Array.isArray(allTicket) && allTicket.length > 0) {
			let allSum = 0, allPrice = 0;
			if (Array.isArray(allTicket) && allTicket.length > 0) {
				if (!oldTicket || oldTicket == '' || oldTicket == undefined || oldTicket == null) {
					console.log(allTicket)


					const {
						totalCents,
						totalNum
					} = allTicket.reduce((acc, item) => {
						const price = Number(item.settlementPrice);
						const quantity = Number(item.num);

						// 转换为分并四舍五入
						const priceInCents = Math.round(price * 100);
						acc.totalCents += priceInCents * quantity;
						acc.totalNum += quantity;
						return acc;
					}, {
						totalCents: 0,
						totalNum: 0
					});

					// 结果处理（分转元+保留两位小数）
					this.ticketSum = parseFloat(totalNum.toFixed(2));
					this.priceSum = parseFloat((totalCents / 100).toFixed(2));

					this.ticketList = allTicket;


				}
				else {
					const index = allTicket.findIndex(i => Number(i.id) == Number(oldTicket.id) && i.date == oldTicket.date);//需要更新的索引
					allTicket.splice(index, 1, oldTicket)
					const {
						totalCents,
						totalNum
					} = allTicket.reduce((acc, item) => {
						const price = Number(item.settlementPrice);
						const quantity = Number(item.num);

						// 转换为分并四舍五入
						const priceInCents = Math.round(price * 100);
						acc.totalCents += priceInCents * quantity;
						acc.totalNum += quantity;
						return acc;
					}, {
						totalCents: 0,
						totalNum: 0
					});

					// 结果处理（分转元+保留两位小数）
					this.ticketSum = parseFloat(totalNum.toFixed(2));
					this.priceSum = parseFloat((totalCents / 100).toFixed(2));

					this.ticketList = allTicket;
				}
			} else {
				this.ticketList = []
				this.ticketSum = 0;
				this.priceSum = 0;
			}

		} else {
			this.ticketList = []
			this.ticketSum = 0;
			this.priceSum = 0;
		}

	},
	watch: {
		ticketList: {
			handler(val) {


				let obj = {};
				let allSum = 0, allPrice = 0;
				val.forEach((item) => {

					//debugger
					obj.ticketId = item.id;
					obj.ticketName = item.ticketname;
					obj.num = item.num;
					obj.ticketPrice = item.settlementPrice;
					obj.date = item.date;
					obj.visitorInfoList = item.visitorInfoList
				});

				uni.setStorageSync('ALL_TICKET', val);
				const {
					totalCents,
					totalNum
				} = val.reduce((acc, item) => {
					const price = Number(item.settlementPrice);
					const quantity = Number(item.num);

					// 转换为分并四舍五入
					const priceInCents = Math.round(price * 100);
					acc.totalCents += priceInCents * quantity;
					acc.totalNum += quantity;
					return acc;
				}, {
					totalCents: 0,
					totalNum: 0
				});

				// 结果处理（分转元+保留两位小数）
				this.ticketSum = parseFloat(totalNum.toFixed(2));
				this.priceSum = parseFloat((totalCents / 100).toFixed(2));

				this.ticketList = val;
			},
			deep: true
		}
	},
	onHide() {
		this.orderTickets = []
	},
	onUnload() {
		this.orderTickets = []
	},

	methods: {
		getMaxValue(item) {
			//debugger
			if (item.inventorySettings == 1) {
				// 如果库存不限，则不设置最大值
				return Number.MAX_SAFE_INTEGER;
			} else if (item.inventorySettings == 2) {
				// 计算所有相同id的item的num总和
				let totalNum = this.ticketList
					.filter(i => i.id == item.id)
					.reduce((sum, i) => sum + i.num, 0);
				// 计算最大值
				let maxValue = item.currentinventory - totalNum + item.num;
				return maxValue > 0 ? maxValue : 0;
			} else {
				return item.rkc
			}
		},
		compareArrays(arr1, arr2) {
			return arr1.filter(item1 =>
				arr2.some(item2 => item1.id === item2.id && item1.date === item2.date)
			);
		},		//生成订单
		verifyAndCreateOrder() {
			this.couldSub = true
			this.ticketList.forEach((item) => {
				this.orderTickets.push({
					ticketId: item.id,
					ticketName: item.ticketname,
					num: item.num,
					ticketPrice: item.settlementPrice,
					date: item.date,
					visitorInfoList: item.visitorInfoList,
					ticketType:item.ticketType
				})
			});

			const obj = {
				ticketList: this.orderTickets,
				orderPrice: this.priceSum,
				settlementAmount: this.priceSum,
			};
			//debugger
			uni.showLoading({
				title: '请等待...'
			});
			verifyAndCreateOrder(obj).then(res => {
				uni.hideLoading();
				console.log(res)
				this.couldSub = false
				const data = JSON.stringify(res.data)
				uni.navigateTo({
					url: '/pages/orderDetail/orderDetail?order=' + data
				})
			}).catch(err => {
				console.log(err)
			})
		},
		sumPrice(val) {
			const priceInCents = Math.round(Number(val.settlementPrice) * 100);
			const quantity = Number(val.num);
			return quantity * priceInCents/100;
		},
		overlimit(val) {
			console.log(val);
		},
		valChange(e, itm, ig) {
			let that = this
			let index
			const oldNum = itm.num;
			console.log('当前值为: ' + e.value, itm);//3*3种情况
			if (e.value >= 1) {
				//不限库存
				if (itm.inventorySettings == 1) {
					//debugger
					//无需游客信息/需要一个游客信息
					if (itm.touristInformation == 1 || itm.touristInformation == 2) {
						itm.num = e.value
						uni.setStorageSync('ALL_TICKET', that.ticketList)
					}
					//需要全部游客信息
					if (itm.touristInformation == 3) {
						//debugger
						uni.setStorageSync('oldTicket', itm)
						uni.setStorageSync('ALL_TICKET', that.ticketList)
						const data = JSON.stringify(itm)
						uni.navigateTo({
							url: '/pages/addUserinfo/addUserinfo?needInfoItem=' + data + '&count=' + e.value
						})
					}
				}
				//总库存
				if (itm.inventorySettings == 2) {
					//debugger
					//无需游客信息/需要一个游客信息
					if (itm.touristInformation == 1 || itm.touristInformation == 2) {
						// const filteredItems = that.ticketList.filter(item => item.id == itm.id && item.date == itm.date);
						// index = that.ticketList.findIndex(item => item.id == itm.id && item.date == itm.date);
						// console.log(filteredItems, 'kllll')
						// // 计算总库存
						// const totalNum = filteredItems.reduce((sum, item) => sum + item.num, 0);

						// // 获取当前库存
						// const currentInventory = Number(itm.currentinventory);
						// if (totalNum >= currentInventory) {
						// 	uni.showToast({
						// 		title: '库存已达上限',
						// 		icon: 'none'
						// 	});
						// 	itm.disablePlus = true
						// 	that.$set(that.ticketList, index, itm)
						// 	that.$refs['numberBox' + ig][0].value = itm.num
						// 	console.log(that.$refs['numberBox' + ig][0].value,'----')
						itm.num = e.value
						uni.setStorageSync('ALL_TICKET', that.ticketList)
						// } else {
						// 	itm.num = e.value
						// 	itm.disablePlus = false
						// 	uni.setStorageSync('ALL_TICKET', that.ticketList)
						// }

					}
					//需要全部游客信息
					if (itm.touristInformation == 3) {
						// const filteredItems = that.ticketList.filter(item => item.id == itm.id && item.date == itm.date);
						// console.log(filteredItems, 'kllll')
						// // 计算总库存
						// const totalNum = filteredItems.reduce((sum, item) => sum + item.num, 0);

						// // 获取当前库存
						// const currentInventory = Number(itm.currentinventory);
						// if (totalNum == currentInventory) {
						// 	uni.showToast({
						// 		title: '库存不足',
						// 		icon: 'none'
						// 	});
						// 	itm.disablePlus = true
						// 	that.$refs['numberBox' + ig][0].value = itm.num
						uni.setStorageSync('oldTicket', itm)
						uni.setStorageSync('ALL_TICKET', that.ticketList)
						const data = JSON.stringify(itm)
						uni.navigateTo({
							url: '/pages/addUserinfo/addUserinfo?needInfoItem=' + data + '&count=' + e.value
						})
						// } else {
						// 	itm.num = e.value
						// 	itm.disablePlus = false
						// 	uni.setStorageSync('oldTicket', itm)
						// 	uni.setStorageSync('ALL_TICKET', that.ticketList)
						// 	const data = JSON.stringify(itm)
						// 	uni.navigateTo({
						// 		url: '/pages/addUserinfo/addUserinfo?needInfoItem=' + data + '&count=' + e.value
						// 	})
						// }
					}
				}
				//日库存
				if (itm.inventorySettings == 3) {
					//debugger
					//无需游客信息/需要一个游客信息
					if (itm.touristInformation == 1 || itm.touristInformation == 2) {
						// if (Number(itm.num) >= Number(itm.rkc)) {
						// 	uni.showToast({
						// 		title: '库存不足',
						// 		icon: 'none'
						// 	});
						// 	that.$refs['numberBox' + ig][0].value = itm.num
						// 	itm.disablePlus = true
						// 	that.$set(that.ticketList, index, itm)
						itm.num = e.value
						uni.setStorageSync('ALL_TICKET', that.ticketList)
						// } else {
						// 	itm.num = e.value
						// 	itm.disablePlus = false
						// 	uni.setStorageSync('ALL_TICKET', that.ticketList)
						// }

					}
					//需要全部游客信息
					if (itm.touristInformation == 3) {
						// if (Number(itm.num) == Number(itm.rkc)) {
						// 	uni.showToast({
						// 		title: '库存不足',
						// 		icon: 'none'
						// 	});
						// 	that.$refs['numberBox' + ig][0].value = itm.num
						// 	itm.disablePlus = true
						uni.setStorageSync('oldTicket', itm)
						uni.setStorageSync('ALL_TICKET', that.ticketList)
						const data = JSON.stringify(itm)
						uni.navigateTo({
							url: '/pages/addUserinfo/addUserinfo?needInfoItem=' + data + '&count=' + e.value
						})
						// } else {
						// 	itm.num = e.value
						// 	itm.disablePlus = false
						// 	uni.setStorageSync('oldTicket', itm)
						// 	uni.setStorageSync('ALL_TICKET', that.ticketList)
						// 	const data = JSON.stringify(itm)
						// 	uni.navigateTo({
						// 		url: '/pages/addUserinfo/addUserinfo?needInfoItem=' + data + '&count=' + e.value
						// 	})
						// }
					}
				}
			}
			if (e.value < 1) {
				uni.showModal({
					title: '提示',
					content: '确定删除此票吗？',
					success: function (res) {
						if (res.confirm) {
							const index = that.ticketList.findIndex(i => Number(i.id) == Number(itm.id) && i.date == itm.date)//需要更新的索引
							that.ticketList.splice(index, 1)//执行删除操作
							uni.setStorageSync('ALL_TICKET', that.ticketList);
							console.log('用户点击确定');
						} else if (res.cancel) {
							that.$nextTick(() => {
								itm.num = 1
							})

							console.log('用户点击取消');
						}
					}
				})
			}
		},
		parseTime(val) {
			return parseTime(val, '{y}-{m}-{d}');
		},
		parseArrayTime(val) {
			return parseArrayTime(val);
		},
		back() {
			uni.navigateBack({
				delta: 1
			});
		},
		clearCar() {
			let that = this;
			uni.showModal({
				title: '警告',
				content: '确认清空吗',
				cancelText: '再想想',
				confirmText: '清空',
				success: function (res) {
					if (res.confirm) {
						uni.showLoading({
							title: '请等待...'
						});
						uni.removeStorageSync("ALL_TICKET");
						uni.removeStorageSync("oldTicket");
						that.ticketSum = 0,
							that.priceSum = 0,
							that.ticketList = [],
							that.orderTickets = []
						setTimeout(() => {
							uni.hideLoading();
						}, 1000);
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.m-ticket-box {
	margin: 20upx 20upx 150upx;
	padding-bottom: 150upx;
}

.m-empty {
	padding-top: 150upx;
}

.item {
	background: #ffffff;
	border-radius: 20upx;
	margin-bottom: 20upx;
	display: flex;
	flex-direction: column;
	align-items: start;
	height: fit-content;
	padding: 20upx;

	.item-title {
		font-family: Source Han Sans SC;
		font-weight: 500;
		margin-bottom: 22upx;
		font-size: 32upx;
		color: #1b1b1b;
	}

	.item-date {
		display: flex;
		align-items: center;
		font-size: 26upx;

		.m-date-label {
			font-family: Source Han Sans SC;
			font-weight: 400;
			color: #666666;
		}

		.m-date-value {
			color: rgba(34, 119, 240, 1);
		}
	}

	.footer {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		margin-top: 44upx;

		.item-price {
			font-family: DIN Alternate;
			font-weight: bold;
			font-size: 38upx;
			color: #ff5400;
		}

		.m-btn {
			display: block;
			margin: 0;
			background: rgba(34, 119, 240, 0.1);
			border-radius: 12Upx;
			color: rgba(34, 119, 240, 1);
		}

		::v-deep .m-number {

			.u-number-box__minus,
			.u-number-box__plus {
				width: 36upx;
				height: 36upx !important;
				border-radius: 50%;
				background-color: transparent !important;
				border: 2upx solid #2277f0;

				.u-icon {
					.u-icon__icon {
						font-size: 18upx !important;
						color: #2277f0 !important;
					}
				}
			}

			.u-number-box__minus--disabled {
				border: solid 1upx #d0d2d4 !important;

				.u-icon {
					.u-icon__icon {
						color: #d0d2d4 !important;
					}
				}
			}

			.u-number-box__input {
				background-color: transparent !important;
			}
		}
	}
}

.m-botom {
	width: 100%;
	height: 136upx;
	background: #ffffff;
	position: fixed;
	bottom: 0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 40upx;

	.m-botm-left {
		.m-red {
			color: #ff5400;

			.m-price {
				font-size: 48upx;
			}
		}
	}

	.m-botm-right {
		.m-prime {
			height: 80upx;
			line-height: 80upx;
			background: linear-gradient(90deg, #5097fa 0%, #2277f0 100%);
			border-radius: 16upx;

			font-family: Source Han Sans SC;
			font-weight: 500;
			font-size: 32upx;
			color: #ffffff;
		}
	}
}
</style>
