<template>
	<view class="page">
		<!-- #ifdef APP -->
		<statusBar></statusBar>
		<!-- #endif -->
		
		<!-- 导航栏 -->
		<uni-nav-bar 
			:fixed="true" 
			:statusBar="true" 
			:border="false"
			title="AI销冠系统" 
			leftIcon="left" 
			@clickLeft="goBack"
			color="#333"
			backgroundColor="#FFFFFF">
		</uni-nav-bar>
		
		<view class="content">
			<!-- 标签页 -->
			<view class="tabs" :style="{ top: computedNavbarTop || navbarTop }">
				<view 
					class="tab-item" 
					:class="{ active: activeTab === 'reception' }"
					@click="switchTab('reception')">
					<text>开始接待</text>
				</view>
				<view 
					class="tab-item" 
					:class="{ active: activeTab === 'status' }"
					@click="switchTab('status')">
					<text>服务中</text>
				</view>
				<view 
					class="tab-item" 
					:class="{ active: activeTab === 'tag' }"
					@click="switchTab('tag')">
					<text>标签管理</text>
				</view>
			</view>
			
			<!-- 服务状态列表 -->
			<service-list-furniture
				v-if="activeTab === 'status'"
				ref="serviceListRef"
				class="service-status-container"
				:style="{ top: computedContentTop || contentTop }"
			></service-list-furniture>
			
			<!-- 开始接待表单 -->
			<common-begin-reception 
				v-if="activeTab === 'reception'"
				class="reception-form-container"
				:style="{ top: computedContentTop || contentTop }"
				:initial-data="receptionForm"
				@cancel="onReceptionCancel"
				@save-success="onReceptionSaveSuccess"
				@save-error="onReceptionSaveError"
			/>
			
			<tag-management-panel
				v-if="activeTab === 'tag'"
				ref="tagPanelRef"
				:content-top="computedContentTop || contentTop"
			/>
		</view>
	</view>
</template>

<script>
	// #ifdef APP
	import statusBar from "@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-status-bar";
	// #endif
import CommonBeginReception from "./common_begin_reception.vue";
import ServiceListFurniture from "./serviceListFurniture.vue";
import TagManagementPanel from "./tag_management_panel.vue";
	
	export default {
		props: {
			incomingTab: {
				type: String,
				default: ''
			}
		},
		// #ifdef APP
		components: {
			statusBar,
			CommonBeginReception,
			ServiceListFurniture,
			TagManagementPanel
		},
		// #endif
		// #ifndef APP
		components: {
			CommonBeginReception,
			ServiceListFurniture,
			TagManagementPanel
		},
		// #endif
		data() {
			return {
				activeTab: 'status',
				// 导航栏位置相关
				navbarTop: '88rpx', // 默认值，会在onLoad/onShow时动态计算
				contentTop: '160rpx', // 默认值，会在onLoad/onShow时动态计算
				receptionForm: {
					id: "",
					customerName: "",
					contact: "",
					customerSource: "",
					gender: "女",
					age: "",
					dealershipId: "",
					dealershipName: "",
					salesId: "",
					salesName: "",
					salesPhone: "",
					recordingCount: 0,
					intendedModel: "",
					infoCard: "",
					remark: "",
					detailedAddress: "",
					contactCount: 0
				}
			}
		},
		watch: {
			incomingTab: {
				immediate: true,
				handler(tab) {
					this.applyIncomingTab(tab);
				}
			}
		},
		computed: {
			// 计算导航栏和内容区域的位置（使用计算属性确保响应式）
			computedNavbarTop() {
				const systemInfo = uni.getSystemInfoSync();
				const statusBarHeight = systemInfo.statusBarHeight || 20;
				const navbarHeight = 44;
				const windowWidth = systemInfo.windowWidth || systemInfo.screenWidth || 375;
				const pxToRpx = 750 / windowWidth;
				const totalNavbarHeightRpx = (statusBarHeight + navbarHeight) * pxToRpx;
				return totalNavbarHeightRpx + 'rpx';
			},
			computedContentTop() {
				const systemInfo = uni.getSystemInfoSync();
				const statusBarHeight = systemInfo.statusBarHeight || 20;
				const navbarHeight = 44;
				const windowWidth = systemInfo.windowWidth || systemInfo.screenWidth || 375;
				const pxToRpx = 750 / windowWidth;
				const totalNavbarHeightRpx = (statusBarHeight + navbarHeight) * pxToRpx;
				return (totalNavbarHeightRpx + 72) + 'rpx'; // tab栏高度72rpx
			}
		},
		onLoad() {
			console.log('[FurnitureReception][onLoad] 页面加载');
			// 更新导航栏位置
			this.updateNavbarPosition();
			// 加载当前登录用户信息，填充销售姓名和电话
			this.loadCurrentUserInfo();
		},
		onShow() {
			console.log('[FurnitureReception][onShow] 页面显示');
			// 每次页面显示时都重新计算导航栏位置，确保通过导航菜单进入时也能正确显示
			// 使用 $nextTick 确保DOM更新后再设置样式
			this.$nextTick(() => {
				this.updateNavbarPosition();
				// 再次延迟更新，确保样式已应用
				setTimeout(() => {
					this.updateNavbarPosition();
					console.log('[FurnitureReception][onShow] 延迟更新后的位置:', {
						navbarTop: this.navbarTop,
						contentTop: this.contentTop,
						computedNavbarTop: this.computedNavbarTop,
						computedContentTop: this.computedContentTop
					});
				}, 50);
			});
		},
		onReady() {
			// 页面渲染完成后，检查tab栏是否显示
			console.log('[FurnitureReception][onReady] 页面渲染完成');
			console.log('[FurnitureReception][onReady] activeTab:', this.activeTab);
			console.log('[FurnitureReception][onReady] navbarTop:', this.navbarTop);
			console.log('[FurnitureReception][onReady] contentTop:', this.contentTop);
			console.log('[FurnitureReception][onReady] computedNavbarTop:', this.computedNavbarTop);
			console.log('[FurnitureReception][onReady] computedContentTop:', this.computedContentTop);
			
			// 再次更新导航栏位置，确保渲染后位置正确
			this.updateNavbarPosition();

			// 延迟初始化URL隐藏，避免干扰页面刷新加载
			this.initUrlHidingAfterPageLoad();
			
			const systemInfo = uni.getSystemInfoSync();
			console.log('[FurnitureReception][onReady] 系统信息:', {
				statusBarHeight: systemInfo.statusBarHeight,
				windowHeight: systemInfo.windowHeight,
				screenHeight: systemInfo.screenHeight
			});
			
			// 检查tab栏元素是否存在和可见
			// #ifdef MP-WEIXIN
			setTimeout(() => {
				const query = uni.createSelectorQuery().in(this);
				query.select('.tabs').boundingClientRect((data) => {
					console.log('[FurnitureReception][onReady] tab栏元素信息:', data);
					if (!data) {
						console.error('[FurnitureReception][onReady] tab栏元素未找到！');
					} else {
						console.log('[FurnitureReception][onReady] tab栏位置:', {
							top: data.top,
							left: data.left,
							width: data.width,
							height: data.height,
							expectedTop: this.navbarTop,
							computedNavbarTop: this.computedNavbarTop,
							isVisible: data.width > 0 && data.height > 0,
							isOnScreen: data.top >= 0 && data.top < systemInfo.windowHeight
						});
						
						// 如果tab栏不可见，强制更新位置
						if (data.width === 0 || data.height === 0 || data.top < 0) {
							console.warn('[FurnitureReception][onReady] tab栏不可见，强制更新位置');
							this.updateNavbarPosition();
							this.$forceUpdate();
						}
					}
				}).exec();
			}, 100);
			// #endif
		},
		methods: {
			/**
			 * 由宿主页 onShow / 分包就绪后调用。tab 页缓存时子列表的 mounted 不会重复执行，需在此主动拉取后端数据。
			 */
			refreshPageData() {
				this.$nextTick(() => {
					const list = this.$refs.serviceListRef;
					if (this.activeTab === 'status') {
						if (list && typeof list.onServiceStatusRefresh === 'function') {
							list.onServiceStatusRefresh();
						}
					} else if (this.activeTab === 'tag') {
						const tagPanel = this.$refs.tagPanelRef;
						if (tagPanel && typeof tagPanel.refreshTagList === 'function') {
							tagPanel.refreshTagList();
						}
					}
				});
			},
			scheduleTagPanelRefresh() {
				this.$nextTick(() => {
					this.$nextTick(() => {
						const p = this.$refs.tagPanelRef;
						if (p && typeof p.refreshTagList === 'function') {
							p.refreshTagList();
						}
					});
				});
			},
			applyIncomingTab(tab) {
				const allowed = ['status', 'reception', 'tag'];
				if (!allowed.includes(tab)) {
					return;
				}

				// 切tab并执行必要初始化（开始接待需要重置表单）
				if (this.activeTab !== tab) {
					this.activeTab = tab;
				}
				if (tab === 'reception') {
					this.resetReceptionForm();
				} else if (tab === 'tag') {
					this.scheduleTagPanelRefresh();
				} else if (tab === 'status') {
					// 从工作台进入「服务中」时补拉列表（mounted 可能早于布局或与 refresh 竞态）
					this.$nextTick(() => {
						this.refreshPageData();
					});
				}
			},
			// 计算并更新导航栏和内容区域的位置
			updateNavbarPosition() {
				console.log('[FurnitureReception][updateNavbarPosition] 开始更新导航栏位置');
				const systemInfo = uni.getSystemInfoSync();
				const statusBarHeight = systemInfo.statusBarHeight || 20; // 默认20px
				const navbarHeight = 44; // navbar高度44px
				// 转换为rpx：1px = 2rpx（在375px设计稿下）
				const statusBarHeightRpx = statusBarHeight * 2;
				const navbarHeightRpx = navbarHeight * 2;
				const totalNavbarHeight = statusBarHeightRpx + navbarHeightRpx;
				
				const navbarTop = totalNavbarHeight + 'rpx';
				const contentTop = (totalNavbarHeight + 72) + 'rpx'; // tab栏高度72rpx
				
				console.log('[FurnitureReception][updateNavbarPosition] 更新导航栏位置:', {
					statusBarHeight: statusBarHeight,
					navbarHeight: navbarHeight,
					totalNavbarHeight: totalNavbarHeight,
					navbarTop: navbarTop,
					contentTop: contentTop,
					currentNavbarTop: this.navbarTop,
					currentContentTop: this.contentTop
				});
				
				// 强制更新，确保响应式数据变化被检测到
				this.$set(this, 'navbarTop', navbarTop);
				this.$set(this, 'contentTop', contentTop);
				
				// 在微信小程序中，可能需要强制更新视图
				// #ifdef MP-WEIXIN
				this.$forceUpdate();
				// #endif
			},
			/**
			 * 加载当前登录用户信息，填充销售姓名和电话
			 */
			loadCurrentUserInfo() {
				try {
					// 从本地存储获取登录响应信息
					const loginResponse = uni.getStorageSync('backend-login-response') || {};
					
					// 填充销售姓名
					if (loginResponse.userName) {
						this.receptionForm.salesName = loginResponse.userName;
					}
					
					// 填充销售电话：如果电话为空，则使用姓名作为电话
					if (loginResponse.phone) {
						this.receptionForm.salesPhone = loginResponse.phone;
					} else if (loginResponse.userName) {
						// 如果电话为空，使用姓名作为电话
						this.receptionForm.salesPhone = loginResponse.userName;
					}
					
					// 如果有 userId，也可以填充到 salesId
					if (loginResponse.userId) {
						this.receptionForm.salesId = String(loginResponse.userId);
					}
				} catch (e) {
					console.error('加载当前登录用户信息失败:', e);
				}
			},
			goBack() {
				// 检查页面栈，如果当前是第一个页面，则不能返回
				const pages = getCurrentPages();
				if (pages.length <= 1) {
					// 作为 tabBar 页从其他入口跳转进来时，兜底切回工作台
					uni.switchTab({
						url: '/pages/workbench/workbench',
						fail: (err) => {
							console.error('[FurnitureReception][goBack] 切回工作台失败:', err);
						}
					});
					return;
				}
				uni.navigateBack({
					fail: (err) => {
						console.error('[FurnitureReception][goBack] 返回失败:', err);
						// 如果返回失败，可能是页面栈问题，忽略错误
					}
				});
			},
			switchTab(tab) {
				this.activeTab = tab;
				if (tab === 'reception') {
					this.resetReceptionForm();
				} else if (tab === 'tag') {
					this.scheduleTagPanelRefresh();
				}
			},
			resetReceptionForm() {
				// 重置表单数据
				this.receptionForm = {
					id: "",
					customerName: "",
					contact: "",
					customerSource: "",
					gender: "女",
					age: "",
					dealershipId: "",
					dealershipName: "",
					salesId: "",
					salesName: "",
					salesPhone: "",
					recordingCount: 0,
					intendedModel: "",
					infoCard: "",
					remark: "",
					detailedAddress: "",
					contactCount: 0
				};
				// 重新加载当前登录用户信息
				this.loadCurrentUserInfo();
			},
			onReceptionCancel() {
				// 组件内部已处理取消逻辑，这里只需要重置表单数据
				this.resetReceptionForm();
			},
			onReceptionSaveSuccess({ action, data }) {
				// 保存成功后，更新本地表单数据
				if (data) {
					this.receptionForm = {
						...this.receptionForm,
						...data
					};
				}
				// 重置表单
				this.resetReceptionForm();
				// 如果是开始接待操作，可以在这里处理后续逻辑
				if (action === 'start') {
					// 可以在这里添加开始接待后的逻辑，比如跳转到接待页面等
					console.log('开始接待成功', data);
				}
			},
			onReceptionSaveError({ action, error }) {
				// 保存失败时的处理
				console.error('保存失败:', error);
			},

			// 页面加载后的URL隐藏初始化：只在页面完全稳定后执行
			initUrlHidingAfterPageLoad() {
				// #ifdef H5
				console.log('[FurnitureReception][initUrlHidingAfterPageLoad] 开始页面加载后URL隐藏初始化');

				// 路径映射
				this.urlPathMap = {
					'pages-subpackage/furniture_customer/furniture_customer': '/customer',
					'pages/furniture_reception/furniture_reception': '/reception',
					'pages/ai_qa/ai_qa': '/ai-qa',
					'pages/ai_analysis/ai_analysis': '/ai-analysis',
					'pages/xixi/xixi': '/xixi',
					'pages/ucenter/ucenter': '/profile'
				};

				// 策略：只在用户明确进行页面导航时才隐藏URL
				// 避免在页面刷新或直接访问时执行，以防止空白页面

				// 监听tabBar切换事件（用户主动导航）
				this.setupTabNavigationHiding();

				// 监听浏览器前进后退（用户主动导航）
				this.setupBrowserNavigationHiding();

				console.log('[FurnitureReception][initUrlHidingAfterPageLoad] URL隐藏系统已准备，只在用户导航时激活');
				// #endif
			},

			// 为当前页面尝试URL隐藏
			attemptUrlHidingForCurrentPage() {
				// #ifdef H5
				try {
					const pages = getCurrentPages();
					if (pages.length === 0) {
						console.log('[FurnitureReception][attemptUrlHidingForCurrentPage] 页面栈为空，跳过');
						return;
					}

					const currentPage = pages[pages.length - 1];
					const currentPath = currentPage.route;

					if (!currentPath) {
						console.log('[FurnitureReception][attemptUrlHidingForCurrentPage] 页面路径为空，跳过');
						return;
					}

					// 只为当前页面的路径执行URL隐藏
					if (currentPath === 'pages/furniture_reception/furniture_reception' && this.urlPathMap[currentPath]) {
						const shortPath = this.urlPathMap[currentPath];
						const currentPathname = window.location.pathname;

						if (currentPathname !== shortPath) {
							console.log(`[FurnitureReception][attemptUrlHidingForCurrentPage] 执行URL隐藏: ${currentPathname} -> ${shortPath}`);

							// 使用try-catch包装history操作
							try {
								const newUrl = `${window.location.origin}${shortPath}`;
								window.history.replaceState(null, '', newUrl);
								console.log('[FurnitureReception][attemptUrlHidingForCurrentPage] URL隐藏成功');
							} catch (historyError) {
								console.warn('[FurnitureReception][attemptUrlHidingForCurrentPage] history操作失败:', historyError);
							}
						} else {
							console.log('[FurnitureReception][attemptUrlHidingForCurrentPage] URL已经是隐藏状态');
						}
					}
				} catch (error) {
					console.warn('[FurnitureReception][attemptUrlHidingForCurrentPage] URL隐藏尝试失败:', error);
				}
				// #endif
			},

			// 设置tab导航时的URL隐藏
			setupTabNavigationHiding() {
				// #ifdef H5
				console.log('[FurnitureReception][setupTabNavigationHiding] 设置tab导航监听');

				// 监听uni-app的页面显示事件（当通过tabBar切换到此页面时）
				if (typeof uni !== 'undefined' && uni.on) {
					uni.on('onShow', () => {
						console.log('[FurnitureReception][setupTabNavigationHiding] 页面显示事件触发，可能是tab切换');
						// 延迟检查，确保是tab切换而不是页面刷新
						setTimeout(() => {
							this.attemptUrlHidingForCurrentPage();
						}, 300);
					});
				}

				console.log('[FurnitureReception][setupTabNavigationHiding] tab导航监听已设置');
				// #endif
			},

			// 设置浏览器导航时的URL隐藏
			setupBrowserNavigationHiding() {
				// #ifdef H5
				console.log('[FurnitureReception][setupBrowserNavigationHiding] 设置浏览器导航监听');

				// 监听前进后退按钮
				window.addEventListener('popstate', () => {
					console.log('[FurnitureReception][setupBrowserNavigationHiding] 浏览器前进后退事件');
					setTimeout(() => {
						this.attemptUrlHidingForCurrentPage();
					}, 200);
				});

				console.log('[FurnitureReception][setupBrowserNavigationHiding] 浏览器导航监听已设置');
				// #endif
			},


		}
	}
</script>

<style>
	page {
		background-color: #F5F5F5;
	}
	
	.page {
		/* #ifndef MP-WEIXIN */
		min-height: 100vh;
		/* #endif */
		/* #ifdef MP-WEIXIN */
		/* 微信小程序：确保页面容器铺满整个视口 */
		height: 100vh !important;
		min-height: 100vh !important;
		/* #endif */
		background-color: #F5F5F5;
	}
	
	.content {
		padding-top: 0; /* 移除padding-top，因为tab页和scroll-view都使用绝对定位 */
		margin-top: 0;
		position: relative;
		/* #ifndef MP-WEIXIN */
		min-height: 100vh; /* 确保content有足够高度 */
		/* #endif */
		/* #ifdef MP-WEIXIN */
		/* 微信小程序：确保内容容器铺满整个视口，底部导航栏是 fixed 定位，不占用文档流 */
		height: 100vh !important;
		min-height: 100vh !important;
		max-height: 100vh !important;
		/* #endif */
	}
	
	/* 隐藏导航栏占位区域（红色区域） */
	::v-deep .uni-navbar__placeholder {
		display: none !important;
		height: 0 !important;
	}
	
	::v-deep .uni-navbar__placeholder-view {
		display: none !important;
		height: 0 !important;
	}
	
	/* 隐藏导航栏底部边框 */
	::v-deep .uni-navbar--border {
		border-bottom: none !important;
	}
	
	/* 标签页 - 使用固定定位，确保显示在导航栏下方 */
	.tabs {
		display: flex !important; /* 强制显示 */
		visibility: visible !important; /* 强制可见 */
		opacity: 1 !important; /* 强制不透明 */
		background-color: #FFFFFF;
		border-bottom: 1px solid #E0E0E0;
		padding: 0 16rpx;
		margin-top: 0;
		position: fixed; /* 改为fixed定位，确保始终可见 */
		/* 导航栏高度：statusBar + navbar，动态计算 */
		/* 使用内联样式动态设置top值 */
		left: 0;
		right: 0;
		z-index: 999; /* 提高z-index确保在最上层 */
		height: 72rpx; /* 明确设置标签页高度 */
		box-sizing: border-box;
		align-items: center;
		/* 确保tab栏始终可见 */
		will-change: top; /* 优化渲染性能 */
	}
	
	
	.tab-item {
		padding: 24rpx 32rpx;
		position: relative;
	}
	
	.tab-item text {
		font-size: 30rpx;
		color: #666;
	}
	
	.tab-item.active text {
		color: #333;
		font-weight: 500;
	}
	
	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 32rpx;
		right: 32rpx;
		height: 4rpx;
		background-color: #007AFF;
		border-radius: 2rpx;
	}
	
	/* 服务状态列表容器 */
	.service-status-container {
		/* 使用绝对定位，从tab页底部开始，到底部导航栏结束 */
		position: absolute;
		/* top值通过内联样式动态设置 */
		left: 0;
		right: 0;
		/* #ifdef MP-WEIXIN */
		/* 子组件内 scroll-view 需明确高度链；flex 可避免 MP 下 height:100% 失效导致空白 */
		display: flex;
		flex-direction: column;
		min-height: 0;
		/* #endif */
		/* #ifndef MP-WEIXIN */
		bottom: 96rpx; /* H5环境：底部导航栏高度 */
		/* #endif */
		/* #ifdef MP-WEIXIN */
		/* 微信小程序：底部导航栏是 fixed 定位，不占用文档流，容器可以延伸到视口底部 */
		bottom: 0 !important;
		/* #endif */
	}

</style>
