<template>
	<view class="container">
		<image class="banner" src="@/static/images/mine/back.png" mode="aspectFill" />
		<view class="title" :style="{ top: `${paddingTop * 2}rpx` }">
			<view class="title_back" @click="handleBack">
				<wd-icon name="thin-arrow-left" color="#001713" size="18"></wd-icon>
			</view>

			电子交通卡充值
		</view>

		<!-- 内容区域 -->
		<scroll-view class="body" scroll-y @scrolltolower="scrolltolower">
			<view class="body_title">选择充值面额</view>

			<!-- 每一个充值选项区域 -->
			<view class="body_item" :class="{ active: item.isChecked }" v-for="(item, index) in chongList" :key="index" @click="hadnleChange(item)">
				<view class="item_price">
					¥
					<text class="text">{{item.account3}}</text>
				</view>
				<!-- <view class="item_msg">赠送{{item.account4}}元补贴包，立得{{item.account3+item.account4}}元出行金</view> -->
				<view class="item_check" v-if="item.isChecked" @click="item.isChecked!=item.isChecked">
					<wd-icon name="check-bold" color="#fff" size="20"></wd-icon>
				</view>
			</view>
		</scroll-view>

		<!-- 底部支付区域 -->
		<view class="foot">
			<view class="foot_left">
				<view class="left_top">
					合计
					<text class="text">¥{{totalAmount}}</text>
				</view>

				<!-- <view class="left_bottom">
					充值成功后赠送补贴金
					<text class="text">¥{{zengAmount}}</text>
				</view> -->
			</view>

			<view class="foot_right" @click="handlePay">点击支付</view>
		</view>
	</view>

	<!-- 选择付款方式弹窗区域 -->
	<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 { onMounted, ref } from 'vue'
import { myRequest } from '@/utils/api.ts'
import { useTabParamStore } from '@/utils/tabParams.js';
const tabParamStore = useTabParamStore();
const userInfo = uni.getStorageSync('carUserInfo')
// 胶囊按钮距离页面顶部的距离
const paddingTop = ref(0)

// 当前选择的索引
const currentIndex = ref(0)

// 付款方式弹窗显示隐藏控制
const popShow_pay = ref(false)
//充值套餐
const chongList = ref([])
// 每页多少条
const pageSize = ref(10)
// 当前页
const currentPage = ref(1)
// 总条数
const total = ref(0)
//合计支付金额
const totalAmount = ref(0)
//合计赠送金额
const zengAmount = ref(0)

// 支付方式列表
const payList = ref([
	{
		text: '微信支付',
		icon: '/static/images/pay/wx.png',
		isCheck: true
	},
	// {
	// 	text: '电子交通卡支付',
	// 	icon: '/static/images/pay/card.png',
	// 	isCheck: false
	// }
])
// 存储支付参数
const payParams = ref({
  timeStamp: '',
  nonceStr: '',
  signType: '',
  paySign: '',
  appId:'',
  // prepay_id:'',
  package:'',
});
// 选中的支付方式
const selectedPay = ref(null);

onMounted(() => {
	console.log(uni.getStorageSync('cardTypeNum'),'身份')
	paddingTop.value = uni.getMenuButtonBoundingClientRect().top
	getChongcommon()
})

// 点击切换选项的回调    
const hadnleChange = (item) => {
	chongList.value.forEach(item => {
	    item.isChecked = false;
	  });
	item.isChecked = true;
	totalAmount.value=item.account3
	zengAmount.value=item.account4
}
//交通卡充值
const jiaotong = async () => {
	const res = await myRequest({
		url: '/cardrecharge.action',
		method: 'POST', // 明确指定请求方法为POST
		data: {
			mobile: userInfo.mobile,
			type: uni.getStorageSync('cardTypeNum'),
			account4: totalAmount.value,
			account5: zengAmount.value,
		}
	})
	if(res.code==200){
		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,
		};
		invokeWechatPay(); // 调起支付
	}
}
// 调起微信支付
const invokeWechatPay = () => {
	console.log(payParams.value,'支付')
  uni.requestPayment({
	  ...payParams.value,
    success: (res) => {
      uni.showToast({ title: '支付成功' });
	  popShow_pay.value = false
	  setTimeout(function() {
	  	uni.navigateTo({
			url:'/pages/transportation/transportation'
		})
	  }, 1000)
      // 支付成功后逻辑（如跳转到订单详情）
    },
    fail: (err) => {
      uni.showToast({ title: '支付失败', icon: 'none' });
      console.error('支付失败', err);
    }
  });
};

// 获取套餐列表数据
const getChongcommon = async () => {
	let data = {
		page: currentPage.value,
		rows: pageSize.value,
	}
	try {
	    const res = await myRequest({
	      url: '/reBenefitlist.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) {
	        chongList.value = formattedRows; 
	      } else {
	        chongList.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 {
	  }
}

// 页面下滑到底部触发的回调
const scrolltolower = () => {
	if (chongList.value.length < total.value) {
		currentPage.value++
		getChongcommon()
	} else {
		uni.showToast({
			title: '没有更多数据了',
			icon: 'none'
		})
	}
}

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

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

// 顶部返回图标回调
const handleBack = () => {
	uni.navigateBack()
}

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

//立即支付
const payTime = () => {
	console.log(123222)
	// if (!selectedPay.value) {
	// 	uni.showModal({
	// 		content:'请选择支付方式'
	// 	})
	//     return;
	//   }
	jiaotong()
}
</script>

<style lang="scss" scoped>
.container {
	position: relative;
	height: 100vh;
	color: #001713;
	background-color: #fff;
	overflow: hidden;

	.banner {
		width: 100%;
		height: 482rpx;
	}

	.title {
		position: absolute;
		display: flex;
		align-items: center;
		width: 100vh;
		font-size: 40rpx;

		.title_back {
			margin-left: 26rpx;
			margin-right: 192rpx;
		}
	}

	.body {
		position: absolute;
		top: 160rpx;
		box-sizing: border-box;
		padding: 0 30rpx 30rpx;
		width: 100%;
		height: calc(100vh - 406rpx);
		font-size: 32rpx;
		color: #001713;

		.body_title {
			margin-bottom: 30rpx;
		}

		.body_item {
			position: relative;
			box-sizing: border-box;
			padding: 30rpx;
			margin-bottom: 40rpx;
			border: 2rpx solid #aba6a6;
			border-radius: 16rpx;
			background-color: #fff;

			.item_price {
				font-size: 28rpx;

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

			.item_msg {
				margin-top: 20rpx;
			}

			.item_check {
				position: absolute;
				top: 0;
				right: 0;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 60rpx;
				height: 44rpx;
				border-radius: 0 14rpx 0 16rpx;
				background-color: #ff8205;
			}
		}

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

	.foot {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0;
		box-sizing: border-box;
		padding: 0 30rpx 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 244rpx;
		box-shadow: 0px 3px 6px #000000;

		.foot_left {
			.left_top {
				font-size: 32rpx;

				.text {
					font-size: 48rpx;
					color: #dc2626;
				}
			}

			.left_bottom {
				margin-top: 10rpx;
				font-size: 24rpx;

				.text {
					color: #dc2626;
				}
			}
		}

		.foot_right {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 272rpx;
			height: 94rpx;
			color: #fff;
			font-size: 36rpx;
			border-radius: 50rpx;
			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>
