<template>
	<view class="page">
		<u-navbar title="我的排队" :border-bottom="false" :background="bgc" back-icon-color="#fff" title-color='#fff'
			title-size='36' height='36' id="navbar">
		</u-navbar>
		
		<scroll-view class="content" @scrolltolower="handleLoadMore" scroll-y refresher-enabled @refresherrefresh="onRefresh" :refresher-triggered="isRefreshing" refresher-default-style="white">
			<!-- 记录列表 -->
			<view class="queue-list">
				<view v-if="loading && pageNum === 1" style="color:#808080;font-size:28rpx;padding:20rpx;">加载中...</view>
				<view v-else-if="!queueList.length && !loading" style="color:#808080;font-size:28rpx;padding:20rpx;">
					{{ errorMessage || '暂无数据' }}
				</view>
				<view 
					v-for="(item, index) in queueList" 
					:key="item.id || index"
					class="queue-item"
				>
					<!-- 记录头部 -->
					<view class="item-header">
						<view class="store-info">
							<view class="store-icon"><image src="https://api.ccttiot.com/smartmeter/img/static/uYpIXrpxk4rW7fHQh70X" alt="" /></view>
							<text class="store-name">{{ item.storeName || '门店名称' }}</text>
						</view>
						<view class="status-text" :class="'status-' + normalizeStatus(item.status)">
							{{ getStatusText(item.status) }}
						</view>
					</view>
					
					<!-- 记录详情 -->
					<view class="item-details">
						<view class="detail-row">
							<text class="detail-label">我的号码</text>
							<text class="detail-value number">{{ item.number }}</text>
						</view>
						<view class="detail-row">
							<text class="detail-label">卡座类型</text>
							<text class="detail-value">{{ item.tableType || '大桌 5-10人' }}</text>
						</view>
						<view class="detail-row">
							<text class="detail-label">取号时间</text>
							<text class="detail-value">{{ item.createTime }}</text>
						</view>
					</view>
					
					<!-- 详情按钮 -->
					<view class="detail-btn-wrapper">
						<view class="detail-btn" @click="goDetail(item, index)">详情</view>
					</view>
				</view>
				
				<!-- 加载更多提示 -->
				<view v-if="hasMore && queueList.length > 0" class="load-more">
					<view v-if="loadingMore" style="color:#808080;font-size:28rpx;text-align:center;padding:20rpx;">加载更多...</view>
					<view v-else style="color:#808080;font-size:28rpx;text-align:center;padding:20rpx;">上拉加载更多</view>
				</view>
				
				<!-- 没有更多数据提示 -->
				<view v-if="!hasMore && queueList.length > 0" class="no-more">
					<view style="color:#808080;font-size:28rpx;text-align:center;padding:20rpx;">没有更多数据了</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				bgc: {
					backgroundColor: "#000",
				},
				queueList: [],
				loading: false,
				loadingMore: false,
				errorMessage: '',
				total: 0,
				pageNum: 1,
				pageSize: 10,
				hasMore: true,
				isRefreshing: false,
			}
		},
		onShow() {
			this.resetAndLoad()
		},
		methods: {
			// 重置并加载数据
			resetAndLoad() {
				this.pageNum = 1
				this.queueList = []
				this.hasMore = true
				this.getMyList()
			},
			
			// 上拉加载更多
			handleLoadMore() {
				if (this.loadingMore || !this.hasMore) return
				this.loadMore()
			},
			
			// 加载更多数据
			loadMore() {
				if (this.loadingMore || !this.hasMore) return
				
				this.loadingMore = true
				this.pageNum++
				this.getMyList(true)
			},
			
			// 下拉刷新
			onRefresh() {
				this.isRefreshing = true
				this.resetAndLoad()
				setTimeout(() => {
					this.isRefreshing = false
				}, 1000)
			},
			
			// 拉取我的排队记录
			getMyList(isLoadMore = false){
				if (isLoadMore) {
					this.loadingMore = true
				} else {
					this.loading = true
				}
				
				this.errorMessage = ''
				const storeId = this.$store && this.$store.state ? this.$store.state.storeId : ''
				
				if(!storeId){
					uni.showToast({ title:'缺少门店信息', icon:'none' })
					this.queueList = []
					this.loading = false
					this.loadingMore = false
					return
				}
				
				this.$u.get(`/app/queueUser/list?storeId=${storeId}&pageNum=${this.pageNum}&pageSize=${this.pageSize}&orderByColumn=createTime&isAsc=desc`).then(res =>{
					if(res.code == 200){
						const newData = res.rows || res.data || []
						this.total = res.total || 0
						
						if (isLoadMore) {
							// 加载更多时，追加数据
							this.queueList = [...this.queueList, ...newData]
						} else {
							// 首次加载或刷新时，替换数据
							this.queueList = newData
						}
						
						// 判断是否还有更多数据
						this.hasMore = this.queueList.length < this.total
						
						// 如果当前页数据少于pageSize，说明没有更多数据了
						if (newData.length < this.pageSize) {
							this.hasMore = false
						}
						
					}else if(res.code == 401){
						uni.showModal({
						  title: '提示',
						  content: '你还未登录，是否去登录？', 
						  success: function (res) {
						    if (res.confirm) {
						      console.log('用户点击确定')
							  uni.reLaunch({
							  	url:'/pages/login/login'
							  })
						    } else if (res.cancel) {
						      console.log('用户点击取消')
							  uni.navigateBack()
						    }
						  }
						})
					} else {
						if (!isLoadMore) {
							this.queueList = []
						}
						this.errorMessage = (res && res.msg) ? res.msg : '加载失败'
					}
				}).catch(()=>{
					if (!isLoadMore) {
						this.queueList = []
					}
					this.errorMessage = '网络错误'
				}).finally(()=>{ 
					this.loading = false 
					this.loadingMore = false
				})
			},
			
			// 跳转详情
			goDetail(item, index){
				console.log('=== 调试信息开始 ===');
				console.log('传入的item参数:', item);
				console.log('传入的index参数:', index);
				console.log('当前queueList:', this.queueList);
				console.log('当前queueList长度:', this.queueList.length);
				
				// 如果item是undefined，尝试从queueList中获取
				if (!item && typeof index === 'number' && this.queueList[index]) {
					item = this.queueList[index];
					console.log('从queueList中获取的item:', item);
				}
				
				// 如果仍然没有item，显示错误
				if (!item) {
					console.error('无法获取排队记录信息');
					uni.showToast({ title: '无法获取记录信息', icon: 'none' });
					return;
				}
				
				console.log('最终使用的item:', item);
				console.log('记录ID:', item?.id);
				console.log('记录完整信息:', JSON.stringify(item, null, 2));
				
				// 尝试多种可能的ID字段
				let recordId = item?.id || item?.queueUserId || item?.queueId || item?.recordId;
				console.log('最终使用的ID:', recordId);
				
				if (!recordId) {
					// 如果没有ID，尝试使用其他唯一标识符
					recordId = item?.number || item?.createTime || Date.now();
					console.log('使用备用标识符:', recordId);
				}
				
				// 构建跳转URL
				const targetUrl = `/page_shanghu/paidui/hexiao?id=${recordId}`;
				console.log('跳转URL:', targetUrl);
				console.log('=== 调试信息结束 ===');
				
				uni.navigateTo({ 
					url: targetUrl,
					fail: (err) => {
						console.error('跳转失败:', err);
						uni.showToast({ title: '跳转失败', icon: 'none' });
					}
				});
			},
			
			// 规范状态
			normalizeStatus(status) {
				if (status === 1 || status === '1') return 'inQueue'
				if (status === 2 || status === '2') return 'calling'
				if (status === 3 || status === '3') return 'verified'
				if (status === 4 || status === '4') return 'missed'
				if (status === 5 || status === '5') return 'cancelled'
				return status
			},
			
			getStatusText(status) {
				const statusTexts = {
					'inQueue': '排队中',
					'calling': '叫号中',
					'missed': '已过号',
					'verified': '已核销',
					'cancelled': '已取消'
				};
				const key = this.normalizeStatus(status)
				return statusTexts[key] || '';
			},
		}
	}
</script>

<style lang="scss">
	page {
		background: #000;
	}

	.page {
		min-height: 100vh;
		background: #000;
	}

	.content {
		width: 100%;
		height: 87vh;
		overflow: scroll;
		padding: 0 30rpx;
		padding-bottom: 20rpx;
		box-sizing: border-box;
		margin-top: 30rpx;
	}

	/* 记录列表 */
	.queue-list {
		.queue-item {
			background: #1a1a1a;
			border: 1px solid #333;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 24rpx;
			position: relative;
			
			/* 记录头部 */
			.item-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 24rpx;
				
				.store-info {
					display: flex;
					align-items: center;
					gap: 12rpx;
					
					.store-icon {
						width: 40rpx;
						height: 40rpx;
					}
					
					.store-name {
						color: #fff;
						font-size: 28rpx;
						font-weight: 500;
					}
				}
				
				.status-text {
					color: #fff;
					font-size: 26rpx;
					
					&.status-inQueue {
						color: #FF8998;
					}
					
					&.status-calling {
						color: #FF8998;
					}
					
					&.status-verified {
						color: #999;
					}
					
					&.status-cancelled {
						color: #999;
					}
					
					&.status-missed {
						color: #999;
					}
				}
			}
			
			/* 记录详情 */
			.item-details {
				margin-bottom: 24rpx;
				
				.detail-row {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 16rpx;
					
					&:last-child {
						margin-bottom: 0;
					}
					
					.detail-label {
						color: #999;
						font-size: 26rpx;
					}
					
					.detail-value {
						color: #fff;
						font-size: 26rpx;
						
						&.number {
							color: #FF8998;
							font-weight: 600;
							font-size: 28rpx;
						}
					}
				}
			}
			
			/* 详情按钮 */
			.detail-btn-wrapper {
				display: flex;
				justify-content: flex-end;
				
				.detail-btn {
					padding: 16rpx 24rpx;
					border-radius: 12rpx;
					font-size: 26rpx;
					text-align: center;
					background: transparent;
					color: #FF8998;
					border: 1px solid #FF8998;
					transition: all 0.3s ease;
					min-width: 120rpx;
					
					&:active {
						background: rgba(255, 137, 152, 0.1);
					}
				}
			}
		}
		
		/* 加载更多提示 */
		.load-more {
			margin-top: 20rpx;
		}
		
		/* 没有更多数据提示 */
		.no-more {
			margin-top: 20rpx;
		}
	}
</style>