<template>
	<view class="feeding-record-add-page">
		<!-- 可滚动内容区域 -->
		<scroll-view class="scrollable-content" scroll-y="true">
			<!-- 广告横幅 -->
			<swiper class="banner-swiper" :indicator-dots="swiperData.length > 1" :autoplay="swiperData.length > 1"
				:circular="swiperData.length > 1" indicator-color="#dfddd9" indicator-active-color="#b27c1e"
				:indicator-top="596">
				<swiper-item v-for="(item, index) in swiperData" :key="index">
					<image class="banner-img" :src="`${item?.bannerImg}`" mode="aspectFill"
						@click="bannerHandler(item)" />
				</swiper-item>
			</swiper>

			<!-- 喂养时间 -->
			<view class="feeding-time">
				<view class="baby-info" @click="showBabySwitch" v-if="babyList.length > 0">
					<image class="avatar-img"
						:src="babyList[currentBabyIndex]?.avatar || '/static/feedingIndex/v1/avatar.png'"></image>
					<view class="baby-name-section">
						<text class="baby-name">{{ babyList[currentBabyIndex]?.name || '加载中...' }}</text>
						<image class="dropdown-icon" src="/static/feedingIndex/v1/icon_arrow_yellow_drop.png" />
					</view>
				</view>
				<view class="baby-info" v-else>
					<image class="avatar-img" src="/static/feedingIndex/v1/avatar.png"></image>
					<view class="baby-name-section">
						<text class="baby-name">加载中...</text>
						<image class="dropdown-icon" src="/static/feedingIndex/v1/icon_arrow_yellow_drop.png" />
					</view>
				</view>
				<view class="time-section">
					<text class="time-label">喂养时间</text>
					<uni-datetime-picker ref="timePickerRef" v-model="currentTime" type="datetime" :clear-icon="false"
						:border="false" @change="onTimeChange" :start="earliestDateString" :end="latestDateString">
						<view class="time-display">
							<text class="time-value">{{ formatCurrentTime() }}</text>
							<image class="edit-icon" src="/static/feedingIndex/v1/icon_modify.png" />
						</view>
					</uni-datetime-picker>
				</view>
			</view>

			<!-- 喂养记录 -->
			<view class="feeding-records" @click="goToFeedingRecord">
				<text class="records-link">喂养记录</text>
				<image class="arrow-right" src="/static/feedingIndex/v1/icon_arrow_yellow.png"></image>
			</view>

			<!-- 喂养类型选择 -->
			<view class="feeding-types">
				<view class="type-item" v-for="(type, index) in feedingTypes" :key="index"
					:class="{ active: selectedType === type.value }" @click="selectType(type.value)">
					<image class="icon-bg" src="/static/feedingIndex/v1/icon_bg.png" mode="aspectFit"
						v-if="selectedType === type.value" />
					<view class="type-icon-wrapper">

						<image class="type-icon" :src="type.icon" mode="aspectFit" />
					</view>
					<text class="type-label">{{ type.label }}</text>
				</view>
			</view>

			<!-- 下半部分背景 -->
			<view class="bottom-section">
				<image class="bottom-bg" src="/static/feedingIndex/v1/bottom_bg.png" mode="aspectFill" />

				<!-- 温馨提示 -->
				<view class="warm-tip"
					v-if="selectedType === 'breastfeeding' && recordMethods[selectedType] === 'manual'">
					<text>温馨提示:每十分钟建议更换一侧,更推荐瓶装方式喂养~</text>
				</view>

				<!-- 动态表单区域 -->
				<view v-if="shouldShowForm" class="form-section">
					<!-- 母乳亲喂表单 -->
					<view v-if="selectedType === 'breastfeeding'" class="breastfeeding-form">
						<view class="duration-controls">
							<view class="duration-item">
								<view class="duration-circle">
									<image class="circle-bg" src="/static/feedingIndex/v1/iconBg.png"
										mode="aspectFit" />
									<view class="circle-content">
										<text class="duration-number">{{ feedingData.breastfeeding.leftDuration
										}}</text>
										<text class="duration-unit">分钟</text>
									</view>
								</view>
								<view class="duration-buttons">
									<image class="btn-minus"
										:src="feedingData.breastfeeding.leftDuration <= 0 ? '/static/feedingIndex/v1/icon-G.png' : '/static/feedingIndex/v1/icon-L.png'"
										mode="aspectFit" @click="adjustDuration('left', -1)"
										:class="{ disabled: feedingData.breastfeeding.leftDuration <= 0 }" />
									<image class="btn-plus"
										:src="feedingData.breastfeeding.leftDuration >= 60 ? '/static/feedingIndex/v1/icon+G.png' : '/static/feedingIndex/v1/icon+L.png'"
										mode="aspectFit" @click="adjustDuration('left', 1)"
										:class="{ disabled: feedingData.breastfeeding.leftDuration >= 60 }" />
								</view>
								<text class="duration-label">左侧哺乳时长</text>
							</view>
							<view class="duration-item">
								<view class="duration-circle">
									<image class="circle-bg" src="/static/feedingIndex/v1/iconBg.png"
										mode="aspectFit" />
									<view class="circle-content">
										<text class="duration-number">{{ feedingData.breastfeeding.rightDuration
										}}</text>
										<text class="duration-unit">分钟</text>
									</view>
								</view>
								<view class="duration-buttons">
									<image class="btn-minus"
										:src="feedingData.breastfeeding.rightDuration <= 0 ? '/static/feedingIndex/v1/icon-G.png' : '/static/feedingIndex/v1/icon-L.png'"
										mode="aspectFit" @click="adjustDuration('right', -1)"
										:class="{ disabled: feedingData.breastfeeding.rightDuration <= 0 }" />
									<image class="btn-plus"
										:src="feedingData.breastfeeding.rightDuration >= 60 ? '/static/feedingIndex/v1/icon+G.png' : '/static/feedingIndex/v1/icon+L.png'"
										mode="aspectFit" @click="adjustDuration('right', 1)"
										:class="{ disabled: feedingData.breastfeeding.rightDuration >= 60 }" />
								</view>
								<text class="duration-label">右侧哺乳时长</text>
							</view>
						</view>
					</view>

					<!-- 母乳瓶喂/奶粉喂养表单 -->
					<view v-if="(selectedType === 'bottle' || selectedType === 'formula')" class="bottle-form">
						<view class="bottle-graphic">
							<!-- 左侧喂奶量显示 -->
							<view class="amount-bubble">
								<text class="bubble-label">喂奶量</text>
								<text class="bubble-value">{{ feedingData[selectedType].amount }}ml</text>
							</view>

							<!-- 中间瓶子图形 -->
							<view class="bottle-container">
								<image class="bottle-image" src="/static/feedingIndex/v1/icon_milk_bottle.png"
									mode="aspectFit" />

								<!-- 奶量选择器 -->
								<picker-view class="amount-picker" :value="pickerValue" @change="onPickerChange"
									:mask-style="{ opacity: 0 }" :indicator-style="indicatorStyle"
									indicator-class="amount-picker" mask-style="opacity: 0.5; border: none;">
									<picker-view-column>
										<view class="picker-item" v-for="(amount, index) in pickerAmounts" :key="amount"
											:class="{ active: pickerValue[0] === index }">
											{{ amount }}ml
										</view>
									</picker-view-column>
								</picker-view>
							</view>
						</view>
					</view>

					<!-- 辅食表单 -->
					<view v-if="selectedType === 'food'" class="food-form">
						<!-- 已选择的辅食展示区域 -->
						<view class="selected-items">
							<text>{{ feedingData.food.selectedItems.join(',') || '请选择辅食' }}</text>
						</view>

						<!-- 分隔线 -->
						<view class="divider"></view>

						<!-- 辅食分类标题和操作按钮 -->
						<view class="food-categories">
							<text class="category-title">辅食分类</text>
							<view class="category-actions">
								<text v-if="foodSelectionState.isEditMode" class="complete-btn" @click="exitEditMode">
									完成
								</text>
								<view v-else class="delete-btn" @click="enterEditMode">
									<image class="delete-icon" src="/static/feedingIndex/v1/icon_shanchu.png"
										mode="aspectFit" />
									<text>删除</text>
								</view>
							</view>
						</view>

						<!-- 辅食分类列表 -->
						<view class="category-list">
							<view v-for="(category, categoryName) in foodCategories" :key="categoryName"
								class="category-item">
								<text class="category-name">{{ categoryName }}</text>
								<image class="add-btn" :class="{ disabled: foodSelectionState.isEditMode }"
									src="/static/feedingIndex/v1/icon_fushi_add.png" mode="aspectFit"
									@click="showAddFoodPopup(categoryName)" />
								<view class="selected-tags">
									<!-- 默认辅食项 -->
									<text v-for="(item, index) in category.items" :key="item" class="tag" :class="{
										active: feedingData.food.selectedItems.includes(item),
										editing: foodSelectionState.isEditMode,
										hidden: !category.expanded && index >= 3
									}" @click="toggleFoodSelection(item)">
										{{ item }}
										<image v-if="foodSelectionState.isEditMode" class="delete-x"
											src="/static/feedingIndex/v1/icon_shanchu_x.png" mode="aspectFit"
											@click.stop="removeFoodItem(categoryName, item)" />
									</text>
									<!-- 自定义辅食项 -->
									<text v-for="(item, index) in category.customItems" :key="`custom-${item}`"
										class="tag" :class="{
											active: feedingData.food.selectedItems.includes(item),
											editing: foodSelectionState.isEditMode,
											hidden: !category.expanded && index >= 3
										}" @click="toggleFoodSelection(item)">
										{{ item }}
										<image v-if="foodSelectionState.isEditMode" class="delete-x"
											src="/static/feedingIndex/v1/icon_shanchu_x.png" mode="aspectFit"
											@click.stop="removeFoodItem(categoryName, item)" />
									</text>
									<!-- 展开/缩起按钮 -->
									<view v-if="(category.items.length + category.customItems.length) > 3"
										class="expand-btn" @click="toggleCategoryExpansion(categoryName)">
										<image class="expand-icon"
											:src="category.expanded ? '/static/feedingIndex/v1/icon_fushi_up.png' : '/static/feedingIndex/v1/icon_fushi_drop.png'"
											mode="aspectFit" />
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 录音控制区域 -->
				<view v-if="recordMethods[selectedType] === 'voice'" class="voice-controls">
					<!-- 提示文字 -->
					<view class="voice-tip">
						<text class="tip-text">你可以尝试这样说:</text>
					</view>

					<!-- 示例语音 -->
					<view class="voice-example">
						<text class="example-text" v-if="selectedType === 'breastfeeding'">"早上8点,左边5分钟,右边6分钟"</text>
						<text class="example-text" v-else>"早上8点,喂奶量90毫升"</text>
					</view>

					<!-- 麦克风图标 -->
					<view class="voice-microphone" @touchstart="startRecording" @touchend="stopRecording"
						@touchcancel="stopRecording">
						<image class="microphone-icon"
							:src="voiceRecognitionState.isRecording ? '/static/feedingIndex/v1/icon_luyining.gif' : '/static/feedingIndex/v1/icon_luyin.png'"
							mode="aspectFit" />
					</view>

					<!-- 录音提示 -->
					<view class="voice-click-tip">
						<text class="click-text" v-if="voiceRecognitionState.isRecording">
							正在录音... {{ formatRecordingDuration(voiceRecognitionState.recordingDuration) }}
						</text>
						<text class="click-text" v-else-if="voiceRecognitionState.isPolling">正在识别...</text>
						<text class="click-text" v-else>长按录音</text>
					</view>
				</view>

				<!-- 计时器控制区域 -->
				<view v-if="recordMethods[selectedType] === 'timer'" class="timer-controls">
					<!-- 总时长显示 -->
					<view class="total-duration">
						<text class="total-duration-label">总时长</text>
						<text class="total-duration-value">{{ formatTotalDuration() }}</text>
					</view>

					<!-- 圆形计时器 -->
					<view class="circular-timers">
						<!-- 左侧计时器 -->
						<view class="timer-circle left-timer">
							<image class="timer-icon"
								:src="isLeftTimerRunning ? '/static/feedingIndex/v1/icon_stop.png' : '/static/feedingIndex/v1/icon_start.png'"
								mode="aspectFit" @click="toggleTimer('left')" />
							<text class="timer-time">{{ formatTime(timerData.leftDuration) }}</text>
							<text class="timer-label">左侧</text>
						</view>

						<!-- 右侧计时器 -->
						<view class="timer-circle right-timer">
							<image class="timer-icon"
								:src="isRightTimerRunning ? '/static/feedingIndex/v1/icon_stop.png' : '/static/feedingIndex/v1/icon_start.png'"
								mode="aspectFit" @click="toggleTimer('right')" />
							<text class="timer-time">{{ formatTime(timerData.rightDuration) }}</text>
							<text class="timer-label">右侧</text>
						</view>
					</view>
				</view>

				<!-- 记录方式选择 - 母乳亲喂 -->
				<view class="record-methods1" v-if="selectedType === 'breastfeeding'">
					<image class="tab-image" :src="getTabImage()" mode="aspectFill" />
					<view class="click-area left" @click="setRecordMethod('manual')"></view>
					<view class="click-area center" @click="setRecordMethod('timer')"></view>
					<view class="click-area right" @click="setRecordMethod('voice')"></view>
				</view>

				<!-- 记录方式选择 - 母乳瓶喂/奶粉喂养 -->
				<view class="record-methods2" v-if="selectedType === 'bottle' || selectedType === 'formula'">
					<image class="tab-image" :src="getTabImage2()" mode="aspectFill" />
					<view class="click-area left" @click="setRecordMethod('manual')">
					</view>
					<view class="click-area right" @click="setRecordMethod('voice')">
					</view>
				</view>

				<!-- 底部完成按钮 -->
				<view class="bottom_complete-btn" :class="{ 'disabled': isSubmitting }" @click="completeRecord">
					<image class="complete-btn-bg" src="/static/feedingIndex/v1/complete_btn.png" />
					<!-- <text class="complete-btn-text">{{ isSubmitting ? '保存中...' : '完成记录' }}</text> -->
				</view>
			</view>
		</scroll-view>
	</view>

	<!-- 添加辅食弹窗 -->
	<uni-popup ref="addFoodPopup" type="center" :mask-click="false">
		<view class="add-food-popup">
			<view class="popup-header">
				<text class="popup-title">新增辅食名称快捷键</text>
			</view>
			<view class="popup-content">
				<view class="input-container">
					<input class="food-input" v-model="foodSelectionState.newFoodItem" placeholder="请输入辅食名称"
						maxlength="10" />
					<text class="char-count">{{ foodSelectionState.newFoodItem.length }}/10</text>
				</view>
			</view>
			<view class="popup-buttons">
				<image class="cancel-btn" src="/static/feedingIndex/v1/icon_fushi_btn_cancel.png" mode="aspectFit" @click="cancelAddFood"></image>
				<image class="confirm-btn" src="/static/feedingIndex/v1/icon_fushi_btn_add.png" mode="aspectFit" @click="confirmAddFood"></image>
			</view>
		</view>
	</uni-popup>

	<!-- 语音识别结果页面 -->
	<view v-if="voiceRecognitionState.showResultPage" class="voice-result-page">
		<view class="result-container">
			<!-- 识别结果标题 -->
			<view class="result-header">
				<text class="result-title">识别结果</text>
			</view>

			<!-- 喂养信息展示 -->
			<view class="feeding-info">
				<view class="info-item">
					<text class="info-label">喂养时间</text>
					<text class="info-value">{{ formatCurrentTime() }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">喂养方式</text>
					<text class="info-value">{{ getFeedingTypeLabel() }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">录音时长</text>
					<text class="info-value">{{ formatRecordingDuration(voiceRecognitionState.recordingDuration)
					}}</text>
				</view>
				<view class="info-item">
					<text class="info-label">喂养详情</text>
					<input class="detail-input" v-model="voiceRecognitionState.recognizedText" placeholder="请输入喂养详情"
						maxlength="20" />
				</view>
			</view>

			<!-- 操作按钮 -->
			<view class="result-actions">
				<text class="re-recognize-btn" @click="reRecognize">不对，重新识别</text>
				<text class="complete-record-btn" @click="completeVoiceRecord">完成记录</text>
			</view>
		</view>
	</view>

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

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import BabySwitchPopup from '@/components/BabySwitchPopup.vue'
import { feedingHome, feedingRecords, feedingFoodsCustom, feedingFoodsCustomAdd, feedingFoodsCustomDelete, feedingTimerStart, feedingTimerStop, feedingVoiceUpload, feedingVoiceResult } from '@/api/feeding.js'
import { useFeedStore } from '@/stores/feed.js'

// 弹窗引用
const addFoodPopup = ref(null)

const swiperData = ref([{ bannerImg: '/static/feedingIndex/v1/banner.png' }, { bannerImg: '/static/feedingIndex/v1/banner.png' }, { bannerImg: '/static/feedingIndex/v1/banner.png' }]);
const indicatorStyle = `height: 40px; border: none;`

// 当前时间，使用 home 接口的 timestamp
const currentTime = ref(null)

// 日期范围限制
const earliestDateString = ref('2020-01-01')
const latestDateString = ref('2030-12-31')

// 接口返回的数据
const homeData = ref({
	timestamp: null,
	lastRecordType: 0,
	lastBreastMilkVolume: 0,
	lastFormulaVolume: 0,
	leftTimerRunning: false,
	leftTimerDuration: 0,
	rightTimerRunning: false,
	rightTimerDuration: 0
})

// 记录相关数据
const currentRecordId = ref(null) // 当前记录ID，用于区分新增和修改
const isSubmitting = ref(false) // 提交状态
const bannerHandler = (item) => {
	console.log(item);
}

const feedingTypes = ref([
	{ value: 'breastfeeding', label: '母乳亲喂', icon: '/static/feedingIndex/v1/icon_muruqinwei.png' },
	{ value: 'bottle', label: '母乳瓶喂', icon: '/static/feedingIndex/v1/icon_murupinwei.png' },
	{ value: 'formula', label: '奶粉喂养', icon: '/static/feedingIndex/v1/icon_naifen.png' },
	{ value: 'food', label: '辅食', icon: '/static/feedingIndex/v1/icon_fushi.png' }
])

// 根据接口数据初始化选中的喂养类型
const selectedType = ref('breastfeeding')

// 为每种喂养方式设置独立的记录方法
const recordMethods = ref({
	breastfeeding: 'manual',
	bottle: 'manual',
	formula: 'manual',
	food: 'manual'
})
const isRecording = ref(false)
const isLeftTimerRunning = ref(false)
const isRightTimerRunning = ref(false)

// 辅食数据结构 - 使用接口数据
const foodCategories = ref({
	主食: {
		items: [],
		customItems: [],
		expanded: false
	},
	蔬菜: {
		items: [],
		customItems: [],
		expanded: false
	},
	水果: {
		items: [],
		customItems: [],
		expanded: false
	},
	其他: {
		items: [],
		customItems: [],
		expanded: false
	}
})

// 辅食ID映射，用于删除操作
const foodIdMap = ref(new Map())

// 辅食类型映射
const foodTypeMap = {
	1: '主食',
	2: '蔬菜',
	3: '水果',
	4: '其他'
}

// 辅食选择状态
const foodSelectionState = ref({
	isEditMode: false, // 是否处于编辑模式
	showAddPopup: false, // 是否显示添加弹窗
	currentCategory: '', // 当前添加的分类
	newFoodItem: '', // 新添加的辅食项
	pendingDeletes: [] // 待删除的辅食列表
})

// 语音识别状态
const voiceRecognitionState = ref({
	isRecording: false, // 是否正在录音
	showResultPage: false, // 是否显示识别结果页面
	recognizedText: '', // 识别结果文本
	recordingDuration: 0, // 录音时长
	recordingStartTime: null, // 录音开始时间
	recordingTimer: null, // 录音时长定时器
	taskId: '', // 语音识别任务ID
	isPolling: false, // 是否正在轮询识别结果
	pollingInterval: null // 轮询定时器
})

// 全局状态管理
const feedStore = useFeedStore()

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

// 为每种喂养方式设置独立的数据 - 根据接口数据初始化
const feedingData = ref({
	breastfeeding: {
		leftDuration: 5,
		rightDuration: 5
	},
	bottle: {
		amount: 0 // 首次默认定位到0ml
	},
	formula: {
		amount: 0 // 首次默认定位到0ml
	},
	food: {
		selectedItems: []
	}
})

// 刻度标记数组 (0-500ml，每5ml一个刻度)
const scaleMarks = ref([0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500])

// picker-view相关数据
const pickerAmounts = ref([0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 185, 190, 195, 200, 205, 210, 215, 220, 225, 230, 235, 240, 245, 250, 255, 260, 265, 270, 275, 280, 285, 290, 295, 300, 305, 310, 315, 320, 325, 330, 335, 340, 345, 350, 355, 360, 365, 370, 375, 380, 385, 390, 395, 400, 405, 410, 415, 420, 425, 430, 435, 440, 445, 450, 455, 460, 465, 470, 475, 480, 485, 490, 495, 500])

// 滑动相关状态
const isDragging = ref(false)
const startY = ref(0)
const startAmount = ref(0)

// 计时器数据 - 根据接口数据初始化
const timerData = ref({
	leftDuration: 0,
	rightDuration: 0
})

// 计时器间隔ID
let leftTimerInterval = null
let rightTimerInterval = null

// 计算属性 - 判断是否显示表单
const shouldShowForm = computed(() => {
	const currentMethod = recordMethods.value[selectedType.value]
	return currentMethod === 'manual' // 只有手动模式显示表单
})

// 计算属性 - 同步picker-view的值
const pickerValue = computed({
	get() {
		const currentAmount = feedingData.value[selectedType.value].amount
		const index = pickerAmounts.value.indexOf(currentAmount)
		return [index >= 0 ? index : 0]
	},
	set(value) {
		// 这个setter不会被直接调用，但需要保持响应式
	}
})

// 计算属性 - 判断是否为语音模式（辅食除外）
const isVoiceMode = computed(() => {
	return recordMethods.value[selectedType.value] === 'voice' && selectedType.value !== 'food'
})

// 计算属性 - 获取宝宝信息
const babyList = computed(() => feedStore.babyList)
const currentBabyIndex = computed(() => feedStore.currentBabyIndex)
const currentBaby = computed(() => feedStore.getCurrentBaby())
const currentBabyId = computed(() => feedStore.getCurrentBabyId())

// 页面加载时获取数据
onMounted(() => {
	console.warn('页面加载，开始初始化数据...')
	loadBabyInfo()
	loadFoodsData()
})

// 页面显示时刷新数据
onShow(() => {
	// 刷新宝宝信息和首页数据
	loadBabyInfo()
})

// 页面卸载时清理计时器
onUnmounted(() => {
	// 清理左侧计时器
	if (leftTimerInterval) {
		clearInterval(leftTimerInterval)
		leftTimerInterval = null
	}
	// 清理右侧计时器
	if (rightTimerInterval) {
		clearInterval(rightTimerInterval)
		rightTimerInterval = null
	}
	// 清理语音识别轮询
	clearPollingInterval()
	// 清理录音定时器
	if (voiceRecognitionState.value.recordingTimer) {
		clearInterval(voiceRecognitionState.value.recordingTimer)
		voiceRecognitionState.value.recordingTimer = null
	}
})

// 页面参数接收
onLoad((options) => {
	console.log('页面参数:', options)

	// 如果是修改记录，接收记录ID
	if (options.recordId) {
		currentRecordId.value = options.recordId
		console.log('修改记录ID:', currentRecordId.value)
	}

	// 如果有其他参数，可以在这里处理
	if (options.babyId) {
		// 设置选中的宝宝
		const babyIndex = feedStore.babyList.findIndex(baby => baby.id == options.babyId)
		if (babyIndex > -1) {
			feedStore.switchBaby(babyIndex)
		}
	}

	if (options.feedingType) {
		// 设置喂养类型
		const typeMap = {
			'1': 'breastfeeding',
			'2': 'bottle',
			'3': 'formula',
			'4': 'food'
		}
		selectedType.value = typeMap[options.feedingType] || 'breastfeeding'
	}
})

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}`
}

// 获取宝宝信息
async function loadBabyInfo() {
	try {
		console.log('开始加载宝宝信息...')

		// 使用全局状态管理加载宝宝信息
		await feedStore.loadBabyInfo()

		console.log('宝宝信息加载完成')

		// 加载宝宝信息后，加载首页数据
		await loadHomeData()
	} catch (error) {
		console.error('获取宝宝信息失败:', error)

		// 即使宝宝信息加载失败，也要加载首页数据
		await loadHomeData()

		uni.showToast({
			title: '获取宝宝信息失败，使用默认数据',
			icon: 'none'
		})
	}
}

// 获取首页数据
async function loadHomeData() {
	try {
		const response = await feedingHome(feedStore.getCurrentBabyId())
		console.log('首页数据:', response)

		if (response && response.data) {
			const data = response.data
			homeData.value = {
				timestamp: data.timestamp,
				lastRecordType: data.lastRecordType,
				lastBreastMilkVolume: data.lastBreastMilkVolume,
				lastFormulaVolume: data.lastFormulaVolume,
				leftTimerRunning: data.leftTimerRunning,
				leftTimerDuration: data.leftTimerDuration,
				rightTimerRunning: data.rightTimerRunning,
				rightTimerDuration: data.rightTimerDuration
			}
		}

		// 根据接口数据初始化页面状态
		initializePageData()
	} catch (error) {
		console.error('获取首页数据失败:', error)

		// 使用模拟数据作为fallback
		homeData.value = {
			timestamp: Date.now(),
			lastRecordType: 2,
			lastBreastMilkVolume: 120,
			lastFormulaVolume: 0,
			leftTimerRunning: false,
			leftTimerDuration: 0,
			rightTimerRunning: false,
			rightTimerDuration: 0
		}
		initializePageData()

		uni.showToast({
			title: '获取数据失败，使用默认数据',
			icon: 'none'
		})
	}
}

// 根据接口数据初始化页面状态
function initializePageData() {
	const data = homeData.value

	// 设置当前时间，优先使用 home 接口的 timestamp
	if (data.timestamp) {
		currentTime.value = data.timestamp
	} else {
		// 如果没有 timestamp，使用当前时间作为 fallback
		currentTime.value = getCurrentTime()
	}

	// 根据上次记录类型设置默认选中的喂养类型
	if (data.lastRecordType > 0) {
		const typeMap = {
			1: 'breastfeeding',
			2: 'bottle',
			3: 'formula',
			4: 'food'
		}
		selectedType.value = typeMap[data.lastRecordType] || 'breastfeeding'
	}

	// 设置上次的喂养量
	if (data.lastRecordType === 2 && data.lastBreastMilkVolume > 0) {
		feedingData.value.bottle.amount = data.lastBreastMilkVolume
	}
	if (data.lastRecordType === 3 && data.lastFormulaVolume > 0) {
		feedingData.value.formula.amount = data.lastFormulaVolume
	}

	// 设置计时器状态
	if (data.leftTimerRunning) {
		isLeftTimerRunning.value = true
		timerData.value.leftDuration = Math.floor(data.leftTimerDuration / 1000) // 转换为秒
		startLeftTimer()
	}

	if (data.rightTimerRunning) {
		isRightTimerRunning.value = true
		timerData.value.rightDuration = Math.floor(data.rightTimerDuration / 1000) // 转换为秒
		startRightTimer()
	}

	// 如果有计时器在运行，切换到计时器模式
	if (data.leftTimerRunning || data.rightTimerRunning) {
		recordMethods.value.breastfeeding = 'timer'
	}
}

// 方法
function selectType(type) {
	// 检查是否有正在进行的计时器
	if (isLeftTimerRunning.value || isRightTimerRunning.value) {
		uni.showToast({
			title: '记录进行中，不可切换',
			icon: 'none'
		})
		return
	}

	// 如果切换的是不同的类型，清空之前的状态
	if (selectedType.value !== type) {
		clearPreviousState()
	}

	selectedType.value = type
}

// 清空之前的状态
function clearPreviousState() {
	// 清理轮询定时器
	clearPollingInterval()

	// 清理录音定时器
	if (voiceRecognitionState.value.recordingTimer) {
		clearInterval(voiceRecognitionState.value.recordingTimer)
		voiceRecognitionState.value.recordingTimer = null
	}

	// 清空语音识别状态
	voiceRecognitionState.value = {
		isRecording: false,
		showResultPage: false,
		recognizedText: '',
		recordingDuration: 0,
		recordingStartTime: null,
		recordingTimer: null,
		taskId: '',
		isPolling: false,
		pollingInterval: null
	}

	// 清空辅食选择状态
	foodSelectionState.value = {
		isEditMode: false,
		showAddPopup: false,
		currentCategory: '',
		newFoodItem: '',
		pendingDeletes: []
	}

	// 清空录音状态
	isRecording.value = false

	// 清空计时器状态（如果不在计时中）
	if (!isLeftTimerRunning.value && !isRightTimerRunning.value) {
		// 重置母乳亲喂的时长
		feedingData.value.breastfeeding.leftDuration = 5
		feedingData.value.breastfeeding.rightDuration = 5
	}

	// 清空其他喂养方式的数据
	feedingData.value.bottle.amount = 0
	feedingData.value.formula.amount = 0
	feedingData.value.food.selectedItems = []

	// 重置记录方法为手动
	recordMethods.value[selectedType.value] = 'manual'

	// 清空计时器数据（如果不在计时中）
	if (!isLeftTimerRunning.value && !isRightTimerRunning.value) {
		timerData.value.leftDuration = 0
		timerData.value.rightDuration = 0
	}

	// 清空滑动状态
	isDragging.value = false
	startY.value = 0
	startAmount.value = 0
}

// 清空喂养数据（保存成功后调用）
function clearFeedingData() {
	// 清空所有喂养方式的数据
	feedingData.value.breastfeeding.leftDuration = 5
	feedingData.value.breastfeeding.rightDuration = 5
	feedingData.value.bottle.amount = 0
	feedingData.value.formula.amount = 0
	feedingData.value.food.selectedItems = []

	// 清空计时器数据
	timerData.value.leftDuration = 0
	timerData.value.rightDuration = 0

	// 停止所有计时器
	if (leftTimerInterval) {
		clearInterval(leftTimerInterval)
		leftTimerInterval = null
	}
	if (rightTimerInterval) {
		clearInterval(rightTimerInterval)
		rightTimerInterval = null
	}

	// 重置计时器状态
	isLeftTimerRunning.value = false
	isRightTimerRunning.value = false

	// 清空语音识别状态
	voiceRecognitionState.value = {
		isRecording: false,
		showResultPage: false,
		recognizedText: '',
		recordingDuration: 0,
		recordingStartTime: null,
		recordingTimer: null,
		taskId: '',
		isPolling: false,
		pollingInterval: null
	}

	// 清空辅食选择状态
	foodSelectionState.value = {
		isEditMode: false,
		showAddPopup: false,
		currentCategory: '',
		newFoodItem: '',
		pendingDeletes: []
	}

	// 清空录音状态
	isRecording.value = false

	// 清空滑动状态
	isDragging.value = false
	startY.value = 0
	startAmount.value = 0

	// 重置记录方法为手动
	recordMethods.value.breastfeeding = 'manual'
	recordMethods.value.bottle = 'manual'
	recordMethods.value.formula = 'manual'
	recordMethods.value.food = 'manual'

	// 重置当前时间，使用 home 接口的最新 timestamp
	if (homeData.value.timestamp) {
		currentTime.value = homeData.value.timestamp
	} else {
		currentTime.value = getCurrentTime()
	}

	console.log('喂养数据已清空')
}

function adjustDuration(side, value) {
	const currentData = feedingData.value.breastfeeding
	if (side === 'left') {
		// 限制在0-60分钟范围内
		const newValue = currentData.leftDuration + value
		if (newValue >= 0 && newValue <= 60) {
			currentData.leftDuration = newValue
		}
	} else {
		// 限制在0-60分钟范围内
		const newValue = currentData.rightDuration + value
		if (newValue >= 0 && newValue <= 60) {
			currentData.rightDuration = newValue
		}
	}
}



function adjustAmount(value) {
	const currentType = selectedType.value
	if (currentType === 'bottle' || currentType === 'formula') {
		const currentData = feedingData.value[currentType]
		currentData.amount = Math.max(0, Math.min(500, currentData.amount + value))
	}
}

// 滑动选择相关方法
function onTouchStart(e) {
	isDragging.value = true
	startY.value = e.touches[0].clientY
	startAmount.value = feedingData.value[selectedType.value].amount
}

function onTouchMove(e) {
	if (!isDragging.value) return

	const currentY = e.touches[0].clientY
	const deltaY = startY.value - currentY // 向上滑动为增加

	// 计算滑动距离对应的数值变化 (每10px对应5ml)
	const deltaAmount = Math.round(deltaY / 10) * 5
	const newAmount = Math.max(0, Math.min(500, startAmount.value + deltaAmount))

	// 确保是5的倍数
	const adjustedAmount = Math.round(newAmount / 5) * 5

	feedingData.value[selectedType.value].amount = adjustedAmount
}

function onTouchEnd() {
	isDragging.value = false
}

function getSliderPosition() {
	const currentAmount = feedingData.value[selectedType.value].amount
	// 将0-500ml映射到0-100%的位置
	return 100 - (currentAmount / 500) * 100
}

// picker-view选择事件
function onPickerChange(e) {
	const index = e.detail.value[0]
	const selectedAmount = pickerAmounts.value[index]
	feedingData.value[selectedType.value].amount = selectedAmount
}

function setRecordMethod(method) {
	// 辅食不支持语音模式
	if (selectedType.value === 'food' && method === 'voice') {
		uni.showToast({
			title: '辅食只支持手动选择模式',
			icon: 'none'
		})
		return
	}

	// 母乳亲喂计时器运行时阻止切换记录方式
	if (selectedType.value === 'breastfeeding' && (isLeftTimerRunning.value || isRightTimerRunning.value)) {
		uni.showToast({
			title: '计时器正在运行，请先停止计时',
			icon: 'none'
		})
		return
	}

	// 语音识别运行时阻止切换记录方式
	if (voiceRecognitionState.value.isRecording) {
		uni.showToast({
			title: '语音识别正在进行，请先停止录音',
			icon: 'none'
		})
		return
	}

	recordMethods.value[selectedType.value] = method

	// 如果切换到语音模式，检查录音权限
	if (method === 'voice') {
		checkVoicePermission()
	}
}

function toggleRecording() {
	isRecording.value = !isRecording.value
}

async function toggleTimer(side) {
	const babyId = feedStore.getCurrentBabyId()

	if (side === 'left') {
		// 左侧计时逻辑
		if (!isLeftTimerRunning.value) {
			// 开始左侧计时
			try {
				const response = await feedingTimerStart({
					babyId: babyId,
					side: 'left'
				})
				console.log('开始左侧计时成功:', response)
				isLeftTimerRunning.value = true
				startLeftTimer()
			} catch (error) {
				console.error('开始左侧计时失败:', error)
				uni.showToast({
					title: '开始计时失败',
					icon: 'none'
				})
			}
		} else {
			// 停止左侧计时
			try {
				const response = await feedingTimerStop({
					babyId: babyId,
					side: 'left'
				})
				console.log('停止左侧计时成功:', response)
				isLeftTimerRunning.value = false
				stopLeftTimer()
			} catch (error) {
				console.error('停止左侧计时失败:', error)
				uni.showToast({
					title: '停止计时失败',
					icon: 'none'
				})
			}
		}
	} else if (side === 'right') {
		// 右侧计时逻辑
		if (!isRightTimerRunning.value) {
			// 开始右侧计时
			try {
				const response = await feedingTimerStart({
					babyId: babyId,
					side: 'right'
				})
				console.log('开始右侧计时成功:', response)
				isRightTimerRunning.value = true
				startRightTimer()
			} catch (error) {
				console.error('开始右侧计时失败:', error)
				uni.showToast({
					title: '开始计时失败',
					icon: 'none'
				})
			}
		} else {
			// 停止右侧计时
			try {
				const response = await feedingTimerStop({
					babyId: babyId,
					side: 'right'
				})
				console.log('停止右侧计时成功:', response)
				isRightTimerRunning.value = false
				stopRightTimer()
			} catch (error) {
				console.error('停止右侧计时失败:', error)
				uni.showToast({
					title: '停止计时失败',
					icon: 'none'
				})
			}
		}
	}
}

function startLeftTimer() {
	// 开始左侧计时
	console.log('开始左侧计时')
	// 如果已经有计时器在运行，先停止
	if (leftTimerInterval) {
		clearInterval(leftTimerInterval)
	}
	leftTimerInterval = setInterval(() => {
		timerData.value.leftDuration++
	}, 1000) // 每秒增加1秒
}

function stopLeftTimer() {
	// 停止左侧计时
	console.log('停止左侧计时')
	if (leftTimerInterval) {
		clearInterval(leftTimerInterval)
		leftTimerInterval = null
	}
}

function startRightTimer() {
	// 开始右侧计时
	console.log('开始右侧计时')
	// 如果已经有计时器在运行，先停止
	if (rightTimerInterval) {
		clearInterval(rightTimerInterval)
	}
	rightTimerInterval = setInterval(() => {
		timerData.value.rightDuration++
	}, 1000) // 每秒增加1秒
}

function stopRightTimer() {
	// 停止右侧计时
	console.log('停止右侧计时')
	if (rightTimerInterval) {
		clearInterval(rightTimerInterval)
		rightTimerInterval = null
	}
}

// 完成记录
async function completeRecord() {
	// 防止重复提交
	if (isSubmitting.value) {
		return
	}

	// 检查当前是否为语音模式（辅食除外）
	const currentMethod = recordMethods.value[selectedType.value]
	if (currentMethod === 'voice' && selectedType.value !== 'food') {
		// 语音模式应该在语音识别结果中确认提交，这里不处理
		uni.showToast({
			title: '请在语音识别结果中确认提交',
			icon: 'none'
		})
		return
	}

	try {
		isSubmitting.value = true

		// 验证数据
		const validationResult = validateRecordData()
		if (!validationResult.valid) {
			uni.showToast({
				title: validationResult.message,
				icon: 'none'
			})
			return
		}

		// 显示加载提示
		uni.showLoading({
			title: '保存中...'
		})

		// 构建记录数据
		const recordData = buildRecordData()
		console.log('提交记录数据:', recordData)

		// 调用接口保存记录
		const response = await feedingRecords(recordData)
		console.log('保存记录成功:', response)

		// 隐藏加载提示
		uni.hideLoading()

		// 刷新 home 数据
		await loadHomeData()

		// 清空喂养数据
		clearFeedingData()

		// 显示成功提示
		uni.showToast({
			title: currentRecordId.value ? '修改成功' : '记录成功',
			icon: 'success'
		})

		// 返回上一页
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)

	} catch (error) {
		console.error('保存记录失败:', error)
		uni.hideLoading()
		uni.showToast({
			title: '保存失败',
			icon: 'none'
		})
	} finally {
		// 添加2秒防连点
		setTimeout(() => {
			isSubmitting.value = false
		}, 2000)
	}
}

// 验证记录数据
function validateRecordData() {
	const currentBaby = feedStore.getCurrentBaby()

	// 验证宝宝信息
	if (!currentBaby || !currentBaby.id) {
		return { valid: false, message: '请选择宝宝' }
	}

	// 验证喂养时间
	if (!currentTime.value) {
		return { valid: false, message: '请选择喂养时间' }
	}

	// 根据喂养类型和记录方式验证具体数据
	switch (selectedType.value) {
		case 'breastfeeding':
			const currentMethod = recordMethods.value.breastfeeding

			if (currentMethod === 'manual') {
				// 手动模式：验证左右侧时长
				const leftDuration = feedingData.value.breastfeeding.leftDuration
				const rightDuration = feedingData.value.breastfeeding.rightDuration
				if (leftDuration === 0 && rightDuration === 0) {
					return { valid: false, message: '请设置喂养时长' }
				}
			} else if (currentMethod === 'timer') {
				// 计时器模式：验证计时器状态
				const leftDuration = timerData.value.leftDuration
				const rightDuration = timerData.value.rightDuration
				if (leftDuration === 0 && rightDuration === 0) {
					return { valid: false, message: '请先启动计时器' }
				}
			} else if (currentMethod === 'voice') {
				// 语音模式：验证语音识别结果
				if (!voiceRecognitionState.value.recognizedText.trim()) {
					return { valid: false, message: '请先进行语音识别' }
				}
			}
			break

		case 'bottle':
		case 'formula':
			const currentMethod2 = recordMethods.value[selectedType.value]

			if (currentMethod2 === 'manual') {
				// 手动模式：验证喂养量
				const amount = feedingData.value[selectedType.value].amount
				if (amount === 0) {
					return { valid: false, message: '请设置喂养量' }
				}
			} else if (currentMethod2 === 'voice') {
				// 语音模式：验证语音识别结果
				if (!voiceRecognitionState.value.recognizedText.trim()) {
					return { valid: false, message: '请先进行语音识别' }
				}
			}
			break

		case 'food':
			// 辅食只有手动选择模式
			const selectedItems = feedingData.value.food.selectedItems
			if (selectedItems.length === 0) {
				return { valid: false, message: '请选择辅食' }
			}
			break
	}

	return { valid: true }
}

// 构建记录数据
function buildRecordData() {
	const currentBaby = feedStore.getCurrentBaby()
	const recordTime = formatCurrentTime()

	// 基础数据
	const baseData = {
		recordId: currentRecordId.value, // 修改时传入记录ID，新增时为null
		babyId: currentBaby.id,
		recordTime: recordTime
	}

	// 根据喂养类型和记录方式构建具体数据
	switch (selectedType.value) {
		case 'breastfeeding':
			const currentMethod = recordMethods.value.breastfeeding

			if (currentMethod === 'manual') {
				// 手动模式：使用手动设置的时长
				return {
					...baseData,
					feedingType: 1, // 母乳亲喂
					durationLeftSeconds: feedingData.value.breastfeeding.leftDuration * 60, // 转换为秒
					durationRightSeconds: feedingData.value.breastfeeding.rightDuration * 60,
					totalDurationSeconds: (feedingData.value.breastfeeding.leftDuration + feedingData.value.breastfeeding.rightDuration) * 60
				}
			} else if (currentMethod === 'timer') {
				// 计时器模式：使用计时器的实际时长
				return {
					...baseData,
					feedingType: 1, // 母乳亲喂
					durationLeftSeconds: timerData.value.leftDuration,
					durationRightSeconds: timerData.value.rightDuration,
					totalDurationSeconds: timerData.value.leftDuration + timerData.value.rightDuration
				}
			} else if (currentMethod === 'voice') {
				// 语音模式：使用语音识别的结果
				return {
					...baseData,
					feedingType: 1, // 母乳亲喂
					foodDetails: voiceRecognitionState.value.recognizedText.trim() // 语音识别的详情作为备注
				}
			}
			break

		case 'bottle':
			const currentMethod2 = recordMethods.value.bottle

			if (currentMethod2 === 'manual') {
				// 手动模式：使用手动设置的喂养量
				return {
					...baseData,
					feedingType: 2, // 母乳瓶喂
					volume: feedingData.value.bottle.amount
				}
			} else if (currentMethod2 === 'voice') {
				// 语音模式：使用语音识别的结果
				return {
					...baseData,
					feedingType: 2, // 母乳瓶喂
					foodDetails: voiceRecognitionState.value.recognizedText.trim()
				}
			}
			break

		case 'formula':
			const currentMethod3 = recordMethods.value.formula

			if (currentMethod3 === 'manual') {
				// 手动模式：使用手动设置的喂养量
				return {
					...baseData,
					feedingType: 3, // 奶粉喂养
					volume: feedingData.value.formula.amount
				}
			} else if (currentMethod3 === 'voice') {
				// 语音模式：使用语音识别的结果
				return {
					...baseData,
					feedingType: 3, // 奶粉喂养
					foodDetails: voiceRecognitionState.value.recognizedText.trim()
				}
			}
			break

		case 'food':
			// 辅食只有手动选择模式
			return {
				...baseData,
				feedingType: 4, // 辅食
				foodDetails: feedingData.value.food.selectedItems.join(',')
			}
	}

	return baseData
}

function goBack() {
	uni.navigateBack()
}

function goToFeedingRecord() {
	uni.navigateTo({
		url: '/pages/feedingRecord/feedingRecord'
	})
}

// 时间选择器相关方法
function onTimeChange(value) {
	currentTime.value = value
}

function formatCurrentTime() {
	if (!currentTime.value) {
		// 如果当前时间未设置，返回当前时间
		const now = new Date()
		const year = now.getFullYear()
		const month = String(now.getMonth() + 1).padStart(2, '0')
		const day = String(now.getDate()).padStart(2, '0')
		const hours = String(now.getHours()).padStart(2, '0')
		const minutes = String(now.getMinutes()).padStart(2, '0')
		return `${year}-${month}-${day} ${hours}:${minutes}`
	}

	const date = new Date(currentTime.value)
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')
	return `${year}-${month}-${day} ${hours}:${minutes}`
}

function getTabImage() {
	const currentMethod = recordMethods.value[selectedType.value]
	if (currentMethod === 'manual') {
		return '/static/feedingIndex/v1/Tab_bottom_write.png'
	} else if (currentMethod === 'timer') {
		return '/static/feedingIndex/v1/Tab_bottom_timer.png'
	} else {
		return '/static/feedingIndex/v1/Tab_bottom_voice.png'
	}
}

function getTabImage2() {
	const currentMethod = recordMethods.value[selectedType.value]
	if (currentMethod === 'manual') {
		return '/static/feedingIndex/v1/Tab_bottom_muruandnaifen_write.png'
	} else {
		return '/static/feedingIndex/v1/Tab_bottom_muruandnaifen_voice.png'
	}
}

// 格式化时间显示 (MM:SS)
function formatTime(seconds) {
	const minutes = Math.floor(seconds / 60)
	const remainingSeconds = seconds % 60
	return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 格式化总时长显示 (HH:MM:SS)
function formatTotalDuration() {
	const totalSeconds = timerData.value.leftDuration + timerData.value.rightDuration
	const hours = Math.floor(totalSeconds / 3600)
	const minutes = Math.floor((totalSeconds % 3600) / 60)
	const seconds = totalSeconds % 60
	return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 辅食选择相关方法
function toggleFoodSelection(item) {
	// 在编辑模式时不允许选择
	if (foodSelectionState.value.isEditMode) {
		return
	}

	const selectedItems = feedingData.value.food.selectedItems
	const index = selectedItems.indexOf(item)

	if (index > -1) {
		// 如果已选中，则取消选中
		selectedItems.splice(index, 1)
	} else {
		// 如果未选中，则添加选中
		selectedItems.push(item)
	}
}

function enterEditMode() {
	if (foodSelectionState.value.isEditMode) {
		// 如果已经在编辑模式，则取消编辑
		cancelEditMode()
	} else {
		// 进入编辑模式
		foodSelectionState.value.isEditMode = true
		// 清空待删除列表
		foodSelectionState.value.pendingDeletes = []
	}
}

function cancelEditMode() {
	// 恢复被删除的辅食到UI中
	foodSelectionState.value.pendingDeletes.forEach(item => {
		const category = foodCategories.value[item.categoryName]
		if (category) {
			// 检查是否已存在，避免重复添加
			if (!category.items.includes(item.foodName) && !category.customItems.includes(item.foodName)) {
				category.items.push(item.foodName)
			}
		}
	})

	// 清空待删除列表
	foodSelectionState.value.pendingDeletes = []
	// 退出编辑模式
	foodSelectionState.value.isEditMode = false
}

async function exitEditMode() {
	// 如果有待删除的辅食，调用接口删除
	if (foodSelectionState.value.pendingDeletes.length > 0) {
		try {
			// 获取所有待删除的foodId
			const foodIds = foodSelectionState.value.pendingDeletes.map(item => item.foodId).join(',')

			// 调用接口删除辅食
			const response = await feedingFoodsCustomDelete({
				foodIds: foodIds
			})

			console.log('批量删除辅食成功:', response)

			// 清空待删除列表
			foodSelectionState.value.pendingDeletes = []

			// 重新加载辅食列表
			await loadFoodsData()

			uni.showToast({
				title: '删除成功',
				icon: 'success'
			})

		} catch (error) {
			console.error('批量删除辅食失败:', error)
			uni.showToast({
				title: '删除失败',
				icon: 'none'
			})
		}
	}

	// 退出编辑模式
	foodSelectionState.value.isEditMode = false
}

function showAddFoodPopup(categoryName) {
	// 在编辑模式下不允许添加
	if (foodSelectionState.value.isEditMode) {
		uni.showToast({
			title: '编辑模式下不能添加辅食',
			icon: 'none'
		})
		return
	}

	foodSelectionState.value.currentCategory = categoryName
	foodSelectionState.value.newFoodItem = ''
	// 显示弹窗
	addFoodPopup.value.open()
}

// 切换分类展开/缩起状态
function toggleCategoryExpansion(categoryName) {
	const category = foodCategories.value[categoryName]
	if (category) {
		category.expanded = !category.expanded
	}
}

function cancelAddFood() {
	addFoodPopup.value.close()
	foodSelectionState.value.newFoodItem = ''
}

function confirmAddFood() {
	const itemName = foodSelectionState.value.newFoodItem.trim()
	const categoryName = foodSelectionState.value.currentCategory

	if (!itemName) {
		uni.showToast({
			title: '请输入辅食名称',
			icon: 'none'
		})
		return
	}

	addCustomFoodItem(categoryName, itemName)
	addFoodPopup.value.close()
}

async function addCustomFoodItem(categoryName, itemName) {
	// 检查字数限制
	if (itemName.length > 10) {
		uni.showToast({
			title: '辅食名称不能超过10个字',
			icon: 'none'
		})
		return
	}

	// 检查分类下的自定义辅食数量限制
	const category = foodCategories.value[categoryName]
	if (category.customItems.length >= 20) {
		uni.showToast({
			title: '该分类下最多可添加20个自定义辅食',
			icon: 'none'
		})
		return
	}

	// 检查是否已存在
	if (category.items.includes(itemName) || category.customItems.includes(itemName)) {
		uni.showToast({
			title: '该辅食已存在',
			icon: 'none'
		})
		return
	}

	try {
		// 获取辅食类型ID
		const foodTypeId = Object.keys(foodTypeMap).find(key => foodTypeMap[key] === categoryName)

		if (!foodTypeId) {
			uni.showToast({
				title: '辅食类型错误',
				icon: 'none'
			})
			return
		}

		// 调用接口添加自定义辅食
		const response = await feedingFoodsCustomAdd({
			foodName: itemName,
			foodType: parseInt(foodTypeId)
		})

		console.log('添加自定义辅食成功:', response)

		// 重新加载辅食列表
		await loadFoodsData()

		uni.showToast({
			title: '添加成功',
			icon: 'success'
		})

	} catch (error) {
		console.error('添加自定义辅食失败:', error)
		uni.showToast({
			title: '添加失败',
			icon: 'none'
		})
	}
}

function removeFoodItem(categoryName, itemName) {
	// 获取foodId
	const foodId = foodIdMap.value.get(itemName)

	if (!foodId) {
		uni.showToast({
			title: '找不到辅食ID',
			icon: 'none'
		})
		return
	}

	// 添加到待删除列表
	foodSelectionState.value.pendingDeletes.push({
		foodId: foodId,
		foodName: itemName,
		categoryName: categoryName
	})

	// 从UI中移除（但不调用接口）
	const category = foodCategories.value[categoryName]

	// 从默认辅食中移除
	const defaultIndex = category.items.indexOf(itemName)
	if (defaultIndex > -1) {
		category.items.splice(defaultIndex, 1)
	}

	// 从自定义辅食中移除
	const customIndex = category.customItems.indexOf(itemName)
	if (customIndex > -1) {
		category.customItems.splice(customIndex, 1)
	}

	// 从已选择的辅食中移除
	const selectedIndex = feedingData.value.food.selectedItems.indexOf(itemName)
	if (selectedIndex > -1) {
		feedingData.value.food.selectedItems.splice(selectedIndex, 1)
	}

	console.log('添加到待删除列表:', itemName, '当前待删除:', foodSelectionState.value.pendingDeletes)
}

// 语音识别相关方法
function checkVoicePermission() {
	// 检查录音权限
	uni.getSetting({
		success: (res) => {
			console.log('录音权限检查结果:', res.authSetting)

			if (!res.authSetting['scope.record']) {
				// 没有录音权限，请求授权
				console.log('请求录音权限...')
				uni.authorize({
					scope: 'scope.record',
					success: () => {
						console.log('录音权限授权成功')
					},
					fail: (err) => {
						console.error('录音权限授权失败:', err)
						// 用户拒绝授权
						uni.showModal({
							title: '需要录音权限',
							content: '为了使用语音识别功能，需要获取录音权限。请在设置中开启录音权限。',
							confirmText: '去设置',
							cancelText: '取消',
							success: (modalRes) => {
								if (modalRes.confirm) {
									// 打开设置页面
									uni.openSetting({
										success: (settingRes) => {
											console.log('设置页面结果:', settingRes)
											if (settingRes.authSetting['scope.record']) {
												console.log('录音权限已开启')
											}
										},
										fail: (err) => {
											console.error('打开设置页面失败:', err)
										}
									})
								}
							}
						})
					}
				})
			} else {
				console.log('已有录音权限')
			}
		},
		fail: (err) => {
			console.error('检查录音权限失败:', err)
			uni.showToast({
				title: '录音权限检查失败',
				icon: 'none'
			})
		}
	})
}

function startRecording() {
	// 再次检查录音权限
	uni.getSetting({
		success: (res) => {
			if (!res.authSetting['scope.record']) {
				uni.showToast({
					title: '请先授权录音权限',
					icon: 'none'
				})
				return
			}

			// 清理之前的录音定时器
			if (voiceRecognitionState.value.recordingTimer) {
				clearInterval(voiceRecognitionState.value.recordingTimer)
				voiceRecognitionState.value.recordingTimer = null
			}

			// 重置录音状态
			voiceRecognitionState.value.isRecording = true
			voiceRecognitionState.value.recordingDuration = 0
			voiceRecognitionState.value.recordingStartTime = null

			console.log('开始录音...')

			// 开始录音
			uni.startRecord({
				success: (res) => {
					console.log('开始录音成功', res)
					// 记录录音开始时间
					voiceRecognitionState.value.recordingStartTime = Date.now()

					// 启动录音时长定时器
					voiceRecognitionState.value.recordingTimer = setInterval(() => {
						if (voiceRecognitionState.value.isRecording && voiceRecognitionState.value.recordingStartTime) {
							const duration = Math.floor((Date.now() - voiceRecognitionState.value.recordingStartTime) / 1000)
							voiceRecognitionState.value.recordingDuration = duration
						}
					}, 1000) // 每秒更新一次
				},
				fail: (err) => {
					console.error('开始录音失败', err)
					voiceRecognitionState.value.isRecording = false
					uni.showToast({
						title: '录音失败',
						icon: 'none'
					})
				}
			})
		},
		fail: (err) => {
			console.error('检查录音权限失败', err)
			uni.showToast({
				title: '录音权限检查失败',
				icon: 'none'
			})
		}
	})
}

async function stopRecording() {
	if (!voiceRecognitionState.value.isRecording) return

	console.log('停止录音...')
	voiceRecognitionState.value.isRecording = false

	// 清理录音定时器
	if (voiceRecognitionState.value.recordingTimer) {
		clearInterval(voiceRecognitionState.value.recordingTimer)
		voiceRecognitionState.value.recordingTimer = null
	}

	// 计算录音时长
	if (voiceRecognitionState.value.recordingStartTime) {
		const duration = Math.floor((Date.now() - voiceRecognitionState.value.recordingStartTime) / 1000)
		voiceRecognitionState.value.recordingDuration = duration
		console.log('录音时长:', duration, '秒')

		// 检查录音时长是否太短
		if (duration < 1) {
			uni.showToast({
				title: '录音时间太短，请重新录音',
				icon: 'none'
			})
			return
		}

		// 检查录音时长是否太长
		if (duration > 60) {
			uni.showToast({
				title: '录音时间太长，请重新录音',
				icon: 'none'
			})
			return
		}
	}

	// 停止录音并上传
	uni.stopRecord({
		success: async (res) => {
			console.log('录音完成，返回结果:', res)

			// 检查录音文件路径 - 不同平台可能返回不同的字段名
			const tempFilePath = res.tempFilePath || res.tempFilePaths?.[0] || res.filePath
			if (!tempFilePath) {
				console.error('录音文件路径不存在，完整返回结果:', res)
				uni.hideLoading()
				uni.showToast({
					title: '录音文件获取失败',
					icon: 'none'
				})
				return
			}

			console.log('获取到录音文件路径:', tempFilePath)

			try {
				// 显示加载提示
				uni.showLoading({
					title: '正在识别...'
				})

				// 上传语音文件
				const uploadResponse = await uploadVoiceFile(tempFilePath)
				console.log('语音上传成功:', uploadResponse)

				// 开始轮询识别结果
				await startPollingRecognitionResult(uploadResponse.taskId)

			} catch (error) {
				handleVoiceRecognitionError(error)
			}
		},
		fail: (err) => {
			console.error('停止录音失败', err)
			uni.showToast({
				title: '录音失败',
				icon: 'none'
			})
		}
	})
}

// 上传语音文件
async function uploadVoiceFile(tempFilePath) {
	return new Promise((resolve, reject) => {
		// 检查文件路径
		if (!tempFilePath || typeof tempFilePath !== 'string') {
			reject(new Error('无效的语音文件路径'))
			return
		}

		console.log('开始读取语音文件:', tempFilePath)

		// 先获取文件信息
		uni.getFileSystemManager().getFileInfo({
			filePath: tempFilePath,
			success: (fileInfo) => {
				console.log('文件信息:', fileInfo)

				// 检查文件大小（限制为10MB）
				if (fileInfo.size > 10 * 1024 * 1024) {
					reject(new Error('语音文件过大，请重新录音'))
					return
				}

				// 读取文件为base64
				uni.getFileSystemManager().readFile({
					filePath: tempFilePath,
					encoding: 'base64',
					success: async (res) => {
						try {
							console.log('语音文件读取成功，开始上传')

							// 调用上传接口
							const response = await feedingVoiceUpload({
								audioData: res.data
							})

							if (response && response.data && response.data.taskId) {
								resolve(response.data)
							} else {
								reject(new Error('上传失败：未获取到taskId'))
							}
						} catch (error) {
							reject(error)
						}
					},
					fail: (err) => {
						console.error('读取语音文件失败:', err)
						reject(new Error('读取语音文件失败：' + err.errMsg))
					}
				})
			},
			fail: (err) => {
				console.error('获取文件信息失败:', err)
				reject(new Error('获取文件信息失败：' + err.errMsg))
			}
		})
	})
}

// 开始轮询识别结果
async function startPollingRecognitionResult(taskId) {
	voiceRecognitionState.value.taskId = taskId
	voiceRecognitionState.value.isPolling = true

	// 设置轮询间隔（每2秒查询一次）
	voiceRecognitionState.value.pollingInterval = setInterval(async () => {
		try {
			const response = await feedingVoiceResult({
				taskId: taskId
			})

			console.log('轮询识别结果:', response)

			if (response && response.data) {
				const result = response.data

				// 检查识别状态
				if (result.status === 'completed') {
					// 识别完成
					clearPollingInterval()
					uni.hideLoading()

					// 显示识别结果
					voiceRecognitionState.value.recognizedText = result.text || '未能识别语音内容'
					voiceRecognitionState.value.showResultPage = true

				} else if (result.status === 'failed') {
					// 识别失败
					clearPollingInterval()
					uni.hideLoading()
					uni.showToast({
						title: '语音识别失败',
						icon: 'none'
					})
				}
				// 如果status是'processing'，继续轮询
			}
		} catch (error) {
			console.error('轮询识别结果失败:', error)
			// 轮询失败时继续尝试，不中断轮询
			// 但如果连续失败次数过多，可以考虑停止轮询
		}
	}, 2000) // 每2秒轮询一次

	// 设置最大轮询时间（30秒后停止）
	setTimeout(() => {
		if (voiceRecognitionState.value.isPolling) {
			clearPollingInterval()
			uni.hideLoading()
			uni.showToast({
				title: '识别超时，请重试',
				icon: 'none'
			})
		}
	}, 30000)
}

// 清理轮询定时器
function clearPollingInterval() {
	if (voiceRecognitionState.value.pollingInterval) {
		clearInterval(voiceRecognitionState.value.pollingInterval)
		voiceRecognitionState.value.pollingInterval = null
	}
	voiceRecognitionState.value.isPolling = false

	// 同时清理录音定时器
	if (voiceRecognitionState.value.recordingTimer) {
		clearInterval(voiceRecognitionState.value.recordingTimer)
		voiceRecognitionState.value.recordingTimer = null
	}
}

// 处理语音识别错误
function handleVoiceRecognitionError(error) {
	console.error('语音识别错误:', error)
	clearPollingInterval()
	uni.hideLoading()

	// 清理录音定时器
	if (voiceRecognitionState.value.recordingTimer) {
		clearInterval(voiceRecognitionState.value.recordingTimer)
		voiceRecognitionState.value.recordingTimer = null
	}

	// 根据错误类型显示不同的提示
	let errorMessage = '语音识别失败，请重试'

	if (error.message) {
		if (error.message.includes('无效的语音文件路径')) {
			errorMessage = '录音文件获取失败，请重试'
		} else if (error.message.includes('读取语音文件失败')) {
			errorMessage = '录音文件读取失败，请重试'
		} else if (error.message.includes('上传失败')) {
			errorMessage = '语音上传失败，请重试'
		} else if (error.message.includes('语音文件过大')) {
			errorMessage = '录音文件过大，请重新录音'
		} else if (error.message.includes('获取文件信息失败')) {
			errorMessage = '录音文件信息获取失败，请重试'
		}
	}

	uni.showToast({
		title: errorMessage,
		icon: 'none'
	})
}

function getFeedingTypeLabel() {
	const typeMap = {
		breastfeeding: '母乳亲喂',
		bottle: '母乳瓶喂',
		formula: '奶粉喂养',
		food: '辅食'
	}
	return typeMap[selectedType.value] || '未知'
}

// 格式化录音时长显示
function formatRecordingDuration(seconds) {
	if (!seconds || seconds <= 0) return '0秒'

	const minutes = Math.floor(seconds / 60)
	const remainingSeconds = seconds % 60

	if (minutes > 0) {
		return `${minutes}分${remainingSeconds}秒`
	} else {
		return `${remainingSeconds}秒`
	}
}

function reRecognize() {
	// 清理轮询状态
	clearPollingInterval()

	// 清理录音定时器
	if (voiceRecognitionState.value.recordingTimer) {
		clearInterval(voiceRecognitionState.value.recordingTimer)
		voiceRecognitionState.value.recordingTimer = null
	}

	// 重置识别状态
	voiceRecognitionState.value.showResultPage = false
	voiceRecognitionState.value.recognizedText = ''
	voiceRecognitionState.value.taskId = ''
	voiceRecognitionState.value.recordingStartTime = null
	voiceRecognitionState.value.recordingDuration = 0
}

async function completeVoiceRecord() {
	// 防止重复提交
	if (isSubmitting.value) {
		return
	}

	const detailText = voiceRecognitionState.value.recognizedText.trim()

	if (!detailText) {
		uni.showToast({
			title: '还没有输入喂养信息哦～',
			icon: 'none'
		})
		return
	}

	try {
		isSubmitting.value = true

		// 显示加载提示
		uni.showLoading({
			title: '保存中...'
		})

		// 构建记录数据（使用统一的构建函数）
		const recordData = buildRecordData()
		console.log('提交语音记录数据:', recordData)

		// 调用接口保存记录
		const response = await feedingRecords(recordData)
		console.log('保存语音记录成功:', response)

		// 隐藏加载提示
		uni.hideLoading()

		// 刷新 home 数据
		await loadHomeData()

		// 清空喂养数据
		clearFeedingData()

		// 关闭结果页面
		voiceRecognitionState.value.showResultPage = false
		voiceRecognitionState.value.recognizedText = ''
		voiceRecognitionState.value.taskId = ''
		voiceRecognitionState.value.recordingStartTime = null
		voiceRecognitionState.value.recordingDuration = 0

		// 清理录音定时器
		if (voiceRecognitionState.value.recordingTimer) {
			clearInterval(voiceRecognitionState.value.recordingTimer)
			voiceRecognitionState.value.recordingTimer = null
		}

		// 显示成功提示
		uni.showToast({
			title: currentRecordId.value ? '修改成功' : '记录成功',
			icon: 'success'
		})

		// 返回上一页
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)

	} catch (error) {
		console.error('保存语音记录失败:', error)
		uni.hideLoading()
		uni.showToast({
			title: '保存失败',
			icon: 'none'
		})
	} finally {
		// 添加2秒防连点
		setTimeout(() => {
			isSubmitting.value = false
		}, 2000)
	}
}



// 宝宝切换相关方法
function showBabySwitch() {
	showBabySwitchPopup.value = true
}

function onBabyChange(baby, index) {
	feedStore.switchBaby(index)
	console.log('切换到宝宝:', baby.name, '索引:', index)

	// 切换宝宝后重新加载该宝宝的喂养数据
	loadHomeData()

	// 清空当前状态，避免数据混乱
	clearPreviousState()
}

// 获取辅食列表数据
async function loadFoodsData() {
	try {
		const response = await feedingFoodsCustom()
		console.log('辅食列表数据:', response)

		if (response && response.data) {
			const foodsList = response.data
			processFoodsData(foodsList)
		} else {
			// 如果没有数据，使用默认数据
			loadDefaultFoodsData()
		}

	} catch (error) {
		console.error('获取辅食列表失败:', error)
		// 使用默认数据作为fallback
		loadDefaultFoodsData()
	}
}

// 处理辅食数据
function processFoodsData(foodsList) {
	// 清空现有数据
	Object.keys(foodCategories.value).forEach(category => {
		foodCategories.value[category].items = []
		foodCategories.value[category].customItems = []
		// 保持展开状态
		foodCategories.value[category].expanded = foodCategories.value[category].expanded || false
	})

	// 清空ID映射
	foodIdMap.value.clear()

	// 按类型分组辅食
	foodsList.forEach(food => {
		const categoryName = foodTypeMap[food.foodType]
		if (categoryName && foodCategories.value[categoryName]) {
			foodCategories.value[categoryName].items.push(food.foodName)
			// 保存foodId映射
			foodIdMap.value.set(food.foodName, food.foodId)
		}
	})

	console.log('处理后的辅食数据:', foodCategories.value)
	console.log('辅食ID映射:', foodIdMap.value)
}

// 加载默认辅食数据（fallback）
function loadDefaultFoodsData() {
	foodCategories.value = {
		主食: {
			items: ['米粉', '面条', '馒头', '包子', '粥'],
			customItems: [],
			expanded: false
		},
		蔬菜: {
			items: ['山药', '萝卜', '土豆', '豆', '青瓜', '白菜', '胡萝卜', '南瓜'],
			customItems: [],
			expanded: false
		},
		水果: {
			items: ['香蕉', '苹果', '牛油果', '橙子', '梨'],
			customItems: [],
			expanded: false
		},
		其他: {
			items: ['鱼油', '维生素'],
			customItems: [],
			expanded: false
		}
	}
}


</script>

<style lang="scss" scoped>
/* ===== 页面整体布局 ===== */
.feeding-record-add-page {
	background: #FFF8F1;
	min-height: 100vh;
	padding: 0;
	position: relative;
}

/* ===== 可滚动内容区域 ===== */
.scrollable-content {
	height: calc(100vh);
	/* 减去底部按钮的高度 */
	overflow-y: auto;
}

/* ===== 底部完成按钮 ===== */
.bottom_complete-btn {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 120rpx;
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;

	.complete-btn-bg {
		width: 100%;
		height: 100%;
	}

	&.disabled {
		opacity: 0.6;
		pointer-events: none;
	}
}

/* ===== 广告横幅 ===== */
.banner-swiper {
	position: absolute;
	top: 0;
	left: 16rpx;
	width: 718rpx;
	height: 174rpx;

	.banner-img {
		width: 100%;
		height: 100%;
		border-radius: 16rpx;
	}
}

/* ===== 喂养时间区域 ===== */
.feeding-time {
	position: absolute;
	top: 174rpx;
	left: 0;
	right: 0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx 5rpx 30rpx;
	background: #FFF8F1;

	.baby-info {
		display: flex;
		align-items: center;
		gap: 15rpx;
		cursor: pointer;
		transition: opacity 0.3s ease;

		&:active {
			opacity: 0.7;
		}

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

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

			.baby-name {
				font-size: 28rpx;
				color: #1d1e25;
				font-weight: 500;
			}

			.dropdown-icon {
				width: 18rpx;
				height: 12rpx;
			}
		}
	}

	.time-section {
		display: flex;
		align-items: center;

		.time-label {
			font-size: 28rpx;
			color: #6f6d67;
			margin-right: 15rpx;
		}

		.time-display {
			display: flex;
			align-items: center;
			cursor: pointer;
		}

		.time-value {
			font-size: 28rpx;
			color: #1d1e25;
			margin-right: 5rpx;
			font-weight: bold;
		}

		.edit-icon {
			width: 61rpx;
			height: 61rpx;
			margin-top: 10rpx;
		}
	}
}

/* ===== 喂养记录链接 ===== */
.feeding-records {
	position: absolute;
	top: 280rpx;
	left: 0;
	right: 0;
	display: flex;
	align-items: center;
	justify-content: flex-end;
	padding: 0rpx 30rpx 20rpx 30rpx;
	background: #FFF8F1;

	.records-link {
		font-size: 28rpx;
		color: #b27c1e;
		margin-right: 5rpx;
	}

	.arrow-right {
		width: 11rpx;
		height: 19rpx;
	}
}



/* ===== 喂养类型选择 ===== */
.feeding-types {
	position: absolute;
	top: 340rpx;
	left: 0;
	right: 0;
	display: flex;
	justify-content: space-between;
	padding: 0rpx 30rpx;
	gap: 15rpx;

	.type-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 8rpx;
		padding: 15rpx 10rpx;
		border-radius: 12rpx;
		background: transparent;
		transition: all 0.3s ease;

		.icon-bg {
			width: 228rpx;
			height: 144rpx;

			position: absolute;
		}

		.type-icon-wrapper {
			position: relative;
			width: 80rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;



			.type-icon {
				width: 48rpx;
				height: 48rpx;
				position: relative;
			}
		}

		.type-label {
			font-size: 26rpx;
			color: #6f6d67;
			font-weight: 500;
			z-index: 2;
		}

		&.active {
			.type-label {
				color: #1d1e25;
				font-weight: 800;
			}
		}
	}
}

/* ===== 温馨提示 ===== */
.warm-tip {
	position: absolute;
	top: 20rpx;
	left: 0;
	right: 0;
	text-align: center;
	padding: 20rpx 30rpx;
	z-index: 2;

	text {
		font-size: 24rpx;
		color: #000;
	}
}

/* ===== 表单区域 ===== */
.form-section {
	position: absolute;
	top: 80rpx;
	left: 0;
	right: 0;
	padding: 30rpx;
	// margin-top: 30rpx;
	// height: 300rpx;
	z-index: 2;
}

/* ===== 母乳亲喂表单 ===== */
.breastfeeding-form {

	.duration-controls {
		display: flex;
		justify-content: space-around;
		gap: 40rpx;
		padding: 30rpx;
		margin-top: 30rpx;

		.duration-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 20rpx;
			position: relative;

			.duration-circle {
				width: 278rpx;
				height: 278rpx;
				position: relative;
				display: flex;
				align-items: center;
				justify-content: center;

				.circle-bg {
					position: absolute;
					width: 100%;
					height: 100%;
				}

				.circle-content {
					position: relative;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;

					.duration-number {
						font-size: 48rpx;
						color: #333;
						font-weight: bold;
					}

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

			.duration-buttons {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				display: flex;
				justify-content: space-between;
				align-items: center;
				pointer-events: none;

				.btn-minus,
				.btn-plus {
					width: 78rpx;
					height: 180rpx;
					margin-top: -45rpx;
					pointer-events: auto;

					&.disabled {
						pointer-events: none;
					}
				}
			}

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

/* ===== 母乳瓶喂/奶粉喂养表单 ===== */
.bottle-form {
	.bottle-graphic {
		width: 100%;
		height: 574rpx;
		margin-top: -90rpx;

		.amount-bubble {
			position: absolute;
			left: 50rpx;
			top: 200rpx;
			text-align: center;
			width: 200rpx;
			height: 120rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			&::before {
				content: '';
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background-image: url('/static/feedingIndex/v1/icon_left_arrow_tip.png');
				background-size: contain;
				background-repeat: no-repeat;
				background-position: center;
				z-index: -1;
			}

			.bubble-label {
				display: block;
				font-size: 24rpx;
				color: #333;
				margin-bottom: 10rpx;
				position: relative;
				z-index: 1;
			}

			.bubble-value {
				display: block;
				font-size: 36rpx;
				color: #333;
				font-weight: bold;
				position: relative;
				z-index: 1;
			}
		}

		.bottle-container {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			width: 408rpx;
			height: 574rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.bottle-image {
				width: 408rpx;
				height: 574rpx;
				position: relative;
				z-index: 1;
			}

			.amount-picker {
				margin-top: 40rpx;
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
				width: 180rpx;
				height: 300rpx;
				z-index: 2;
				mask: none;
				-webkit-mask: none;

				:deep(.amount-picker::before) {
					content: none;
				}

				:deep(.amount-picker::after) {
					content: none;
				}


				.picker-item {
					height: 60rpx;
					line-height: 60rpx;
					text-align: center;
					font-size: 36rpx;
					color: #b27c1e;
					font-weight: normal;
					transition: all 0.3s ease;
					opacity: 0.6;
					transform: scale(0.9);
				}

				.picker-item.active {
					opacity: 1;
					transform: scale(1);
					font-weight: bold;
					color: #b27c1e;
					font-size: 50rpx;
				}
			}
		}

	}
}

/* ===== 辅食表单 ===== */
.food-form {
	margin-top: -80rpx;

	.selected-items {
		background: white;
		padding: 20rpx;
		border-radius: 20rpx;
		margin-bottom: 30rpx;

		text {
			font-size: 28rpx;
			color: #333;
			font-weight: bold;
		}
	}

	.divider {
		height: 1rpx;
		background: #E0E0E0;
		margin: 20rpx 0;
	}

	.food-categories {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding: 0 20rpx;

		.category-title {
			font-size: 28rpx;
			color: #1d1e25;
			font-weight: bold;
		}

		.category-actions {
			display: flex;
			gap: 20rpx;

			.complete-btn {
				font-size: 26rpx;
				color: #6f6d67;
				cursor: pointer;
			}

			.delete-btn {
				display: flex;
				align-items: center;
				gap: 8rpx;
				font-size: 26rpx;
				color: #6f6d67;
				cursor: pointer;

				.delete-icon {
					width: 24rpx;
					height: 24rpx;
				}
			}
		}
	}

	.category-list {
		.category-item {
			display: flex;
			align-items: flex-start;
			gap: 20rpx;
			margin-bottom: 20rpx;
			flex-wrap: wrap;
			padding: 0 20rpx;

			.category-name {
				font-size: 26rpx;
				color: #1d1e25;
				min-width: 80rpx;
				margin-top: 8rpx;
			}

			.add-btn {
				width: 40rpx;
				height: 40rpx;
				cursor: pointer;
				margin-top: 8rpx;
				transition: all 0.3s ease;

				&.disabled {
					opacity: 0.5;
					cursor: not-allowed;
				}
			}

			.selected-tags {
				display: flex;
				flex-wrap: wrap;
				gap: 10rpx;
				flex: 1;

				.tag {
					background: #f6f8fa;
					color: #1d1e25;
					padding: 8rpx 16rpx;
					border-radius: 20rpx;
					font-size: 22rpx;
					cursor: pointer;
					position: relative;
					transition: all 0.3s ease;
					border: none;

					&.active {
						background: #fef7f2;
						color: #dcb477;
						border: 1rpx solid #ffe9c2;
					}

					// 未选中的标签样式
					&:not(.active) {
						background: #f6f8fa;
						border: none;
						color: #1d1e25;
					}

					&.editing {
						padding-right: 30rpx;
					}

					&.hidden {
						display: none;
					}

					.delete-x {
						position: absolute;
						right: -5rpx;
						top: -5rpx;
						width: 20rpx;
						height: 20rpx;
						cursor: pointer;
						z-index: 1;
					}
				}

				.expand-btn {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 40rpx;
					height: 40rpx;
					cursor: pointer;
					margin-left: 10rpx;

					.expand-icon {
						width: 24rpx;
						height: 24rpx;
					}
				}
			}
		}
	}
}

/* ===== 添加辅食弹窗 ===== */
.add-food-popup {
	background: white;
	border-radius: 40rpx;
	width: 654rpx;
	height: 414rpx;
	// padding: 40rpx;
	box-sizing: border-box;

	.popup-header {
		text-align: left;
		padding-left: 40rpx;
		padding-top: 40rpx;
		margin-bottom: 30rpx;

		.popup-title {
			margin-left: 0rpx;
			font-size: 36rpx;
			color: #1d1e25;
			font-weight: bold;
		}
	}

	.popup-content {
		margin-bottom: 10rpx;
		display: flex;
		justify-content: center;

		.input-container {
			position: relative;
			width: 590rpx;
		}

		.food-input {
			width: 590rpx;
			height: 110rpx;
			padding: 20rpx;
			border: 5rpx solid #ffe9c2;
			border-radius: 25rpx;
			font-size: 28rpx;
			color: #1d1e25;
			box-sizing: border-box;
			background: white;
		}

		.char-count {
			position: absolute;
			right: 20rpx;
			top: 50%;
			transform: translateY(-50%);
			font-size: 24rpx;
			color: #999;
			pointer-events: none;
		}
	}

	.popup-buttons {
		display: flex;
		margin-top: 50rpx;
		gap: 40rpx;
		justify-content: center;

		.cancel-btn,
		.confirm-btn {
			width: 284rpx;
			height: 94rpx;
		}

		.cancel-btn {
			// background: #f6f8fa;
			// color: #dcb477;
		}

		.confirm-btn {
			// background: #dcb477;
			// color: white;
		}
	}
}

/* ===== 记录方式选择 ===== */
.record-methods1 {
	position: absolute;
	top: 570rpx;
	left: 0;
	right: 0;
	display: flex;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 180rpx;

	.tab-image {
		width: 468rpx;
		height: 180rpx;
	}

	.click-area {
		position: absolute;
		top: 0;
		height: 100%;
		width: 156rpx;
	}

	.left {
		left: calc(50% - 234rpx);
	}

	.center {
		left: calc(50% - 78rpx);
	}

	.right {
		left: calc(50% + 78rpx);
	}
}

/* ===== 记录方式选择 - 母乳瓶喂/奶粉喂养 ===== */
.record-methods2 {
	position: absolute;
	top: 570rpx;
	left: 0;
	right: 0;
	display: flex;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 180rpx;

	.tab-image {
		width: 304rpx;
		height: 180rpx;
	}

	.click-area {
		position: absolute;
		top: 0;
		height: 100%;
		width: 152rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 8rpx;
	}

	.left {
		left: calc(50% - 152rpx);
	}

	.right {
		left: calc(50% + 0rpx);
	}

	.method-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.method-text {
		font-size: 24rpx;
		color: #999;
		transition: color 0.3s ease;

		&.active {
			color: #333;
			font-weight: bold;
		}
	}
}

/* ===== 语音控制区域 ===== */
.voice-controls {
	position: absolute;
	left: 0;
	right: 0;
	top: 30rpx;
	padding: 30rpx;
	display: flex;
	flex-direction: column;
	align-items: center;

	.voice-tip {
		text-align: center;

		.tip-text {
			font-size: 28rpx;
			color: #6f6d67;
			font-weight: 500;
		}
	}

	.voice-example {
		text-align: center;

		.example-text {
			font-size: 38rpx;
			color: #1d1e25;
			font-weight: bolder;
		}
	}

	.voice-microphone {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 278rpx;
		height: 278rpx;
		margin-top: 25rpx;

		.microphone-icon {
			width: 278rpx;
			height: 278rpx;

			&[src*="icon_luyining.gif"] {
				width: 351rpx;
				height: 339rpx;
			}
		}
	}

	.voice-click-tip {
		text-align: center;
		margin-top: 20rpx;

		.click-text {
			font-size: 26rpx;
			color: #6f6d67;
		}
	}
}

/* ===== 计时器控制区域 ===== */
.timer-controls {
	position: absolute;
	left: 0;
	right: 0;
	top: 30rpx;
	padding: 30rpx;
	display: flex;
	flex-direction: column;
	align-items: center;

	/* 总时长显示 */
	.total-duration {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 10rpx;

		.total-duration-label {
			font-size: 28rpx;
			color: #6f6d67;
		}

		.total-duration-value {
			font-size: 48rpx;
			color: #1d1e25;
			font-weight: bold;
		}
	}



	/* 圆形计时器 */
	.circular-timers {
		display: flex;
		justify-content: space-around;
		align-items: center;
		width: 100%;

		.timer-circle {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 20rpx;
			position: relative;

			.timer-icon {
				width: 278rpx;
				height: 278rpx;
			}

			.timer-time {
				font-size: 32rpx;
				color: #1d1e25;
				margin-top: -100rpx;

			}

			.timer-label {
				font-size: 24rpx;
				color: #6f6d67;
				margin-top: 45rpx;
			}
		}
	}
}




/* ===== 下半部分背景区域 ===== */
.bottom-section {
	position: absolute;
	top: 480rpx;
	left: 0;
	right: 0;
	width: 100%;
	height: 1008rpx;
	z-index: 1;

	.bottom-bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 750rpx;
		height: 1008rpx;
		z-index: 0;
	}


	.bottom_complete-btn {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: 100rpx;
		width: 686rpx;
		height: 94rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 2;
		cursor: pointer;
		transition: all 0.3s ease;

		&.disabled {
			opacity: 0.6;
			pointer-events: none;
		}

		.complete-btn-bg {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
		}

		.complete-btn-text {
			position: relative;
			z-index: 1;
			font-size: 32rpx;
			color: white;
			font-weight: bold;
		}
	}
}

// uni-datetime-picker样式覆盖（与feedingRecord页面保持一致）
::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;
}

/* ===== 语音识别结果页面 ===== */
.voice-result-page {
	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;
	justify-content: center;

	.result-container {
		background: white;
		border-radius: 20rpx 20rpx 0 0;
		padding: 40rpx;
		width: 100%;
		max-height: 80vh;
		overflow-y: auto;

		.result-header {
			text-align: center;
			margin-bottom: 40rpx;

			.result-title {
				font-size: 36rpx;
				color: #333;
				font-weight: bold;
			}
		}

		.feeding-info {
			margin-bottom: 40rpx;

			.info-item {
				display: flex;
				align-items: center;
				margin-bottom: 30rpx;

				.info-label {
					font-size: 28rpx;
					color: #666;
					width: 120rpx;
					flex-shrink: 0;
				}

				.info-value {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}

				.detail-input {
					flex: 1;
					padding: 15rpx;
					border: 2rpx solid #E0E0E0;
					border-radius: 12rpx;
					font-size: 28rpx;
					color: #333;
					background: #F8F9FA;
				}
			}
		}

		.result-actions {
			display: flex;
			gap: 20rpx;

			.re-recognize-btn,
			.complete-record-btn {
				flex: 1;
				text-align: center;
				padding: 25rpx;
				border-radius: 12rpx;
				font-size: 28rpx;
				cursor: pointer;
				transition: all 0.3s ease;
			}

			.re-recognize-btn {
				background: #F5F5F5;
				color: #666;
				border: 2rpx solid #E0E0E0;

				&:active {
					background: #E0E0E0;
				}
			}

			.complete-record-btn {
				background: #C89F6B;
				color: white;

				&:active {
					background: #B27C1E;
				}
			}
		}
	}
}

// 语音模式提示样式
.voice-mode-tip {
	position: absolute;
	top: -60rpx;
	left: 50%;
	transform: translateX(-50%);
	background: rgba(0, 0, 0, 0.8);
	color: white;
	padding: 10rpx 20rpx;
	border-radius: 8rpx;
	font-size: 24rpx;
	white-space: nowrap;
	z-index: 10;
}
</style>