<template>
	<view class="content">
		<view class="navbox">
			<view class="status_bar"></view>
			<uni-nav-bar
				left-icon="left"
				:title="title"
				@clickLeft="goBack"
				color="#8B2316"
				:border="false"
				backgroundColor="#eee"
			>
				<template #right>
					<view class="nav-right" v-if="activeTab === 'message'">
						<uni-icons type="search" size="24" color="#8B2316" @click="searchPatients"></uni-icons>
						<uni-icons type="staff" size="24" color="#8B2316" @click="managePatients" style="margin-left: 30rpx;"></uni-icons>
					</view>
					<view class="nav-right" v-else-if="activeTab === 'list'">
						<uni-icons type="search" size="24" color="#8B2316" @click="searchPatients"></uni-icons>
						<uni-icons type="plusempty" size="24" color="#8B2316" @click="goCode" style="margin-left: 30rpx;" ></uni-icons>
					</view>
					<view class="nav-right" v-else-if="activeTab === 'plan'" @click="showAddMenu">
						<view class="save-btn">添加</view>
					</view>
				</template>
			</uni-nav-bar>
		</view>
		<!-- 顶部导航栏 -->
		<!-- <uni-nav-bar
			left-icon="left"
			:title="title"
			@clickLeft="goBack"
			fixed
			color="#8B2316"
			height="180rpx"
			:border="false"
			backgroundColor="#eee"
		>
			<template #right>
				<view class="nav-right" v-if="activeTab === 'message'">
					<uni-icons type="search" size="24" color="#8B2316" @click="searchPatients"></uni-icons>
					<uni-icons type="staff" size="24" color="#8B2316" @click="managePatients" style="margin-left: 30rpx;"></uni-icons>
				</view>
				<view class="nav-right" v-else-if="activeTab === 'list'">
					<uni-icons type="search" size="24" color="#8B2316" @click="searchPatients"></uni-icons>
					<uni-icons type="plusempty" size="24" color="#8B2316" @click="goCode" style="margin-left: 30rpx;" ></uni-icons>
				</view>
				<view class="nav-right" v-else-if="activeTab === 'plan'" @click="showAddMenu">
					<view class="save-btn">保存</view>
				</view>
				
			</template>
		</uni-nav-bar> -->
		
		<!-- 消息列表区域 -->
		<scroll-view 
			class="message-list" 
			v-if="activeTab === 'message'"
			scroll-y="true"
			refresher-enabled="true"
			:refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh"
		>
		 <!-- <ConversationList /> -->
			<!-- 消息项 -->
			<!-- <view class="message-item" v-for="(item, index) in messageList" :key="item.id || index" @click="openMessage(item)">
				<view class="message-avatar">
					<view class="avatar-placeholder" v-if="!item.avatar">
						<uni-icons type="person" size="32" color="#ffffff"></uni-icons>
					</view>
					<image v-else :src="item.avatar" class="patient-avatar" mode="aspectFill"></image>
				</view>
				<view class="message-content">
					<view class="message-header">
						<text class="patient-name">{{ item.patientName }}</text>
						<text class="message-time">{{ item.time }}</text>
					</view>
					<view class="message-preview">
						<text class="preview-text">{{ item.messagePreview }}</text>
					</view>
				</view>
			</view>
			
			<!-- 空状态提示 -->
			<!-- <view class="empty-state" v-if="messageList.length === 0 && !isRefreshing">
				<uni-icons type="chat" size="80" color="#cccccc"></uni-icons>
				<text class="empty-text">暂无患者消息</text>
				<text class="empty-subtext">下拉刷新获取最新申请</text>
				<view class="debug-actions">
					<button class="debug-btn" @click="getApplyList">测试API调用</button>
				</view>
			</view> -->
		</scroll-view>
		
		<!-- 患者列表区域 -->
		<view class="patient-list" v-show="activeTab === 'list'">
			
			<view class="listbox alertContent"  v-if="showAlert">
				<image :src="delImg" class="del-img" mode="widthFix" @click="hideAlert"></image>
				<image :src="alertImg" class="alert-img" mode="widthFix"></image>
			</view>
			<view class="listbox" v-show="patientList.length>0">
				<scroll-view
					class="groups-scroll"
					scroll-y="true"
					:scroll-into-view="scrollIntoViewId"
					:scroll-with-animation="true"
					v-show="loadFinish"
				>
					<view class="special-actions">
						<view class="action-item" @click="addNewPatient">
							<view class="action-icon new-patient">
								<up-image :src="newPatientImg" width="60rpx" height="60rpx"></up-image>
							</view>
							<text class="action-text">新的患者<text class="new-patient-count" v-if="applyList.length > 0">(待审核{{ applyList.length }}人)</text></text>
							<uni-icons type="right" size="20" color="#999"></uni-icons>
						</view>

						<view class="action-item" @click="managePatientGroups">
							<view class="action-icon group-icon">
								<view class="grid-icon">
									<view class="grid-item"></view>
									<view class="grid-item"></view>
									<view class="grid-item"></view>
									<view class="grid-item"></view>
								</view>
							</view>
							<text class="action-text">患者分组 <text class="new-patient-count" v-if="patientList.length > 0">(随访{{ patientList.length }}人)</text></text>
							<uni-icons type="right" size="20" color="#999"></uni-icons>
						</view>
					</view>

					<view
						class="group-section"
						v-for="group in patientGroups"
						:key="group.letter"
						:id="`anchor-${group.letter}`"
					>
						<view class="group-header">{{ group.letter }}</view>
						<view class="patient-item" v-for="item in group.items" :key="item.uuid || item.id" @longpress="onPatientItemLongPress(item)" @click="goPatientDetail(item.uuid)">
							<image class="patient-avatar" :src="getPatientAvatar(item)" mode="aspectFill" @error="handlePatientAvatarError(item)" @click.stop="goPatientDetail(item.uuid)"></image>

							<view class="patient-info">
								<text class="patient-name" >{{ item.nickname || item.realName }}</text>
								<view class="patient-badge" v-if="item.badge">
									<text class="badge-text">{{ item.badge }}</text>
								</view>
							</view>
							<view class="patient-status">
								<up-image :src="editImg" class="edit-img" width="40rpx" height="40rpx" @click.stop="editPatient(item.uuid)"></up-image>
								<text class="follow-date">随访于{{ item.joinDateYMD }}</text>
							</view>
						</view>
					</view>
				</scroll-view>

				<view class="letter-index" v-if="loadFinish && indexList.length > 0">
					<view
						class="letter-item"
						v-for="letter in indexList"
						:key="letter"
						:class="{ active: activeLetter === letter }"
						@click="onLetterTap(letter)"
					>{{ letter }}</view>
				</view>
			</view>
			<view class="listbox" v-show="patientList.length === 0">
				<view class="special-actions" >
				<view class="action-item" @click="addNewPatient">
					<view class="action-icon new-patient">
						<up-image :src="newPatientImg" width="60rpx" height="60rpx" ></up-image>
					</view>
					<text class="action-text">新的患者<text class="new-patient-count" v-if="applyList.length > 0">(待审核{{ applyList.length }}人)</text></text>
					<uni-icons type="right" size="20" color="#999"></uni-icons>
				</view>
				
				<view class="action-item" @click="managePatientGroups">
					<view class="action-icon group-icon">
						<view class="grid-icon">
							<view class="grid-item"></view>
							<view class="grid-item"></view>
							<view class="grid-item"></view>
							<view class="grid-item"></view>
						</view>
					</view>
					<text class="action-text">患者分组 <text class="new-patient-count" v-if="patientList.length > 0">(随访{{ patientList.length }}人)</text></text>
					<uni-icons type="right" size="20" color="#999"></uni-icons>
				</view>
			</view>
				<empty ></empty>
			</view>
		</view>
		<view class="plan" v-show="activeTab === 'plan'">
			<scroll-view 
				class="plan-scroll" 
				scroll-y="true"
				refresher-enabled="true"
				:refresher-triggered="followUpRefreshing"
				@refresherrefresh="onFollowUpRefresh"
				@scrolltolower="onFollowUpLoadMore"
				:lower-threshold="100"
			>
				<view class="plan-list" v-if="groupedFollowUpList.length > 0">
					<view class="plan-group" v-for="group in groupedFollowUpList" :key="group.yearMonth">
						<view class="group-header">{{ group.yearMonth }}</view>
						<view class="plan-card" v-for="item in group.items" :key="item.uuid" @click="goFollowDetail(item)">
							<view class="left-rail">
								<text class="day">{{ formatDay(item.datetime) }}</text>
							</view>
							<view class="linebox">
								<up-image  :src="lineImg" width="14rpx" height="180rpx" ></up-image>
							</view>
							<view class="right-content">
								<view class="leftcontent">
									<view class="note">{{ item.note }}</view>
									<view class="name">{{ item.patientname }}</view>
								</view>
								<uni-icons type="forward" size="20" color="#999"></uni-icons>
							</view>
						</view>
					</view>
					
					<!-- 加载更多状态 -->
					<view class="load-more" v-if="followUpLoading">
						<uni-icons type="spinner-cycle" size="20" color="#999"></uni-icons>
						<text class="load-text">加载中...</text>
					</view>
					
					<!-- 没有更多数据 -->
					<view class="no-more" v-if="!followUpHasMore && followUpList.length > 0">
						<text class="no-more-text">没有更多数据了</text>
					</view>
				</view>
				<empty v-else></empty>
			</scroll-view>
			
			<!-- 悬浮添加按钮 -->
			<!-- <view class="floating-add-btn" @click="showAddMenu">
				<uni-icons type="plus" size="24" color="#ffffff"></uni-icons>
				<text class="btn-text">添加</text>
			</view> -->
			
			<!-- 添加菜单弹窗 -->
			<view class="add-menu-popup" v-if="showAddMenuFlag" @click="hideAddMenu">
				<view class="menu-content" @click.stop>
					<!-- 添加日程 -->
					<view class="menu-item" @click="addSchedule">
							<up-image  :src="dayImg" width="34rpx" height="34rpx" ></up-image>
						<text class="menu-text">添加日程</text>
					</view>
					
					<!-- 分割线 -->
					<view class="menu-divider"></view>
					
					<!-- 添加随访计划 -->
					<view class="menu-item" @click="addFollowUpPlan">
						<up-image  :src="planImg" width="34rpx" height="34rpx" ></up-image>
						<text class="menu-text">添加随访计划</text>
					</view>
				</view>
			</view>
		</view
		<!-- 底部标签栏 -->
		<view class="tab-bar">
			<view class="tab-item" :class="{active: activeTab === 'message'}" @click="switchTab('message')">
				<text class="tab-text">患者消息</text>
			</view>
			<view class="tab-item" :class="{active: activeTab === 'list'}" @click="switchTab('list')">
				<text class="tab-text">患者列表</text>
				<view class="tab-dot" v-if="hasNewPatient"><uni-badge class="uni-badge-left-margin" :text="applyList.length" :offset="[-3, -3]" size="small" /></view>
			</view>
			<view class="tab-item" :class="{active: activeTab === 'plan'}" @click="switchTab('plan')">
				<text class="tab-text">随访计划</text>
			</view>
		</view>
	</view>
	<unidialog :visible="visible" :content="message" @close="visible=false" @confirm="deleteFollowUpFromList"></unidialog>
</template>


<script setup>
	import { ref, getCurrentInstance, computed, nextTick, shallowRef } from 'vue';
	import { onShow,onLoad,onBackPress,onHide} from "@dcloudio/uni-app";
	import dayImg from "@/static/visit_data11.png"
	import planImg from "@/static/visitplan.png"
	import api from '@/api/api.js';
	import navTo from '@/utils/navTo.js';
	import docUrl  from '@/utils/docUrl.js';
	import unidialog from '@/components/dialog/dialog.vue'
	import defaultImg from "@/static/default.png"
	import newPatientImg from "@/static/new_patient.png"
	import delImg from "@/static/iv_delete.png"
	import editImg from "@/static/edit_patitent.png"
	const patientList = ref([]);
	const visible = ref(false)
	const message = ref('')
	const selectedPatientUuid = ref('')
	const selectedPatientName = ref('')
	const patientDataLoaded = ref(false);
	const patientDataLoading = ref(false);
	const firstLetterCache = new Map();
	const showAlert = ref(false);
	const navHeight = ref(40);
	onBackPress(() => {
		plus.runtime.quit();
		return true;
	});
	onHide(() => {
		patientDataLoaded.value = false;
	});
	import alertImg from "@/static/patientgif.png"
	const getNavHeight = () => {
		const systemInfo = uni.getSystemInfoSync();
		console.log(2223);
		console.log(systemInfo);
		navHeight.value = systemInfo.statusBarHeight + 44;
		console.log(navHeight.value);
	}
	import pinyin from 'pinyin';
	import dayjs from 'dayjs'
	import lineImg from "@/static/item_visitplan_fg.png"
	const loadFinish = ref(false);
	//import ConversationList from './conversation-list/index.vue'
    const title = ref('患者消息');
    const goPatientDetail = (uuid) => {
		navTo({
			url: `/pages_app/patientDetail/patientDetail?uuid=${uuid}`
		})
	}
	const editPatient = (uuid) => {
		console.log(uuid)
		navTo({
			url: `/pages_app/patientSetting/patientSetting?uuid=${uuid}`
		})
	}
	const onPatientItemLongPress = (item) => {
		if (!item || !item.uuid) return
		selectedPatientUuid.value = item.uuid
		selectedPatientName.value = item.nickname || item.realName
		message.value = `确认解除[${selectedPatientName.value || '该患者'}]的随访关系？`
		visible.value = true
	}
	const deleteFollowUpFromList = async () => {
		if (!selectedPatientUuid.value) {
			visible.value = false
			return
		}
		const res = await api.cancelRes({
			patientUuid: selectedPatientUuid.value
		})
		if (res.code == 1) {
			uni.showToast({
				title: '解除成功',
				icon: 'none'
			})
			patientListByGBK()
		}
		visible.value = false
	}
	const avatarErrorMap = ref({});
	const getAvatarKey = (item = {}) => String(item.uuid || item.id || item.realName || item.nickname || '');
	const normalizeAvatarUrl = (photo) => {
		const raw = String(photo || '').trim();
		if (!raw) return defaultImg;
		if (/^https?:\/\//i.test(raw)) return raw;
		return `${docUrl}${raw}`;
	};
	const getPatientAvatar = (item = {}) => {
		const key = getAvatarKey(item);
		if (key && avatarErrorMap.value[key]) return defaultImg;
		return item.avatarUrl || defaultImg;
	};
	const handlePatientAvatarError = (item) => {
		if (!item) return;
		const key = getAvatarKey(item);
		if (!key) return;
		avatarErrorMap.value = {
			...avatarErrorMap.value,
			[key]: true
		};
	}
	const goCode = () => {
		navTo({
			url: `/pages_app/myCode/myCode`
		})
	}
	// 仅保留年月日
	const formatYMD = (input) => {
		if (!input) return '';
		const d = dayjs(input);
		return d.isValid() ? d.format('YYYY-MM-DD') : '';
	}
	
	const formatYearMonth = (input) => {
		if (!input) return '';
		const d = dayjs(input);
		return d.isValid() ? d.format('YYYY年MM月') : '';
	}
		// 格式化显示日（如：03）
	const formatDay = (input) => {
		if (!input) return '';
		const d = dayjs(input);
		return d.isValid() ? d.format('DD日') : '';
	}
	// 申请列表数据
	const messageList = ref([
		{
			id: 1,
			patientName: '测试',
			messagePreview: '[图片]',
			time: '2025-08-11',
			avatar: ''
		}
	]);
	
	// 当前激活的标签
	const activeTab = ref('message');
	const activeLetter = ref('A');
	const scrollIntoViewId = ref('');
	
	// 控制添加菜单弹窗显示
	const showAddMenuFlag = ref(false);
	
	// 组件实例（用于 selectorQuery 作用域）
	const { proxy } = getCurrentInstance();
	
	const LETTER_ORDER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
	const sortLetter = (a, b) => {
		if (a === '#') return 1;
		if (b === '#') return -1;
		const ai = LETTER_ORDER.indexOf(a);
		const bi = LETTER_ORDER.indexOf(b);
		if (ai === -1 && bi === -1) return String(a).localeCompare(String(b));
		if (ai === -1) return 1;
		if (bi === -1) return -1;
		return ai - bi;
	};
	// up-index-list 索引使用实际分组字母，避免索引与锚点数量不一致
	const indexList = ref([]);
	// 列表高度（像素）：窗口高度 - 顶部导航(rpx转px) - 底部tab(约100rpx->px) - 操作区(约200rpx->px)
	const groupsListHeight = ref(0);
	const rpxToPx = (rpx) => {
		const { screenWidth } = uni.getSystemInfoSync();
		return Math.round((screenWidth / 750) * rpx);
	};
	const computeListHeight = () => {
		const { windowHeight } = uni.getSystemInfoSync();
		const reserved = rpxToPx(240); // 140rpx(nav) + 100rpx(tab) 近似
		groupsListHeight.value = Math.max(0, windowHeight - reserved);
	};

	// 分组数据（可从接口返回后赋值）
	const patientGroups = shallowRef([]);

	// 根据当前分组重建索引（与 up-index-anchor 一一对应）
	const rebuildIndexList = () => {
		indexList.value = patientGroups.value
			.map(g => String(g?.letter || '').toUpperCase())
			.filter((letter, index, arr) => (letter === '#' || /^[A-Z]$/.test(letter)) && arr.indexOf(letter) === index)
			.sort(sortLetter);
		activeLetter.value = indexList.value[0] || '';
	};
	const onLetterTap = (letter) => {
		if (!letter) return;
		const targetId = `anchor-${letter}`;
		activeLetter.value = letter;
		// 点击同一字母时，先清空再回填，确保 scroll-into-view 能再次触发
		if (scrollIntoViewId.value === targetId) {
			scrollIntoViewId.value = '';
			nextTick(() => {
				scrollIntoViewId.value = targetId;
			});
			return;
		}
		scrollIntoViewId.value = targetId;
	};

	// 生成模拟数据
	// 工具：获取首字母
	const generateMockDate = () => '';
	const getFirstLetter = (name = '') => {
		const firstChar = String(name).trim().charAt(0);
		if (!firstChar) return '#';
		if (/^[A-Za-z]$/.test(firstChar)) return firstChar.toUpperCase();
		if (firstLetterCache.has(firstChar)) {
			return firstLetterCache.get(firstChar);
		}
		try {
			const pinyinArray = pinyin(firstChar, { style: pinyin.STYLE_NORMAL });
			const py = pinyinArray?.[0]?.[0] || '';
			const letter = py ? py.charAt(0).toUpperCase() : '#';
			firstLetterCache.set(firstChar, letter);
			return letter;
		} catch (error) {
			return '#';
		}
	}
	// 根据 patientList 构建按拼音首字母的分组
	const buildGroupsFromPatients = () => {
		avatarErrorMap.value = {};
		const map = new Map();
		
		const source = patientList.value || [];
		for (let i = 0; i < source.length; i++) {
			const p = source[i] || {};
			const normalized = {
				...p,
				avatarUrl: normalizeAvatarUrl(p.photo),
				joinDateYMD: formatYMD(p.join_date)
			};
			const first = getFirstLetter(normalized.nickname || normalized.realName);
			const letter = /^[A-Z]$/.test(first) ? first : '#';
			if (!map.has(letter)) map.set(letter, []);
			map.get(letter).push(normalized);
		}
		const letters = Array.from(map.keys()).sort(sortLetter);
		patientGroups.value = letters.map(l => ({ letter: l, items: map.get(l) }));
		rebuildIndexList();
		if(patientList.value.length==0){
			indexList.value=[]
		}
		nextTick(() => {
			setTimeout(() => {
				uni.hideLoading();
			},1000);
		});
	};
	// 申请列表数据
	const applyList = ref([]);
	const hasNewPatient = computed(() => applyList.value.length > 0);
	
	// 刷新状态
	const isRefreshing = ref(false);
	const getFollowUpList = async (isRefresh = false) => {
		if (followUpLoading.value) return;
		
		followUpLoading.value = true;
		
		try {
			const currentPage = isRefresh ? 1 : page.value;
			const res = await api.followUpList({
				page: currentPage,
				pageSize: followUpPageSize.value
			});
			
			if(res.code === 200) {
				const newData = res.data.list || [];
				
				if (isRefresh) {
					// 下拉刷新：替换数据
					followUpList.value = newData;
					page.value = 1;
				} else {
					// 上拉加载：追加数据
					followUpList.value = [...followUpList.value, ...newData];
				}
				
				// 判断是否还有更多数据
				followUpHasMore.value = newData.length >= followUpPageSize.value;
				
				if (!isRefresh) {
					page.value++;
				}
				
				console.log('随访计划数据:', followUpList.value);
			}
		} catch (error) {
			console.error('获取随访计划失败:', error);
			uni.showToast({
				title: '获取数据失败',
				icon: 'error',
				duration: 2000
			});
		} finally {
			followUpLoading.value = false;
			followUpRefreshing.value = false;
		}
	};
	const getApplyList = async () => {		// 申请列表
		
		try {
			
			let userInfo=uni.getStorageSync('userInfo')
			const res = await api.applyList();
			
			if (res && res.code === 200) {
				applyList.value = res.data;
			} else {
				uni.showToast({
					title: res.message || '获取申请列表失败',
					icon: 'error',
					duration: 2000
				});
			}
		} catch (error) {
			console.error('获取申请列表失败:', error);
			uni.showToast({
				title: '网络请求失败',
				icon: 'error',
				duration: 2000
			});
		}
	};
	const hideAlert = () => {
		showAlert.value = false;
		uni.setStorageSync('hasAlert', true);
	}
	const patientListByGBK = async () => {
		if (patientDataLoading.value) return;
		patientDataLoading.value = true;
		try {
			const res = await api.patientListByGBK();
			if(res.code == 1){
				loadFinish.value = true;
				patientList.value = res.data || [];
				buildGroupsFromPatients();
				patientDataLoaded.value = true;
				if(res.data.length > 1000){
					const hasAlert = uni.getStorageSync('hasAlert');
					if(!hasAlert){
						showAlert.value = true;
					}else{
						showAlert.value = false;
					}
					//showAlert.value = true;
				}
			} else {
				uni.hideLoading();
			}
		} finally {
			patientDataLoading.value = false;
		}
	};
    const page=ref(1)
	const followUpList = ref([]);
	
	// 随访计划相关状态
	const followUpLoading = ref(false);
	const followUpRefreshing = ref(false);
	const followUpHasMore = ref(true);
	const followUpPageSize = ref(10);
	
	// 按年月分组的随访计划数据
	const groupedFollowUpList = computed(() => {
		if (!followUpList.value || followUpList.value.length === 0) {
			return [];
		}
		
		const groups = new Map();
		
		followUpList.value.forEach(item => {
			const yearMonth = formatYearMonth(item.datetime);
			if (!groups.has(yearMonth)) {
				groups.set(yearMonth, []);
			}
			groups.get(yearMonth).push(item);
		});
		
		// 转换为数组格式，按时间正序排列
		return Array.from(groups.entries()).map(([yearMonth, items]) => ({
			yearMonth,
			items: items.sort((a, b) => new Date(a.datetime) - new Date(b.datetime))
		})).sort((a, b) => new Date(a.items[0].datetime) - new Date(b.items[0].datetime));
	});
	
	// 下拉刷新
	const onRefresh = async () => {
		isRefreshing.value = true;
		
		try {
			await getApplyList();
			uni.showToast({
				title: '刷新成功',
				icon: 'none',
				duration: 1500
			});
		} catch (error) {
			console.error('刷新失败:', error);
			uni.showToast({
				title: '刷新失败',
				icon: 'error',
				duration: 1500
			});
		} finally {
			isRefreshing.value = false;
		}
	};
	
	// 随访计划下拉刷新
	const onFollowUpRefresh = async () => {
		followUpRefreshing.value = true;
		await getFollowUpList(true);
		uni.showToast({
			title: '刷新成功',
			icon: 'none',
			duration: 1500
		});
	};
	
	// 随访计划上拉加载
	const onFollowUpLoadMore = async () => {
		if (!followUpHasMore.value || followUpLoading.value) return;
		await getFollowUpList(false);
	};
	
	// 搜索患者
	const searchPatients = () => {
		navTo({
			url: `/pages_app/searchPatient/searchPatient`
		})
	};
	
	// 管理患者
	const managePatients = () => {
		uni.showToast({
			title: '患者管理',
			icon: 'none'
		});
	};
	
	// 打开消息
	const openMessage = (item) => {
		uni.showToast({
			title: `打开患者 ${item?.patientName || '未知'} 的消息`,
			icon: 'none'
		});
		// 这里可以跳转到消息详情页面
		// uni.navigateTo({
		// 	url: `/pages_app/messageDetail/messageDetail?id=${item?.id}`
		// });
	};
	
		// 切换标签
	const switchTab = (tab) => {
		activeTab.value = tab;
		
		
		switch(tab) {
			case 'message':
				// 患者消息页面逻辑 - 刷新申请列表
				uni.sendNativeEvent('goPatientMsg', {
					msg: 'goPatientMsg'
				},ret => {
					console.log(ret);
				})
				// getApplyList();
				// title.value = '患者消息';
				break;
			case 'list':
				title.value = '患者列表';
				if (patientDataLoaded.value) {
					loadFinish.value = true;
					break;
				}
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				patientListByGBK();
				// 显示患者列表
				break;
			case 'plan':
			  title.value = '随访计划';
				// 随访计划页面 - 加载随访计划数据
				if (followUpList.value.length === 0) {
					getFollowUpList(true);
				}
				break;
		}
	};
	
	// 添加新患者
	const addNewPatient = () => {
		navTo({
			url: '/pages_app/myPatient/myPatient?from=patientMsg'
		})
	};
	
	// 管理患者分组
	const managePatientGroups = () => {
		navTo({
			url: '/pages_app/patientGroup/patientGroup?from=patientMsg'
		})
	};
	
	// 打开患者详情
	const openPatient = (patientName) => {
		uni.showToast({
			title: `打开患者: ${patientName}`,
			icon: 'none'
		});
	};
	
	// 添加随访计划
	const addFollowUpPlan = () => {
		showAddMenuFlag.value = false;
		uni.navigateTo({
			url: '/pages_app/visit/visit?from=patientMsg'
		});
	};
	const goBack = () => {
		plus.runtime.quit();
	}
	// 添加日程
	const addSchedule = () => {
		showAddMenuFlag.value = false;
		uni.navigateTo({
			url: '/pages_app/schedule/schedule'
		});
	};
	const fromType=ref('');
	// 显示添加菜单
	const showAddMenu = () => {
		showAddMenuFlag.value = true;
	};
	
	// 隐藏添加菜单
	const hideAddMenu = () => {
		showAddMenuFlag.value = false;
	};
	
	// 使用 up-index-list 后不再需要手动滚动联动逻辑
	
	// 页面显示时加载数据
	onLoad((options) => {
		getNavHeight();
		if(options.from == 'push'){
			fromType.value='push';
		}
		
		loadMessageList();
		computeListHeight();
		getApplyList();
		
		if(options.type=='list'){
			activeTab.value='list';
		   switchTab('list')
		}
		if(options.type=='plan'){
			activeTab.value='plan';
		   switchTab('plan')
		}
		
	});
	onShow(() => {
		followUpList.value = [];
		page.value = 1;
		followUpHasMore.value = true;
		followUpLoading.value = false;
		followUpRefreshing.value = false;
		getFollowUpList(true);
		console.log("onShow");
		console.log(activeTab.value);
		if(activeTab.value == 'list'){
			getApplyList();
			switchTab('list');
			
		}else if(activeTab.value == 'plan'){
			switchTab('plan')
		}
	});
	
	// 加载消息列表
	const loadMessageList = () => {
		// 这里可以调用API获取消息列表
	};

	const goFollowDetail = (raw) => {
		if(!raw) return;
		navTo({
			url: `/pages_app/followDetail/followDetail?followUpUuid=${encodeURIComponent(raw.uuid || '')}&patient_name=${raw.patientname}`
		});
	};
</script>

<style lang="scss" scoped>
.alertContent{
	z-index:99;
	position: fixed;
	bottom: 100rpx;
	width:100%;
	top:calc(var(--status-bar-height) + 44px);
	.alert-img{
		width:100%;
	}
	.del-img{
		position: absolute;
		top: 280rpx;
		z-index: 999;
		right: 100rpx;
		width: 48rpx;
		height: 48rpx;
	}
}
.save-btn {
  font-size: 32rpx;
  color: #8b2316;
  font-weight: 500;
}
	.content {
		background-color: #f5f5f5;
	    height: 100vh;
		overflow-y: hidden;
		
	}   
	.linebox{
		margin:0 20rpx;
	}
	// 导航栏右侧按钮样式
	.nav-right {
		display: flex;
		align-items: center;
	}
	
	// 消息列表样式
	.message-list {
		background-color: #ffffff;
		margin-top: 20rpx;
		
		.message-item {
			display: flex;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1rpx solid #f0f0f0;
			background-color: #ffffff;
			
			&:last-child {
				border-bottom: none;
			}
			
			.message-avatar {
				margin-right: 20rpx;
				
				.avatar-placeholder {
					width: 80rpx;
					height: 80rpx;
					background-color: #ff6b6b;
					border-radius: 10rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
			
			.message-content {
				flex: 1;
				
				.message-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 10rpx;
				}
				
				.patient-name {
					font-size: 32rpx;
					color: #333333;
					font-weight: 500;
				}
				
				.message-time {
					font-size: 24rpx;
					color: #999999;
				}
				
				.message-preview {
					margin-top: 5rpx;
					
					.preview-text {
						font-size: 28rpx;
						color: #666666;
					}
				}
			}
		}
		
		// 空状态样式
		.empty-state {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 100rpx 30rpx;
			
			.empty-text {
				margin-top: 20rpx;
				font-size: 28rpx;
				color: #999999;
			}
			
			.empty-subtext {
				font-size: 26rpx;
				color: #999999;
				margin-top: 16rpx;
			}
			
			.debug-actions {
				margin-top: 30rpx;
				
				.debug-btn {
					background-color: #8B2316;
					color: #ffffff;
					border: none;
					padding: 16rpx 32rpx;
					border-radius: 8rpx;
					font-size: 26rpx;
				}
			}
		}
	}
	
	// 底部标签栏样式
	.tab-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #f8f8f8;
		display: flex;
		align-items: center;
		border-top: 1rpx solid #e0e0e0;
		z-index: 999;
		
		.tab-item {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			position: relative;
			height: 100%;
			
			&:nth-child(2) {
				border: 2rpx solid #ccc;
				border-top: none;
				border-bottom: none;
			}
			
			.tab-text {
				font-size: 32rpx;
				color: #999999;
				transition: color 0.3s;
			}

			.tab-dot {
				position: absolute;
				top: 18rpx;
				right: 28rpx;
				
			}
			
			&.active {
				.tab-text {
					color: #8B2316;
					font-weight: 500;
				}
				
				.tab-line {
					position: absolute;
					bottom: 0;
					width: 60rpx;
					height: 4rpx;
					background-color: #8B2316;
					border-radius: 2rpx;
				}
			}
		}
	}
	
	// 患者列表样式
	.patient-list {
		// position: fixed;
	    width: 100%;
	  
		margin-top:calc(var(--status-bar-height) + 44px);
		height:calc(100vh - var(--status-bar-height) - 44px - 103rpx);
		overflow: hidden;
		
		background-color: #ffffff;
		
		bottom: 103rpx;
		
		.listbox{
			flex:1;
			height: 100%;
		}
		.groups-scroll {
			height: 100%;
		}
		
		.special-actions {
			background-color: #ffffff;
			border-bottom: 1rpx solid #f0f0f0;
			
			.action-item {
				display: flex;
				align-items: center;
				padding: 30rpx;
				border-bottom: 1rpx solid #f0f0f0;
				
				&:last-child {
					border-bottom: none;
				}
				
				.action-icon {
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 20rpx;
					position: relative;
					
					&.new-patient {
						background-color: #8B2316;
					}
					
					&.group-icon {
						background-color: #8B2316;
						
						.grid-icon {
							display: grid;
							grid-template-columns: 1fr 1fr;
							grid-template-rows: 1fr 1fr;
							gap: 2rpx;
							width: 32rpx;
							height: 32rpx;
							
							.grid-item {
								background-color: #ffffff;
								border-radius: 2rpx;
							}
						}
					}
				}
				
				.action-text {
					flex: 1;
					font-size: 32rpx;
					color: #333333;
					.new-patient-count {
						color: red;
						font-size: 32rpx;
						margin-left: 10rpx;
					}
				}
			}
		}
		
	
		.letter-index {
			position: fixed;
			right: 10rpx;
			top: 50%;
			transform: translateY(-50%);
			background-color: rgba(255, 255, 255, 0.9);
			border-radius: 20rpx;
			padding: 10rpx 5rpx;
			z-index: 999;
			
			.letter-item {
				padding: 8rpx 12rpx;
				font-size: 24rpx;
				color: #666666;
				text-align: center;
				border-radius: 10rpx;
				
				&.active {
					color: #8B2316;
					font-weight: 600;
				}
				&:active {
					background-color: #f0f0f0;
				}
			}
		}
	}

		.group-section {
			.group-header {
				padding: 20rpx 30rpx;
				background-color: #e4e4e4;
				font-size: 36rpx;
				color: #666666;
				
			}
			
			.patient-item {
				display: flex;
				align-items: center;
				padding: 30rpx 80rpx 20rpx 30rpx;
				border-bottom: 1rpx solid #f0f0f0;
				background-color: #ffffff;
				
				&:last-child {
					border-bottom: none;
				}
				
				.patient-avatar,
				.patient-avatar-placeholder {
					width: 90rpx;
					height: 90rpx;
					border-radius: 10rpx;
					margin-right: 20rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}
				
				.patient-avatar-placeholder {
					background-color: #ff6b6b;
				}
				
				.patient-info {
					flex: 1;
					
					.patient-name {
						font-size: 32rpx;
						color: #333333;
						font-weight: 500;
						margin-bottom: 8rpx;
					}
					
					.patient-badge {
						background-color: #d4a574;
						border-radius: 20rpx;
						padding: 4rpx 12rpx;
						display: inline-block;
						
						.badge-text {
							font-size: 20rpx;
							color: #ffffff;
							font-weight: 500;
						}
					}
				}
				
				.patient-status {
					display: flex;
					align-items: flex-end;
					flex-direction: column;
					
					.follow-date {
						margin-top: 8rpx;
						font-size: 24rpx;
						color: #666666;
						margin-left: 10rpx;
					}
				}
			}
		}

	.floating-add-btn {
		position: fixed;
		bottom: 140rpx; /* Adjust based on nav-bar height */
		right: 30rpx;
		background-color: #8B2316;
		border-radius: 50%;
		width: 100rpx;
		height: 100rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		z-index: 999;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

		.btn-text {
			font-size: 20rpx;
			color: #ffffff;
			margin-top: 4rpx;
		}
	}
	
	.add-menu-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}
	
	.menu-content {
		background-color: #ffffff;
		border-radius: 20rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
		width: 80%;
		max-width: 400rpx;
		overflow: hidden;
		position: fixed;
    top: calc(var(--status-bar-height) + 48px );
    z-index: 9999;
    right: 20rpx;
	}
	
	.menu-item {
		display: flex;
		align-items: center;
		padding: 30rpx 40rpx;
		border-bottom: 1rpx solid #f0f0f0;
		
		&:last-child {
			border-bottom: none;
		}
		
		.menu-text {
			font-size: 32rpx;
			color: #333333;
			margin-left: 20rpx;
		}
	}
	
	.menu-divider {
		height: 1rpx;
		background-color: #f0f0f0;
		margin: 0 40rpx;
	}
 
	/* 随访计划样式 */
	.plan{
		position: fixed;
		top:calc(var(--status-bar-height) + 44px);
		left: 0;
		right: 0;
		bottom:110rpx;
	}
	
	.plan-scroll {
		height: 100%;
	}
	
	.plan-list{ 
		padding-bottom: 20rpx;
	}
	
	.plan-group{ 
		background:#f5f5f5; 
	}
	
	.group-header{
		text-align: left;
		background:#eee; 
		color:#333; 
		font-size: 30rpx; 
		padding: 20rpx 30rpx; 
	}
	
	.plan-card{ 
		display:flex; 
		align-items:center; 
		background:#fff; 
		padding: 26rpx 30rpx; 
		border-bottom:1rpx solid #f0f0f0; 
	}
	
	.left-rail{ 
		display:flex; 
		align-items:center; 
		color:#8B2316; 
	}
	
	.left-rail .day{ 
		font-size: 36rpx; 
		margin-right: 12rpx; 
	}
	
	.left-rail .rail-dot{ 
		width: 4rpx; 
		height: 60rpx; 
		background:#8B2316; 
		border-radius: 2rpx; 
	}
	
	.right-content{ 
		flex:1; 
		display:flex; 
		align-items:center; 
		justify-content:space-between; 
	}
	
	.right-content .note{ 
		font-size: 30rpx; 
		color:#333; 
	}
	.right-content .name{ 
		margin-top: 30rpx;
		font-size: 28rpx; 
		color:#8B2316; 
	}
	/* 加载状态样式 */
	.load-more {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 30rpx;
		color: #999;
		
		.load-text {
			margin-left: 10rpx;
			font-size: 28rpx;
		}
	}
	
	.no-more {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 30rpx;
		
		.no-more-text {
			font-size: 28rpx;
			color: #999;
		}
	}
 
</style>