<template>
	<view class="user-invite-list-container">
		<!-- 用户信息卡片 -->
		<view class="user-info-card" v-if="targetUserInfo && targetUserId">
			<view class="user-avatar">{{ targetUserInfo.userAvatar }}</view>
			<view class="user-name">{{ targetUserInfo.userName }}</view>
			<view class="user-id">用户ID: {{ targetUserInfo.userId }}</view>
		</view>
		
		<!-- 搜索卡片 -->
		<view class="search-card">
			<u-search 
				v-model="searchKeyword" 
				placeholder="搜索顾客的姓名或者电话" 
				@search="handleSearch" 
				@clear="handleClear"
				@custom="handleSearch"
				class="search-input">
			</u-search>
		</view>
		
		<!-- 邀约列表 -->
		<view class="list-card">
			<view class="list-header">
				<text class="list-title">邀约记录</text>
				<text class="total-count">共 {{ totalCount }} 条</text>
			</view>
			
			<scroll-view scroll-y class="list-content" @scrolltolower="loadMore">
				<view 
					v-for="(item, index) in inviteList" 
					:key="index"
					class="list-item"
					@click="goToDetail(item.id)"
				>
					<view class="item-header">
						<text class="customer-name">{{ item.yykhxm || '未知客户' }}</text>
						<text class="invite-time">{{ formatDateTime(item.lxsj) }}</text>
					</view>
					<view class="item-details">
						<view class="detail-item">
							<text class="detail-label">邀约人:</text>
							<text class="detail-value">{{ item.yyrName || '无' }}</text>
						</view>
					</view>
					<view class="item-details" style="display: flex;">
						<view class="detail-item">
							<text class="detail-label">预约时间:</text>
							<text class="detail-value">{{ formatDateTime(item.yysj) }}</text>
						</view>
					</view>
					<view class="item-footer">
						<text class="detail-label">联系记录: {{ getShortRecord(item.lxjl) }}</text>
						<text class="invite-status" :class="item.dhsfyx=='是'?'success':item.dhsfyx=='否'?'failed':'pending'">
							{{ getStatusText(item.dhsfyx) }}
						</text>
					</view>
				</view>

				<!-- 空状态 -->
				<view v-if="!isLoading && inviteList.length === 0" class="empty-state">
					<view class="empty-icon">📋</view>
					<view class="empty-text">{{ searchKeyword ? '没有找到匹配的邀约记录' : '暂无邀约记录' }}</view>
					<view v-if="searchKeyword" class="empty-subtext">未找到匹配"{{ searchKeyword }}"的记录</view>
				</view>

				<!-- 加载更多 -->
				<u-loadmore v-if="inviteList.length > 0" :status="loadmoreStatus" :load-text="loadText"></u-loadmore>
			</scroll-view>
			
			<!-- 加载状态 -->
			<view v-if="isLoading && inviteList.length === 0" class="loading">
				<u-loading-icon mode="circle" color="#43a047"></u-loading-icon>
				<text class="loading-text">正在加载数据...</text>
			</view>
		</view>
	</view>
</template>

<script>
	import inviteApi from '@/apis/modules/invite.js'
	
	export default {
		data() {
			return {
				// 分页相关
				currentPage: 1,
				pageSize: 5,
				totalCount: 0,
				hasMore: true,
				
				// 数据相关
				inviteList: [],
				searchKeyword: '',
				searchTimeout: null,
				
				// 状态相关
				isLoading: false,
				loadmoreStatus: 'loadmore',
				loadText: {
					loadmore: '点击或上拉加载更多',
					loading: '正在加载...',
					nomore: '没有更多了'
				},
				
				// 用户信息
				targetUserId: '',
				targetUserInfo: null,
				userInfo: null
			}
		},
		onLoad(options) {
			this.initializePage(options);
		},
		
		onUnload() {
			// 页面卸载时清理定时器
			if (this.searchTimeout) {
				clearTimeout(this.searchTimeout);
				this.searchTimeout = null;
			}
		},
		methods: {
			// 初始化页面
			async initializePage(options) {
				try {
					// 获取用户信息
					this.userInfo = uni.getStorageSync('userInfo');
					if (!this.userInfo || Object.keys(this.userInfo).length === 0) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/login/login'
							});
						}, 1500);
						return;
					}
					
					// 获取URL参数
					this.targetUserId = options.userId || '';
					const customerName = options.customerName || '';
					
					
					// 设置目标用户信息
					this.targetUserInfo = {
						userId: this.targetUserId,
						userName: customerName || `用户${this.targetUserId.slice(-4)}`,
						userAvatar: '👤'
					};
					
					// 加载邀约列表
					await this.loadInviteList();
				} catch (error) {
					console.error('页面初始化失败:', error);
					uni.showToast({
						title: '页面初始化失败',
						icon: 'none'
					});
				}
			},
			
			// 搜索处理
			handleSearch() {
				// 清除之前的定时器
				if (this.searchTimeout) {
					clearTimeout(this.searchTimeout);
				}
				
				// 设置防抖，500ms后执行搜索
				this.searchTimeout = setTimeout(() => {
					this.resetAndSearch();
				}, 500);
			},

			// 清空搜索
			handleClear() {
				this.searchKeyword = '';
				this.resetAndSearch();
			},

			// 重置并搜索
			async resetAndSearch() {
				this.currentPage = 1;
				this.hasMore = true;
				this.loadmoreStatus = 'loadmore';
				this.inviteList = [];
				await this.loadInviteList();
			},
			
			// 加载邀约列表
			async loadInviteList() {
				if (this.isLoading) return;
				
				try {
					this.isLoading = true;
					
					const params = {
						currentPage: this.currentPage,
						pageSize: this.pageSize,
					};
					if(this.targetUserId){
						params.yykh = this.targetUserId
					} else {
						params.yyr = this.userInfo.userId
					}
					
					// 添加搜索参数
					if (this.searchKeyword && this.searchKeyword.trim()) {
						// params.yykhxm = this.searchKeyword.trim();
						params.yykh =  await this.utils.gethy(this.searchKeyword.trim())
					}
					
					const result = await inviteApi.getInviteList(params);
					
					if (result.code === 200 && result.data) {
						const data = result.data;
						this.totalCount = data.pagination?.total || 0;
						const list = data.list || [];
						
						if (this.currentPage === 1) {
							// 第一页，清空列表
							this.inviteList = list;
						} else {
							// 加载更多，追加到列表
							this.inviteList = [...this.inviteList, ...list];
						}
						
						// 判断是否还有更多数据
						this.hasMore = list.length === this.pageSize;
						
						// 更新加载状态
						if (this.hasMore) {
							this.loadmoreStatus = 'loadmore';
						} else {
							this.loadmoreStatus = 'nomore';
						}
					} else {
						throw new Error(result.message || '获取数据失败');
					}
				} catch (error) {
					console.error('加载邀约列表失败:', error);
					if (this.currentPage === 1) {
						this.showErrorState('加载数据失败，请重试');
					} else {
						this.showMessage('加载更多数据失败', 'error');
					}
				} finally {
					this.isLoading = false;
				}
			},
			
			// 加载更多
			async loadMore() {
				if (this.isLoading || !this.hasMore || this.loadmoreStatus === 'nomore') return;
				
				this.loadmoreStatus = 'loading';
				this.currentPage++;
				await this.loadInviteList();
			},
			
			// 跳转到详情页
			goToDetail(id) {
				// if (id) {
				// 	uni.navigateTo({
				// 		url: `/pages/invite-detail/invite-detail?id=${id}`
				// 	});
				// } else {
				// 	uni.showToast({
				// 		title: '无法获取邀约ID',
				// 		icon: 'none'
				// 	});
				// }
			},
			
			// 格式化日期时间
			formatDateTime(dateTime) {
				if (!dateTime) return '未知';
				
				try {
					const date = new Date(dateTime);
					return date.toLocaleString('zh-CN', {
						year: 'numeric',
						month: '2-digit',
						day: '2-digit',
						hour: '2-digit',
						minute: '2-digit'
					});
				} catch (error) {
					return dateTime;
				}
			},
		
			// 获取状态文本
			getStatusText(status) {
				if (status === '是') return '电话有效';
				if (status === '否') return '电话无效';
				return '待确认';
			},
			
			// 获取简短联系记录
			getShortRecord(record) {
				if (!record) return '无联系记录';
				return record.length > 20 ? record.substring(0, 20) + '...' : record;
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			// 显示错误状态
			showErrorState(message) {
				uni.showToast({
					title: message,
					icon: 'none'
				});
			},

			// 显示消息提示
			showMessage(message, type = 'info') {
				uni.showToast({
					title: message,
					icon: type === 'error' ? 'error' : 'none'
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.user-invite-list-container {
		min-height: 100vh;
		background: linear-gradient(135deg, #e8f5e9 0%, #b2dfdb 100%);
		padding: 20rpx;
	}
	
	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 40rpx;
	}
	
	.back-btn {
		background: #fff;
		border-radius: 24rpx;
		padding: 16rpx 24rpx;
		color: #388e3c;
		font-size: 28rpx;
		box-shadow: 0 4rpx 16rpx rgba(76, 175, 80, 0.15);
	}
	
	.header-title {
		text-align: center;
		color: #388e3c;
		font-size: 36rpx;
		font-weight: 600;
		letter-spacing: 4rpx;
		flex: 1;
	}
	
	.user-info-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.1);
		padding: 40rpx;
		margin-bottom: 40rpx;
		text-align: center;
	}
	
	.user-avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto 24rpx;
		font-size: 48rpx;
		color: #fff;
		font-weight: bold;
	}
	
	.user-name {
		font-size: 36rpx;
		font-weight: 600;
		color: #2e7d32;
		margin-bottom: 16rpx;
	}
	
	.user-id {
		font-size: 28rpx;
		color: #6a9c6a;
	}
	
	.search-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.1);
		padding: 40rpx;
		margin-bottom: 40rpx;
	}


	.list-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.1);
		overflow: hidden;
		max-height: 80vh;
	}
	
	.list-header {
		background: linear-gradient(120deg, #43e97b 0%, #38f9d7 100%);
		padding: 32rpx 40rpx;
		color: #fff;
		font-weight: 600;
		letter-spacing: 2rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.list-title {
		font-size: 32rpx;
	}
	
	.total-count {
		font-size: 28rpx;
		opacity: 0.9;
	}
	
	.list-content {
		max-height: calc(80vh - 120rpx);
		overflow-y: auto;
	}
	
	.list-item {
		padding: 32rpx 40rpx;
		border-bottom: 2rpx solid #f0f0f0;
		transition: all 0.2s ease;
	}
	
	.list-item:hover {
		background: #f8fff8;
		transform: translateX(8rpx);
	}
	
	.list-item:last-child {
		border-bottom: none;
	}
	
	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
	}
	
	.customer-name {
		font-weight: 600;
		color: #2e7d32;
		font-size: 32rpx;
	}
	
	.invite-time {
		font-size: 24rpx;
		color: #6a9c6a;
	}
	
	.item-details {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 16rpx;
		margin-bottom: 16rpx;
	}
	
	.detail-item {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #555;
	}
	
	.detail-label {
		color: #6a9c6a;
		margin-right: 12rpx;
		font-size: 24rpx;
	}
	
	.detail-value {
		flex: 1;
	}
	
	.item-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 24rpx;
	}
	
	.invite-status {
		padding: 4rpx 16rpx;
		border-radius: 24rpx;
		font-size: 20rpx;
		font-weight: 500;
	}
	
	.invite-status.success {
		background: #e8f5e9;
		color: #2e7d32;
	}
	
	.invite-status.pending {
		background: #fff3e0;
		color: #ef6c00;
	}
	
	.invite-status.failed {
		background: #ffebee;
		color: #c62828;
	}
	
	.loading {
		text-align: center;
		padding: 80rpx 40rpx;
		color: #6a9c6a;
		font-size: 28rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20rpx;
	}
	
	.loading-text {
		font-size: 28rpx;
	}
	
	
	.empty-state {
		text-align: center;
		padding: 120rpx 40rpx;
		color: #6a9c6a;
	}
	
	.empty-icon {
		font-size: 120rpx;
		margin-bottom: 32rpx;
		opacity: 0.5;
	}
	
	.empty-text {
		font-size: 32rpx;
		margin-bottom: 16rpx;
	}
	
	.empty-subtext {
		font-size: 24rpx;
		opacity: 0.7;
		margin-top: 16rpx;
	}
	
	// @media (max-width: 750rpx) {
	// 	.item-details {
	// 		grid-template-columns: 1fr;
	// 	}
		
	// 	.item-header {
	// 		flex-direction: column;
	// 		align-items: flex-start;
	// 		gap: 16rpx;
	// 	}
	// }
</style>
