<template>
	<view class="clue-list-container">
		<!-- 搜索卡片 -->
		<view class="search-card">
			<u-search 
				v-model="searchKeyword" 
				placeholder="搜索顾客的姓名或者电话" 
				@search="onSearchInput" 
				@clear="onSearchInput"
				@custom="onSearchInput"
				class="search-input">
			</u-search>
		</view>
		<!-- 筛选卡片 -->
		<view class="filter-card">
			<!-- 跨店开关 -->
			<!-- v-if="showReport" -->
			<view class="cross-store-toggle" >
				<u-switch 
					v-model="isCrossStore" 
					@change="onCrossStoreChange"
					activeColor="#43e97b"
					inactiveColor="#c8e6c9"
				/>
				<text class="toggle-text">跨店获取数据</text>
			</view>
			
			<!-- 客户类型筛选 -->
			<view class="tab-filter">
				<view class="tab-list">
					<view 
						v-for="(tab, index) in tabList" 
						:key="index"
						class="tab-item"
						:class="{ active: currentFilterType === tab.value }"
						@click="onTabClick(tab.value)"
					>
						{{ tab.label }}
					</view>
				</view>
			</view>
		</view>
		
		<!-- 线索列表 -->
		<view class="clue-list" v-if="clueList.length > 0">
			<view 
				v-for="(clue, index) in clueList" 
				:key="clue.id"
				class="clue-card"
				@click.stop = "gomemberedit(clue.id)"
			>
				<view class="clue-row">
					<view class="clue-item">
						<text class="clue-label">归属门店</text>
						<text class="clue-value">{{ clue.gsmdName }}</text>
					</view>
					<view class="clue-item">
						<text class="clue-label">健康师</text>
						<text class="clue-value">{{ clue.mainHealthUserName }}</text>
					</view>
				</view>
				<view class="clue-row">
					<view class="clue-item">
						<text class="clue-label">负责顾问</text>
						<text class="clue-value">{{ clue.subHealthUserName }}</text>
					</view>
					<view class="clue-item">
						<text class="clue-label">客户类型</text>
						<text class="clue-value">{{ clue.khlxName }}</text>
					</view>
				</view>
				<view class="clue-row">
					<view class="clue-item">
						<text class="clue-label">姓名</text>
						<text class="clue-value">{{ clue.name }}</text>
					</view>
					<view class="clue-item">
						<text class="clue-label">电话</text>
						<text class="clue-value">{{ clue.phone }}</text>
					</view>
				</view>
				<view class="clue-row">
					<view class="clue-item">
						<text class="clue-label">拓客人员</text>
						<text class="clue-value">{{ clue.expandUserName }}</text>
					</view>
				</view>
				<view class="clue-row">
					<view class="clue-item">
						<text class="clue-label">备注</text>
						<text class="clue-value">{{ clue.bz }}</text>
					</view>
				</view>
				<view class="button-group">
					<button 
						type="primary" 
						size="small" 
						class="action-btn invite-btn"
						@click.stop="handleAppointment(clue)"
					>
						预约
					</button>
					<button 
						type="primary" 
						size="small" 
						class="action-btn invite-btn"
						@click.stop="handleAppointmentList(clue)"
					>
						预约列表
					</button>
					<button 
						type="info" 
						size="small" 
						class="action-btn view-invite-btn"
						@click.stop="handleInvite(clue)"
					>
						邀约
					</button>
					<button 
						type="info" 
						size="small" 
						class="action-btn view-invite-btn"
						@click.stop="handleInviteList(clue)"
					>
						邀约列表
					</button>
					
				</view>
				<view class="button-group" style="width: 46%;">
					<button
						type="warning" 
						size="small" 
						class="action-btn remaining-rights-btn"
						@click.stop="goToServiceLog(clue)"
					>
						日志
					</button>
					<button
						type="warning" 
						size="small" 
						class="action-btn remaining-rights-btn"
						@click.stop="handleRemainingRights(clue)"
					>
						剩余权益
					</button>
				</view>
			</view>
		</view>
		
		<!-- 加载状态 -->
		<view v-if="isLoading" class="loading">
			<u-loading-icon mode="circle" color="#43a047"></u-loading-icon>
			<text class="loading-text">正在加载客户数据...</text>
		</view>
		
		<!-- 加载更多 -->
		<view v-if="isLoadingMore" class="loading-more">
			<u-loading-icon mode="circle" color="#43a047" size="16"></u-loading-icon>
			<text class="loading-more-text">正在加载更多...</text>
		</view>
		
		<!-- 无更多数据 -->
		<view v-if="!hasMoreData && clueList.length > 0" class="no-more-data">
			已加载全部数据
		</view>
		
		<!-- 空状态 -->
		<view v-if="!isLoading && clueList.length === 0" class="empty-state">
			<view class="empty-state-icon">📋</view>
			<view class="empty-state-text">暂无客户数据</view>
			<view class="empty-state-subtext">请稍后再试或联系管理员</view>
		</view>
		
		<!-- 搜索空状态 -->
		<view v-if="!isLoading && clueList.length === 0 && isSearching" class="empty-state">
			<view class="empty-state-icon">🔍</view>
			<view class="empty-state-text">未找到匹配的客户</view>
			<view class="empty-state-subtext">请尝试其他搜索关键词</view>
		</view>
	</view>
</template>

<script>
	import clueApi from '@/apis/modules/clue.js'
	
	export default {
		data() {
			return {
				// 搜索相关
				searchKeyword: '',
				searchTimeout: null,
				isSearching: false,
				
				// 筛选相关
				isCrossStore: false,
				currentFilterType: '',
				tabList: [
					{ label: '全部', value: '' }
				],
				
				// 列表相关
				clueList: [],
				allClues: [],
				currentPage: 1,
				pageSize: 5,
				isLoading: false,
				isLoadingMore: false,
				hasMoreData: true,
				
				// 用户信息
				userInfo: null
			}
		},
		computed: {
			// 根据用户权限显示报表按钮
			showReport() {
				if (!this.userInfo || !this.userInfo.userAccount) return false
				const adminAccounts = ['admin', '13198568627', '18884847552', '13608016021', '18628973287']
				return adminAccounts.includes(this.userInfo.userAccount)
			}
		},
		onLoad() {
			this.initializePage();
		},
		onReachBottom() {
			this.loadMoreData();
		},
		methods: {
			gomemberedit(id){
				uni.navigateTo({
					url:'/pages/member-edit/member-edit?id='+id
				})
			},
			// 初始化页面
			async initializePage() {
				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;
					}
					
					// 获取客户类型列表
					await this.loadCustomerTypes();
					
					await this.loadCustomerData(true);
				} catch (error) {
					console.error('页面初始化失败:', error);
					uni.showToast({
						title: '数据加载失败',
						icon: 'none'
					});
				}
			},
			
			// 获取客户类型列表
			async loadCustomerTypes() {
				try {
					console.log('正在获取客户类型列表...');
					const response = await this.API.getCustomerTypes();
					
					if (response.code === 200 && response.data) {
						// 构建tabList，包含"全部"选项和API返回的类型
						this.tabList = [
							{ label: '全部', value: '' },
							...response.data.map(item => ({
								label: item.Name,
								value: item.Value
							}))
						];
						console.log('客户类型列表加载成功:', this.tabList);
					} else {
						console.warn('获取客户类型失败，使用默认列表');
						// 使用默认的客户类型列表
						this.tabList = [
							{ label: '全部', value: '' },
							{ label: '线索', value: '0' },
							{ label: '新客', value: '1' },
							{ label: '散客', value: '2' },
							{ label: '会员', value: '3' }
						];
					}
				} catch (error) {
					console.error('获取客户类型失败:', error);
					// 出错时使用默认列表
					this.tabList = [
						{ label: '全部', value: '' },
						{ label: '线索', value: '线索' },
						{ label: '新客', value: '新客' },
						{ label: '散客', value: '散客' },
						{ label: '会员', value: '会员' }
					];
				}
			},
			
			// 搜索输入处理
			onSearchInput() {
				// 清除之前的定时器
				if (this.searchTimeout) {
					clearTimeout(this.searchTimeout);
				}
				
				// 设置防抖，500ms后执行搜索
				this.searchTimeout = setTimeout(() => {
					if (this.searchKeyword.trim()) {
						this.isSearching = true;
					} else {
						this.isSearching = false;
					}
					
					// 重置分页状态
					this.currentPage = 1;
					this.hasMoreData = true;
					this.loadCustomerData(true);
				}, 500);
			},
			// 跳转到服务日志页面
			goToServiceLog(item) {
				console.log('跳转到服务日志:', item)
				uni.navigateTo({
					url: `/pages/serviceDiary/serviceDiaryuser?userid=${item.id}&memberName=${encodeURIComponent(item.name || '未知会员')}`
				})
			},
			// 跨店开关变化
			onCrossStoreChange() {
				// 重置分页状态
				this.currentPage = 1;
				this.hasMoreData = true;
				// 重新加载数据
				this.loadCustomerData(true);
			},
			
			// Tab点击处理
			onTabClick(type) {
				this.currentFilterType = type;
				// 重置分页状态
				this.currentPage = 1;
				this.hasMoreData = true;
				// 重新加载数据
				this.loadCustomerData(true);
			},
			
			// 加载客户数据
			async loadCustomerData(isFirstLoad = false) {
				if (this.isLoading) return;
				
				try {
					this.isLoading = true;
					
					if (isFirstLoad) {
						this.isLoadingMore = false;
					} else {
						this.isLoadingMore = true;
					}
					
					const params = {
						currentPage: this.currentPage,
						pageSize: this.pageSize
					};
					
					// 添加搜索参数
					if (this.searchKeyword.trim()) {
						params.keyword = this.searchKeyword.trim();
					}
					
					// 添加筛选参数
					if (this.currentFilterType || this.currentFilterType === 0) {
						params.khlx = this.currentFilterType;
					}
					
					// 添加跨店参数
					if (!this.isCrossStore) {
						if(this.userInfo && this.userInfo.mdid) {
							params.gsmd = this.userInfo.mdid;
						} else{
							params.gsmd = '暂无';
						}
					}
					
					const result = await clueApi.getCustomerClues(params);
					
					if (result.code === 200 && result.data && result.data.list) {
						const clues = result.data.list.map(item => ({
							id: item.id,
							name: item.khmc || '未知客户',
							phone: item.sjh || '无电话',
							store: item.gsmd || '未知门店',
							date: this.formatDate(item.zcsj),
							subHealthUserName: item.subHealthUserName || '暂无',
							type: item.khlx || '未知客户类型',
							gsmdName: item.gsmdName || '未知门店',
							khlxName: item.khlxName || '未知客户类型',
							mainHealthUserName:item.mainHealthUserName || '暂无',
							expandUserName:item.expandUserName || '暂无',
							bz:item.bz || '暂无',
						}));
						
						if (isFirstLoad) {
							this.allClues = clues;
							this.clueList = [...clues];
						} else {
							this.allClues = [...this.allClues, ...clues];
							this.clueList = [...this.clueList, ...clues];
						}
						
						// 检查是否还有更多数据
						this.hasMoreData = clues.length === this.pageSize;
					} else {
						// 使用测试数据
						const clues = [];
						if (isFirstLoad) {
							this.allClues = clues;
							this.clueList = [...clues];
						} else {
							this.allClues = [...this.allClues, ...clues];
							this.clueList = [...this.clueList, ...clues];
						}
						this.hasMoreData = clues.length === this.pageSize;
					}
					
					this.currentPage++;
				} catch (error) {
					console.error('加载客户数据失败:', error);
					// 使用测试数据
					const clues = [];
					if (isFirstLoad) {
						this.allClues = clues;
						this.clueList = [...clues];
					} else {
						this.allClues = [...this.allClues, ...clues];
						this.clueList = [...this.clueList, ...clues];
					}
					this.hasMoreData = clues.length === this.pageSize;
				} finally {
					this.isLoading = false;
					this.isLoadingMore = false;
				}
			},
			
			// 加载更多数据
			async loadMoreData() {
				if (this.isLoading || !this.hasMoreData) return;
				await this.loadCustomerData(false);
			},
			
			
			// 格式化日期
			formatDate(date) {
				if (typeof date === 'string') {
					return date;
				}
				if (date instanceof Date) {
					return date.toLocaleDateString('zh-CN');
				}
				// 处理时间戳格式
				if (typeof date === 'number') {
					const dateObj = new Date(date);
					return dateObj.toLocaleDateString('zh-CN');
				}
				return '未知日期';
			},
			
			// 处理预约
			handleAppointment(clue) {
				uni.navigateTo({
					url: '/pages/appointment/appointment?name='+clue.name + '&type='+clue.type+'&id='+clue.id
				});
			},
			
			// 处理预约列表
			handleAppointmentList(clue) {
				uni.navigateTo({
					url: '/pages/user-appointment-list/user-appointment-list?userId='+clue.id + '&customerName='+clue.name
				});
			},
			
			// 处理邀约
			handleInvite(clue) {
				uni.navigateTo({
					url: '/pages/invite/invite?name=' +clue.name + '&phone='+clue.phone+'&id='+clue.id  
				});
			},
			
			// 处理邀约列表
			handleInviteList(clue) {
				uni.navigateTo({
					url: '/pages/user-invite-list/user-invite-list?userId='+ clue.id+'&customerName='+clue.name
				});
			},
			
			// 处理剩余权益
			handleRemainingRights(clue) {
				uni.navigateTo({
					url: '/pages/member-rights/member-rights?memberId=' + clue.id + '&memberName=' + clue.name
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.clue-list-container {
		min-height: 100vh;
		background: linear-gradient(135deg, #e8f5e9 0%, #b2dfdb 100%);
		padding: 20rpx;
	}
	
	.page-title {
		text-align: center;
		color: #388e3c;
		margin-bottom: 48rpx;
		letter-spacing: 4rpx;
		font-size: 24rpx;
		font-weight: 600;
	}
	
	.search-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.1);
		padding: 40rpx;
		margin-bottom: 40rpx;
	}
	

	
	.filter-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 40rpx 0 rgba(76, 175, 80, 0.12);
		border: 2rpx solid #e8f5e9;
		padding: 40rpx;
		margin-bottom: 40rpx;
	}
	
	.cross-store-toggle {
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-bottom: 32rpx;
		padding-bottom: 32rpx;
		border-bottom: 2rpx solid #e8f5e9;
	}
	
	.toggle-text {
		font-size: 28rpx;
		color: #388e3c;
		font-weight: 500;
	}
	
	.tab-filter {
		margin: 0;
		padding: 0;
		background: none;
		border: none;
		box-shadow: none;
	}
	
	.tab-list {
		display: flex;
		gap: 16rpx;
		overflow-x: auto;
		padding-bottom: 8rpx;
		/* 隐藏滚动条 */
		scrollbar-width: none; /* Firefox */
		-ms-overflow-style: none; /* IE and Edge */
	}
	
	.tab-list::-webkit-scrollbar {
		display: none; /* Chrome, Safari and Opera */
	}
	
	.tab-item {
		flex: 1;
		min-width: 120rpx;
		padding: 20rpx 24rpx;
		background: #f8fdf8;
		border: 2rpx solid #e8f5e9;
		border-radius: 16rpx;
		text-align: center;
		cursor: pointer;
		transition: all 0.2s ease;
		font-size: 28rpx;
		font-weight: 500;
		color: #388e3c;
		white-space: nowrap;
	}
	
	.tab-item:hover {
		background: #e8f5e9;
		transform: translateY(-2rpx);
	}
	
	.tab-item.active {
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		color: #fff;
		border-color: #43e97b;
		box-shadow: 0 4rpx 16rpx rgba(67, 233, 123, 0.3);
	}
	
	.clue-list {
		margin-bottom: 40rpx;
	}
	
	.clue-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 40rpx 0 rgba(76, 175, 80, 0.12);
		border: 2rpx solid #e8f5e9;
		padding: 40rpx;
		margin-bottom: 32rpx;
		transition: all 0.2s ease;
	}
	
	.clue-card:hover {
		transform: translateY(-4rpx);
		box-shadow: 0 12rpx 48rpx 0 rgba(76, 175, 80, 0.18);
	}
	
	.clue-row {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 24rpx;
		gap: 16rpx;
	}
	
	.clue-row:last-child {
		margin-bottom: 0;
	}
	
	.clue-item {
		flex: 1 1 calc(50% - 8rpx);
		min-width: 0;
		display: flex;
		align-items: center;
		gap: 12rpx;
		padding: 16rpx 24rpx;
		background: #f8fdf8;
		border-radius: 16rpx;
		border: 2rpx solid #e8f5e9;
	}
	
	.clue-label {
		color: #388e3c;
		font-weight: 600;
		font-size: 28rpx;
		white-space: nowrap;
		margin-right: 30rpx;
		text-align: center;
	}
	
	.clue-value {
		color: #2e7d32;
		font-size: 30rpx;
		font-weight: 500;
		word-break: break-all;
		flex: 1;
	}
	
	.button-group {
		display: flex;
		justify-content: space-between;
		margin-top: 32rpx;
		// gap: 16rpx;
		// flex-wrap: wrap;
		// justify-content: space-around;
	}
	
	.action-btn {
		// flex: 1;
		// height: 80rpx;
		font-size: 22rpx;
		border-radius: 24rpx;
		letter-spacing: 2rpx;
		padding-top: 20rpx;
		padding-bottom: 20rpx;
		margin-left: 0;
		margin-right: 0;
	}
	
	.invite-btn {
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		border: none;
		box-shadow: 0 8rpx 32rpx rgba(67, 233, 123, 0.3);
		color: #fff;
	}
	
	.view-invite-btn {
		background: linear-gradient(135deg, #2196f3 0%, #42a5f5 100%);
		border: none;
		box-shadow: 0 8rpx 32rpx rgba(33, 150, 243, 0.3);
		color: #fff;
	}
	
	.remaining-rights-btn {
		background: linear-gradient(135deg, #ff9800 0%, #ff6b35 100%);
		border: none;
		box-shadow: 0 8rpx 32rpx rgba(255, 152, 0, 0.3);
		color: #fff;
	}
	
	.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;
	}
	
	.loading-more {
		text-align: center;
		padding: 40rpx;
		color: #6a9c6a;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 16rpx;
	}
	
	.loading-more-text {
		font-size: 28rpx;
	}
	
	.no-more-data {
		text-align: center;
		padding: 40rpx;
		color: #6a9c6a;
		font-size: 28rpx;
		opacity: 0.8;
	}
	
	.empty-state {
		text-align: center;
		padding: 120rpx 40rpx;
		color: #6a9c6a;
	}
	
	.empty-state-icon {
		font-size: 120rpx;
		margin-bottom: 32rpx;
		opacity: 0.6;
	}
	
	.empty-state-text {
		font-size: 32rpx;
		margin-bottom: 16rpx;
	}
	
	.empty-state-subtext {
		font-size: 28rpx;
		opacity: 0.8;
	}
	
	/* 响应式设计 */
	// @media (max-width: 750rpx) {
	// 	.clue-item {
	// 		flex: 1 1 100%;
	// 	}
		
	// 	.clue-label {
	// 		min-width: 100rpx;
	// 		font-size: 26rpx;
	// 	}
		
	// 	.clue-value {
	// 		font-size: 28rpx;
	// 	}
	// }
</style>
