<template>
	<view class="production-calendar">
		<!-- <view class="page-top">
			<view class="header-content">
				<image @tap="backHandler" class="btnback" src="/static/chanjianTool/back.png"></image>
				<view class="page_title">
					<view class="info-l">
						<image :src="$baseUrl + 'common/default_avatar.png'"></image>
					</view>
					<view class="info-r">
						<view class="info-r-t">
							孕期
						</view>
						<view class="info-r-b">
							怀孕{{ info.gestationalWeeks }}周
						</view>
					</view>
				</view>
			</view>
		</view> -->
		 <customize-navigation>
			<template v-slot:navbar-content>
				<view class="page-top">
					<image @tap="backHandler" class="btnback" :src="`${$baseUrl}chanjianTool/1001/back.png`"></image>
					<view class="page_title">
						<view class="info-l">
							<image :src="babyInfo?.content?.babyAvatar || $baseUrl + 'common/default_avatar.png'"></image>
						</view>
						<view class="info-r">
							<view class="info-r-t">
								孕中
							</view>
							<view class="info-r-b">
								怀孕{{ info.gestationalWeeks }}周
							</view>
						</view>
					</view>
				</view>
			</template>
		</customize-navigation>
		<!-- 显示区域 -->
		<view class="production-calendar-con">
			<view class="calendar-box">
				<!-- 日期选择器和统计按钮 -->
				<view class="date-stats-row">
					<view class="date-selector">
						<!-- :end="todayDateString" -->
						<uni-datetime-picker ref="datePickerRef" v-model="currentSelectedDate" type="date"
							:start="earliestDateString"  @change="onDateChange" :clear-icon="false" :border="false">
							<view class="date-display">
								<text class="date-text">{{ formatCurrentDate() }}</text>
								<image :src="`${$baseUrl}chanjianTool/1001/icon27.png`" class="arrow-icon" />
							</view>
						</uni-datetime-picker>
					</view>
				</view>
				<!-- 日历组件 -->
				<view class="calendar-wrapper">
					<!-- 星期标题 -->
					<view class="weekday-row">
						<view class="weekday-cell" v-for="day in weekdays" :key="day">{{ day }}</view>
					</view>

					<!-- 日期网格 -->
					<view class="date-grid collapsed">
						<!-- 'disabled': date.isFuture -->
						<view v-for="(date, index) in calendarDates" :key="index" class="date-cell" :class="{
							'selected': date.isSelected,
							'today': date.isToday,
							'other-month': !date.isCurrentMonth,
							'future': date.isFuture,
							'past-with-record': date.isPast && hasRecordOnDate(date.dateString) && date.isCurrentMonth,
							'past-no-record': date.isPast && !hasRecordOnDate(date.dateString) && date.isCurrentMonth,
							'other-month-clickable': !date.isCurrentMonth && !date.isFuture,
							
						}" @click="selectDate(date)">
						
							<text class="date-text">
								{{ date.isToday ? '今' : date.day }}
							</text>
							<view v-if="hasRecordOnDate(date.dateString)" class="record-indicator"></view>
						</view>
					</view>
				</view>
			</view>
			<view class="con-list">
				<view v-if="todayRecords.length === 0" class="empty-state">
					<text class="empty-text">当日暂无记录</text>
				</view>
				<view class="con-list-item" v-for="(item, index) in todayRecords" :key="index"
					@click="onDetails(item)">
					<view class="item-time">
						<view class="">
							第{{ item.index }}次产检
						</view>
						<view class="">
							产检时间：{{ item.checkupDate }}
						</view>
					</view>
					<view class="item-line">

					</view>
					<view class="item-week">
						孕期{{ item.pregnancyWeek }}周
					</view>
					<view class="item-proect">
						重点：{{ getProject(item.examinationItems) }}
					</view>
				</view>
			</view>
		</view>
		<!-- 新增产检 -->
		<button class="form-btn" @click="onAdd">
			<image :src="`${$baseUrl}chanjianTool/1001/icon23.png`"></image>
			新增产检
		</button>
	</view>
</template>
<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import {
	onLoad,
	onShow
} from '@dcloudio/uni-app'
import { useUserStore } from "@/stores/user";
import {
	throttleTap,
	dateFormatter
} from '@/utils/index.js';

import {
	getInfo
} from '../../api/obstetric.js';

import md from '../../md';
// 获取用户信息
const userStore = useUserStore();
const babyInfo =ref(userStore?.babyInfo || {}) 
// 新增日历组件 start-------
const currentSelectedDate = ref('')
const currentDate = ref(new Date())
const datePickerRef = ref(null)
// 添加一个强制更新标志
const forceUpdate = ref(0)
// 添加当前显示月份的字符串表示，确保响应性
const currentMonthKey = ref('')
// 星期标题
const weekdays = ['日', '一', '二', '三', '四', '五', '六']

// 新增日历组件 end -------
// 监听currentDate变化
watch(currentDate, (newDate, oldDate) => {
	console.log('====== currentDate变化监听 ======')
	console.log('旧值:', oldDate)
	console.log('新值:', newDate)
	console.log('新月份:', newDate.getMonth() + 1)

	// 避免无限循环：只在月份真正改变时才调用handleMonthChange
	if (oldDate && (oldDate.getMonth() !== newDate.getMonth() || oldDate.getFullYear() !== newDate.getFullYear())) {
		console.log('月份发生变化，调用handleMonthChange')
		// 只更新月份键和强制更新，不再次修改currentDate
		const newMonthKey = `${newDate.getFullYear()}-${newDate.getMonth()}`
		currentMonthKey.value = newMonthKey
		forceUpdate.value++

		nextTick(() => {
			console.log('watch: nextTick后再次强制更新')
			forceUpdate.value++
		})
	}
}, { immediate: false })
// 用户信息
const info = ref({})

function formatDateString(date) {
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	return `${year}-${month}-${day}`
}

// 日期格式化
function formatCurrentDate() {
  if (!currentSelectedDate.value) return ''
  const date = new Date(currentSelectedDate.value)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}年 ${month}月 ${day}日`
}
// 标记是否有记录
function hasRecordOnDate(date) {
	return info.value.checkupList && info.value.checkupList.some(item => item.checkupDate == date);
}
function isSameDay(date1, date2) {
	return date1.getFullYear() === date2.getFullYear() &&
		date1.getMonth() === date2.getMonth() &&
		date1.getDate() === date2.getDate()
}

// 方法
function createDateObject(date) {
	const today = new Date()
	const currentMonth = currentDate.value.getMonth()
	const currentYear = currentDate.value.getFullYear()
	const dateString = formatDateString(date)

	// 创建只包含日期部分的Date对象进行比较
	const dateOnly = new Date(date.getFullYear(), date.getMonth(), date.getDate())
	// const todayOnly = new Date(today.getFullYear(), today.getMonth(), today.getDate())
	const todayOnly = new Date(today.getFullYear(), today.getMonth() + 1, 0); // 下个月的第1天
	// 修复：确保正确判断是否为当前月份
	const isCurrentMonth = date.getMonth() === currentMonth && date.getFullYear() === currentYear
	const isToday = isSameDay(date, today)
	const isFuture = dateOnly > todayOnly
	const isPast = dateOnly < todayOnly

	const dateObj = {
		date: new Date(date),
		day: date.getDate(),
		dateString,
		isToday,
		isCurrentMonth,
		isSelected: currentSelectedDate.value === dateString,
		isFuture,
		isPast
	}


	return dateObj
}
// 日期对应的产检数组
const todayRecords = computed(() => {
  if (!currentSelectedDate.value || !info.value.checkupList) return [];
  const records = info.value.checkupList.filter(item => item.checkupDate === currentSelectedDate.value);
  return records;
});

// 计算属性 - 最早可选日期（往前一年）
const earliestDateString = computed(() => {
	const today = new Date()
	const earliestDate = new Date(today.getFullYear() - 1, today.getMonth(), today.getDate())
	const dateStr = formatDateString(earliestDate)
	console.log('uni-datetime-picker最早可选日期:', dateStr)
	return dateStr
})


// 日期最晚可选日期
// const todayDateString = computed(() => {
//   const today = new Date();
//   // 获取下个月的第0天（即当前月的最后一天）
//   const nextMonthLastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
//   const dateStr = formatDateString(nextMonthLastDay);
//   console.log('uni-datetime-picker最大可选日期:', dateStr);
//   return dateStr;
// });

function selectDate(dateObj) {
	// 只禁止选择未来日期
	// if (dateObj.isFuture) {
	// 	console.log('不能选择未来日期:', dateObj.dateString)
	// 	return
	// }

	console.log('====== selectDate ======')
	console.log('点击日期:', dateObj.dateString, '当月:', dateObj.isCurrentMonth)
	console.log('当前设置月份:', currentDate.value.getFullYear() + '-' + (currentDate.value.getMonth() + 1))
	console.log('点击日期月份:', dateObj.date.getFullYear() + '-' + (dateObj.date.getMonth() + 1))

	// 选择日期
	currentSelectedDate.value = dateObj.dateString

	// 如果点击的是非当月日期，切换到该日期所在的月份
	if (!dateObj.isCurrentMonth) {
		console.log('切换到:', dateObj.date.getFullYear(), '年', dateObj.date.getMonth() + 1, '月')

		// 直接设置新的日期和月份键
		const newCurrentDate = new Date(dateObj.date.getFullYear(), dateObj.date.getMonth(), 1)
		const newMonthKey = `${dateObj.date.getFullYear()}-${dateObj.date.getMonth()}`

		console.log('设置新月份:', newMonthKey)

		// 同步更新所有相关状态
		currentDate.value = newCurrentDate
		currentMonthKey.value = newMonthKey
		forceUpdate.value++



		// 使用 nextTick 确保 DOM 更新后再强制更新一次
		nextTick(() => {
			console.log('selectDate: nextTick后再次强制更新')
			forceUpdate.value++

			// 再次使用 nextTick 确保所有更新完成
			nextTick(() => {
				console.log('selectDate: 第二次nextTick后强制更新')
				forceUpdate.value++
			})
		})
		console.log('月份切换完成')
	}
}
// 日期时间
function onDateChange(event) {
	if (event) {
		console.log('====== uni-datetime-picker变化 ======')
		console.log('选择的日期:', event)

		// 验证选择的日期不能是未来日期
		const selectedDate = new Date(event)
		const today = new Date()
		// const todayOnly = new Date(today.getFullYear(), today.getMonth(), today.getDate())
		const todayOnly = new Date(today.getFullYear(), today.getMonth()+1, 0)
		const selectedOnly = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate())

		// if (selectedOnly > todayOnly) {
		// 	console.warn('警告：尝试选择未来日期，已阻止')
		// 	uni.showToast({
		// 		title: '不能选择未来日期',
		// 		icon: 'none'
		// 	})
		// 	return
		// }

		currentSelectedDate.value = event
        console.log('currentSelectedDate', currentSelectedDate)
		// 计算新的月份（使用已声明的selectedDate变量）
		const newCurrentDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), 1)
		const newMonthKey = `${selectedDate.getFullYear()}-${selectedDate.getMonth()}`

		console.log('设置新月份:', newMonthKey)

		// 同步更新所有相关状态
		currentDate.value = newCurrentDate
		currentMonthKey.value = newMonthKey
		forceUpdate.value++

		// 使用 nextTick 确保 DOM 更新后再强制更新一次
		nextTick(() => {
		  console.log('onDateChange: nextTick后再次强制更新')
		  forceUpdate.value++

		  // 再次使用 nextTick 确保所有更新完成
		  nextTick(() => {
		    console.log('onDateChange: 第二次nextTick后强制更新')
		    forceUpdate.value++
		  })
		})

		console.log('uni-datetime-picker月份切换完成')
	}
}

// 获取日历数据
const calendarDates = computed(() => {
	// 依赖多个响应性值来确保更新
	const year = currentDate.value.getFullYear()
	const month = currentDate.value.getMonth()
	
	// 获取当月第一天
	const firstDay = new Date(year, month, 1)

	// 获取第一周的开始日期（周日为0）
	const startDate = new Date(firstDay)
	startDate.setDate(firstDay.getDate() - firstDay.getDay())

	const dates = []

	// 展开状态显示完整月份（6周）
	for (let i = 0; i < 42; i++) {
		const date = new Date(startDate)
		date.setDate(startDate.getDate() + i)
		dates.push(createDateObject(date))
	}


	return dates
})
// 返回
const backHandler = () => {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "产检日历页",
		buttonName: '返回'
	});
	uni.navigateBack()
}
// 跳转新增产检页面
const onAdd = () => {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "产检日历页",
		buttonName: '新增产检'
	});
	uni.navigateTo({
		url: `/pages/addPostnatal/addPostnatal?time=${currentSelectedDate.value}`
	})
}
// 拼接检查项目名称
const getProject = (projects) => {
	return projects.map(project => project.itemName).join('、');
}

// 跳转产检详情页面
const onDetails = (item) => {
	const { id, type } = item
	// 如果是新增的就不跳转
	if(type === '1') return
	uni.navigateTo({
		url: `/pages/productionDetails/productionDetails?id=${id}`
	})
}

// 获取信息接口
const getInfoFn = async () => {
	
	// 获取信息
	const {code,success, message, data } = await getInfo({babyId: babyInfo.value?.content?.id})
	console.log('日历页面获取信息', code, success, message, data)
	if (success) {
        // 保留 data 里面 checkupList 里面 status 等于 completed 的数据
       info.value = {
		...data,
		checkupList: data.checkupList.filter(item => item.status === 'completed')
		}
       console.log('日历获取数据:', info.value)

	} else {
		uni.showToast({
			title: message,
			icon: "none",
		});
	}
}
onLoad((option) => {
 	md.sensorLogTake({
		xcxPage: "小程序页面浏览事件",
		pageName: "产检日历页"
	});
})
onShow(() => {
  // 使用真实的今天日期
  const today = new Date()
  const todayString = formatDateString(today)
  currentSelectedDate.value = todayString
  currentDate.value = new Date(today.getFullYear(), today.getMonth(), 1) // 当前月份的第一天
  currentMonthKey.value = `${today.getFullYear()}-${today.getMonth()}` // 设置月份键
  console.log('初始化今日日期:', todayString, '当前月份:', currentDate.value, '月份键:', currentMonthKey.value)
  // 获取信息
  getInfoFn()
})
</script>
<style lang="less" scoped>
.production-calendar {
	width: 100%;
	height: 100vh;
	background-color: #fdf6eb;
	&-con {
		// position: absolute;
		// top: 176rpx;
		// left: 31rpx;
		width: 100%;
		box-sizing: border-box;

		.calendar-box {
			width: 100%;
			background-color: #fdf6eb;
			// height: 473rpx;
			padding: 31rpx 0 0 0;
			box-sizing: border-box;
		}

		.con-list {
			position: absolute;
			left: 0;
			top: 820rpx;
			height: calc(100vh - 820rpx);
			background: #fff;
			border-radius: 24rpx;
			padding: 30rpx;
			overflow-y: auto;
            width: 100%;
            box-sizing: border-box;
			padding-bottom: 100px;
			.con-list-item {
				width: 689rpx;
				// height: 221rpx;
				border-radius: 24rpx;
				background: #f7f8fa;
				padding: 40rpx 63rpx 40rpx 35rpx;
				box-sizing: border-box;
				margin-bottom: 25rpx;

				.item-time {
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: 24rpx;
					font-weight: bold;
					color: #1d1e25;
				}

				.item-line {
					width: 100%;
					height: 1rpx;
					background-color: #e6e6e8;
					margin: 20rpx 0;
				}

				.item-week {
					color: #b27c1e;
					font-size: 38rpx;
				}

				.item-proect {
					width: 100%;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					margin-top: 12rpx;
					color: #6f6d67;
					font-size: 23rpx;
				}
			}
		}
	}

	// 自定义头部
	.page-top {
		width: 100%;
		display: flex;
		align-items: center;
		background-color: #fdf6eb;
	}

	.header-content {
		display: flex;
		align-items: center;
	}

	.btnback {
		width: 16rpx;
		height: 29rpx;
	}

	.page_title {
		color: #1d1e25;
		margin-left: 70rpx;
		display: flex;
		align-items: center;

		.info-l {
			width: 87rpx;
			height: 88rpx;
			border-radius: 50%;
			overflow: hidden;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.info-r {
			display: flex;
			flex-direction: column;
			margin-left: 11rpx;

			.info-r-t {
				display: flex;
				align-items: center;
				font-size: 30rpx;
				font-weight: bold;

				image {
					width: 18rpx;
					height: 12rpx;
					margin-left: 10rpx;
				}
			}

			.info-r-b {
				margin-top: 10rpx;
				font-size: 24rpx;
			}
		}
	}

	// 保存
	.form-btn {
		width: 686rpx;
		height: 94rpx;
		border-radius: 46rpx;
		background-color: #d3a358;
		color: #ffffff;
		font-size: 38rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		position: fixed;
		bottom: 60rpx;
		left: 50%;
		transform: translateX(-50%);
		z-index: 2;

		image {
			width: 42rpx;
			height: 42rpx;
			margin-right: 12rpx;
		}
	}

	// 日期选择器和统计按钮行
	.date-stats-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: #fef6eb;
		padding: 24rpx 30rpx;

		.date-selector {
			cursor: pointer;

			.date-display {
				display: flex;
				align-items: center;
			}

			.date-text {
				font-size: 28rpx;
				font-weight: 500;
				color: #1d1e25;
				margin-right: 10rpx;
			}

			.arrow-icon {
				width: 20rpx;
				height: 12rpx;
				margin-top: 3rpx;
			}
		}

		.stats-section {
			display: flex;
			align-items: center;
			gap: 8rpx;

			.stats-icon {
				width: 28rpx;
				height: 33rpx;
			}

			.stats-btn {
				font-size: 28rpx;
				color: #1d1e25;
				line-height: 33rpx;
				vertical-align: bottom;
				font-weight: 500;
			}
		}
	}

	// 日历容器
	.calendar-wrapper {
		background: #fef6eb;
		position: relative;

		.weekday-row {
			display: flex;
			padding: 20rpx 30rpx 0;

			.weekday-cell {
				flex: 1;
				text-align: center;
				font-size: 22rpx;
				color: #b27c1e;
				height: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
        .collapsed {
			grid-template-rows: repeat(6, 1fr);
			max-height: 480rpx;
		}
		.date-grid {
			display: grid;
			grid-template-columns: repeat(7, 1fr);
			padding: 0 30rpx;
			transition: all 0.3s ease;

			

			.date-cell {
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;
				cursor: pointer;

				.date-text {
					font-size: 28rpx;
					color: #333; // 默认为当月日期的颜色
					font-weight: 400;
					transition: all 0.2s ease;
					min-width: 56rpx;
					height: 56rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				.record-indicator {
					position: absolute;
					bottom: 18rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 6rpx;
					height: 6rpx;
					background: #D4A574;
					border-radius: 50%;
				}

				// 当月日期默认样式（确保优先级）
				&:not(.other-month):not(.disabled) {
					.date-text {
						color: #333;
					}
				}

				// 1. 置灰且禁用：未来日期
				&.disabled {
					cursor: not-allowed;

					.date-text {
						color: #bab5af;
					}

					.record-indicator {
						background: #bab5af;
					}
				}

				// 非当月日期（可点击切换月份）
				&.other-month-clickable {
					cursor: pointer;

					.date-text {
						color: #bab5af;
						transition: all 0.2s ease;
					}

					.record-indicator {
						background: #bab5af;
					}

					&:hover {
						.date-text {
							color: #888;
							background: rgba(212, 165, 116, 0.1);
							border-radius: 50%;
						}
					}

					&:active {
						.date-text {
							transform: scale(0.95);
						}
					}
				}

				// 2. 高亮带黄点：当月已过日期且有喂养记录
				&.past-with-record:not(.selected) {
					.date-text {
						color: #333;
						font-weight: 500;
					}
				}

				// 3. 仅高亮无黄点：当月已过日期但无喂养记录
				&.past-no-record:not(.selected) {
					.date-text {
						color: #333;
						font-weight: 500;
					}
				}

				// 4. 日期带黄圈：选中状态
				&.selected {
					.date-text {
						background: #D4A574;
						color: #fff !important;
						border-radius: 50%;
						font-weight: 600;
					}

					.record-indicator {
						background: #fff;
					}
				}

				// 5. 当日显示【今】- 已在模板中处理
				&.today.selected {
					.date-text {
						color: #fff;
					}
				}

				&.today:not(.selected) {
					.date-text {
						background: #fff;
						border-radius: 50%;
						font-weight: 600;
					}
				}

				// 非当月未来日期样式（既是other-month又是future的情况）
				&.other-month.future {
					.date-text {
						color: #bab5af;
					}
				}

				// 未来日期样式
				&.future {
					.date-text {
						color: #bab5af;
					}
				}
			}
		}



		.expand-btn {
			display: flex;
			justify-content: center;
			align-items: center;
			cursor: pointer;
			background: white;
			margin-top: 0rpx;

			.expand-icon {
				width: 136rpx;
				height: 46rpx;
				transition: all 0.3s ease;
			}
		}
	}
}
.empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 400rpx;

    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }
// uni-datetime-picker样式覆盖（与naming页面保持一致）
::v-deep .uni-datetime-picker--btn {
  background-color: #D4A574 !important;
}

::v-deep .uni-calendar-item--checked {
  background-color: #D4A574 !important;
}

::v-deep .uni-datetime-picker-btn-text {
  color: #D4A574 !important;
}
::v-deep .uni-calendar--fixed{
  z-index: 100 !important;
}
::v-deep .uni-calendar__mask{
  z-index: 100 !important;
}
</style>