<template>
	<view class="notice-board">
		<view class="board-header">
			<text class="board-title">人员留观通知</text>
		</view>
		
		<!-- 表格容器 -->
		<view class="table-container">
			<!-- 主要表头 -->
			<view class="table-header">
				<view class="table-row header-row">
					<view class="table-cell cell-id">编号</view>
					<view class="table-cell cell-name">姓名</view>
					<view class="table-cell cell-time">留观时间</view>
					<view class="table-cell cell-status">状态</view>
				</view>
			</view>
			
			<!-- 特殊状态数据展示区域（固定） -->
			<view class="special-status-container" v-if="specialStatusData.length > 0">
				<view 
					class="table-row special-row"
					v-for="(item, index) in specialStatusData"
					:key="item.id"
					:class="{
						'status-completed': item.status === 1,
						'status-left': item.status === 2
					}">
					<view class="table-cell cell-id">{{ item.id }}</view>
					<view class="table-cell cell-name">{{ item.name }}</view>
					<view class="table-cell cell-time">{{ formatTime(item.watchTime) }}</view>
					<view class="table-cell cell-status">
						<view class="status-tag" :class="getStatusClass(item.status)">
							{{ getStatusText(item.status) }}
						</view>
					</view>
				</view>
				<!-- 分隔线 -->
				<view class="divider"></view>
			</view>
			
			<!-- 普通数据内容区域 -->
			<view 
				class="table-body"
				@touchstart="handleTouchStart"
				@touchmove="handleTouchMove"
				@touchend="handleTouchEnd">
				<view 
					class="table-row"
					v-for="(item, index) in displayNormalData"
					:key="item.id"
					:class="{
						'row-even': index % 2 === 0, 
						'row-odd': index % 2 === 1,
						'buffer-row': index === actualPageSize, // 缓冲行
						'status-watching': item.status === 0
					}">
					<view class="table-cell cell-id">{{ item.id }}</view>
					<view class="table-cell cell-name">{{ item.name }}</view>
					<view class="table-cell cell-time">{{ formatTime(item.watchTime) }}</view>
					<view class="table-cell cell-status">
						<view class="status-tag" :class="getStatusClass(item.status)">
							{{ getStatusText(item.status) }}
						</view>
					</view>
				</view>
				
				<!-- 空数据提示 -->
				<view v-if="displayNormalData.length === 0 && !loading" class="empty-tip">
					暂无留观人员信息
				</view>
			</view>
		</view>
		
		<!-- 分页控制 -->
		<view class="pagination-control">
			<view class="page-info">
				第 {{ currentPage }} / {{ totalPages }} 页 (共{{ normalData.length }}人)
			</view>
			
			<view class="control-buttons">
				<button 
					class="control-btn"
					:disabled="currentPage <= 1"
					@click="prevPage">
					上一页
				</button>
				
				<label class="auto-scroll-label">
					<switch 
						:checked="autoScroll" 
						@change="toggleAutoScroll" 
						color="#007AFF"/>
					<text>自动播放</text>
				</label>
				
				<button 
					class="control-btn"
					:disabled="currentPage >= totalPages"
					@click="nextPage">
					下一页
				</button>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			// 所有数据
			allData: [],
			// 当前页码
			currentPage: 1,
			// 每页显示条数（自适应计算）
			pageSize: 10,
			// 是否自动滚动
			autoScroll: true,
			// 自动滚动定时器
			autoScrollTimer: null,
			// 滚动间隔时间（毫秒）
			scrollInterval: 3000,
			// 加载状态
			loading: false,
			// 窗口高度
			windowHeight: 0,
			// 触摸相关
			touchStartX: 0,
			touchStartTime: 0,
			isTouching: false,
			touchStartY: 0,
			// 垂直滑动相关
			lastSwipeTime: 0
		}
	},
	
	computed: {
		// 特殊状态数据（状态1和2）
		specialStatusData() {
			return this.allData.filter(item => item.status === 1 || item.status === 2)
		},
		
		// 普通状态数据（状态0）
		normalData() {
			return this.allData.filter(item => item.status === 0)
		},
		
		// 实际显示的条数（减去缓冲行）
		actualPageSize() {
			return Math.max(1, this.pageSize - 1)
		},
		
		// 总页数（基于普通数据计算）
		totalPages() {
			if (this.actualPageSize <= 0 || this.normalData.length === 0) return 1
			return Math.ceil(this.normalData.length / this.actualPageSize)
		},
		
		// 显示的普通数据（包含缓冲行）
		displayNormalData() {
			const start = (this.currentPage - 1) * this.actualPageSize
			const end = Math.min(start + this.pageSize, this.normalData.length)
			return this.normalData.slice(start, end)
		}
	},
	
	mounted() {
		this.initPage()
		this.loadData()
		// 在H5平台添加鼠标滚轮支持
		//#ifdef H5
		this.addMouseWheelSupport()
		//#endif
	},
	
	beforeDestroy() {
		this.stopAutoScroll()
		uni.offWindowResize(this.handleWindowResize)
		//#ifdef H5
		this.removeMouseWheelSupport()
		//#endif
	},
	
	methods: {
		// 初始化页面
		initPage() {
			this.calculatePageSize()
			this.handleWindowResize = this.debounce(this.calculatePageSize, 300)
			uni.onWindowResize(this.handleWindowResize)
		},
		
		// 计算自适应的页面大小
		calculatePageSize() {
			try {
				// 获取系统信息
				const systemInfo = uni.getSystemInfoSync()
				this.windowHeight = systemInfo.windowHeight
				
				// 计算可用高度
				const headerHeight = uni.upx2px(100) // 头部高度
				const paginationHeight = uni.upx2px(120) // 分页区域高度
				const tableHeaderHeight = uni.upx2px(80) // 表格头部高度
				const specialDataHeight = this.specialStatusData.length > 0 ? 
					uni.upx2px(80 * this.specialStatusData.length) : 0 // 特殊数据区域高度 + 分隔线
				const padding = uni.upx2px(0) // 上下padding
				
				const availableHeight = this.windowHeight - headerHeight - paginationHeight - 
					tableHeaderHeight - specialDataHeight - padding
				
				// 计算行高（px）- 固定60rpx
				const rowHeightPx = uni.upx2px(60)
				
				// 计算可显示的行数
				const calculatedPageSize = Math.floor(availableHeight / rowHeightPx)
				
				// 设置页面大小（最少显示4行，最多显示30行）
				this.pageSize = Math.max(4, Math.min(30, calculatedPageSize))
				
				// 验证当前页
				this.validateCurrentPage()
				
			} catch (error) {
				console.error('计算页面大小失败:', error)
				this.pageSize = 10 // 默认值
			}
		},
		
		// 防抖函数
		debounce(func, wait) {
			let timeout
			return function executedFunction(...args) {
				const later = () => {
					clearTimeout(timeout)
					func(...args)
				}
				clearTimeout(timeout)
				timeout = setTimeout(later, wait)
			}
		},
		
		// 验证当前页是否有效
		validateCurrentPage() {
			if (this.currentPage > this.totalPages && this.totalPages > 0) {
				this.currentPage = this.totalPages
			}
			if (this.currentPage < 1) {
				this.currentPage = 1
			}
		},
		
		// 加载数据 - 状态1和2只保留一条实例
		loadData() {
			this.loading = true
			try {
				// 生成模拟数据
				const mockData = []
				const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十', '郑一', '王二']
				
				// 生成100条数据
				for (let i = 1; i <= 100; i++) {
					const randomName = names[Math.floor(Math.random() * names.length)] + i
					
					let status = 0 // 默认状态为0（留观中）
					
					// 特殊处理：只让第10条数据状态为1（完成），第20条数据状态为2（提前离开）
					if (i === 10) {
						status = 1 // 完成
					} else if (i === 20) {
						status = 2 // 提前离开
					}
					// 其他所有数据保持状态0（留观中）
					
					mockData.push({
						id: i,
						name: randomName,
						watchTime: Date.now() - Math.random() * 24 * 60 * 60 * 1000,
						status: status // 0=留观中，1=完成，2=提前离开
					})
				}
				this.allData = mockData
				
				console.log('数据加载完成，状态分布:', {
					'留观中(0)': this.normalData.length,
					'已完成(1)': this.specialStatusData.filter(item => item.status === 1).length,
					'提前离开(2)': this.specialStatusData.filter(item => item.status === 2).length
				})
				
				// 验证当前页
				this.validateCurrentPage()
				
			} catch (error) {
				console.error('加载数据失败:', error)
				uni.showToast({
					title: '数据加载失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		
		// 格式化时间
		formatTime(timestamp) {
			if (!timestamp) return ''
			const date = new Date(timestamp)
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
		},
		
		// 获取状态文本
		getStatusText(status) {
			switch (status) {
				case 0: return '留观中'
				case 1: return '已完成'
				case 2: return '提前离开'
				default: return '未知'
			}
		},
		
		// 获取状态样式类
		getStatusClass(status) {
			switch (status) {
				case 0: return 'status-watching-tag'
				case 1: return 'status-completed-tag'
				case 2: return 'status-left-tag'
				default: return ''
			}
		},
		
		// 上一页
		prevPage() {
			if (this.currentPage > 1) {
				this.currentPage--
				this.resetAutoScroll()
			}
		},
		
		// 下一页
		nextPage() {
			if (this.currentPage < this.totalPages) {
				this.currentPage++
				this.resetAutoScroll()
			}
		},
		
		// 触摸开始
		handleTouchStart(e) {
			this.touchStartX = e.touches[0].clientX
			this.touchStartY = e.touches[0].clientY
			this.touchStartTime = Date.now()
			this.isTouching = true
			// 停止自动滚动
			if (this.autoScroll) {
				this.stopAutoScroll()
			}
		},
		
		// 触摸移动
		handleTouchMove(e) {
			if (!this.isTouching) return
		},
		
		// 触摸结束
		handleTouchEnd(e) {
			if (!this.isTouching) return
			
			const touchEndX = e.changedTouches[0].clientX
			const touchEndY = e.changedTouches[0].clientY
			const touchEndTime = Date.now()
			
			const deltaX = touchEndX - this.touchStartX
			const deltaY = touchEndY - this.touchStartY
			const deltaTime = touchEndTime - this.touchStartTime
			
			// 防抖：限制滑动切换频率
			const now = Date.now()
			if (now - this.lastSwipeTime < 300) {
				this.isTouching = false
				return
			}
			
			// 判断滑动方向
			const absDeltaX = Math.abs(deltaX)
			const absDeltaY = Math.abs(deltaY)
			
			// 水平滑动优先
			if (absDeltaX > 50 && absDeltaX > absDeltaY && deltaTime < 500) {
				this.lastSwipeTime = now
				if (deltaX > 0) {
					// 向右滑动 - 上一页
					this.prevPage()
				} else {
					// 向左滑动 - 下一页
					this.nextPage()
				}
			}
			// 垂直滑动
			else if (absDeltaY > 50 && absDeltaY > absDeltaX && deltaTime < 500) {
				this.lastSwipeTime = now
				if (deltaY > 0) {
					// 向下滑动 - 上一页
					this.prevPage()
				} else {
					// 向上滑动 - 下一页
					this.nextPage()
				}
			}
			
			this.isTouching = false
			
			// 如果开启了自动滚动，重新启动
			if (this.autoScroll) {
				this.resetAutoScroll()
			}
		},
		
		// 添加鼠标滚轮支持（仅H5平台）
		//#ifdef H5
		addMouseWheelSupport() {
			const tableBody = document.querySelector('.table-body')
			if (tableBody) {
				this.wheelHandler = this.debounce((e) => {
					e.preventDefault()
					const delta = e.wheelDelta || -e.detail
					if (delta < 0) {
						// 向下滚动 - 下一页
						this.nextPage()
					} else {
						// 向上滚动 - 上一页
						this.prevPage()
					}
				}, 150)
				
				tableBody.addEventListener('mousewheel', this.wheelHandler, { passive: false })
				tableBody.addEventListener('DOMMouseScroll', this.wheelHandler, { passive: false })
			}
		},
		
		// 移除鼠标滚轮支持
		removeMouseWheelSupport() {
			const tableBody = document.querySelector('.table-body')
			if (tableBody && this.wheelHandler) {
				tableBody.removeEventListener('mousewheel', this.wheelHandler)
				tableBody.removeEventListener('DOMMouseScroll', this.wheelHandler)
			}
		},
		//#endif
		
		// 切换自动滚动
		toggleAutoScroll(e) {
			this.autoScroll = e.detail.value
			if (this.autoScroll) {
				this.startAutoScroll()
			} else {
				this.stopAutoScroll()
			}
		},
		
		// 开始自动滚动
		startAutoScroll() {
			this.stopAutoScroll()
			if (this.autoScroll && this.normalData.length > 0 && this.totalPages > 1) {
				this.autoScrollTimer = setInterval(() => {
					if (this.currentPage < this.totalPages) {
						this.currentPage++
					} else {
						this.currentPage = 1 // 回到第一页
					}
				}, this.scrollInterval)
			}
		},
		
		// 停止自动滚动
		stopAutoScroll() {
			if (this.autoScrollTimer) {
				clearInterval(this.autoScrollTimer)
				this.autoScrollTimer = null
			}
		},
		
		// 重置自动滚动（手动操作后）
		resetAutoScroll() {
			if (this.autoScroll) {
				this.stopAutoScroll()
				setTimeout(() => {
					this.startAutoScroll()
				}, this.scrollInterval)
			}
		}
	},
	
	watch: {
		// 监听数据变化
		allData: {
			handler() {
				this.$nextTick(() => {
					this.validateCurrentPage()
					if (this.autoScroll) {
						this.startAutoScroll()
					}
				})
			},
			immediate: true
		},
		
		// 监听页面大小变化
		pageSize() {
			this.validateCurrentPage()
		},
		
		// 监听特殊状态数据变化
		specialStatusData() {
			// 特殊状态数据变化时重新计算页面大小
			this.$nextTick(() => {
				this.calculatePageSize()
			})
		}
	}
}
</script>

<style scoped>
.notice-board {
	width: 100%;
	height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: #f0f2f5;
	padding: 20rpx;
	box-sizing: border-box;
}

.board-header {
	text-align: center;
	margin-bottom: 20rpx;
	flex-shrink: 0;
}

.board-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.table-container {
	flex: 1;
	background-color: #fff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	overflow: hidden;
	display: flex;
	flex-direction: column;
}

.table-header {
	background: linear-gradient(135deg, #007AFF, #0066CC);
	color: #fff;
	flex-shrink: 0;
}

.table-row {
	display: flex;
	flex-direction: row;
	min-height: 60rpx; /* 控制行高为60rpx */
	line-height: 60rpx;
	border-bottom: 1rpx solid #eee;
	transition: all 0.2s ease;
}

.header-row {
	font-weight: bold;
}

.table-cell {
	flex: 1;
	padding: 0 15rpx;
	font-size: 24rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	display: flex;
	align-items: center;
}

.cell-id {
	flex: 0.5;
	text-align: center;
	justify-content: center;
}

.cell-name {
	flex: 1.5;
}

.cell-time {
	flex: 2;
}

.cell-status {
	flex: 1;
	text-align: center;
	justify-content: center;
}

/* 特殊状态数据容器 */
.special-status-container {
	background-color: #fff8e6;
}

.special-row {
	background-color: #fff8e6 !important;
	min-height: 60rpx;
	line-height: 60rpx;
}

/* 分隔线 */
.divider {
	height: 1rpx;
	background-color: #ddd;
}

/* 普通数据内容区域 */
.table-body {
	flex: 1;
	overflow-y: auto;
	/* 添加触摸反馈 */
	-webkit-overflow-scrolling: touch;
	touch-action: pan-y;
}

.row-even {
	background-color: #fff;
}

.row-odd {
	background-color: #fafafa;
}

/* 状态行样式 */
.status-watching {
	background-color: #e6f7ff !important;
	border-left: 4rpx solid #1890ff;
}

.status-completed {
	background-color: #f6ffed !important;
	border-left: 4rpx solid #52c41a;
}

.status-left {
	background-color: #fff2e8 !important;
	border-left: 4rpx solid #fa8c16;
}

/* 缓冲行样式 */
.buffer-row {
	background-color: #f0f0f0 !important;
	opacity: 0.6;
}

/* 状态标签样式 - 控制高度不超过40rpx */
.status-tag {
	padding: 4rpx 12rpx;
	border-radius: 20rpx;
	font-size: 20rpx;
	font-weight: normal;
	line-height: 32rpx;
	height: 40rpx;
	display: inline-flex;
	align-items: center;
	justify-content: center;
	min-width: 100rpx;
}

.status-watching-tag {
	background-color: #e6f7ff;
	color: #1890ff;
	border: 1rpx solid #91d5ff;
}

.status-completed-tag {
	background-color: #f6ffed;
	color: #52c41a;
	border: 1rpx solid #b7eb8f;
}

.status-left-tag {
	background-color: #fff2e8;
	color: #fa8c16;
	border: 1rpx solid #ffbb96;
}

.empty-tip {
	text-align: center;
	padding: 80rpx;
	color: #999;
	font-size: 28rpx;
}

/* 分页控制 */
.pagination-control {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin: 20rpx 0;
	padding: 0 20rpx;
	flex-shrink: 0;
	background-color: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.page-info {
	font-size: 24rpx;
	color: #666;
	margin-bottom: 20rpx;
}

.control-buttons {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
	width: 100%;
}

.control-btn {
	flex: 1;
	height: 60rpx;
	line-height: 60rpx;
	font-size: 24rpx;
	background: linear-gradient(135deg, #007AFF, #0066CC);
	color: #fff;
	border: none;
	border-radius: 10rpx;
	margin: 0 10rpx;
}

.control-btn[disabled] {
	background: #ccc;
	opacity: 0.6;
}

.auto-scroll-label {
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	color: #666;
	flex: 1;
}

.auto-scroll-label text {
	margin-left: 10rpx;
}

/* 响应式优化 */
@media screen and (max-height: 600px) {
	.table-row {
		min-height: 50rpx;
		line-height: 50rpx;
	}
	
	.table-cell {
		font-size: 22rpx;
		padding: 0 10rpx;
	}
	
	.status-tag {
		padding: 2rpx 10rpx;
		font-size: 18rpx;
		line-height: 28rpx;
		height: 32rpx;
		min-width: 80rpx;
	}
	
	.control-btn {
		height: 50rpx;
		line-height: 50rpx;
		font-size: 22rpx;
	}
}

/* 滚动条样式 */
.table-body::-webkit-scrollbar {
	width: 4rpx;
}

.table-body::-webkit-scrollbar-track {
	background: #f1f1f1;
	border-radius: 6rpx;
}

.table-body::-webkit-scrollbar-thumb {
	background: #c1c1c1;
	border-radius: 6rpx;
}

.table-body::-webkit-scrollbar-thumb:hover {
	background: #a8a8a8;
}
</style>