<template>
	<view class="page">
		<!-- #ifdef APP -->
		<statusBar></statusBar>
		<!-- #endif -->
		<uni-nav-bar
			:fixed="true"
			:statusBar="true"
			:border="false"
			title="接待中"
			leftIcon="left"
			@clickLeft="goBack"
			color="#333"
			backgroundColor="#FFFFFF"
		/>
		<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>
			<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"
			/>
			<service-list-furniture
				v-if="activeTab === 'status'"
				ref="serviceListRef"
				class="service-status-container"
				:style="{ top: computedContentTop || contentTop }"
				:show-record-state-indicator="false"
				empty-list-hint="暂无接待中记录"
				:show-reception-entry-shortcut="true"
			/>
			<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 {
	name: '接待中',
	// #ifdef APP
	components: {
		statusBar,
		CommonBeginReception,
		ServiceListFurniture,
		TagManagementPanel,
	},
	// #endif
	// #ifndef APP
	components: {
		CommonBeginReception,
		ServiceListFurniture,
		TagManagementPanel,
	},
	// #endif
	data() {
		return {
			activeTab: 'status',
			navbarTop: '88rpx',
			contentTop: '160rpx',
			receptionForm: {
				id: '',
				customerName: '',
				contact: '',
				customerSource: '',
				gender: '女',
				age: '',
				dealershipId: '',
				dealershipName: '',
				salesId: '',
				salesName: '',
				salesPhone: '',
				recordingCount: 0,
				intendedModel: '',
				infoCard: '',
				remark: '',
				detailedAddress: '',
				contactCount: 0,
			},
		};
	},
	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';
		},
	},
	onLoad() {
		this.updateNavbarPosition();
		this.loadCurrentUserInfo();
	},
	onShow() {
		this.$nextTick(() => {
			this.updateNavbarPosition();
			setTimeout(() => this.updateNavbarPosition(), 50);
			if (this.activeTab === 'status') {
				this.$nextTick(() => {
					const list = this.$refs.serviceListRef;
					if (list && typeof list.onServiceStatusRefresh === 'function') {
						list.onServiceStatusRefresh();
					}
				});
			} else if (this.activeTab === 'tag') {
				this.$nextTick(() => {
					const tagPanel = this.$refs.tagPanelRef;
					if (tagPanel && typeof tagPanel.refreshTagList === 'function') {
						tagPanel.refreshTagList();
					}
				});
			}
		});
	},
	methods: {
		updateNavbarPosition() {
			const systemInfo = uni.getSystemInfoSync();
			const statusBarHeight = systemInfo.statusBarHeight || 20;
			const navbarHeight = 44;
			const statusBarHeightRpx = statusBarHeight * 2;
			const navbarHeightRpx = navbarHeight * 2;
			const totalNavbarHeight = statusBarHeightRpx + navbarHeightRpx;
			this.$set(this, 'navbarTop', totalNavbarHeight + 'rpx');
			this.$set(this, 'contentTop', totalNavbarHeight + 72 + 'rpx');
			// #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;
				}
				if (loginResponse.userId) {
					this.receptionForm.salesId = String(loginResponse.userId);
				}
			} catch (e) {
				console.error('[ReceptionInProgress] 加载当前登录用户信息失败:', e);
			}
		},
		goBack() {
			const pages = getCurrentPages();
			if (pages.length <= 1) {
				uni.switchTab({
					url: '/pages/workbench/workbench',
					fail: (err) => {
						console.error('[ReceptionInProgress] 切回工作台失败:', err);
					},
				});
				return;
			}
			uni.navigateBack({
				fail: (err) => {
					console.error('[ReceptionInProgress] 返回失败:', err);
				},
			});
		},
		switchTab(tab) {
			if (tab !== 'reception' && tab !== 'status' && tab !== 'tag') {
				return;
			}
			this.activeTab = tab;
			if (tab === 'reception') {
				this.resetReceptionForm();
			} else if (tab === 'tag') {
				this.$nextTick(() => {
					this.$nextTick(() => {
						const p = this.$refs.tagPanelRef;
						if (p && typeof p.refreshTagList === 'function') {
							p.refreshTagList();
						}
					});
				});
			}
		},
		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') {
				this.activeTab = 'status';
				this.$nextTick(() => {
					const list = this.$refs.serviceListRef;
					if (list && typeof list.onServiceStatusRefresh === 'function') {
						list.onServiceStatusRefresh();
					}
				});
			}
		},
		onReceptionSaveError({ action, error }) {
			console.error('[ReceptionInProgress] 保存失败:', action, error);
		},
	},
};
</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;
	margin-top: 0;
	position: relative;
	/* #ifndef MP-WEIXIN */
	min-height: 100vh;
	/* #endif */
	/* #ifdef MP-WEIXIN */
	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;
	left: 0;
	right: 0;
	z-index: 999;
	height: 72rpx;
	box-sizing: border-box;
	align-items: center;
	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,
.reception-form-container {
	position: absolute;
	left: 0;
	right: 0;
	/* #ifdef MP-WEIXIN */
	display: flex;
	flex-direction: column;
	min-height: 0;
	bottom: 0 !important;
	/* #endif */
	/* #ifndef MP-WEIXIN */
	bottom: 96rpx;
	/* #endif */
}
</style>
