<template>
	<view class="content">
		<view class="navbox">
			<view class="status_bar"></view>
			<uni-nav-bar
				left-icon="left"
				title="随访计划"
				@clickLeft="goBack"
				color="#8B2316"
				:border="false"
				backgroundColor="#eee"
			>
				<template #right>
					<view class="nav-right" @click="showAddMenu">
						<view class="save-btn">添加</view>
					</view>
				</template>
			</uni-nav-bar>
		</view>

		<view class="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="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" @click="goMessageTab">
				<text class="tab-text">患者消息</text>
			</view>
			<view class="tab-item" @click="goListTab">
				<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 active">
				<text class="tab-text">随访计划</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { computed, ref } from 'vue';
import { onBackPress, onLoad, onShow } from '@dcloudio/uni-app';
import dayjs from 'dayjs';
import api from '@/api/api.js';
import navTo from '@/utils/navTo.js';
import dayImg from '@/static/visit_data11.png';
import planImg from '@/static/visitplan.png';
import lineImg from '@/static/item_visitplan_fg.png';

const applyList = ref([]);
const page = ref(1);
const followUpList = ref([]);
const followUpLoading = ref(false);
const followUpRefreshing = ref(false);
const followUpHasMore = ref(true);
const followUpPageSize = ref(10);
const showAddMenuFlag = ref(false);

const hasNewPatient = computed(() => applyList.value.length > 0);
const formatYearMonth = (input) => {
	if (!input) return '';
	const d = dayjs(input);
	return d.isValid() ? d.format('YYYY年MM月') : '';
};
const formatDay = (input) => {
	if (!input) return '';
	const d = dayjs(input);
	return d.isValid() ? d.format('DD日') : '';
};

const groupedFollowUpList = computed(() => {
	if (!followUpList.value.length) 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 getApplyList = async () => {
	try {
		const res = await api.applyList();
		if (res && res.code === 200) {
			applyList.value = res.data || [];
		}
	} catch (error) {}
};

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++;
		}
	} finally {
		followUpLoading.value = false;
		followUpRefreshing.value = false;
	}
};

const onFollowUpRefresh = async () => {
	followUpRefreshing.value = true;
	await getFollowUpList(true);
	uni.showToast({ title: '刷新成功', icon: 'none', duration: 1200 });
};
const onFollowUpLoadMore = async () => {
	if (!followUpHasMore.value || followUpLoading.value) return;
	await getFollowUpList(false);
};

const addFollowUpPlan = () => {
	showAddMenuFlag.value = false;
	navTo({ url: '/pages_app/visit/visit?from=patientMsg' });
};
const addSchedule = () => {
	showAddMenuFlag.value = false;
	navTo({ url: '/pages_app/schedule/schedule' });
};
const showAddMenu = () => {
	showAddMenuFlag.value = true;
};
const hideAddMenu = () => {
	showAddMenuFlag.value = false;
};
const goFollowDetail = (raw) => {
	if (!raw) return;
	navTo({
		url: `/pages_app/followDetail/followDetail?followUpUuid=${encodeURIComponent(raw.uuid || '')}&patient_name=${raw.patientname}`
	});
};

const goBack = () => {
	plus.runtime.quit();
};
const goMessageTab = () => {
	navTo({ url: '/pages_app/patientMsg/patientMsg' });
};
const goListTab = () => {
	navTo({ url: '/pages_app/patientMsg/patientList' });
};

onBackPress(() => {
	plus.runtime.quit();
	return true;
});
onLoad(() => {
	getApplyList();
	getFollowUpList(true);
});
onShow(() => {
	getApplyList();
});
</script>

<style lang="scss" scoped>
.content {
	background-color: #f5f5f5;
	height: 100vh;
	overflow-y: hidden;
}
.save-btn {
	font-size: 32rpx;
	color: #8b2316;
	font-weight: 500;
}
.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%;
}
.tab-item:nth-child(2) {
	border: 2rpx solid #ccc;
	border-top: none;
	border-bottom: none;
}
.tab-item .tab-text {
	font-size: 32rpx;
	color: #999;
}
.tab-item.active .tab-text {
	color: #8B2316;
	font-weight: 500;
}
.tab-dot {
	position: absolute;
	top: 18rpx;
	right: 28rpx;
}
.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;
}
.linebox {
	margin: 0 20rpx;
}
.left-rail .day {
	font-size: 36rpx;
	color: #8B2316;
}
.right-content {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.note {
	font-size: 30rpx;
	color: #333;
}
.name {
	margin-top: 30rpx;
	font-size: 28rpx;
	color: #8B2316;
}
.load-more,
.no-more {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 30rpx;
}
.load-text,
.no-more-text {
	font-size: 28rpx;
	color: #999;
}
.add-menu-popup {
	position: fixed;
	inset: 0;
	background-color: rgba(0, 0, 0, 0);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
}
.menu-content {
	background-color: #fff;
	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);
	right: 20rpx;
}
.menu-item {
	display: flex;
	align-items: center;
	padding: 30rpx 40rpx;
}
.menu-text {
	font-size: 32rpx;
	color: #333;
	margin-left: 20rpx;
}
.menu-divider {
	height: 1rpx;
	background-color: #f0f0f0;
	margin: 0 40rpx;
}
</style>
