<template>
  <view class="feeding-record-page">
    <!-- 状态栏占位 -->
    <view class="status-bar-placeholder"></view>

    <!-- 头部导航 -->
    <view class="header">
      <view class="nav-left">
        <image :src="feedingRecordRes.icon_return" class="back-btn" @click="goBack" />
        <!-- <image :src="feedingRecordRes.icon_star" class="baby-icon-star" /> -->
        <image class="avatar-img" :src="currentBaby?.babyAvatar || feedingRecordRes.avatar" />
        <view class="baby-info" @click="showBabySwitch" v-if="babyList.length > 1">
          <text class="baby-name">{{ getCurrentBabyName() }}</text>
          <text class="baby-age">{{ getCurrentBabyAge() }}</text>
        </view>
        <view class="baby-info" v-else>
          <text class="baby-name">{{ getCurrentBabyName() }}</text>
          <text class="baby-age">{{ getCurrentBabyAge() }}</text>
        </view>
        <image :src="feedingRecordRes.icon_baby_change" class="baby-icon-change" v-if="babyList.length > 1" />
      </view>
    </view>

    <!-- 日期选择器和统计按钮 -->
    <view class="date-stats-row">
      <view class="date-selector" @click="showDatePicker">
        <uni-datetime-picker ref="datePickerRef" v-model="currentSelectedDate" type="date" :start="earliestDateString"
          :end="todayDateString" @change="onDateChange" :clear-icon="false" :border="false">
          <view class="date-display">
            <text class="date-text">{{ formatCurrentDate() }}</text>
            <image :src="feedingRecordRes.icon_arrow_yellow" class="arrow-icon" />
          </view>
        </uni-datetime-picker>
      </view>
      <view class="stats-section" @click="goToFeedingAnalysis">
        <image :src="feedingRecordRes.icon_analysis" class="stats-icon" />
        <text class="stats-btn"> 统计</text>
      </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" :class="{ 'collapsed': !isCalendarExpanded }">
        <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,
          'disabled': 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 class="expand-btn" @click="toggleCalendarExpand">
        <image :src="isCalendarExpanded ? feedingRecordRes.dropUp : feedingRecordRes.dropDown" class="expand-icon" />
      </view>
    </view>

    <!-- 喂养记录列表 -->
    <scroll-view class="records-container" scroll-y>
      <view v-if="isLoading" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>
      <view v-else-if="todayRecords.length === 0" class="empty-state">
        <text class="empty-text">当日暂无记录</text>
      </view>
      <view v-else class="record-list">
        <template v-for="(record, index) in todayRecords" :key="index">
          <view class="record-item">
            <view class="time-dot">
              <view class="dot" :style="{ backgroundColor: getRecordColor(record.type) }"></view>
              <text class="time">{{ record.time }}</text>
            </view>
            <view class="record-content" :style="{ backgroundColor: getRecordBgColor(record.type) }">
              <view class="record-header">
                <image :src="getRecordIcon(record.type)" :class="getRecordIconClass(record.type)" />
                <text class="record-type">{{ record.type }}</text>
                <text class="delete-btn" @click="deleteRecord(record.recordId)">删除</text>
                <text class="edit-btn" @click="editRecord(index)">修改</text>
              </view>
              <view class="record-details">
                <!-- 优先显示 foodDetails，如果存在则显示，否则显示原有字段 -->
                <view v-if="record.foodDetails" class="content-info">
                  <view class="content-text">{{ record.foodDetails }}</view>
                </view>

                <!-- 如果没有 foodDetails，则显示原有字段 -->
                <view v-else>
                  <!-- 母乳亲喂：显示左右时间，时间加粗 -->
                  <view v-if="record.type === '母乳亲喂' && (record.leftDuration || record.rightDuration)"
                    class="duration-info">
                    <view v-if="record.leftDuration" class="duration-text">
                      <text class="duration-label">左</text>
                      <text class="duration-time">{{ record.leftDuration }}</text>
                    </view>
                    <view v-if="record.rightDuration" class="duration-text">
                      <text class="duration-label">右</text>
                      <text class="duration-time">{{ record.rightDuration }}</text>
                    </view>
                  </view>

                  <!-- 母乳瓶喂：显示总乳量 -->
                  <view v-if="record.type === '母乳瓶喂' && record.amount" class="amount-info">
                    <view class="amount-text">
                      <text class="amount-label">总乳量</text>
                      <text class="amount-value">{{ record.amount }}</text>
                    </view>
                  </view>

                  <!-- 奶粉喂养：显示总奶量 -->
                  <view v-if="record.type === '奶粉喂养' && record.amount" class="amount-info">
                    <view class="amount-text">
                      <text class="amount-label">总奶量</text>
                      <text class="amount-value">{{ record.amount }}</text>
                    </view>
                  </view>

                  <!-- 辅食：显示内容，超出显示... -->
                  <view v-if="record.type === '辅食' && record.content" class="content-info">
                    <view class="content-text">{{ record.content }}</view>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <!-- 在两个记录之间添加连接线 -->
          <view v-if="index < todayRecords.length - 1" class="timeline-connector"></view>
        </template>
      </view>
    </scroll-view>

    <!-- 底部添加按钮 -->
    <view class="bottom-add-btn" @click="goToFeedingIndex">
      <image :src="feedingRecordRes.add_btn" class="add-btn-img" />
    </view>


    <!-- 编辑弹窗 -->
    <view class="popup-mask" v-if="showEditPopup" @click="closeEditPopup" @touchmove.prevent>
      <view class="popup-content" @click.stop @touchmove.stop>
        <view class="popup-title">确认修改内容</view>
        <view class="form-item">
          <text class="label">喂养时间</text>
          <picker mode="time" :value="editForm.time" @change="onEditTimeChange">
            <view class="picker">{{ editForm.time || '请选择时间' }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">喂养方式</text>
          <picker :range="feedingTypes" @change="onEditTypeChange">
            <view class="picker">{{ editForm.type || '请选择类型' }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">喂养详情</text>
          <view class="input-container">
            <input class="input" v-model="editForm.content" :placeholder="getEditFormPlaceholder()" maxlength="20" />
          </view>
        </view>
        <view class="popup-buttons">
          <image :src="feedingRecordRes.icon_change_btn_cancel" class="cancel-btn" @click="closeEditPopup" />
          <image :src="feedingRecordRes.icon_change_btn_confirm" class="confirm-btn" @click="saveEditRecord" />
        </view>
      </view>
    </view>
  </view>


  <!-- 删除二次确认弹窗 -->
  <view class="popup-mask" v-if="showDelPopup" @click="closeDelPopup" @touchmove.prevent>
    <view class="popup-content del-popup-content" @click.stop @touchmove.stop>
      <image :src="feedingRecordRes.delRecordBg" class="del-record-bg" />
      <view class="del-buttons-container">
        <image :src="feedingRecordRes.delRecordCancelBtn" class="del-record-cancel-btn" @click="closeDelPopup" />
        <image :src="feedingRecordRes.delRecordConfirmBtn" class="del-record-confirm-btn" @click="confirmDelRecord" />
      </view>
    </view>
  </view>

  <!-- 切换宝宝弹窗 -->
  <BabySwitchPopup v-model:visible="showBabySwitchPopup" :selected-index="currentBabyIndex" @change="onBabyChange"
    v-if="babyList.length > 1" />
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick, getCurrentInstance } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import BabySwitchPopup from '@/components/BabySwitchPopup.vue'
import { feedingRecordsByDate, feedingRecordsCalendarStatus, feedingRecords as feedingRecordsAPI, feedingRecordsDelete } from '@/api/feeding.js'
import { useUserStore } from '@/stores/user.js'
import md from '../../md'

// API 集成说明：
// 1. 使用 /c/feeding/records GET 方法查询指定日期的喂养记录列表
//    - 参数：babyId (宝宝ID), date (日期，格式：YYYY-MM-DD)
//    - 返回：该日期的所有喂养记录数组
// 2. 使用 /c/feeding/records/calendar-status GET 方法获取日历状态
//    - 参数：babyId (宝宝ID), month (月份，格式：YYYY-MM)
//    - 返回：该月份每天的记录状态数组 [{date: "2025-07-01", hasRecord: false}, ...]
// 3. 实现了缓存机制、错误重试、超时处理、数据验证等功能
// 4. 支持本地数据作为 fallback，确保页面正常显示
// 5. 添加了性能监控和调试开关
// 6. 支持宝宝切换时自动刷新数据
// 7. 支持页面显示时自动刷新数据

const { proxy } = getCurrentInstance();
const $baseUrl = proxy.$baseUrl;

const version = 'v1'
const DEBUG_API = false // 调试开关，控制是否输出详细的API调试信息


const feedingRecordRes = {
  dropDown: $baseUrl + `feedingRecord/${version}/dropDown.png`,
  dropUp: $baseUrl + `feedingRecord/${version}/dropUp.png`,
  icon_analysis: $baseUrl + `feedingRecord/${version}/icon_analysis.png`,
  icon_arrow_yellow: $baseUrl + `feedingRecord/${version}/icon_arrow_yellow.png`,
  icon_fushi: $baseUrl + `feedingRecord/${version}/icon_fushi.png`,
  icon_muru: $baseUrl + `feedingRecord/${version}/icon_muru.png`,
  icon_naifen: $baseUrl + `feedingRecord/${version}/icon_naifen.png`,
  icon_pingwei: $baseUrl + `feedingRecord/${version}/icon_pingwei.png`,
  icon_star: $baseUrl + `feedingRecord/${version}/icon_star.png`,
  icon_return: $baseUrl + `feedingRecord/${version}/icon_return.png`,
  icon_baby_change: $baseUrl + `feedingRecord/${version}/icon_baby_change.png`,
  add_btn: $baseUrl + `feedingRecord/${version}/addBtn.png`,
  icon_change_btn_confirm: $baseUrl + `feedingRecord/${version}/icon_change_btn_confirm.png`,
  icon_change_btn_cancel: $baseUrl + `feedingRecord/${version}/icon_change_btn_cancel.png`,
  avatar: $baseUrl + `feedingIndex/${version}/avatar.png`,

  delRecordBg: $baseUrl + `feedingRecord/${version}/delRecordBg.png`,
  delRecordCancelBtn: $baseUrl + `feedingRecord/${version}/delRecordCancelBtn.png`,
  delRecordConfirmBtn: $baseUrl + `feedingRecord/${version}/delRecordConfirmBtn.png`,


}


// 响应式数据
const currentSelectedDate = ref(formatDateString(new Date()))
const showPopup = ref(false)
const isCalendarExpanded = ref(false)
const currentDate = ref(new Date())
const datePickerRef = ref(null)
// 添加一个强制更新标志
const forceUpdate = ref(0)
// 添加当前显示月份的字符串表示，确保响应性
const currentMonthKey = ref('')

// 全局状态管理
const userStore = useUserStore()
const babyId = computed(() => userStore.babyInfo?.content?.id)

// 宝宝切换相关状态
const showBabySwitchPopup = ref(false)

// 新记录表单
const newRecord = ref({
  time: '',
  type: '',
  leftDuration: '',
  rightDuration: '',
  amount: '',
  content: ''
})

// 编辑表单
const editForm = ref({
  time: '',
  type: '',
  content: ''
})

// 编辑状态
const showEditPopup = ref(false)
const editingRecord = ref(null)

// 删除状态
const showDelPopup = ref(false)
const deletingRecordId = ref(null)

// 喂养类型选项
const feedingTypes = ['母乳亲喂', '母乳瓶喂', '奶粉喂养', '辅食']

// 星期标题
const weekdays = ['日', '一', '二', '三', '四', '五', '六']

// API 数据存储
const apiRecords = ref({}) // 存储从API获取的记录数据
const calendarStatus = ref({}) // 存储日历状态数据
const isLoading = ref(false) // 加载状态
const loadingRecords = ref(new Set()) // 正在加载的记录日期集合，避免重复请求
const loadingCalendar = ref(new Set()) // 正在加载的日历月份集合，避免重复请求
const recordsCache = ref(new Map()) // 记录数据缓存，避免重复请求
const calendarCache = ref(new Map()) // 日历状态缓存，避免重复请求

// 计算属性 - 获取宝宝信息（只显示已出生的宝宝）
const babyList = computed(() => {
  const allBabies = userStore.babyInfo?.allBabyBaseInfo || []
  // 只返回已出生的宝宝（babyStage === 2）
  return allBabies.filter(baby => baby.babyStage === 2)
})
const currentBabyIndex = computed(() => {
  if (!babyList.value || !currentBaby.value) return 0
  return babyList.value.findIndex(baby => baby.id === currentBaby.value.id)
})
const currentBaby = computed(() => userStore.babyInfo?.content)
const currentBabyId = computed(() => userStore.babyInfo?.content?.id)

// 检查是否有多个宝宝（已移除，直接使用 babyList.length > 1）

// 计算属性 - 当前选中日期的记录
const todayRecords = computed(() => {
  if (!currentSelectedDate.value) return []
  // 优先使用API数据，如果没有则使用本地数据
  return apiRecords.value[currentSelectedDate.value] || []
})

// 计算属性 - 今天的日期字符串（用于限制uni-datetime-picker）
const todayDateString = computed(() => {
  const today = new Date()
  const dateStr = formatDateString(today)
  console.log('uni-datetime-picker最大可选日期:', dateStr)
  return dateStr
})

// 计算属性 - 最早可选日期（往前一年）
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 calendarDates = computed(() => {
  // 依赖多个响应性值来确保更新
  const updateFlag = forceUpdate.value
  const monthKey = currentMonthKey.value
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth()
  const selectedDate = currentSelectedDate.value
  const expanded = isCalendarExpanded.value

  // console.log(`====== 重新计算日历数据 (${updateFlag}) ======`)
  // console.log(`计算属性触发 - 年月: ${year}-${month + 1}, 月份键: ${monthKey}`)
  // console.log(`当前选中日期: ${selectedDate}`)
  // console.log(`日历展开状态: ${expanded}`)
  // console.log(`当前月份设置: ${currentDate.value.getFullYear()}-${currentDate.value.getMonth() + 1}`)

  // 获取当月第一天
  const firstDay = new Date(year, month, 1)

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

  const dates = []

  // 如果是收起状态，只显示包含选中日期的那一周
  if (!expanded && selectedDate) {
    // console.warn("323333333333")
    const selectedDateObj = new Date(selectedDate)
    const selectedDayOfWeek = selectedDateObj.getDay()
    const weekStartDate = new Date(selectedDateObj)
    weekStartDate.setDate(selectedDateObj.getDate() - selectedDayOfWeek)

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

  return dates
})


function showDatePicker() {
  md.sensorLogTake({
    xcxClick: "小程序页面点击事件",
    pageName: "喂养记录页",
    buttonName: "日期下拉按钮",
  });
}


function goToFeedingIndex() {
  uni.navigateBack()
}

// 方法
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 isCurrentMonth = date.getMonth() === currentMonth && date.getFullYear() === currentYear
  const isToday = isSameDay(date, today)
  const isFuture = dateOnly > todayOnly
  const isPast = dateOnly < todayOnly

  // console.warn("555555555555", dateString, 'isCurrentMonth:', isCurrentMonth, 'isToday:', isToday, 'isFuture:', isFuture, 'isPast:', isPast)


  // 调试信息：检查月份判断逻辑
  // if (date.getMonth() === 6 && date.getFullYear() === 2025 && date.getDate() <= 5) {
  //   const status = isToday ? '今天' : isFuture ? '未来' : '过去'
  //   console.log(`7月${date.getDate()}日: ${status}, 当月=${isCurrentMonth}, 当前设置月份=${currentMonth + 1}, 日期月份=${date.getMonth() + 1}`)

  //   // 检查bug
  //   if (currentYear === 2025 && currentMonth === 6 && !isCurrentMonth) {
  //     console.error(`❌ BUG: 7月${date.getDate()}日被错误标记为非当月!`)
  //     console.error(`当前设置: ${currentYear}-${currentMonth + 1}, 日期: ${date.getFullYear()}-${date.getMonth() + 1}`)
  //   }
  // }

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

  // 调试：检查月份切换后的状态
  // if (date.getMonth() === 6 && date.getFullYear() === 2025 && date.getDate() <= 5) {
  //   console.log(`创建日期对象: 7月${date.getDate()}日, 当月=${dateObj.isCurrentMonth}, 选中=${dateObj.isSelected}`)
  // }

  return dateObj
}



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

  // 加载选中日期的记录
  loadRecordsByDate(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()}-${String(dateObj.date.getMonth() + 1).padStart(2, '0')}`

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

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

    // 切换月份时，如果日历是收起状态，自动展开以显示完整月份
    if (!isCalendarExpanded.value) {
      console.log('自动展开日历')
      isCalendarExpanded.value = true
    }

    // 加载新月份的日历状态
    const newMonth = formatMonthString(newCurrentDate)
    loadCalendarStatus(newMonth)

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

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

    console.log('月份切换完成')
  }
}

function toggleCalendarExpand() {
  md.sensorLogTake({
    xcxClick: "小程序页面点击事件",
    pageName: "喂养记录页",
    buttonName: "日历展开按钮",
  });
  isCalendarExpanded.value = !isCalendarExpanded.value
}

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 selectedOnly = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate())

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

    currentSelectedDate.value = event

    // 加载选中日期的记录
    loadRecordsByDate(event)

    // 计算新的月份（使用已声明的selectedDate变量）
    const newCurrentDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), 1)
    const newMonthKey = `${selectedDate.getFullYear()}-${String(selectedDate.getMonth() + 1).padStart(2, '0')}`

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

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

    // 加载新月份的日历状态
    const newMonth = formatMonthString(newCurrentDate)
    loadCalendarStatus(newMonth)

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

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

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



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) {
  // 优先使用API返回的日历状态数据
  if (calendarStatus.value[date] !== undefined) {
    return calendarStatus.value[date]
  }
  // 如果没有API数据，则使用本地数据判断
  return apiRecords.value[date] && apiRecords.value[date].length > 0
}

function getRecordIcon(type) {
  const icons = {
    '母乳亲喂': feedingRecordRes.icon_muru,
    '母乳瓶喂': feedingRecordRes.icon_pingwei,
    '奶粉喂养': feedingRecordRes.icon_naifen,
    '辅食': feedingRecordRes.icon_fushi,
  }
  return icons[type]
}

function getRecordIconClass(type) {
  const classes = {
    '母乳亲喂': 'record-icon-img-muruqinwei',
    '母乳瓶喂': 'record-icon-img-pingwei',
    '奶粉喂养': 'record-icon-img-naifen',
    '辅食': 'record-icon-img-fushi',
  }
  return classes[type]
}
function getRecordColor(type) {
  // 统一使用 #d3a358 颜色
  return '#d3a358'
}

function getRecordBgColor(type) {
  const colors = {
    '母乳亲喂': '#fdeded',
    '母乳瓶喂': '#f1edf4',
    '奶粉喂养': '#fff6e5',
    '辅食': '#ecf6f0',
  }
  return colors[type] || '#FEF2F2'
}

async function deleteRecord(recordId) {
  md.sensorLogTake({
    xcxClick: "小程序页面点击事件",
    pageName: "喂养记录页",
    buttonName: "删除",
  });
  console.log('删除记录:', recordId)
  // 设置要删除的记录ID并显示确认弹窗
  deletingRecordId.value = recordId
  showDelPopup.value = true
}

function editRecord(index) {
  md.sensorLogTake({
    xcxClick: "小程序页面点击事件",
    pageName: "喂养记录页",
    buttonName: "修改",
  });
  const record = todayRecords.value[index]
  if (!record) return

  console.log('编辑记录数据:', record)
  console.log('record.foodDetails:', record.foodDetails)
  console.log('record.content:', record.content)

  // 根据记录类型设置不同的字段
  let content = ''
  if (record.type === '母乳亲喂') {
    // 母乳亲喂：优先显示 foodDetails，如果没有则从左右时间构建
    if (record.foodDetails) {
      content = record.foodDetails
    } else {
      const leftTime = record.leftDuration || ''
      const rightTime = record.rightDuration || ''
      // 如果存在时间，需要加上"左"或"右"
      let timeContent = ''
      if (leftTime) {
        timeContent += `左${leftTime}`
      }
      if (rightTime) {
        if (timeContent) timeContent += ' '
        timeContent += `右${rightTime}`
      }
      content = timeContent
    }
  } else if (record.type === '母乳瓶喂') {
    // 母乳瓶喂：优先显示 foodDetails，如果没有则显示 amount
    if (record.foodDetails) {
      content = record.foodDetails
    } else {
      const amount = record.amount || ''
      content = amount ? `总乳量${amount}` : ''
    }
  } else if (record.type === '奶粉喂养') {
    // 奶粉喂养：优先显示 foodDetails，如果没有则显示 amount
    if (record.foodDetails) {
      content = record.foodDetails
    } else {
      const amount = record.amount || ''
      content = amount ? `总奶量${amount}` : ''
    }
  } else if (record.type === '辅食') {
    // 辅食：显示食物详情，如果超过20字则截断
    content = record.foodDetails || record.content || ''
    if (content && content.length > 20) {
      content = content.substring(0, 20)
    }
  }

  editForm.value = {
    time: record.time || getCurrentTime(), // 使用记录的原始时间，如果没有则使用当前时间
    type: record.type || '',
    content: content
  }

  console.log('设置后的editForm:', editForm.value)

  editingRecord.value = { index, record }
  showEditPopup.value = true
  md.sensorPopLogTake({
    xcxPopExposure: "true",
    toolName: "喂养记录",
    popName: "日历页确认修改内容弹窗"
  });

}

function closeEditPopup(type) {
  if (type !== 'nonePop') {
    md.sensorPopLogTake({
      xcxPopClick: "true",
      toolName: "喂养记录",
      popName: "日历页确认修改内容弹窗",
      buttonName: "取消"
  });
  }
   
  showEditPopup.value = false
  editingRecord.value = null
  editForm.value = { time: '', type: '', content: '' }
}

// 关闭删除确认弹窗
function closeDelPopup() {
  showDelPopup.value = false
  deletingRecordId.value = null
}

// 确认删除记录
async function confirmDelRecord() {
  if (!deletingRecordId.value) {
    uni.showToast({
      title: '删除记录ID不存在',
      icon: 'none'
    })
    return
  }

  try {
    uni.showLoading({
      title: '删除中...'
    })

    // 调用删除接口
    const res = await feedingRecordsDelete({ recordId: deletingRecordId.value })

    if (res && res.code === '000000') {
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      })

      // 关闭弹窗
      closeDelPopup()

      // 清空缓存，确保获取最新数据
      clearCache()

      // 重新加载当前日期的记录
      if (currentSelectedDate.value) {
        await loadRecordsByDate(currentSelectedDate.value)
      }

      // 重新加载当前月份的日历状态
      if (currentMonthKey.value) {
        const currentMonth = formatMonthString(currentDate.value)
        await loadCalendarStatus(currentMonth)
      }
    } else {
      throw new Error(res?.message || '删除失败')
    }
  } catch (error) {
    console.error('删除记录失败:', error)
    uni.showToast({
      title: error.message || '删除失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

function onEditTimeChange(event) {
  editForm.value.time = event.detail.value
}

function onEditTypeChange(event) {
  editForm.value.type = feedingTypes[event.detail.value]
}

async function saveEditRecord() {
  md.sensorPopLogTake({
    xcxPopClick: "true",
    toolName: "喂养记录",
    popName: "日历页确认修改内容弹窗",
    buttonName: "保存修改"
  });
  if (!editForm.value.time || !editForm.value.type) {
    uni.showToast({ title: '请填写完整信息', icon: 'none' })
    return
  }

  // 处理辅食内容截断
  let content = editForm.value.content || ''
  if (editForm.value.type === '辅食' && content.length > 20) {
    content = content.substring(0, 20)
    editForm.value.content = content
  } else if (content && content.length > 20) {
    uni.showToast({ title: '喂养详情最多20字', icon: 'none' })
    return
  }

  if (!editingRecord.value) {
    uni.showToast({ title: '编辑记录不存在', icon: 'none' })
    return
  }

  try {
    uni.showLoading({
      title: '保存中...'
    })

    const { index, record } = editingRecord.value

    // 根据记录类型处理不同的数据
    let apiData = {
      recordId: record.recordId,
      babyId: babyId.value,
      recordTime: formatDateTimeString(currentSelectedDate.value, editForm.value.time),
      feedingType: getFeedingTypeId(editForm.value.type)
    }

    // 所有类型都使用 foodDetails 字段保存
    apiData.foodDetails = editForm.value.content || ''

    // 根据记录类型设置其他字段
    if (editForm.value.type === '母乳亲喂') {
      // 母乳亲喂：解析时间（格式：时间1 时间2）
      const content = editForm.value.content || ''
      const timeParts = content.trim().split(/\s+/)

      if (timeParts.length >= 1 && timeParts[0]) {
        apiData.durationLeftSeconds = parseTimeToSeconds(timeParts[0])
      }
      if (timeParts.length >= 2 && timeParts[1]) {
        apiData.durationRightSeconds = parseTimeToSeconds(timeParts[1])
      }
    } else if (editForm.value.type === '母乳瓶喂' || editForm.value.type === '奶粉喂养') {
      // 母乳瓶喂和奶粉喂养：解析奶量
      const content = editForm.value.content || ''
      const volumeMatch = content.match(/(\d+)ml/)
      if (volumeMatch) {
        apiData.volume = parseInt(volumeMatch[1])
      }
    }

    const response = await feedingRecordsAPI(apiData)
    uni.hideLoading()

    if (response && response.code === '000000') {
      uni.showToast({
        title: '保存成功',
        icon: 'none'
      })

      closeEditPopup('nonePop')

      // 清空缓存，确保获取最新数据
      clearCache()

      // 重新加载当前日期的记录
      if (currentSelectedDate.value) {
        await loadRecordsByDate(currentSelectedDate.value)
      }

      // 重新加载当前月份的日历状态
      const currentMonth = formatMonthString(currentDate.value)
      await loadCalendarStatus(currentMonth)
    } else {
      throw new Error(response?.message || '保存失败')
    }
  } catch (error) {
    console.error('保存记录失败:', error)
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

function goToFeedingAnalysis() {
  md.sensorLogTake({
    xcxClick: "小程序页面点击事件",
    pageName: "喂养记录页",
    buttonName: "统计",
  });
  uni.redirectTo({
    url: '/pages/feedingAnalysis/feedingAnalysis'
  })
}

// 返回上一页
function goBack() {

  md.sensorLogTake({
    xcxClick: "小程序页面点击事件",
    pageName: "喂养记录页",
    buttonName: "返回",
  });
  uni.navigateBack()
}

// 宝宝切换相关方法
function showBabySwitch() {
  md.sensorLogTake({
    xcxClick: "小程序页面点击事件",
    pageName: "喂养记录页",
    buttonName: "切换宝宝",
  });
  // 只有当有多个宝宝时才显示切换弹窗
  if (babyList.value.length > 1) {
    showBabySwitchPopup.value = true
  }
}

async function onBabyChange(baby, index) {
  // 切换宝宝
  await userStore.changeBabySelected(baby.id)
  console.log('切换到宝宝:', baby.babyName, '索引:', index)

  // 切换宝宝后清空缓存，重新加载数据
  clearCache()

  // 重新加载当前日期的记录
  if (currentSelectedDate.value) {
    loadRecordsByDate(currentSelectedDate.value)
  }

  // 重新加载当前月份的日历状态
  if (currentMonthKey.value) {
    loadCalendarStatus(currentMonthKey.value)
  }
}

function calculateBabyAge(birthday) {
  // 检查生日参数是否有效
  if (!birthday) {
    return '0天'
  }

  try {
    const birthDate = new Date(birthday)
    const today = new Date()

    // 检查日期是否有效
    if (isNaN(birthDate.getTime()) || isNaN(today.getTime())) {
      console.warn('无效的日期格式:', birthday)
      return '0天'
    }

    const diffTime = Math.abs(today - birthDate)
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

    // 检查计算结果是否有效
    if (isNaN(diffDays) || diffDays < 0) {
      console.warn('日期计算错误:', { birthday, diffDays })
      return '0天'
    }

    const years = Math.floor(diffDays / 365)
    const days = diffDays % 365

    if (years > 0) {
      return `${years}岁${days}天`
    } else {
      return `${days}天`
    }
  } catch (error) {
    console.error('计算宝宝年龄时出错:', error, birthday)
    return '0天'
  }
}

// 安全获取当前宝宝姓名
function getCurrentBabyName() {
  try {
    if (currentBaby.value?.babyName) {
      return currentBaby.value.babyName
    }
    return '宝宝'
  } catch (error) {
    console.error('获取宝宝姓名时出错:', error)
    return '宝宝'
  }
}

// 安全获取当前宝宝年龄
function getCurrentBabyAge() {
  try {
    if (userStore.babyInfo?.babyAge) {
      return userStore.babyInfo.babyAge
    }
    return '0天'
  } catch (error) {
    console.error('获取宝宝年龄时出错:', error)
    return '0天'
  }
}

// API 调用函数
async function loadRecordsByDate(date) {
  // 避免重复请求
  if (loadingRecords.value.has(date)) {
    console.log('该日期正在加载中，跳过重复请求:', date)
    return
  }

  // 检查缓存
  const cacheKey = `${date}_${babyId.value}`
  const cachedData = recordsCache.value.get(cacheKey)
  if (cachedData && Date.now() - cachedData.timestamp < 5 * 60 * 1000) { // 5分钟缓存
    console.log('使用缓存的记录数据:', date)
    apiRecords.value[date] = cachedData.data
    return
  }

  try {
    const startTime = Date.now()
    loadingRecords.value.add(date)
    // 只有在没有其他加载中的记录时才显示全局加载状态
    if (loadingRecords.value.size === 1) {
      isLoading.value = true
    }
    const currentBabyId = babyId.value

    // 添加超时处理
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('请求超时')), 10000) // 10秒超时
    })

    const apiPromise = feedingRecordsByDate({
      babyId: currentBabyId,
      date: date
    })

    const response = await Promise.race([apiPromise, timeoutPromise])

    console.log('获取指定日期记录:', date, response)

    // 检查响应状态
    if (response && response.code && response.code !== '000000') {
      throw new Error(`API返回错误: ${response.message || '未知错误'}`)
    }
    if (DEBUG_API) {
      console.log('API返回数据结构:', JSON.stringify(response, null, 2))
    }

    if (response && response.data) {
      // 验证数据格式
      if (!Array.isArray(response.data)) {
        console.error('API返回的数据格式不正确，期望数组:', response.data)
        apiRecords.value[date] = []
        return
      }

      // 转换API数据格式为页面需要的格式
      const records = response.data.map(record => {
        // 验证记录格式
        if (!record || typeof record !== 'object') {
          console.warn('跳过无效的记录:', record)
          return null
        }

        return {
          id: record.id, // 保留原始记录ID，用于修改时传递
          recordId: record.recordId, // 添加recordId字段用于编辑
          time: formatTimeFromTimestamp(record.recordTime),
          type: getFeedingTypeLabel(record.feedingType),
          leftDuration: record.durationLeftSeconds ? formatDuration(record.durationLeftSeconds) : '',
          rightDuration: record.durationRightSeconds ? formatDuration(record.durationRightSeconds) : '',
          amount: record.volume ? `${record.volume}ml` : '',
          content: record.foodDetails || '',
          foodDetails: record.foodDetails || '' // 添加foodDetails字段
        }
      }).filter(record => record !== null) // 过滤掉无效记录

      // 按时间排序
      records.sort((a, b) => a.time.localeCompare(b.time))

      apiRecords.value[date] = records
      console.log('转换后的记录数据:', records)

      // 添加到缓存
      recordsCache.value.set(cacheKey, {
        data: records,
        timestamp: Date.now()
      })

      // 记录性能
      const endTime = Date.now()
      console.log(`获取记录数据耗时: ${endTime - startTime}ms`)
    } else {
      apiRecords.value[date] = []
      console.log('API返回空数据')

      // 缓存空数据
      recordsCache.value.set(cacheKey, {
        data: [],
        timestamp: Date.now()
      })

      // 记录性能
      const endTime = Date.now()
      console.log(`获取记录数据耗时: ${endTime - startTime}ms`)
    }
  } catch (error) {
    handleApiError(error, '获取指定日期记录')

    // 简单的重试机制（最多重试1次）
    if (!loadingRecords.value.has(`${date}_retry`)) {
      console.log('尝试重试获取记录数据...')
      loadingRecords.value.add(`${date}_retry`)
      setTimeout(() => {
        loadRecordsByDate(date)
      }, 2000) // 2秒后重试
      return
    }

    // 在API失败时不再使用本地mock数据作为fallback
    // apiRecords.value[date] = feedingRecords.value[date] || []

    // 显示错误提示（可选）
    console.warn('API获取记录失败，不使用本地数据作为fallback')
    // 注释掉错误提示，避免用户体验不佳
    // uni.showToast({
    //   title: '获取记录失败，显示本地数据',
    //   icon: 'none',
    //   duration: 2000
    // })
  } finally {
    loadingRecords.value.delete(date)
    // 只有在没有其他加载中的记录时才隐藏全局加载状态
    if (loadingRecords.value.size === 0) {
      isLoading.value = false
    }
  }
}

async function loadCalendarStatus(month) {
  // 避免重复请求
  if (loadingCalendar.value.has(month)) {
    console.log('该月份正在加载中，跳过重复请求:', month)
    return
  }

  // 检查缓存
  const cacheKey = `${month}_${babyList.value[currentBabyIndex.value]?.id || 1}`
  const cachedData = calendarCache.value.get(cacheKey)
  if (cachedData && Date.now() - cachedData.timestamp < 10 * 60 * 1000) { // 10分钟缓存
    console.log('使用缓存的日历状态数据:', month)
    calendarStatus.value = { ...calendarStatus.value, ...cachedData.data }
    return
  }

  try {
    const startTime = Date.now()
    loadingCalendar.value.add(month)
    const currentBabyId = babyId.value

    // 添加超时处理
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('请求超时')), 10000) // 10秒超时
    })
    console.log('刷新当前月份日历状态:', month)

    const apiPromise = feedingRecordsCalendarStatus({
      babyId: currentBabyId,
      month: month // 格式：YYYY-MM
    })

    const response = await Promise.race([apiPromise, timeoutPromise])

    console.log('获取日历状态:', month, response)

    // 检查响应状态
    if (response && response.code && response.code !== '000000') {
      throw new Error(`API返回错误: ${response.message || '未知错误'}`)
    }
    if (DEBUG_API) {
      console.log('日历状态API返回数据结构:', JSON.stringify(response, null, 2))
    }

    if (response && response.data) {
      // 验证数据格式
      if (!Array.isArray(response.data)) {
        console.error('日历状态API返回的数据格式不正确，期望数组:', response.data)
        return
      }

      // 将API返回的日历状态数据转换为对象格式
      const statusMap = {}
      response.data.forEach(item => {
        // 验证项目格式
        if (item && typeof item === 'object' && item.date && typeof item.hasRecord === 'boolean') {
          statusMap[item.date] = item.hasRecord
        } else {
          console.warn('跳过无效的日历状态项目:', item)
        }
      })
      calendarStatus.value = { ...calendarStatus.value, ...statusMap }
      console.log('日历状态数据:', statusMap)

      // 添加到缓存
      calendarCache.value.set(cacheKey, {
        data: statusMap,
        timestamp: Date.now()
      })

      // 记录性能
      const endTime = Date.now()
      console.log(`获取日历状态耗时: ${endTime - startTime}ms`)
    } else {
      console.log('日历状态API返回空数据')

      // 缓存空数据
      calendarCache.value.set(cacheKey, {
        data: {},
        timestamp: Date.now()
      })

      // 记录性能
      const endTime = Date.now()
      console.log(`获取日历状态耗时: ${endTime - startTime}ms`)
    }
  } catch (error) {
    handleApiError(error, '获取日历状态')

    // 简单的重试机制（最多重试1次）
    if (!loadingCalendar.value.has(`${month}_retry`)) {
      console.log('尝试重试获取日历状态...')
      loadingCalendar.value.add(`${month}_retry`)
      setTimeout(() => {
        loadCalendarStatus(month)
      }, 2000) // 2秒后重试
      return
    }

    // 在API失败时不再使用本地mock数据作为fallback
    // 这里可以根据本地数据生成日历状态
    const localStatusMap = {}
    Object.keys(apiRecords.value).forEach(date => {
      if (date.startsWith(month)) {
        localStatusMap[date] = apiRecords.value[date] && apiRecords.value[date].length > 0
      }
    })
    calendarStatus.value = { ...calendarStatus.value, ...localStatusMap }
  } finally {
    loadingCalendar.value.delete(month)
  }
}

// 统一错误处理函数
function handleApiError(error, context) {
  console.error(`${context} 失败:`, error)

  // 检查网络状态
  uni.getNetworkType({
    success: (res) => {
      if (res.networkType === 'none') {
        console.warn('网络连接不可用')
      }
    }
  })

  // 根据错误类型提供不同的处理建议
  if (error.message && error.message.includes('超时')) {
    console.warn('请求超时，可能是网络问题')
  } else if (error.message && error.message.includes('API返回错误')) {
    console.warn('服务器返回错误，请检查参数')
  } else {
    console.warn('未知错误，请检查网络连接')
  }
}

// 工具函数
function formatTimeFromTimestamp(timestamp) {
  if (!timestamp) return ''

  let date
  // 处理不同的时间戳格式
  if (typeof timestamp === 'string') {
    // 如果是字符串格式，直接解析
    date = new Date(timestamp)
  } else if (typeof timestamp === 'number') {
    // 如果是数字格式，判断是否为毫秒级时间戳
    if (timestamp > 1000000000000) {
      // 毫秒级时间戳
      date = new Date(timestamp)
    } else {
      // 秒级时间戳
      date = new Date(timestamp * 1000)
    }
  } else {
    date = new Date(timestamp)
  }

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    console.error('无效的时间戳:', timestamp)
    return ''
  }

  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

function formatDuration(seconds) {
  if (!seconds || seconds <= 0) return ''
  const minutes = seconds / 60
  if (minutes < 1) {
    // 不足1分钟时显示小数，保留2位小数
    return `${minutes.toFixed(2)}min`
  } else {
    // 1分钟以上时显示整数
    return `${Math.floor(minutes)}min`
  }
}

// 解析时间格式为秒数
function parseTimeToSeconds(timeString) {
  if (!timeString) return 0
  const parts = timeString.split(':')
  if (parts.length === 2) {
    const minutes = parseInt(parts[0], 10)
    const seconds = parseInt(parts[1], 10)
    return minutes * 60 + seconds
  }
  return 0
}



// 获取编辑表单的占位符
function getEditFormPlaceholder() {
  return '输入具体内容'
}

function getFeedingTypeLabel(type) {
  const typeMap = {
    1: '母乳亲喂',
    2: '母乳瓶喂',
    3: '奶粉喂养',
    4: '辅食'
  }
  return typeMap[type] || '未知'
}

function getFeedingTypeId(label) {
  const typeMap = {
    '母乳亲喂': 1,
    '母乳瓶喂': 2,
    '奶粉喂养': 3,
    '辅食': 4
  }
  return typeMap[label] || 1 // 默认值
}

function formatDateTimeString(dateString, timeString) {
  const date = new Date(dateString);
  const [hours, minutes] = timeString.split(':');
  date.setHours(parseInt(hours, 10));
  date.setMinutes(parseInt(minutes, 10));
  date.setSeconds(0);
  date.setMilliseconds(0);

  // 使用本地时间而不是UTC时间，避免时区问题
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day}T${hour}:${minute}:${second}`;
}

function loadBabyFeedingRecords(baby) {
  // 根据宝宝信息加载对应的喂养记录
  console.log('加载宝宝喂养记录:', baby.name)
  // 清空之前的API数据和缓存
  apiRecords.value = {}
  calendarStatus.value = {}
  recordsCache.value.clear()
  calendarCache.value.clear()

  // 重新加载当前选中日期的记录和日历状态
  if (currentSelectedDate.value) {
    loadRecordsByDate(currentSelectedDate.value)
  }

  // 加载当前月份的日历状态
  const currentMonth = formatMonthString(currentDate.value)
  loadCalendarStatus(currentMonth)
}

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

// 移除addFeedingRecord、saveRecord、closePopup等相关方法

// 清空缓存函数
function clearCache() {
  console.log('清空缓存...')
  // 清空记录缓存
  recordsCache.value.clear()
  // 清空日历状态缓存
  calendarCache.value.clear()
  // 清空API数据
  apiRecords.value = {}
  calendarStatus.value = {}
  // 清空加载状态
  loadingRecords.value.clear()
  loadingCalendar.value.clear()
  console.log('缓存清空完成')
}

function getCurrentTime() {
  const now = new Date()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

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 isSameDay(date1, date2) {
  return date1.getFullYear() === date2.getFullYear() &&
    date1.getMonth() === date2.getMonth() &&
    date1.getDate() === date2.getDate()
}

// 生命周期
onLoad(() => {
  // 使用真实的今天日期
  const today = new Date()
  const todayString = formatDateString(today)
  currentSelectedDate.value = todayString
  currentDate.value = new Date(today.getFullYear(), today.getMonth(), 1) // 当前月份的第一天
  currentMonthKey.value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}` // 设置月份键
  console.log('初始化今日日期:', todayString, '当前月份:', currentDate.value, '月份键:', currentMonthKey.value)

  // 初始化API数据
  initializeApiData()
})

// 初始化API数据
async function initializeApiData() {
  console.log('初始化API数据...')

  // 加载当前选中日期的记录
  if (currentSelectedDate.value) {
    console.log('加载当前选中日期记录:', currentSelectedDate.value)
    await loadRecordsByDate(currentSelectedDate.value)
  }

  // 加载当前月份的日历状态
  const currentMonth = formatMonthString(currentDate.value)
  console.log('加载当前月份日历状态:', currentMonth)
  await loadCalendarStatus(currentMonth)

  console.log('API数据初始化完成')
}

// 通用的月份切换处理函数（已简化，避免重复调用）
function handleMonthChange(newDate, source = 'unknown') {
  console.log(`====== 处理月份切换 (${source}) ======`)
  console.log('新月份:', newDate.getMonth() + 1)

  // 只更新月份键和强制更新，避免重复修改currentDate
  const newMonthKey = `${newDate.getFullYear()}-${String(newDate.getMonth() + 1).padStart(2, '0')}`
  console.log('更新月份键:', currentMonthKey.value, '->', newMonthKey)
  currentMonthKey.value = newMonthKey

  // 强制更新
  forceUpdate.value++

  // 加载新月份的日历状态
  const newMonth = formatMonthString(newDate)
  loadCalendarStatus(newMonth)

  // 使用nextTick确保DOM更新
  nextTick(() => {
    console.log(`${source}: nextTick后再次强制更新`)
    forceUpdate.value++
  })
}

// 监听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()}-${String(newDate.getMonth() + 1).padStart(2, '0')}`
    currentMonthKey.value = newMonthKey
    forceUpdate.value++

    // 加载新月份的日历状态
    const newMonth = formatMonthString(newDate)
    loadCalendarStatus(newMonth)

    nextTick(() => {
      console.log('watch: nextTick后再次强制更新')
      forceUpdate.value++
    })
  }
}, { immediate: false })

onMounted(async () => {

  md.sensorLogTake({
    xcxPage: "小程序页面浏览事件",
    pageName: "喂养记录页",
  });

  // 组件挂载后的操作
  // 加载宝宝信息
  await userStore.loadBabyInfo()
  console.log('宝宝信息加载完成:', userStore.babyInfo)
})

// 页面卸载时清理资源
onUnmounted(() => {
  // 清理缓存
  recordsCache.value.clear()
  calendarCache.value.clear()
  loadingRecords.value.clear()
  loadingCalendar.value.clear()
})

// 页面显示时刷新数据
onShow(async () => {
  // 加载宝宝信息
  await userStore.loadBabyInfo()
  console.log('宝宝信息加载完成:', userStore.babyInfo)

  // 如果已经有选中日期，刷新当前日期的记录
  if (currentSelectedDate.value) {
    loadRecordsByDate(currentSelectedDate.value)
  }

  // 刷新当前月份的日历状态
  const currentMonth = formatMonthString(currentDate.value)
  loadCalendarStatus(currentMonth)
})

// 测试函数（开发时使用）
function testApiIntegration() {
  console.log('=== 测试API集成 ===')
  console.log('当前选中日期:', currentSelectedDate.value)
  console.log('当前月份:', formatMonthString(currentDate.value))
  console.log('当前宝宝ID:', babyList.value[currentBabyIndex.value]?.id)
  console.log('API记录数据:', apiRecords.value)
  console.log('日历状态数据:', calendarStatus.value)
  console.log('缓存状态:', {
    recordsCache: recordsCache.value.size,
    calendarCache: calendarCache.value.size
  })
}

// 功能总结：
// 1. 自动加载：页面加载、显示、日期切换时自动调用API
// 2. 智能缓存：避免重复请求，提升性能
// 3. 错误处理：网络错误、超时、服务器错误等
// 4. 重试机制：失败时自动重试，提高成功率
// 5. 数据验证：确保API返回数据的正确性
// 6. 性能监控：记录API调用耗时
// 7. 调试支持：可控制的调试信息输出
// 8. 资源清理：页面卸载时清理缓存和定时器
</script>

<style lang="scss" scoped>
.feeding-record-page {
  min-height: 100vh;
  background: #ffffff;
  position: relative;
}

// 顶部间距占位
.status-bar-placeholder {
  height: 75rpx;
  background: #fef6eb;
  width: 100%;
}

// 头部导航
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #fef6eb;

  .nav-left {
    display: flex;
    align-items: center;

    .back-btn {
      width: 20rpx;
      height: 32rpx;
      margin-right: 20rpx;
    }

    .baby-icon-star {
      width: 70rpx;
      height: 70rpx;
      margin-right: 10rpx;
    }

    .avatar-img {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 10rpx;
    }

    .baby-info {
      display: flex;
      flex-direction: column;
      cursor: pointer;
      transition: opacity 0.3s ease;

      &:active {
        opacity: 0.7;
      }

      .baby-name {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }

      .baby-age {
        font-size: 24rpx;
        color: #666;
        margin-top: 4rpx;
      }
    }

    .baby-icon-change {
      width: 18rpx;
      height: 13rpx;
      margin-top: -35rpx;
      margin-left: 10rpx;
    }
  }


}

// 日期选择器和统计按钮行
.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;
    }
  }

  .date-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    padding: 0 30rpx;
    transition: all 0.3s ease;

    &.collapsed {
      grid-template-rows: repeat(1, 1fr);
      overflow: hidden;
      max-height: 80rpx;
    }

    &:not(.collapsed) {
      grid-template-rows: repeat(6, 1fr);
      max-height: 480rpx;
    }

    .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;
    }
  }
}

// 记录容器
.records-container {
  flex: 1;
  // padding: 20rpx;
  padding-bottom: 180rpx; // 为浮动按钮留出空间

  .loading-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 400rpx;

    .loading-text {
      font-size: 28rpx;
      color: #999;
    }
  }

  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 400rpx;

    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }

  .record-list {
    padding: 20rpx 35rpx 0rpx 20rpx;

    .timeline-connector {
      width: 1rpx;
      height: 156rpx;
      background: #d3a358;
      margin-left: 16rpx;
      margin-top: -125rpx;
      margin-bottom: -32rpx;
    }

    .record-item {
      display: flex;
      margin-bottom: 40rpx; // 增加间距以容纳连接线

      .time-dot {
        width: 120rpx;
        display: flex;
        align-items: flex-start; // 改为顶部对齐
        margin-right: 0rpx;
        margin-left: 10rpx;
        padding-top: 30rpx; // 调整顶部内边距，与文案第一行对齐

        .dot {
          width: 16rpx;
          height: 16rpx;
          border-radius: 50%;
          margin-right: 16rpx;
          margin-top: 8rpx; // 调整圆点位置，与文案第一行对齐
        }

        .time {
          font-size: 24rpx;
          color: #666;
          white-space: nowrap;
          line-height: 1.4; // 调整行高，与文案保持一致
        }
      }

      .record-content {
        flex: 1;
        width: 548rpx;
        height: 142rpx;
        border-radius: 32rpx;
        padding: 24rpx;
        box-sizing: border-box; // 确保padding包含在宽高中
        overflow: hidden; // 防止内容溢出

        .record-header {
          display: flex;
          align-items: center;
          margin-bottom: 12rpx; // 减少底部间距，适应固定高度


          .record-icon-img-muruqinwei {
            width: 30rpx;
            height: 34rpx;
            margin-right: 12rpx;
            line-height: 1; // 确保图标行高一致
          }

          .record-icon-img-pingwei {
            width: 26rpx;
            height: 37rpx;
            margin-right: 12rpx;
            line-height: 1; // 确保图标行高一致
          }

          .record-icon-img-naifen {
            width: 30rpx;
            height: 34rpx;
            margin-right: 12rpx;
            line-height: 1; // 确保图标行高一致
          }

          .record-icon-img-fushi {
            width: 36rpx;
            height: 31rpx;
            margin-right: 12rpx;
            line-height: 1; // 确保图标行高一致
          }

          .record-type {
            flex: 1;
            font-size: 28rpx;
            font-weight: 600;
            color: #333;
            line-height: 1.4; // 与时间文字保持一致的行高
          }

          .edit-btn {
            font-size: 24rpx;
            color: #1d1e25;
            padding: 8rpx 16rpx;
            border: 1rpx solid #ffffff;
            border-radius: 20rpx;
            background: #ffffff;
            opacity: 0.8;
          }

          .delete-btn {
            font-size: 24rpx;
            color: #1d1e25;
            padding: 8rpx 16rpx;
            border: 1rpx solid #ffffff;
            border-radius: 20rpx;
            background: #ffffff;
            opacity: 0.8;
            margin-right: 16rpx;
          }
        }

        .record-details {
          .duration-info {
            display: flex;
            gap: 16rpx; // 减少间距
            margin-bottom: 6rpx; // 减少底部间距

            .duration-text {
              display: flex;
              align-items: center;
              gap: 16rpx; // 进一步增加间距

              .duration-label {
                font-size: 24rpx;
                color: #666;
              }

              .duration-time {
                font-size: 24rpx;
                color: #333;
                font-weight: 600; // 时间加粗
              }
            }
          }

          .amount-info {
            margin-bottom: 6rpx; // 减少底部间距

            .amount-text {
              display: flex;
              align-items: center;
              gap: 16rpx; // 进一步增加间距

              .amount-label {
                font-size: 24rpx;
                color: #666;
              }

              .amount-value {
                font-size: 24rpx;
                color: #333;
                font-weight: 600; // 数值加粗
              }
            }
          }

          .content-info {
            .content-text {
              font-size: 24rpx;
              color: #333;
              font-weight: 600; // 辅食内容加粗
              line-height: 1.4;
              white-space: nowrap; // 强制一行显示
              overflow: hidden; // 隐藏超出部分
              text-overflow: ellipsis; // 超出显示...
              max-width: 100%; // 确保不超出容器
              word-break: keep-all; // 防止单词被截断
            }
          }
        }
      }


    }
  }
}

// 底部添加按钮
.bottom-add-btn {
  position: fixed;
  bottom: 0rpx;
  left: 0rpx;
  right: 0rpx;
  width: 750rpx;
  height: 218rpx;
  display: flex;
  background: #fff;
  justify-content: center;
  align-items: center;
  z-index: 10;

  .add-btn-img {
    width: 686rpx;
    height: 94rpx;
    display: block;
  }

  .temp-btn-text {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 32rpx;
    color: #D4A574;
    font-weight: 600;
    z-index: 11;
  }

  &:active {
    transform: scale(0.95);
  }
}

// 弹窗样式
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
  overflow: hidden;
  touch-action: none;
}

.popup-content {
  background: #f6f8fa;
  width: 100%;
  border-radius: 20rpx 20rpx 0 0;
  padding: 40rpx 30rpx;
  animation: slideUp 0.3s ease-out;
  max-height: 80vh;
  overflow-y: auto;

  .popup-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    text-align: left;
    margin-bottom: 40rpx;
  }

  .form-item {
    margin-bottom: 30rpx;
    position: relative;

    .label {
      position: absolute;
      left: 24rpx;
      top: 50%;
      transform: translateY(-50%);
      font-size: 28rpx;
      color: #333;
      z-index: 2;
      pointer-events: none;
    }

    .input-container {
      position: relative;
      width: 100%;
    }

    .picker,
    .input {
      width: 100%;
      padding: 24rpx 24rpx 24rpx 120rpx;
      background: #ffffff;
      border-radius: 12rpx;
      font-size: 28rpx;
      text-align: right;

      min-height: 88rpx;
      color: #333;
      border: 1rpx solid #e9ecef;
      box-sizing: border-box;
    }

    .picker {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      min-height: 88rpx;
    }



    .picker {
      display: flex;
      align-items: center;
      min-height: 88rpx;
    }
  }

  .popup-buttons {
    display: flex;
    gap: 20rpx;
    margin-top: 50rpx;

    .cancel-btn,
    .confirm-btn {
      width: 331rpx;
      height: 94rpx;
      flex: none;
    }

    .cancel-btn {
      &:active {
        opacity: 0.8;
      }
    }

    .confirm-btn {
      &:active {
        opacity: 0.8;
      }
    }
  }
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }

  to {
    transform: translateY(0);
  }
}

// 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;
}

// 删除二次确认弹窗样式
.del-popup-content {
  position: relative;
  background: transparent;
  width: 100%;
  height: 100%;
  padding: 0;
  border-radius: 0;
  max-height: none;
  overflow: visible;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .del-record-bg {
    width: 618rpx;
    height: 493rpx;
    display: block;
    margin: 0 auto;
  }

  .del-buttons-container {
    position: absolute;
    bottom: 80rpx;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    gap: 40rpx;
    align-items: center;

    .del-record-cancel-btn,
    .del-record-confirm-btn {
      width: 279rpx;
      height: 101rpx;
      margin-top: -1200rpx;
      display: block;
    }
  }
}
</style>
