<template>
	<view class="container">	
		<!-- 标签页 -->
		<view class="tabs">
			<view class="tab-item" :class="{ active: activeTab === 'pending' }" @click="switchTab('pending')">
				<text>待确认</text>
				<view class="tab-indicator" v-if="activeTab === 'pending'"></view>
			</view>
			<view class="tab-item" :class="{ active: activeTab === 'confirmed' }" @click="switchTab('confirmed')">
				<text>已确认</text>
				<view class="tab-indicator" v-if="activeTab === 'confirmed'"></view>
			</view>
		</view>
		
		<!-- 内容区域 -->
		<scroll-view class="content" scroll-y @scrolltolower="loadMore">
			<view class="order-list">
				<view class="month-group" v-for="(group, groupIndex) in groupedOrders" :key="group.month">
					<view class="month-header">
						<!-- <view class="month-icon">○</view> -->
						<text class="month-text">{{ formatMonth(group.month) }}</text>
					</view>
					<view class="order-items">
						<view class="order-item" v-for="(item, index) in group.items" :key="getItemKey(item, index)" @click.stop="(e) => goToConfirm(item, e)">
							<view class="order-content">
								<view class="order-title">服务确认单</view>
								<view class="order-time">{{ item.createTime }}</view>
							</view>
							<view class="order-action" v-if="activeTab === 'pending'">
								<view class="confirm-btn">去确认</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view class="empty-state y-bc" v-if="groupedOrders.length === 0">
				<image class="w300 h300" src="@/static/image/img_blank_nodata.png" mode=""></image>
				<text>暂无数据</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { getServiceOrderList, getServiceOrderStatusList} from '@/api/serviceOrder'
export default {
	data() {
		return {
			activeTab: 'pending', // pending: 待确认, confirmed: 已确认
			orderData: {}, // 存储接口返回的按月份分组的数据 { "2026-01": [...], "2026-02": [...] }
			page: 1,
			pageSize: 10,
			hasMore: true
		}
	},
	computed: {
		// 将接口返回的月份分组数据转换为页面需要的格式
		groupedOrders() {
			const groups = []
			// 根据当前 tab 确定 doctorConfirm 值
			const doctorConfirm = this.activeTab === 'pending' ? 0 : 1
			// 遍历接口返回的数据对象
			Object.keys(this.orderData).forEach(month => {
				const items = (this.orderData[month] || []).filter(item => {
					// 根据 doctorConfirm 过滤数据
					return item.doctorConfirm === doctorConfirm
				})
				if (items.length > 0) {
					groups.push({
						month: month,
						items: items
					})
				}
			})
			// 按月份倒序排列（最新的月份在前）
			return groups.sort((a, b) => {
				return b.month.localeCompare(a.month)
			})
		}
	},
	onLoad() {
		// this.loadStatusList()
		//this.loadData(true)
	},
	onShow() {
		this.loadData(true)
	},
	methods: {
		async loadData(refresh = false) {
			if (refresh) {
				this.page = 1
				this.hasMore = true
				this.orderData = {}
			}
			
			if (!this.hasMore) return
			
			try {
				uni.showLoading({ title: '加载中...' })
				// 根据当前 tab 设置 doctorConfirm 参数
				const doctorConfirm = this.activeTab === 'pending' ? 0 : 1
				const res = await getServiceOrderList({
					doctorConfirm: doctorConfirm, // 0: 待确认, 1: 已确认
					pageNum: this.page,
					pageSize: this.pageSize
				})
				uni.hideLoading()
				
				if (res.code === 200 && res.data) {
					// 接口返回的数据结构：{ "2026-01": [...], "2026-02": [...] }
					const monthData = res.data || {}
					
					if (refresh) {
						// 刷新时直接替换
						this.orderData = { ...monthData }
					} else {
						// 加载更多时合并数据
						Object.keys(monthData).forEach(month => {
							if (this.orderData[month]) {
								// 如果该月份已存在，合并数组
								this.orderData[month] = [...this.orderData[month], ...monthData[month]]
							} else {
								// 如果该月份不存在，直接添加
								this.orderData[month] = [...monthData[month]]
							}
						})
					}
					
					// 判断是否还有更多数据（根据返回的月份数量判断）
					const monthCount = Object.keys(monthData).length
					this.hasMore = monthCount > 0
					if (this.hasMore) {
						this.page++
					}
				} else {
					// 如果接口失败，使用空对象
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
					if (refresh) {
						this.orderData = {}
					}
				}
			} catch (e) {
				uni.hideLoading()
				console.error('加载服务单列表失败', e)
				if (refresh) {
					this.orderData = {}
				}
			}
		},
		// async loadStatusList() {
		// 	// 加载服务单状态列表（如果需要）
		// 	try {
		// 		const res = await getServiceOrderStatusList()
		// 		if (res.code === 200 && res.data) {
		// 			// 可以用于状态筛选等功能
		// 			console.log('服务单状态列表', res.data)
		// 		}
		// 	} catch (e) {
		// 		console.error('加载服务单状态列表失败', e)
		// 	}
		// },
		getDefaultData() {
			uni.hideLoading()
			// 示例数据
			const list = []
			const currentDate = new Date()
			for (let i = 0; i < 3; i++) {
				const date1 = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 23, 16, 0, 0)
				list.push({
					id: `order_${i + 1}`,
					title: '服务确认单',
					createTime: this.formatDate(date1),
					status: this.activeTab === 'pending' ? 0 : 1
				})
			}
			for (let i = 0; i < 3; i++) {
				const date2 = new Date(currentDate.getFullYear(), currentDate.getMonth() - 2, 23, 16, 0, 0)
				list.push({
					id: `order_${i + 4}`,
					title: '服务确认单',
					createTime: this.formatDate(date2),
					status: this.activeTab === 'pending' ? 0 : 1
				})
			}
			return list
		},
		formatDate(date) {
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hours = String(date.getHours()).padStart(2, '0')
			const minutes = String(date.getMinutes()).padStart(2, '0')
			const seconds = String(date.getSeconds()).padStart(2, '0')
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
		},
		switchTab(tab) {
			if (this.activeTab === tab) return
			this.activeTab = tab
			this.loadData(true)
		},
		loadMore() {
			this.loadData(false)
		},
		goBack() {
			uni.navigateBack()
		},
		goToDetail(item) {
			uni.navigateTo({
				url: `/pages_user/serviceOrderDetail?id=`+item.id+`&status=1`
			})
		},
		goToConfirm(item, e) {
			// 阻止事件冒泡
			if (e) {
				e.stopPropagation()
			}
			if (!item) {
				console.error('goToConfirm: item is undefined')
				return
			}
			console.log('item', item)
			const orderId = item.id
			if (!orderId) {
				uni.showToast({
					icon: 'none',
					title: '订单ID不存在'
				})
				return
			}
			uni.navigateTo({
				url: `/pages_user/serviceOrderDetail?id=${orderId}&status=0`
			})
		},
		// 格式化月份显示（可选：将 2026-01 格式化为 2026年01月）
		formatMonth(month) {
			if (!month) return '未知'
			const parts = month.split('-')
			if (parts.length === 2) {
				return `${parts[0]}年${parts[1]}月`
			}
			return month
		},
		// 获取列表项的 key（用于 v-for）
		getItemKey(item, index) {
			return item.id || item.serviceTicketId || item.ticketId || `item_${index}`
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	display: flex;
	flex-direction: column;
}

.navbar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 24rpx;
	background: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	
	.nav-left {
		width: 60rpx;
		
		.back-icon {
			font-size: 36rpx;
			color: #333;
			font-weight: bold;
		}
	}
	
	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.nav-right {
		display: flex;
		align-items: center;
		gap: 24rpx;
		width: 60rpx;
		justify-content: flex-end;
		
		.more-icon {
			font-size: 32rpx;
			color: #333;
		}
		
		.eye-icon {
			font-size: 32rpx;
			color: #333;
		}
	}
}

.tabs {
	display: flex;
	background: #fff;
	//border-bottom: 1rpx solid #f0f0f0;
	
	.tab-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 24rpx 0;
		position: relative;
		
		text {
			font-size: 30rpx;
			color: #999;
		}
		
		&.active {
			text {
				color: #333;
				font-weight: 500;
			}
			
			.tab-indicator {
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 80rpx;
				height: 6rpx;
				background: #388BFF;
				border-radius: 3rpx 3rpx 3rpx 3rpx;
			}
		}
	}
}

.content {
	flex: 1;
}

.order-list {
	padding: 24rpx;
}

.month-group {
	margin-bottom: 32rpx;
	
	&:last-child {
		margin-bottom: 0;
	}
	
	.month-header {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
		
		.month-icon {
			width: 16rpx;
			height: 16rpx;
			border-radius: 50%;
			background: #ccc;
			margin-right: 16rpx;
		}
		
		.month-text {
			font-size: 28rpx;
			color: #666;
		}
	}
	
	.order-items {
		.order-item {
			background: #fff;
			border-radius: 16rpx;
			padding: 32rpx 24rpx;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.order-content {
				flex: 1;
				
				.order-title {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #333333;
					margin-bottom: 12rpx;
				}
				
				.order-time {
					font-family: PingFang SC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #666666;
				}
			}
			
			.order-action {
				.confirm-btn {
					padding: 12rpx 32rpx;
					background: #388BFF;
					border-radius: 44rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #FFFFFF;
				}
			}
		}
	}
}

.empty-state {
	padding: 120rpx 24rpx;
	text-align: center;
	font-size: 28rpx;
	color: #999;
}
</style>




