<template>
	<view class="container">
		<view v-if="tabsReady">
			<u-tabs :list="tabList" :current="currentTab" @change="handleTabChange" border="false"
				active-color="#1989fa" bg-color="#f8f8f8"></u-tabs>

			<!-- 会议室列表 -->
			<view class="room-list" v-if="currentTab === 0">
				11111111111111
				<view v-if="meetingRoomList.length === 0" class="empty-container">
				    <text>暂无会议室数据 ({{ meetingRoomList }})</text>
				  </view>
				<view class="room-item" v-for="(item, index) in meetingRoomList" :key="index">
					<image class="room-img" 
					       :src="item.imgs && item.imgs.length > 0 ? `${IMAGE_BASE_URL}${item.imgs[0]}` : '/static/default-room.jpg'"
					       mode="aspectFill"
					       @error="handleImageError"
					       @click="goDetail(item)">
					</image>
					<view class="room-info">
						<view class="room-header">
							<view class="room-name">{{ item.title}}</view>
							<view class="room-status" :class="item.status == 2 ? 'available':''">可预约</view>
						</view>
						<view class="room-meta">
							<view class="meta-item">
								<u-icon name="account" size="30" color="#666"></u-icon>
								<text>可容纳人数：{{ item.maxNum }}人</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 预约记录列表 -->
			<view class="order-list" v-else>
				<view v-if="orderList.length === 0" class="empty-container">
					<u-icon name="list" class="empty-icon" size="48"></u-icon>
					<text class="empty-text">暂无预约记录</text>
				</view>
				<view class="order-item" v-for="(item, index) in orderList" :key="index">
					<view class="order-header" @click="goDetail(item.roomInfo || item)">
						<view class="order-name">{{ item.roomInfo ? item.roomInfo.title : '会议室' }}</view>
						<view class="order-status" :class="getStatusClass(item.status)">
							{{ getStatusText(item.status) }}
						</view>
					</view>

					<view class="order-content">
						<image class="room-img" 
							   :src="item.imgs && item.imgs.length > 0 ? `${IMAGE_BASE_URL}${item.imgs[0]}` : '/static/default-room.jpg'"
							   mode="aspectFill"
							   @error="handleImageError"
							   @click="goDetail(item)">
						</image>

						<view class="order-details">
							<view class="detail-item">
								<u-icon name="account" size="16" color="#666" class="detail-icon"></u-icon>
								<text>联系人: {{ item.concatName }} ({{ item.concatPhone }})</text>
							</view>

							<view class="detail-item">
								<u-icon name="calendar" size="16" color="#666" class="detail-icon"></u-icon>
								<text>预约日期: {{ formatDate(item.startAt) }}</text>
							</view>

							<view class="detail-item">
								<u-icon name="clock" size="16" color="#666" class="detail-icon"></u-icon>
								<text>时间段: {{ formatTimeRange(item.startAt, item.endAt) }}</text>
							</view>

							<view class="detail-item" v-if="item.remark">
								<u-icon name="edit-pen" size="16" color="#666" class="detail-icon"></u-icon>
								<text>备注: {{ item.remark }}</text>
							</view>
						</view>
					</view>

					<view class="order-actions">
						<u-button type="primary" size="mini" plain
							@click="goDetail(item.roomInfo || item)">查看详情</u-button>
						<u-button type="error" size="mini" plain v-if="item.status === 0" @click="cancelOrder(item.id)">
							取消预约
						</u-button>
					</view>
				</view>
			</view>
		</view>

		<view v-else class="loading-container">
			<u-loading-icon mode="circle" size="36"></u-loading-icon>
			<text class="loading-text">加载会议室信息中...</text>
		</view>
	</view>
</template>

<script>
	import {
		get,
		post
	} from '@/utils/request';
	import {
		IMAGE_BASE_URL,
		BASE_URL
	} from '@/utils/config';
	import {
		formatTime,
		formatRelativeTime
	} from '@/utils/timeFormat';
	export default {
		data() {
			return {
				IMAGE_BASE_URL,
				tabsReady: false,
				tabList: [{
						name: '会议预约'
					},
					{
						name: '预约记录'
					}
				],
				currentTab: 0,
				meetingRoomList: [],
				orderList: [] // 新增单独订单列表
			};
		},
		onLoad() {
			 this.getList(); 
			// this.fetchMeetingRooms().then(() => {
			// 	this.$nextTick(() => {
			// 		this.tabsReady = true;
			// 	});
			// });
		},
		// mounted() {
		// 	this.getList();
		// },
		computed: {
		  formattedOrderList() {
		    return this.orderList.map(item => ({
		      ...item,
		      roomTitle: item.roomInfo ? item.roomInfo.title : '会议室',
		      hasImages: item.roomInfo && item.roomInfo.imgs && item.roomInfo.imgs.length > 0,
		      firstImage: item.roomInfo && item.roomInfo.imgs && item.roomInfo.imgs[0] ? 
		        `${IMAGE_BASE_URL}${item.roomInfo.imgs[0]}` : ''
		    }))
		  }
		},
		methods: {

			handleTabChange(index) {
				this.currentTab = index.index;
				if (index.index == 1) {
					this.getOrderList();
				} else {
					this.getList();
				}
				console.log("=======index", index)
			},
			// 格式化日期
			formatDate(dateString) {
				if (!dateString) return '';
				const date = new Date(dateString);
				return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
			},

			// 格式化时间段
			formatTimeRange(startAt, endAt) {
				if (!startAt || !endAt) return '';
				const start = new Date(startAt);
				const end = new Date(endAt);
				return `${start.getHours()}:${start.getMinutes().toString().padStart(2, '0')} - ${end.getHours()}:${end.getMinutes().toString().padStart(2, '0')}`;
			},
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					0: '待确认',
					1: '已确认',
					2: '已取消',
					3: '已拒绝',
					4: '已完成'
				};
				return statusMap[status] || '未知状态';
			},

			// 获取状态样式类
			getStatusClass(status) {
				const classMap = {
					0: 'pending',
					1: 'confirmed',
					2: 'cancelled',
					3: 'rejected',
					4: 'completed'
				};
				return classMap[status] || '';
			},

			// 取消预约
			async cancelOrder(orderId) {
				try {
					uni.showLoading({
						title: '处理中...',
						mask: true
					});
					const res = await post('/api/v1/app_auth/metting-room/order/cancel', {
						id: orderId
					});

					if (res?.success) {
						uni.showToast({
							title: '取消成功',
							icon: 'success'
						});
						this.getOrderList(); // 刷新列表
					} else {
						uni.showToast({
							title: res?.message || '取消失败',
							icon: 'none'
						});
					}
				} catch (err) {
					console.error('取消预约失败:', err);
					uni.showToast({
						title: '取消失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			goDetail(item) {
				// 调试输出完整数据结构
				console.log('点击项完整数据:', JSON.stringify(item));

				// 安全获取ID（兼容各种可能的字段名）
				const id = item.id;

				if (!id) {
					console.error('无效的会议室数据，缺少ID字段:', item);
					uni.showToast({
						title: '会议室信息异常',
						icon: 'none'
					});
					return;
				}

				// 调试输出最终使用的ID
				console.log('导航使用的ID:', id);

				uni.navigateTo({
					url: `/pages/meetingDetail/index?Id=${encodeURIComponent(id)}`, // 使用encodeURIComponent防止特殊字符问题
					success: () => {
						console.log('导航成功，ID:', id);
					},
					fail: (err) => {
						console.error('导航失败:', err);
						uni.showToast({
							title: '打开详情页失败',
							icon: 'none'
						});
					}
				});
			},
			// 获取会议室列表
			async getList() {
				try {
					const res = await get('/api/v1/apps/home/metting-room', {
						current: 1,
						pageSize: 10,
					});

					console.log("===res", res)

					if (res?.success) {
						this.meetingRoomList = [...res.data];
						console.log("======this.meetingRoomList", this.meetingRoomList)
						this.tabsReady = true;
					}

				} catch (err) {
					console.error('获取我的求助失败:', err);
					uni.showToast({
						title: '加载列表失败',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
				}
			},
			// 获取我的预约记录
			async getOrderList() {
				try {
					const res = await get('/api/v1/app_auth/metting-room/order', {
						current: 1,
						pageSize: 10,
					});

					console.log("===res", res)

					if (res?.success) {
						this.orderList = [...res.data]; 
						this.tabsReady = true;
					}

				} catch (err) {
					console.error('获取我的求助失败:', err);
					uni.showToast({
						title: '加载列表失败',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
				}
			},

		}
	};
</script>

<style lang="scss" scoped>
	// 定义变量
	$primary-color: #1989fa;
	$success-color: #07c160;
	$warning-color: #ff976a;
	$error-color: #ee0a24;
	$text-color: #333;
	$sub-text-color: #666;
	$light-text-color: #999;
	$border-color: #f0f0f0;
	$bg-color: #f8f8f8;
	$card-radius: 12px;
	$tag-radius: 4px;

	.container {
		padding: 0;
		min-height: 100vh;
		background-color: $bg-color;

		.loading-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			height: 70vh;

			.loading-text {
				margin-top: 16px;
				font-size: 15px;
				color: $sub-text-color;
			}
		}

		.room-list {
			padding: 15px;

			.room-item {
				display: flex;
				margin-bottom: 20px;
				border-radius: $card-radius;
				overflow: hidden;
				background-color: #fff;
				box-shadow: 0 3px 12px rgba(0, 0, 0, 0.04);

				.room-img {
					width: 120px;
					height: 120px;
					flex-shrink: 0;
				}

				.room-info {
					flex: 1;
					padding: 12px 15px;
					display: flex;
					flex-direction: column;

					.room-header {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 8px;

						.room-name {
							font-size: 16px;
							font-weight: bold;
							color: $text-color;
						}

						.room-status {
							font-size: 12px;
							padding: 2px 8px;
							border-radius: 10px;

							&.available {
								background-color: rgba($success-color, 0.1);
								color: $success-color;
							}

							&.pending {
								background-color: rgba($warning-color, 0.1);
								color: $warning-color;
							}

							&.confirmed {
								background-color: rgba($primary-color, 0.1);
								color: $primary-color;
							}
						}
					}

					.room-meta {
						display: flex;
						margin: 8px 0 12px;

						.meta-item {
							display: flex;
							align-items: center;
							margin-right: 15px;
							font-size: 13px;
							color: $sub-text-color;

							u-icon {
								margin-right: 4px;
							}
						}
					}

					.room-facilities {
						display: flex;
						flex-wrap: wrap;
						margin-top: auto;

						.facility-tag {
							font-size: 11px;
							padding: 2px 8px;
							margin-right: 8px;
							margin-bottom: 5px;
							border-radius: $tag-radius;
							background-color: #f0f7ff;
							color: $primary-color;
						}
					}
				}
			}
		}

		.order-list {
			padding: 15px;

			.order-item {
				margin-bottom: 20px;
				border-radius: $card-radius;
				overflow: hidden;
				background-color: #fff;
				padding: 16px;
				box-shadow: 0 3px 12px rgba(0, 0, 0, 0.04);

				.order-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding-bottom: 12px;
					border-bottom: 1px solid #f5f5f5;

					.order-name {
						font-size: 16px;
						font-weight: bold;
						color: $text-color;
					}

					.order-status {
						font-size: 13px;

						&.pending {
							color: $warning-color;
						}

						&.confirmed {
							color: $success-color;
						}
					}
				}

				.order-details {
					padding: 15px 0;

					.detail-item {
						display: flex;
						align-items: center;
						margin-bottom: 10px;
						font-size: 14px;
						color: $sub-text-color;

						.item-icon {
							width: 50rpx;
							height: 50rpx;
							text-align: center !important;
							padding-top: 10rpx;
						}

						.detail-icon {
							display: flex;
							align-items: center;
							justify-content: center;
							width: 20px;
							height: 20px;
							margin-right: 8px;
						}

						.detail-text {
							line-height: 1.5;
						}

						&:last-child {
							margin-bottom: 0;
						}
					}
				}

				.order-actions {
					display: flex;
					justify-content: flex-end;
					gap: 10px;
					padding-top: 10px;
					border-top: 1px solid #f5f5f5;
				}
			}
		}

		// 空状态提示
		.empty-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 40px 0;

			.empty-icon {
				font-size: 48px;
				color: #ccc;
				margin-bottom: 15px;
			}

			.empty-text {
				font-size: 15px;
				color: $sub-text-color;
			}
		}
		
			.order-content {
				display: flex;
				padding: 15px 0;
				border-bottom: 1px solid #f5f5f5;
			}
			
			.order-img {
				width: 120px;
				height: 90px;
				border-radius: 6px;
				margin-right: 15px;
				flex-shrink: 0;
			}
			
			.order-details {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
			}
			
			.detail-item {
				display: flex;
				align-items: center;
				margin-bottom: 8px;
				font-size: 14px;
				color: #666;
				
				&:last-child {
					margin-bottom: 0;
				}
			}
			
			.detail-icon {
				margin-right: 8px;
			}
			
			/* 状态样式补充 */
			.order-status {
				font-size: 13px;
				padding: 2px 8px;
				border-radius: 10px;
				
				&.pending {
					background-color: rgba(#ff976a, 0.1);
					color: #ff976a;
				}
				
				&.confirmed {
					background-color: rgba(#07c160, 0.1);
					color: #07c160;
				}
				
				&.cancelled, &.rejected {
					background-color: rgba(#ee0a24, 0.1);
					color: #ee0a24;
				}
				
				&.completed {
					background-color: rgba(#1989fa, 0.1);
					color: #1989fa;
				}
			}
			
			.empty-container {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 60px 0;
				
				.empty-icon {
					color: #ccc;
					margin-bottom: 15px;
				}
				
				.empty-text {
					font-size: 15px;
					color: #999;
				}
			}
	}
</style>