<template>
	<view class="container">
		<!-- 信息区域 -->
		<view class="body">
			<!-- 车辆信息区域 -->
			<view class="carMsg">
				<view class="carMsg_time">{{info.s_date}} {{info.ci_time}}</view>
				<view class="carMsg_number">车牌：{{info.car_number}}</view>
				<view class="carMsg_volume">容量：{{info.contain}}座</view>

				<image class="carMsg_line" src="@/static/images/chooseCar/line.png" mode="aspectFill" />

				<!-- <view class="carMsg_start">{{getRouteParts(info.route_end).prefix}}</view> -->
				<view class="carMsg_start"> 
					<view :class="{ '': true, 'app': index2 > 0 }"  v-for="(item2, index2) in getRouteParts(info.route_end)" :key="index2">{{item2}}</view>
				</view>

				<!-- <view class="carMsg_end">{{getRouteParts(info.route_end).suffix}}</view> -->

				<view class="carMsg_bottom">
					<view class="bottom_box" @click="handleRule">退改规则</view>
				</view>
			</view>

			<!-- 乘客信息区域 -->
			<view class="peopleMsg">
				<view class="peopleMsg_title">乘客信息</view>
				<view class="peopleMsg_list">
					<view v-for="(item,index) in selectedPassengers" :key="index" class="list_item active" @click="toggleCheck(item)">
						{{item.username}}

						<view class="item_active">
							<wd-icon name="check" color="#fff" size="8" />
						</view>
					</view>

					<view class="list_more" @click="handleMore">+ 更多</view>
				</view>

				<view class="peopleMsg_choose">
					<view v-for="(item,index) in selectedPassengers" :key="index" class="choose_item">
						<wd-icon name="minus-circle" color="#FF8205" size="22" @click="toggleCheck(item)" />
						<view class="item_msg">
							<view class="msg_top">{{item.username}}</view>
							<view class="msg_bottom">身份证 {{item.sfzh}}</view>
						</view>
					</view>
				</view>

				<view class="peopleMsg_foot">
					<view class="foot_left">
						<wd-icon name="phone" color="#FF8205" size="25" />
						<view class="left_text">手机号</view>
					</view>

					<view class="foot_phone">
						<input v-model="value" :maxlength="11" placeholder-style="font-size:28rpx;color:#ABA6A6;text-align: end;" type="text" placeholder="请填写联系手机号" />
					</view>
				</view>
			</view>

			<!-- 优惠券区域 -->
			<view class="coupon">
				<view class="coupon_title">优惠</view>

				<view class="coupon_box">
					<view class="box_left">
						<image class="left_img" src="@/static/images/chooseCar/coupon.png" mode="aspectFill" />

						优惠券
					</view>

					<view class="box_right">
						暂无优惠券
						<wd-icon name="chevron-right" color="#ABA6A6" size="18" />
					</view>
				</view>
			</view>
		</view>

		<!-- 底部按钮区域 -->
		<view class="foot">
			<view class="foot_box">
				<view class="box_text">
					¥
					<text class="text">{{info.price}}</text>
				</view>

				<view class="box_btn" @click="handlePay">立即购买</view>
			</view>
		</view>
	</view>

	<!-- 退改规则弹窗区域 -->
	<wd-popup v-model="popShow_rule" position="bottom" safe-area-inset-bottom :close-on-click-modal="false">
		<view class="pop_rule">
			<view class="rule_title">退改规则</view>
			<view class="rule_body">
				<view class="body_text">
					<view class="text">发车前{{guizea1}}小时以上，免收手续费;</view>
					<view class="text">发车前{{guizea2}}小时以上{{guizea3}}小时以内，收取{{guizea4}}%手续费;</view>
					<view class="text">发车前{{guizea5}}小时以内，收取{{guizea6}}%手续费;</view>
					<view class="text">发车后不退票。</view>
				</view>

				<view class="body_btn" @click="handleCloseRule">我知道了</view>
			</view>
		</view>
	</wd-popup>

	<!-- 常用旅客弹窗区域 -->
	<wd-popup v-model="popShow_common" position="bottom" safe-area-inset-bottom :close-on-click-modal="false">
		<view class="pop_common">
			<view class="common_title">
				常用旅客
				<view class="title_close" @click="handleCloseCommon">
					<wd-icon name="close" color="#ABA6A6" size="20" />
				</view>
			</view>
			<view class="common_body">
				<view class="body_add" @click="handleAdd">+ 添加乘客</view>
				<scroll-view 
				  scroll-y 
				  class="scroll-container" 
				  @scrolltolower="loadNextPage"
				>
					<view class="body_list">
						<!-- 每一个乘客区域 -->
						<view v-for="(item,index) in dataList" :key="index" class="list_item">
							<view class="item_left">
								<wd-icon name="edit-outline" color="#ABA6A6" size="17" @click="handleUp(item)" />
								<view class="left_msg">
									<view class="msg_name">{{item.username}}</view>
									<view class="msg_idcard">身份证 {{item.sfzh}}</view>
									<view class="msg_phone">手机号 {{item.mobile}}</view>
								</view>
							</view>

							<view class="item_right">
								<radio color="#FF8205" :checked="item.isCheck" @click="toggleCheck(item)" />
							</view>
						</view>
					</view>
					<!-- 加载状态提示 -->
					<view v-if="isLoading" class="loading">加载中...</view>
				</scroll-view>
				<view class="body_btn" @click="handleConfirm">确认</view>
			</view>
		</view>
	</wd-popup>
	
	<!-- 选择付款方式弹窗区域 -->
	<wd-popup v-model="popShow_pay" position="bottom" safe-area-inset-bottom :close-on-click-modal="false">
		<view class="pop_pay">
			<view class="pay_title">选择付款方式</view>
			<view class="pay_close" @click="handleClose">
				<wd-icon name="close-bold" color="#ABA6A6" size="22"></wd-icon>
			</view>
	
			<!-- 支付方式列表区域 -->
			<view class="pay_list">
				<!-- 每一个支付方式区域 -->
				<view class="list_item" v-for="(item, index) in payList" :key="index">
					<view class="item_left">
						<image class="img" :src="item.icon" mode="aspectFill"></image>
						{{ item.text }}
					</view>
	
					<view class="item_right">
						<radio style="scale: 0.8" color="#FF8205" :checked="item.isCheck" @click="togglePay(item)" />
					</view>
				</view>
			</view>
	
			<!-- 立即付款按钮区域 -->
			<view class="pay_btn" @click="payTime">立即付款</view>
		</view>
	</wd-popup>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref,computed  } from 'vue'
import { myRequest } from '@/utils/api.ts'
import debounce from 'lodash/debounce'

const userInfo = uni.getStorageSync('carUserInfo')

const popShow_rule = ref(false)

const popShow_common = ref(false)
const info = ref({})

// 每页多少条
const pageSize = ref(8)
// 当前页
const currentPage = ref(1)
// 总条数
const total = ref(0)
// 常用旅客数组数据
const dataList = ref([])
//加载中状态
const isLoading = ref(false)
//是否还有更多数据
const hasMore = ref(true)
// 已选乘车人列表
const selectedPassengers = ref([]);
// 联系手机号
const phoneValue = ref('');
// 付款方式弹窗显示隐藏控制
const popShow_pay = ref(false)
// 支付方式列表
const payList = ref([
	{
		text: '微信支付',
		icon: '/static/images/pay/wx.png',
		isCheck: false
	},
	{
		text: '电子交通卡支付',
		icon: '/static/images/pay/card.png',
		isCheck: false
	}
])
// 选中的支付方式
const selectedPay = ref(null);

//退改规则
const guizea1 = ref(0)
const guizea2 = ref(0)
const guizea3 = ref(0)
const guizea4 = ref(0)
const guizea5 = ref(0)
const guizea6 = ref(0)

// 存储支付参数
const payParams = ref({
  timeStamp: '',
  nonceStr: '',
  signType: '',
  paySign: '',
  appId:'',
  // prepay_id:'',
  package:'',
});

// 截取箭头前后的文字
const getRouteParts = (str) => {
  if (typeof str === 'string' && str.length > 0) {
  	return str.split('→');
  }
  
  return [];
};

onLoad((options) => {
	if (options.info) {
		info.value = JSON.parse(decodeURIComponent(options.info))
		console.log(info.value)
	}
})

function handleRule() {
	popShow_rule.value = true
	getTuigai()
}

function handleCloseRule() {
	popShow_rule.value = false
}

//退改规则
async function getTuigai() {
	const res = await myRequest({
		url: '/carBook/cnqueryHb.action',
		data: {
		}
	})
	if(res.code==200){
		guizea1.value=res.data.refundRule.a1.start
		guizea2.value=res.data.refundRule.a2.start
		guizea3.value=res.data.refundRule.a2.end
		guizea4.value=(res.data.refundRule.a2.fee)*100
		guizea5.value=res.data.refundRule.a3.end
		guizea6.value=(res.data.refundRule.a3.fee)*100
	}else{
		uni.showToast({
		  title: res.message,
		  icon: 'none'
		});
	}
}

function handleMore() {
	popShow_common.value = true
	getCommonData()
}

// 获取常用旅客列表数据
const getCommonData = async () => {
	if (isLoading.value || !hasMore.value) return;
	isLoading.value = true;
	let data = {
		page: currentPage.value,
		rows: pageSize.value,
		mobile: userInfo.mobile
	}
	try {
	    const res = await myRequest({
	      url: '/ctUserlist.action',
	      data
	    });
	    if (res.code === 200) {
			// 对返回的每一条数据添加 isCheck: false
			const formattedRows = res.rows.map(item => ({
				...item, // 保留原有数据
				isCheck: false // 新增 isCheck 参数，默认 false
			}));
		  // 🔴 同步已勾选状态：对比 selectedPassengers，标记匹配项的 isCheck 为 true
		  formattedRows.forEach(row => {
			const isSelected = selectedPassengers.value.some(p => p.id === row.id);
			if (isSelected) {
			  row.isCheck = true;
			}
		  });
	      if (currentPage.value === 1) {
	        dataList.value = formattedRows; 
	      } else {
	        dataList.value.push(...formattedRows); 
	      }
		  total.value = res.total
	    } else {
	      // 接口返回非200状态时的提示（可选）
	      uni.showToast({ title: '数据获取失败', icon: 'none' });
	    }
	  } catch (err) {
	    console.error('请求异常', err);
	    uni.showToast({ title: '网络异常', icon: 'none' });
	  } finally {
	    isLoading.value = false; // 无论成功失败，都关闭加载状态
	  }
}
// 乘客触底触发加载下一页
function loadNextPage() {
	if (dataList.value.length < total.value) {
		currentPage.value++
		getCommonData()
	} else {
		uni.showToast({
			title: '没有更多数据了',
			icon: 'none'
		})
	}
}

// 勾选/取消勾选逻辑
const toggleCheck = (item) => {
  item.isCheck = !item.isCheck;
  if (item.isCheck) {
    selectedPassengers.value.push(item);
  } else {
    selectedPassengers.value = selectedPassengers.value.filter(p => p.id !== item.id);
  }
};

function handleCloseCommon() {
	popShow_common.value = false
}

function handleConfirm() {
	popShow_common.value = false
}

function handleAdd() {
	uni.navigateTo({
		url: '/pages/handlePeople/handlePeople'
	})
}
function handleUp(item){
	let info = encodeURIComponent(JSON.stringify(item))
	uni.navigateTo({
		url: `/pages/handlePeople/handlePeople?info=${info}`
	})
}

// 点击支付按钮回调
const handlePay = () => {
	popShow_pay.value = true
}

// 点击弹窗关闭按钮回调
const handleClose = () => {
	popShow_pay.value = false
}

// 切换支付方式（单选逻辑）
const togglePay = (item) => {
  // 先重置所有支付方式为未选中
  payList.value.forEach(pay => {
    pay.isCheck = false;
  });
  // 标记当前点击的支付方式为选中
  item.isCheck = true;
  selectedPay.value = item; // 同步选中的支付方式
};

//立即支付
const payTime = () => {
	if (!selectedPay.value) {
		uni.showModal({
			content:'请选择支付方式'
		})
	    return;
	  }
	if(selectedPay.value.text=='微信支付'){
		payWei()
	}else if(selectedPay.value.text=='电子交通卡支付'){
		jiaotongka()
	}
}

//交通卡支付
const jiaotongka = async () => {
	// 计算属性：判断是否为空
	const isPassengerEmpty = computed(() => selectedPassengers.value.length === 0);
	if (isPassengerEmpty.value) {
	    uni.showToast({
	      title: '请选择乘车人',
	      icon: 'none'
	    });
	    return;
	}
	// 计算属性：将id拼接为逗号分隔的字符串
	const userListStr = computed(() => {
	  return selectedPassengers.value.map(item => item.id).join(',');
	});
	const res = await myRequest({
		url: '/cardorder.action',
		method: 'POST', // 明确指定请求方法为POST
		data: {
			userId: userInfo.id,
			schedueId: info.value.id,
			userList: userListStr.value,
			payAmount: info.value.price,
			carNumber: info.value.car_number,
			contain: info.value.contain,
			ciDate: info.value.s_date,
			ciTime: info.value.ci_time,
			route: info.value.route,
			routeEnd: info.value.route_end,
		}
	})
	if(res.code==200){
		uni.showToast({
		  title: res.message,
		  icon: 'none'
		});
	}else{
		uni.showToast({
		  title: res.message,
		  icon: 'none'
		});
	}
}

//微信支付
const payWei = async () => {
	// 计算属性：判断是否为空
	const isPassengerEmpty = computed(() => selectedPassengers.value.length === 0);
	if (isPassengerEmpty.value) {
	    uni.showToast({
	      title: '请选择乘车人',
	      icon: 'none'
	    });
	    return;
	}
	// 计算属性：将id拼接为逗号分隔的字符串
	const userListStr = computed(() => {
	  return selectedPassengers.value.map(item => item.id).join(',');
	});
	const res = await myRequest({
		url: '/tApporder_pay.action',
		method: 'POST', // 明确指定请求方法为POST
		data: {
			userId: userInfo.id,
			schedueId: info.value.id,
			userList: userListStr.value,
			payAmount: info.value.price,
			carNumber: info.value.car_number,
			contain: info.value.contain,
			ciDate: info.value.s_date,
			ciTime: info.value.ci_time,
			route: info.value.route,
			routeEnd: info.value.route_end,
		}
	})
	if(res.code==200){
		// payParams.value = res.data; // 存储微信支付所需参数
		payParams.value = {
		  timeStamp: res.data.timeStamp,
		  nonceStr: res.data.nonceStr,
		  package: 'prepay_id=' + res.data.prepay_id,
		  signType: res.data.signType,
		  paySign: res.data.paySign,
		  // prepay_id:res.data.prepay_id
		};
		invokeWechatPay(); // 调起支付
	}
}

// 调起微信支付
const invokeWechatPay = () => {
	console.log(payParams.value,'支付')
  uni.requestPayment({
	  ...payParams.value,
    success: (res) => {
      uni.showToast({ title: '支付成功' });
	  setTimeout(function() {
	  	uni.switchTab({
			url:'/pages/order/order'
		})
	  }, 1000)
      // 支付成功后逻辑（如跳转到订单详情）
    },
    fail: (err) => {
      uni.showToast({ title: '支付失败', icon: 'none' });
      console.error('支付失败', err); 
    }
  });
};
</script>

<style lang="scss" scoped>
.container {
	display: flex;
	height: 100vh;
	color: #001713;

	.body {
		width: 100%;
		height: calc(100vh - 244rpx);
		overflow-y: auto;

		.carMsg {
			position: relative;
			box-sizing: border-box;
			padding: 0 55rpx;
			margin: 20rpx auto 0;
			width: 720rpx;
			height: 320rpx;
			font-size: 32rpx;
			color: #001713;
			background: url(@/static/images/chooseCar/box.png);
			background-size: 100% 100%;

			.carMsg_time {
				position: relative;
				top: 36rpx;
				font-size: 36rpx;
				color: #001713;
			}

			.carMsg_number {
				position: relative;
				top: -8rpx;
				left: 180px;
				font-size: 24rpx;
				color: #f86818;
			}

			.carMsg_volume {
				position: relative;
				top: 10rpx;
				left: 180px;
				font-size: 24rpx;
				color: #f86818;
			}

			.carMsg_line {
				position: relative;
				top: 2rpx;
				left: 1px;
				width: 14rpx;
				height: 88rpx;
			}

			.carMsg_start {
				position: relative;
				top: -110rpx;
				left: 15px;
				width: 460rpx;
			}
			.app{
				margin-top: 1px;
			}

			.carMsg_end {
				position: absolute;
				top: 185rpx;
				left: 95rpx;
				width: 460rpx;
			}

			.carMsg_bottom {
				position: relative;
				top: -100rpx;
				// left: 46rpx;
				display: flex;
				align-items: center;
				width: 630rpx;
				height: 66rpx;
				border-top: 2rpx dotted #e6e6e6;

				.bottom_box {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 128rpx;
					height: 42rpx;
					font-size: 24rpx;
					color: #ff8205;
					border-radius: 8rpx;
					background-color: #fff2e5;
				}
			}
		}

		.peopleMsg {
			box-sizing: border-box;
			padding: 30rpx 30rpx 0;
			margin: auto;
			width: 670rpx;
			font-size: 28rpx;
			box-shadow: 0px 3px 6px #ccc;
			background-color: #fff;

			.peopleMsg_title {
				margin-bottom: 20rpx;
				font-size: 36rpx;
			}

			.peopleMsg_list {
				display: flex;
				flex-wrap: wrap;
				align-items: center;

				.list_item {
					position: relative;
					display: flex;
					justify-content: center;
					align-items: center;
					margin-right: 30rpx;
					margin-bottom: 26rpx;
					padding: 0 24rpx;
					height: 68rpx;
					color: #aba6a6;
					border-radius: 8rpx;
					border: 2rpx solid #aba6a6;

					.item_active {
						position: absolute;
						bottom: -20rpx;
						right: -20rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						width: 60rpx;
						height: 60rpx;
						background-image: url(@/static/images/chooseCar/active.png);
						background-size: 100% 100%;
					}
				}

				.active {
					color: #ff8205;
					border: 2rpx solid #ff8205;
				}

				.list_more {
					display: flex;
					justify-content: center;
					align-items: center;
					margin-bottom: 26rpx;
					width: 132rpx;
					height: 68rpx;
					color: #ff8205;
					border-radius: 8rpx;
					border: 2rpx solid #aba6a6;
				}
			}

			.peopleMsg_choose {
				.choose_item {
					display: flex;
					align-items: center;

					.item_msg {
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						margin-left: 26rpx;
						margin-bottom: 26rpx;
						height: 90rpx;

						.msg_top {
							font-size: 36rpx;
						}

						.msg_bottom {
							font-size: 24rpx;
							color: #aba6a6;
						}
					}
				}
			}

			.peopleMsg_foot {
				display: flex;
				align-items: center;
				justify-content: space-between;
				height: 116rpx;
				font-size: 36rpx;
				border-top: 2rpx solid #ebecf1;

				.foot_left {
					display: flex;
					align-items: center;

					.left_text {
						margin-left: 12rpx;
					}
				}

				.foot_phone {
					text-align: end;
				}
			}
		}

		.coupon {
			box-sizing: border-box;
			padding: 0 30rpx 30rpx;
			margin: 20rpx auto 50rpx;
			width: 670rpx;
			color: #001713;
			box-shadow: 0px 3px 6px #ccc;
			background-color: #fff;

			.coupon_title {
				height: 96rpx;
				line-height: 96rpx;
				font-size: 36rpx;
			}

			.coupon_box {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 70rpx;

				.box_left {
					display: flex;
					align-items: center;

					.left_img {
						margin-right: 14rpx;
						width: 46rpx;
						height: 46rpx;
					}
				}

				.box_right {
					display: flex;
					align-items: center;
					font-size: 24rpx;
					color: #aba6a6;
				}
			}
		}
	}

	.foot {
		position: absolute;
		bottom: 0;
		box-sizing: border-box;
		padding: 0 30rpx;
		width: 100%;
		height: 244rpx;
		box-shadow: 0px -3px 6px #eee;
		background-color: #fff;

		.foot_box {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-top: 46rpx;
			height: 96rpx;

			.box_text {
				color: #dc2626;
				font-size: 36rpx;

				.text {
					font-size: 48rpx;
				}
			}

			.box_btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 272rpx;
				height: 96rpx;
				font-size: 36rpx;
				color: #fff;
				border-radius: 64rpx;
				background-color: #ff8205;
			}
		}
	}
}

.pop_rule {
	height: 568rpx;
	color: #001713;
	overflow: hidden;

	.rule_title {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 114rpx;
		font-size: 36rpx;
		background-color: #fff2e5;
	}

	.rule_body {
		box-sizing: border-box;
		padding: 0 32rpx;

		.body_text {
			box-sizing: border-box;
			padding: 30rpx;
			margin-top: 20rpx;
			font-size: 24rpx;
			border-radius: 32rpx;
			background-color: #fff2e5;

			.text {
				margin-bottom: 8rpx;
			}
		}

		.body_btn {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 20rpx;
			height: 94rpx;
			font-size: 36rpx;
			color: #fff;
			border-radius: 64rpx;
			background-color: #ff8205;
		}
	}
}

.pop_common {
	height: 70vh;
	font-size: 36rpx;
	color: #001713;
	overflow: hidden;

	.common_title {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100rpx;
		border-bottom: 20rpx solid #ff8205;

		.title_close {
			position: absolute;
			top: 34rpx;
			right: 40rpx;
			width: 40rpx;
			height: 40rpx;
		}
	}

	.common_body {
		box-sizing: border-box;
		padding: 0 32rpx;

		.body_add {
			margin: 25rpx 0 25rpx auto;
			width: 170rpx;
			font-size: 32rpx;
			color: #ff8205;
		}

		.body_list {
			height: calc(70vh - 396rpx);
			overflow-y: auto;

			.list_item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 20rpx;
				height: 120rpx;

				.item_left {
					display: flex;
					align-items: center;
					height: 100%;

					.left_msg {
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						margin-left: 20rpx;
						height: 100%;
						font-size: 24rpx;
						color: #aba6a6;

						.msg_name {
							font-size: 36rpx;
							color: #001713;
						}
					}
				}

				.item_right {
				}
			}
		}
		.scroll-container {
		  height: calc(80vh -  396rpx - 92rpx); /* 根据实际布局计算 */
		}
		.loading, .no-more {
		  text-align: center;
		  padding: 5rpx 0;
		  font-size: 22rpx;
		  color: #999;
		}

		.body_btn {
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 48rpx 0;
			width: 100%;
			height: 92rpx;
			color: #fff;
			border-radius: 48rpx;
			background-color: #ff8205;
		}
	}
}
// 选择付款方式弹窗
.pop_pay {
	height: 566rpx;
	color: #001713;
	font-size: 28rpx;

	.pay_title {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		font-size: 32rpx;
		border-bottom: 18rpx solid #ff8205;
	}

	.pay_close {
		position: absolute;
		top: 24rpx;
		right: 42rpx;
	}

	.pay_list {
		box-sizing: border-box;
		padding: 55rpx 0;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		height: 265rpx;

		.list_item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			box-sizing: border-box;
			padding: 0 32rpx 0 46rpx;

			.item_left {
				display: flex;
				align-items: center;

				.img {
					margin-right: 26rpx;
					width: 54rpx;
					height: 54rpx;
				}
			}

			.item_right {
			}
		}
	}

	.pay_btn {
		display: flex;
		align-items: center;
		justify-content: center;
		margin: auto;
		width: 720rpx;
		height: 94rpx;
		font-size: 36rpx;
		color: #fff;
		border-radius: 50rpx;
		background-color: #ff8205;
	}
}
</style>
