<template>
	<view class="container">
		<!-- 标题区域 -->
		<view class="title" :style="{ top: `${paddingTop * 2}rpx` }">我的出行</view>

		<wd-tabs v-model="tabIndex" auto-line-width custom-class="custom_class_tab" @click="handleChange">
			<block v-for="tab in tabs" :key="tab">
				<wd-tab :title="`${tab}`" :name="tab">
					<scroll-view scroll-y class="content" @scrolltolower="scrolltolower">
						<!-- 每一个订单区域 -->
						<view v-for="item in listData" :key="item.id" class="order_box">
							<view class="box_top">
								<view class="top_left">
									<image class="left_img" src="@/static/images/mine/riding.png" mode="aspectFill" />
									墨轩出行
								</view>
								<view class="top_status red" v-if="item.payState==0">待支付</view>
								<view class="top_status red" v-if="item.payState==2">退款中</view> 
								<view class="top_status red" v-if="item.payState==3">已取消</view>
								<view v-if="item.payState==1">
									<view class="top_status red" v-if="item.byState==1">预约成功</view>
									<view class="top_status red" v-if="item.byState==2">已乘车</view>
									<view class="top_status red" v-if="item.byState==3">未乘车</view>
								</view>
								<!-- <view class="top_status red" v-if="item.byState==5">预约失败</view> -->
							</view>

							<view class="box_center">
								<image class="center_img" src="@/static/images/home/line.png" mode="aspectFill" />

								<!-- <view class="center_text" v-for="item2 in getRouteParts(item.route_end).parts" :key="item2.id">
									<view class="text_start">{{item2}}</view> -->

									<!-- <view class="text_end">{{getRouteParts(item.route_end).suffix}}</view> -->
								<!-- </view> -->
								<view class="center_text">
									<view :class="{ 'text_start': true, 'app': index2 > 0 }"  v-for="(item2, index2) in getRouteParts(item.route_end)" :key="index2">{{item2}}</view>
								</view>

								<view class="center_price">
									¥
									<text class="text">{{ item.payAmount }}</text>
								</view>
							</view>

							<view class="box_bottom">
								<view class="bottom_time">出行时间：{{ item.ciDate }}</view>
								<view class="bottom_btns" v-if="item.payState==0">
									<view class="btn_item" @click="handleDetail(item)">查看详情</view>
									<view class="btn_item pay" @click="handlePay(item)">立即支付</view>
								</view>
								<view class="bottom_btns" v-if="item.payState==3">
									<view class="btn_item" @click="handleDetail(item)">查看详情</view>
								</view>
								<!-- <view class="bottom_btns" v-if="item.byState==5">
									<view class="btn_item" @click="handleDetail(item)">查看详情</view>
								</view> -->
								<view v-if="item.payState==1">
									<view class="bottom_btns" v-if="item.byState==1">
										<view class="btn_item" @click="handleDetail(item)">查看详情</view>
									</view>
									<view class="bottom_btns" v-if="item.byState==2">
										<view class="btn_item" @click="handleDetail(item)">查看详情</view>
									</view>
									<view class="bottom_btns" v-if="item.byState==3">
										<view class="btn_item" @click="handleDetail(item)">查看详情</view>
										<view class="btn_item hexiao" @click="showQrCodeDialog(item)">去核销</view>
									</view>
								</view>
							</view>
							<view class="box_bottom">
								<view class="bottom_time"></view>
								<view v-if="item.payState==1 &&item.state!=4">
									<view class="bottom_btns" v-if="item.byState==3||item.byState==1">
										<view class="btn_item pay" @click="tuiPay(item)">退款</view>
									</view>
								</view>
							</view>
						</view>

						<view v-if="!listData.length" style="padding-top: 100rpx">
							<wd-status-tip image="content" tip="暂无数据" />
						</view>
					</scroll-view>
				</wd-tab>
			</block>
		</wd-tabs>
	</view>
	
	<!-- 二维码弹框（默认隐藏） -->
	<wd-popup v-model="isDialogShow" safe-area-inset-bottom :close-on-click-modal="false">
		<view class="qr-dialog">
		  <view class="dialog-content">
			<uv-qrcode ref="qrcode" size="180" class="qr-img" :value="ErorderNo"></uv-qrcode>
			<text class="dialog-tip">请出示此二维码给工作人员核销</text> 
			<button class="close-btn" @click="isDialogShow = false">关闭</button> 
		  </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 { onMounted, ref,  } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { myRequest } from '@/utils/api.ts'
import debounce from 'lodash/debounce'
import { useTabParamStore } from '@/utils/tabParams.js';
const tabParamStore = useTabParamStore();

// 用户信息
const userInfo = uni.getStorageSync('carUserInfo')

// 胶囊按钮距离页面顶部的距离
const paddingTop = ref(0)

const tabIndex = ref(0)
// 控制二维码弹框显示隐藏
const isDialogShow = ref(false);

// 预约状态 0:全部 1:预约成功 2:已乘车 3:未乘车 4:已取消 5:预约失败6待支付
const result_state = ref(0)
// 时间状态 1:全部 2:当天 3:本周 4:本月
const date_state = ref(1)
// 每页多少条数据
const pageSize = ref(6)
// 当前是第几页
const currentPage = ref(1)
// 总共多少条数据
const total = ref(0)
// 预约记录数据
const listData = ref([])
//二维码核销数据
const ErorderNo=ref('')

const tabs = 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 orderNo = ref('');
// 存储支付参数
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 [];
};

// 获取用户预约数据
async function getMyData() {
	const res = await myRequest({
		url: '/tAppqueryUserBuy.action',
		data: {
			result_state: result_state.value,
			date_state: date_state.value,
			id: userInfo.id,
			rows: pageSize.value,
			page: currentPage.value
		}
	})
	// console.log(res)

	const result = JSON.parse(res.data.data)

	total.value = result.totalCount

	// 处理数据
	result.list.forEach((ele) => {
		// 如果是待支付状态,算出剩余支付时间
		if (ele.state === 1 && ele.payState === 0) { 
			const temLockTime = 5
			// 兼容ios部分系统转换时间格式
			const createTime = ele.createTime.slice(0, 19).replace(/-/g, '/')
			ele.countDownTime = new Date(createTime).getTime() + temLockTime * 60 * 1000 - new Date().getTime()
		}    
	})
	listData.value = [...listData.value, ...result.list] 
	console.log(listData,'ls')
}

onMounted(() => {
	console.log(userInfo)
	paddingTop.value = uni.getMenuButtonBoundingClientRect().top
	console.log(paddingTop.value)
	getMyData()
});
onShow(() => {
  // 读取全局状态中的参数
  const type = tabParamStore.type;
  if (type) {
    console.log('接收到type参数11 ：', type);
	tabIndex.value=type
	result_state.value=type
	listData.value =[]
	getMyData()
  }
});

// 页面拉到底部触发函数
function scrolltolower() {
	if (listData.value.length < total.value) {
		currentPage.value++
		getMyData()
	} else {
		uni.showToast({
			title: '没有更多数据了',
			icon: 'none'
		})
	}
}

function handleChange(e) {
	console.log(e)
	result_state.value = e.index
	listData.value = []
	currentPage.value = 1
	total.value = 0
	getMyData()
}

function handleDetail(item) {
	const info = encodeURIComponent(JSON.stringify(item))
	uni.navigateTo({
		url: `/pages/orderDetail/orderDetail?info=${info}`
	})
}

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

// 点击弹窗关闭按钮回调
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=='电子交通卡支付'){
	}
}
//微信支付
const payWei = async () => {
	const res = await myRequest({
		url: '/tAppcontinuePay.action',
		// method: 'POST', // 明确指定请求方法为POST
		data: {
			order_num:orderNo.value,
		}
	})
	if(res.code==200){
		payParams.value = res.data; // 存储微信支付所需参数
		invokeWechatPay(); // 调起支付
	}else{
		uni.showToast({ title: res.message });
	}
}

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

// 点击“去核销”显示弹框
const showQrCodeDialog = (item) => {
  isDialogShow.value = true;
  ErorderNo.value=item.id
};
//点击退款
const tuiPay = async (item) => {
	const res = await myRequest({
		url: '/tApprefund.action',
		// method: 'POST', // 明确指定请求方法为POST
		data: {
			order_num:item.orderNo,
			id:item.id
		}
	})
	if(res.code==200){
		uni.showToast({ title: '退款成功' });
		setTimeout(function() {
			getMyData()
		}, 1000)
	}else{
		uni.showToast({ title: res.message });
	}
}
</script>

<style lang="scss" scoped>
.container {
	position: relative;
	display: flex;
	box-sizing: border-box;
	padding-top: 162rpx;
	height: 100%;
	color: #001713;
	background-color: #fff;
	overflow: hidden;

	.title {
		position: absolute;
		left: 314rpx;
		font-size: 40rpx;
	}

	.content {
		box-sizing: border-box;
		padding: 30rpx;
		height: calc(100vh - 246rpx);
		color: #001713;
		overflow-y: auto;

		.order_box {
			margin-bottom: 20rpx;
			box-sizing: border-box;
			padding: 40rpx 20rpx;
			box-shadow: 0px 3px 6px #ccc;

			.box_top {
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 28rpx;
				color: #ff8205;

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

					.left_img {
						margin-right: 12rpx;
						width: 32rpx;
						height: 32rpx;
					}
				}

				.top_status {
					font-size: 32rpx;
				}

				.red {
					color: #dc2626;
				}

				.gray {
					color: #707070;
				}
			}

			.box_center {
				display: flex;
				align-items: center;
				margin-top: 40rpx;
				font-weight: bold;

				.center_img {
					width: 14rpx;
					height: 88rpx;
				}

				.center_text {
					margin-left: 16rpx;

					.text_start {
						margin-top: -8rpx;
						width: 480rpx;
						text-overflow: ellipsis;
						white-space: nowrap;
						overflow: hidden;
					}
					.app{
						margin-top: 1px;
					}

					.text_end {
						margin-top: 30rpx;
						width: 480rpx;
						text-overflow: ellipsis;
						white-space: nowrap;
						overflow: hidden;
					}
				}

				.center_price {
					margin-left: auto;
					font-size: 24rpx;
					color: #dc2626;

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

			.box_bottom {
				display: flex;
				align-items: flex-end;
				justify-content: space-between;
				margin-top: 8rpx;
				font-size: 24rpx;
				color: #aba6a6;

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

					.btn_item {
						display: flex;
						align-items: center;
						justify-content: center;
						padding: 0 15rpx;
						margin-left: 10rpx;
						height: 50rpx;
						font-size: 24rpx;
						border-radius: 32rpx;
						border: 2rpx solid #aba6a6;
					}

					.pay {
						color: #ff8205;
						border: 2rpx solid #ff8205;
					}
					.hexiao{
						background-color: #FF8205;
						border: 2rpx solid #ff8205;
						color: #fff;
					}

					.cancel {
						color: #fff;
						background-color: #ff8205;
					}
				}
			}
			/* 二维码弹框样式 */
			.qr-dialog {
			  position: fixed;
			  top: 0;
			  left: 0;
			  width: 100%;
			  height: 100%;   
			  background: rgba(0, 0, 0, 0.5);
			  display: flex;
			  justify-content: center;
			  align-items: center;
			  z-index: 999;
			}
			.dialog-content {
			  width: 600rpx;
			  background: #fff;
			  border-radius: 16rpx;
			  padding: 40rpx;
			  text-align: center;
			}
			.qr-img {
			  width: 400rpx;
			  margin-bottom: 20rpx;
			}
			.dialog-tip {
			  display: block;
			  margin-bottom: 30rpx;
			  color: #666;
			}
			.close-btn {
			  background: #ff7a00;
			  color: #fff;
			  border-radius: 8rpx;
			}
		}
	}
}
// 选择付款方式弹窗
.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>
