<template>
	<view class="feeding-record-add-page">
		<!-- 可滚动内容区域 -->
		<!-- 广告横幅 -->
		<swiper class="banner-swiper" v-if="swiperData.length > 0" :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 > 1">
				<image class="avatar-img" :src="currentBaby?.babyAvatar || feedingIndexRes.avatar">
				</image>
				<view class="baby-name-section">
					<text class="baby-name">{{ currentBaby?.babyName || '加载中...' }}</text>
					<image class="dropdown-icon" :src="feedingIndexRes.icon_arrow_yellow_drop" />
				</view>
			</view>
			<view class="baby-info" v-else-if="babyList.length === 1">
				<image class="avatar-img" :src="currentBaby?.babyAvatar || feedingIndexRes.avatar">
				</image>
				<view class="baby-name-section">
					<text class="baby-name">{{ currentBaby?.babyName || '加载中...' }}</text>
				</view>
			</view>
			<view class="baby-info" v-else>
				<image class="avatar-img" :src="feedingIndexRes.avatar"></image>
				<view class="baby-name-section">
					<text class="baby-name">加载中...</text>
					<image class="dropdown-icon" :src="feedingIndexRes.icon_arrow_yellow_drop" />
				</view>
			</view>
			<view class="time-section" @click="showTimePicker">
				<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"
					style="z-index: 999999;">
					<view class="time-display">
						<text class="time-value">{{ formatCurrentTime() }}</text>
						<image class="edit-icon" :src="feedingIndexRes.icon_modify" />
					</view>
				</uni-datetime-picker>
			</view>


		</view>

		<!-- 喂养记录 -->
		<view class="feeding-records" @click="goToFeedingRecord">
			<text class="records-link">喂养记录</text>
			<image class="arrow-right" :src="feedingIndexRes.icon_arrow_yellow"></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="feedingIndexRes.icon_bg" 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="feedingIndexRes.bottom_bg" mode="aspectFill" />

			<view class="bottom-bg-content"></view>

			<!-- 温馨提示 -->
			<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="feedingIndexRes.iconBg" 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 ? feedingIndexRes.icon_G : feedingIndexRes.icon_L"
									mode="aspectFit" @click="adjustDuration('left', -1)"
									:class="{ disabled: feedingData.breastfeeding.leftDuration <= 0 }" />
								<image class="btn-plus"
									:src="feedingData.breastfeeding.leftDuration >= 60 ? feedingIndexRes.icon_G_plus : feedingIndexRes.icon_L_plus"
									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="feedingIndexRes.iconBg" 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 ? feedingIndexRes.icon_G : feedingIndexRes.icon_L"
									mode="aspectFit" @click="adjustDuration('right', -1)"
									:class="{ disabled: feedingData.breastfeeding.rightDuration <= 0 }" />
								<image class="btn-plus"
									:src="feedingData.breastfeeding.rightDuration >= 60 ? feedingIndexRes.icon_G_plus : feedingIndexRes.icon_L_plus"
									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">
							<image class="bubble-bg" :src="feedingIndexRes.icon_left_arrow_tip" mode="aspectFit" />
							<text class="bubble-label">喂奶量</text>
							<text class="bubble-value">{{ feedingData[selectedType].amount }}ml</text>
						</view>

						<!-- 中间瓶子图形 -->
						<view class="bottle-container">
							<image class="bottle-image" :src="feedingIndexRes.icon_milk_bottle" 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; 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"
								:class="{ disabled: foodSelectionState.isDeletingFood }"
								@click="foodSelectionState.isDeletingFood ? null : exitEditMode()">
								完成
							</text>
							<view v-else class="delete-btn" @click="enterEditMode">
								<image class="delete-icon" :src="feedingIndexRes.icon_shanchu" 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>
							<view class="add-section">
								<image class="add-btn"
									:class="{ disabled: foodSelectionState.isEditMode || foodSelectionState.isAddingFood }"
									:src="feedingIndexRes.icon_fushi_add" mode="aspectFit"
									@click="foodSelectionState.isAddingFood ? null : showAddFoodPopup(categoryName)" />
							</view>
							<view class="selected-tags">
								<!-- 默认辅食项 -->
								<view v-for="(item, index) in category.items" :key="item" class="tag-item" :class="{
									active: feedingData.food.selectedItems.includes(item),
									editing: foodSelectionState.isEditMode,
									hidden: !category.expanded && index >= 3
								}" @click="toggleFoodSelection(item)">
									<text class="tag">{{ item }}</text>
									<image v-if="foodSelectionState.isEditMode" class="delete-x"
										:src="feedingIndexRes.icon_shanchu_x" mode="aspectFit"
										@click.stop="removeFoodItem(categoryName, item)" />
								</view>
								<!-- 自定义辅食项 -->
								<view v-for="(item, index) in category.customItems" :key="`custom-${item}`"
									class="tag-item" :class="{
										active: feedingData.food.selectedItems.includes(item),
										editing: foodSelectionState.isEditMode,
										hidden: !category.expanded && index >= 3
									}" @click="toggleFoodSelection(item)">
									<text class="tag">{{ item }}</text>
									<image v-if="foodSelectionState.isEditMode" class="delete-x"
										:src="feedingIndexRes.icon_shanchu_x" mode="aspectFit"
										@click.stop="removeFoodItem(categoryName, item)" />
								</view>
							</view>
							<!-- 展开/缩起按钮 -->
							<view v-if="(category.items.length + category.customItems.length) > 3" class="expand-btn"
								@click="toggleCategoryExpansion(categoryName)">
								<image class="expand-icon"
									:src="category.expanded ? feedingIndexRes.icon_fushi_up : feedingIndexRes.icon_fushi_drop"
									mode="aspectFit" />
							</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'">"左边5分钟,右边6分钟"</text>
					<text class="example-text" v-else>"喂奶量90毫升"</text>
				</view>

				<!-- 麦克风图标 -->
				<view class="voice-microphone" @touchstart="startRecording" @touchend="stopRecording"
					@touchcancel="stopRecording">
					<image class="microphone-icon"
						:src="voiceRecognitionState.isRecording ? feedingIndexRes.icon_luyining_gif : feedingIndexRes.icon_luyin"
						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 ? feedingIndexRes.icon_stop : feedingIndexRes.icon_start"
							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 ? feedingIndexRes.icon_stop : feedingIndexRes.icon_start"
							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>
		<!-- 底部完成按钮 -->
		<view class="bottom_complete-btn" @click="completeRecord">
			<image class="complete-btn-bg" :src="feedingIndexRes.complete_btn" />
			<!-- <text class="complete-btn-text">{{ isSubmitting ? '保存中...' : '完成记录' }}</text> -->
		</view>
	</view>

	<!-- 添加辅食弹窗 -->
	<uni-popup ref="addFoodPopup" type="center" :mask-click="false" class="add-food-popup-container">
		<view class="add-food-popup">
			<view class="popup-header">
				<text class="popup-title">新增辅食名称</text>
			</view>
			<view class="popup-content2">
				<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="feedingIndexRes.icon_fushi_btn_cancel" mode="aspectFit"
					@click="cancelAddFood"></image>
				<image class="confirm-btn"
					:class="{ disabled: foodSelectionState.isAddingFood || !foodSelectionState.newFoodItem.trim() }"
					:src="feedingIndexRes.icon_fushi_btn_add" mode="aspectFit"
					@click="(foodSelectionState.isAddingFood || !foodSelectionState.newFoodItem.trim()) ? null : confirmAddFood()">
				</image>
			</view>
		</view>
	</uni-popup>

	<!-- 语音识别结果弹窗 -->
	<view v-if="voiceRecognitionState.showResultPage" class="popup-mask" @touchmove.prevent>
		<view class="popup-content" @click.stop @touchmove.stop>
			<view class="popup-header">
				<view class="popup-title">确认识别结果</view>
				<view class="popup-close" @click="closeVoiceResult">
					<text class="close-text">×</text>
				</view>
			</view>

			<!-- 识别状态显示 -->
			<view v-if="voiceRecognitionState.recognitionStatus === 'processing'" class="recognition-status">
				<text class="status-text">识别处理中...</text>
			</view>

			<view class="form-container">
				<!-- 语音识别时间选择器，层级最高，未拉起不显示 -->
				<view class="form-item" style="z-index: 10003; position: relative;">
					<uni-datetime-picker class="voice-time-picker" ref="voiceTimePickerRef"
						v-model="voiceRecognitionState.voiceDateTime" type="datetime" :clear-icon="false"
						:border="false" :start="earliestDateString" :end="latestDateString" @change="onVoiceTimeChange"
						style="z-index: 999999;">
						<text class="label">喂养时间</text>
						<view class="input-container">
							<input class="input" :value="formatVoiceDateTime()" placeholder="请选择时间" readonly
								@click="showVoiceTimePicker" />
						</view>
					</uni-datetime-picker>
				</view>
				<view class="form-item">
					<text class="label">喂养方式</text>
					<view class="picker disabled">{{ getFeedingTypeLabel() }}</view>
				</view>
				<view class="form-item">
					<text class="label">喂养详情</text>
					<view class="input-container">
						<input class="input" v-model="voiceRecognitionState.recognizedText" placeholder="请输入喂养详情"
							maxlength="20" />
					</view>
				</view>
			</view>

			<view class="popup-buttons">
				<image :src="feedingIndexRes.icon_btn_cancel" class="cancel-btn" @click="reRecognize" />
				<image :src="feedingIndexRes.icon_btn_confirm" class="confirm-btn" @click="completeVoiceRecord" />
			</view>
		</view>
	</view>





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

	<!-- 记录成功弹窗 -->
	<uni-popup ref="successPopup" type="center" :mask-click="false">
		<view class="success-popup">
			<image class="success-bg" :src="feedingIndexRes.add_suc_bg" mode="aspectFit" />
			<view class="success-content">
				<view class="success-buttons">

					<image class="success-btn success-btn-close" :src="feedingIndexRes.add_suc_btn_close"
						mode="aspectFit" @click="onSuccessClose" />
					<image class="success-btn success-btn-jump" :src="feedingIndexRes.add_suc_btn_jump" mode="aspectFit"
						@click="onSuccessJump" />
				</view>
			</view>
		</view>
	</uni-popup>

	<popupTip v-if="isTip" type="1" @statusChange="onPopupTipBabyChange" @close="isTip = false"></popupTip>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, getCurrentInstance } from 'vue'
import { onShow, onLoad, onHide } from '@dcloudio/uni-app'
import BabySwitchPopup from '@/components/BabySwitchPopup.vue'
import popupTip from '../../components/popup-tip/popup-tip.vue'
import { fetchFeedingJSON, feedingHome, feedingRecords, feedingFoodsCustom, feedingFoodsCustomAdd, feedingFoodsCustomDelete, feedingTimerStart, feedingTimerStop, feedingVoiceUpload, feedingVoiceResult } from '@/api/feeding.js'
import { useUserStore } from '@/stores/user.js'
import { jump, JumpType, showLoading } from '../../utils'
import { getHealthField } from "@/api/common";
import md from '../../md'

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

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

const version = 'v1'

// 计时器上限时间（秒）
const TIMER_MAX_DURATION = 3600

const feedingIndexRes = {
	// 轮播图
	banner: $baseUrl + `feedingIndex/${version}/banner.png`,

	// 头像和宝宝相关
	avatar: $baseUrl + `feedingIndex/${version}/avatar.png`,
	icon_arrow_yellow_drop: $baseUrl + `feedingIndex/${version}/icon_arrow_yellow_drop.png`,
	icon_arrow_yellow: $baseUrl + `feedingIndex/${version}/icon_arrow_yellow.png`,
	icon_modify: $baseUrl + `feedingIndex/${version}/icon_modify.png`,

	// 背景图片
	icon_bg: $baseUrl + `feedingIndex/${version}/icon_bg.png`,
	bottom_bg: $baseUrl + `feedingIndex/${version}/bottom_bg.png`,
	iconBg: $baseUrl + `feedingIndex/${version}/iconBg.png`,

	// 母乳亲喂相关
	icon_L: $baseUrl + `feedingIndex/${version}/icon-L.png`,
	icon_G: $baseUrl + `feedingIndex/${version}/icon-G.png`,
	icon_L_plus: $baseUrl + `feedingIndex/${version}/icon%2BL.png`,
	icon_G_plus: $baseUrl + `feedingIndex/${version}/icon%2BG.png`,

	// 喂养类型图标
	icon_muruqinwei: $baseUrl + `feedingIndex/${version}/icon_muruqinwei.png`,
	icon_murupinwei: $baseUrl + `feedingIndex/${version}/icon_murupinwei.png`,
	icon_naifen: $baseUrl + `feedingIndex/${version}/icon_naifen.png`,
	icon_fushi: $baseUrl + `feedingIndex/${version}/icon_fushi.png`,

	// 奶瓶和喂奶量相关
	icon_milk_bottle: $baseUrl + `feedingIndex/${version}/icon_milk_bottle.png`,
	icon_left_arrow_tip: $baseUrl + `feedingIndex/${version}/icon_left_arrow_tip.png`,

	// 语音相关
	icon_luyin: $baseUrl + `feedingIndex/${version}/icon_luyin.png`,
	icon_luyining: $baseUrl + `feedingIndex/${version}/icon_luyining.png`,
	icon_luyining_gif: $baseUrl + `feedingIndex/${version}/icon_luyining.gif`,

	// 计时器相关
	icon_start: $baseUrl + `feedingIndex/${version}/icon_start.png`,
	icon_stop: $baseUrl + `feedingIndex/${version}/icon_stop.png`,

	// 完成按钮
	complete_btn: $baseUrl + `feedingIndex/${version}/complete_btn.png`,

	// 记录方式选择
	Tab_bottom_write: $baseUrl + `feedingIndex/${version}/Tab_bottom_write.png`,
	Tab_bottom_timer: $baseUrl + `feedingIndex/${version}/Tab_bottom_timer.png`,
	Tab_bottom_voice: $baseUrl + `feedingIndex/${version}/Tab_bottom_voice.png`,
	Tab_bottom_muruandnaifen_write: $baseUrl + `feedingIndex/${version}/Tab_bottom_muruandnaifen_write.png`,
	Tab_bottom_muruandnaifen_voice: $baseUrl + `feedingIndex/${version}/Tab_bottom_muruandnaifen_voice.png`,

	// 辅食相关
	icon_fushi_add: $baseUrl + `feedingIndex/${version}/icon_fushi_add.png`,
	icon_fushi_up: $baseUrl + `feedingIndex/${version}/icon_fushi_up.png`,
	icon_fushi_drop: $baseUrl + `feedingIndex/${version}/icon_fushi_drop.png`,
	icon_shanchu_x: $baseUrl + `feedingIndex/${version}/icon_shanchu_x.png`,
	icon_shanchu: $baseUrl + `feedingIndex/${version}/icon_shanchu.png`,
	icon_fushi_btn_cancel: $baseUrl + `feedingIndex/${version}/icon_fushi_btn_cancel.png`,
	icon_fushi_btn_add: $baseUrl + `feedingIndex/${version}/icon_fushi_btn_add.png`,


	//添加记录成功弹窗
	add_suc_bg: $baseUrl + `feedingIndex/${version}/add_suc_bg.png`,
	add_suc_btn_jump: $baseUrl + `feedingIndex/${version}/add_suc_btn_jump.png`,
	add_suc_btn_close: $baseUrl + `feedingIndex/${version}/add_suc_btn_close.png`,


	// 识别成功弹窗
	icon_btn_confirm: $baseUrl + `feedingIndex/${version}/icon_btn_confirm.png`,
	icon_btn_cancel: $baseUrl + `feedingIndex/${version}/icon_btn_cancel.png`,
}

const swiperData = ref([

]);
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 timePickerRef = ref(null)
const voiceTimePickerRef = ref(null)

// 接口返回的数据
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) => {
	// 检查是否正在录音
	if (recordingState.value.isRecording || voiceRecognitionState.value.isRecording) {
		uni.showToast({
			title: '录音进行中，不可切换页面',
			icon: 'none'
		})
		return
	}

	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "喂养工具首页",
		buttonName: "banner资源位",
	});

	console.log(item);
	jump({ type: item.jumpType, url: item.url, extra: item.extra })
}

const showTimePicker = () => {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "喂养工具首页",
		buttonName: "选择喂养时间",
	});
}


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

// 根据接口数据初始化选中的喂养类型
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: [], // 待删除的辅食列表
	originalFoodData: null, // 保存原始辅食数据，用于恢复
	isAddingFood: false, // 添加辅食防连点状态
	isDeletingFood: false // 删除辅食防连点状态
})

// 记录成功弹窗状态 - 已移除，改用 .open() 和 .close() 方法

// 语音识别状态
const voiceRecognitionState = ref({
	isRecording: false, // 是否正在录音
	showResultPage: false, // 是否显示识别结果页面
	recognizedText: '', // 识别结果文本
	recordingDuration: 0, // 录音时长
	recordingStartTime: null, // 录音开始时间
	recordingTimer: null, // 录音时长定时器
	taskId: '', // 语音识别任务ID
	isPolling: false, // 是否正在轮询识别结果
	pollingInterval: null, // 轮询定时器
	pollingErrorCount: 0, // 轮询错误计数
	recognitionStatus: 'idle', // 识别状态：idle-空闲, processing-处理中, success-成功, failed-失败
	recordDate: '', // 记录日期
	recordTime: '', // 记录时间
	voiceDateTime: '' // 完整的日期时间字符串
})

// 录音管理器
const recorderManager = uni.getRecorderManager()

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

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

const isTip = ref(true)

// 为每种喂养方式设置独立的数据 - 根据接口数据初始化
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(() => {
	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)

// 页面加载时获取数据
onMounted(async () => {
	md.sensorLogTake({
		xcxPage: "小程序页面浏览事件",
		pageName: "喂养工具首页",
	});
	console.warn('页面加载，开始初始化数据...')
	await loadBabyInfo()
	loadFoodsData()

	// 初始化录音管理器
	initializeRecorderManager()
})

const onPopupTipBabyChange = async () => {
	isTip.value = false
	console.log('onPopupTipBabyChange', isTip.value)
	// showBabySwitchPopup.value = true
	await loadBabyInfo()
	loadHomeData()
}

// 页面显示时刷新数据
onShow(async () => {
	console.log('页面显示，刷新数据...')

	if (!babyId.value) {
		isTip.value = true
		await loadBabyInfo()
	} else {
		isTip.value = false
	}

	// 刷新宝宝信息和首页数据
	loadHomeData()

	// 重置计时器状态，确保状态正确
	resetTimerStatus()

	// 检查录音状态，如果录音管理器正在录音但状态不一致，强制重置
	if (recordingState.value.isRecording || voiceRecognitionState.value.isRecording) {
		console.log('检测到录音状态不一致，强制重置录音状态')
		forceResetRecorderManager()
	} else {
		// 重置录音状态，确保状态正确
		resetRecordingState()
	}

	// 检查录音状态
	checkRecorderStatus()

	// 如果处于编辑模式且有待删除的辅食，恢复编辑状态
	if (hasUnfinishedEdit()) {
		console.log('检测到未完成的辅食删除操作，恢复编辑状态')
		// 延迟执行，确保页面完全加载后再显示弹窗
		setTimeout(() => {
			restoreUnfinishedEdit()
		}, 500)
	}
})

// 页面隐藏时同步计时器状态
onHide(() => {
	console.log('页面隐藏，处理录音状态...')

	// 如果正在录音，停止录音并重置状态
	if (recordingState.value.isRecording || voiceRecognitionState.value.isRecording) {
		console.log('页面隐藏时检测到正在录音，停止录音')
		forceResetRecorderManager()
	}

	// 如果页面隐藏时有计时器在运行，需要同步到后端
	if (isLeftTimerRunning.value && leftTimerInterval) {
		console.log('页面隐藏时同步左侧计时器状态')
		// 这里可以选择是否调用后端接口同步状态
		// 由于页面隐藏时通常不需要立即同步，可以等到页面显示时再同步
	}
	if (isRightTimerRunning.value && rightTimerInterval) {
		console.log('页面隐藏时同步右侧计时器状态')
		// 这里可以选择是否调用后端接口同步状态
	}
})

// 页面卸载时清理计时器
onUnmounted(() => {
	console.log('页面卸载，清理资源...')

	// 清理左侧计时器
	if (leftTimerInterval) {
		clearInterval(leftTimerInterval)
		leftTimerInterval = null
	}
	// 清理右侧计时器
	if (rightTimerInterval) {
		clearInterval(rightTimerInterval)
		rightTimerInterval = null
	}
	// 清理语音识别轮询
	clearPollingInterval()
	// 清理录音定时器
	if (recordingState.value.recordingTimer) {
		clearInterval(recordingState.value.recordingTimer)
		recordingState.value.recordingTimer = null
	}
	// 清理录音管理器事件监听器（兼容性处理）
	try {
		if (recorderManager && typeof recorderManager.offStart === 'function') {
			recorderManager.offStart()
		}
		if (recorderManager && typeof recorderManager.offStop === 'function') {
			recorderManager.offStop()
		}
		if (recorderManager && typeof recorderManager.offError === 'function') {
			recorderManager.offError()
		}
	} catch (error) {
		console.warn('页面卸载时清理录音管理器回调出错:', error)
	}
})

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

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

	// 如果有其他参数，可以在这里处理
	if (options.babyId) {
		// 设置选中的宝宝
		await userStore.changeBabySelected(options.babyId)
	}

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


// 根据记录数据设置表单
function setFormDataFromRecord(recordData) {
	// 设置喂养类型
	const typeMap = {
		1: 'breastfeeding',
		2: 'bottle',
		3: 'formula',
		4: 'food'
	}
	selectedType.value = typeMap[recordData.feedingType] || 'breastfeeding'

	// 设置喂养数据
	if (recordData.feedingType === 1) {
		// 母乳亲喂
		feedingData.value.breastfeeding.leftDuration = Math.floor(recordData.durationLeftSeconds / 60)
		feedingData.value.breastfeeding.rightDuration = Math.floor(recordData.durationRightSeconds / 60)
	} else if (recordData.feedingType === 2 || recordData.feedingType === 3) {
		// 母乳瓶喂或奶粉喂养
		const type = recordData.feedingType === 2 ? 'bottle' : 'formula'
		feedingData.value[type].amount = recordData.volume
	} else if (recordData.feedingType === 4) {
		// 辅食
		if (recordData.foodDetails) {
			feedingData.value.food.selectedItems = recordData.foodDetails.split(',').filter(item => item.trim())
		}
	}

	// 设置喂养详情
	if (recordData.foodDetails) {
		voiceRecognitionState.value.recognizedText = recordData.foodDetails
	}

	// 不清除记录方法，保持用户的选择
}

// 获取宝宝信息
async function loadBabyInfo() {
	try {
		console.log('开始加载宝宝信息...')
		if (userStore.babyInfo?.babyStage != 2) {
			isTip.value = true
			console.log('isTip', isTip.value)
		} else {
			isTip.value = false
			console.log('宝宝信息加载完成')
		}
		// 使用全局状态管理加载宝宝信息
		// 加载宝宝信息 - 由 userStore 管理
		await userStore.loadBabyInfo()
		console.log('宝宝信息加载完成:', userStore.babyInfo, userStore.babyInfo?.babyStage)

		if (userStore.babyInfo?.babyStage != 2) {
			isTip.value = true
			console.log('isTip', isTip.value)
		} else {
			isTip.value = false
			console.log('宝宝信息加载完成')

			// 加载宝宝信息后，加载首页数据
			await loadHomeData()
		}

	} catch (error) {
		console.error('获取宝宝信息失败:', error)

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

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

// 获取首页数据
async function loadHomeData() {
	if (!babyId.value) {
		isTip.value = true
		return
	} else {
		isTip.value = false
	}
	try {
		const response = await feedingHome(babyId.value)
		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'
		})
	}


	// 获取轮播图数据
	try {
		const feedingResponse = await fetchFeedingJSON()
		console.log('轮播图数据:', feedingResponse)

		if (feedingResponse && feedingResponse.data && feedingResponse.data.swiperData && feedingResponse.data.swiperData.length > 0) {
			swiperData.value = feedingResponse.data.swiperData
		}
	} catch (error) {
		console.error('获取轮播图数据失败:', error)
		// 使用默认的轮播图数据作为fallback
		swiperData.value = []
	}
}

// 根据接口数据初始化页面状态
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()
	} else {
		// 如果接口显示没有左侧计时器在运行，但当前有计时器数据，则清空并停止定时器
		if (timerData.value.leftDuration > 0 || isLeftTimerRunning.value) {
			console.log('接口显示左侧计时器未运行，清空左侧计时器数据并停止定时器')
			timerData.value.leftDuration = 0
			isLeftTimerRunning.value = false
			stopLeftTimer()
		}
	}

	if (data.rightTimerRunning) {
		isRightTimerRunning.value = true
		timerData.value.rightDuration = Math.floor(data.rightTimerDuration / 1000) // 转换为秒
		startRightTimer()
	} else {
		// 如果接口显示没有右侧计时器在运行，但当前有计时器数据，则清空并停止定时器
		if (timerData.value.rightDuration > 0 || isRightTimerRunning.value) {
			console.log('接口显示右侧计时器未运行，清空右侧计时器数据并停止定时器')
			timerData.value.rightDuration = 0
			isRightTimerRunning.value = false
			stopRightTimer()
		}
	}

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

	// 重置计时器状态，确保状态和实际运行状态保持一致
	resetTimerStatus()
}

// 重置计时器状态
function resetTimerStatus() {
	// 如果状态显示计时器在运行，但实际没有定时器在运行，则重置状态
	if (isLeftTimerRunning.value && !leftTimerInterval) {
		console.log('重置左侧计时器状态：状态为运行但实际已停止')
		isLeftTimerRunning.value = false
	}
	if (isRightTimerRunning.value && !rightTimerInterval) {
		console.log('重置右侧计时器状态：状态为运行但实际已停止')
		isRightTimerRunning.value = false
	}
}

// 方法
function selectType(type) {
	// 检查是否正在录音
	if (recordingState.value.isRecording || voiceRecognitionState.value.isRecording) {
		uni.showToast({
			title: '录音进行中，不可切换类型',
			icon: 'none'
		})
		return
	}

	// 检查是否有正在进行的计时器（只有在真正有计时器在运行时才阻止）
	if ((isLeftTimerRunning.value && leftTimerInterval) || (isRightTimerRunning.value && rightTimerInterval)) {
		uni.showToast({
			title: '记录进行中，不可切换',
			icon: 'none'
		})
		return
	}

	// 检查是否有计时器结束但未提交的记录
	if (selectedType.value === 'breastfeeding' && recordMethods.value.breastfeeding === 'timer' &&
		(timerData.value.leftDuration > 0 || timerData.value.rightDuration > 0)) {
		uni.showToast({
			title: '记录进行中，不可切换',
			icon: 'none'
		})
		return
	}

	// 检查是否有未保存的辅食删除操作，直接恢复数据
	if (foodSelectionState.value.isEditMode && foodSelectionState.value.pendingDeletes.length > 0) {
		// 取消编辑模式，恢复数据
		cancelEditMode()
	}

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


	if (type === 'breastfeeding') {
		md.sensorLogTake({
			xcxClick: "小程序页面点击事件",
			pageName: "喂养工具首页",
			buttonName: "母乳亲喂",
		});
	}
	if (type === 'bottle') {
		md.sensorLogTake({
			xcxClick: "小程序页面点击事件",
			pageName: "喂养工具首页",
			buttonName: "母乳瓶喂",
		});
	}
	if (type === 'formula') {
		md.sensorLogTake({
			xcxClick: "小程序页面点击事件",
			pageName: "喂养工具首页",
			buttonName: "奶粉喂养",
		});
	}
	if (type === 'food') {
		md.sensorLogTake({
			xcxClick: "小程序页面点击事件",
			pageName: "喂养工具首页",
			buttonName: "辅食",
		});
	}
	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: [],
		originalFoodData: null
	}

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

	// 不清除记录方法，保持用户的选择
	// 不清除喂养数据，保持用户输入

	// 清空滑动状态
	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: [],
		originalFoodData: null
	}

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

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

	// 不清除记录方法，保持用户的选择

	// 重置当前时间，使用 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') {

		if (value > 0) {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "左侧哺乳时长+",
			});
		}
		if (value < 0) {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "左侧哺乳时长-",
			});
		}

		// 限制在0-60分钟范围内
		const newValue = currentData.leftDuration + value
		if (newValue >= 0 && newValue <= 60) {
			currentData.leftDuration = newValue
		}
	} else {

		if (value > 0) {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "右侧哺乳时长+",
			});
		}
		if (value < 0) {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "右侧哺乳时长-",
			});
		}

		// 限制在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 (method === 'manual') {
		if (selectedType.value === 'breastfeeding') {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "母乳亲喂手动记录",
			});
		}
		if (selectedType.value === 'bottle') {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "母乳瓶喂手动记录",
			});
		}
		if (selectedType.value === 'formula') {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "奶粉喂养手动记录",
			});
		}
	}

	if (method === 'voice') {

		if (selectedType.value === 'breastfeeding') {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "母乳亲喂语音记录",
			});
		}
		if (selectedType.value === 'bottle') {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "母乳瓶喂语音记录",
			});
		}
		if (selectedType.value === 'formula') {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "奶粉喂养语音记录",
			});
		}

	}

	if (method === 'timer') {
		md.sensorLogTake({
			xcxClick: "小程序页面点击事件",
			pageName: "喂养工具首页",
			buttonName: "母乳亲喂计时器记录",
		});
	}

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

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

	// 检查是否有计时器结束但未提交的记录
	if (selectedType.value === 'breastfeeding' && recordMethods.value.breastfeeding === 'timer' &&
		(timerData.value.leftDuration > 0 || timerData.value.rightDuration > 0)) {
		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 currentBabyId = babyId.value

	if (side === 'left') {
		// 检查是否已达到上限
		if (timerData.value.leftDuration >= TIMER_MAX_DURATION) {
			uni.showToast({
				title: '计时已达上限',
				icon: 'none'
			})
			return
		}

		// 左侧计时逻辑
		if (!isLeftTimerRunning.value) {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "左侧计时器开始",
			});
			// 开始左侧计时
			try {
				const response = await feedingTimerStart({
					babyId: currentBabyId,
					side: 'left'
				})
				console.log('开始左侧计时成功:', response)
				isLeftTimerRunning.value = true
				startLeftTimer()
			} catch (error) {
				console.error('开始左侧计时失败:', error)
				uni.showToast({
					title: '开始计时失败',
					icon: 'none'
				})
			}
		} else {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "左侧计时器暂停",
			});
			// 停止左侧计时
			try {
				const response = await feedingTimerStop({
					babyId: currentBabyId,
					side: 'left'
				})
				console.log('停止左侧计时成功:', response)
				isLeftTimerRunning.value = false
				stopLeftTimer()
			} catch (error) {
				console.error('停止左侧计时失败:', error)
				uni.showToast({
					title: '停止计时失败',
					icon: 'none'
				})
			}
		}
	} else if (side === 'right') {
		// 检查是否已达到上限
		if (timerData.value.rightDuration >= TIMER_MAX_DURATION) {
			uni.showToast({
				title: '计时已达上限',
				icon: 'none'
			})
			return
		}

		// 右侧计时逻辑
		if (!isRightTimerRunning.value) {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "右侧计时器开始",
			});
			// 开始右侧计时
			try {
				const response = await feedingTimerStart({
					babyId: currentBabyId,
					side: 'right'
				})
				console.log('开始右侧计时成功:', response)
				isRightTimerRunning.value = true
				startRightTimer()
			} catch (error) {
				console.error('开始右侧计时失败:', error)
				uni.showToast({
					title: '开始计时失败',
					icon: 'none'
				})
			}
		} else {
			md.sensorLogTake({
				xcxClick: "小程序页面点击事件",
				pageName: "喂养工具首页",
				buttonName: "右侧计时器暂停",
			});
			// 停止右侧计时
			try {
				const response = await feedingTimerStop({
					babyId: currentBabyId,
					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++

		// 检查是否达到上限，达到时自动暂停
		if (timerData.value.leftDuration >= TIMER_MAX_DURATION) {
			console.log('左侧计时器达到上限，自动暂停')
			stopLeftTimer()
			isLeftTimerRunning.value = false
			// 自动停止时也要调用后端接口
			autoStopLeftTimer()
		}
	}, 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++

		// 检查是否达到上限，达到时自动暂停
		if (timerData.value.rightDuration >= TIMER_MAX_DURATION) {
			console.log('右侧计时器达到上限，自动暂停')
			stopRightTimer()
			isRightTimerRunning.value = false
			// 自动停止时也要调用后端接口
			autoStopRightTimer()
		}
	}, 1000) // 每秒增加1秒
}

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

// 自动停止左侧计时器（调用后端接口）
async function autoStopLeftTimer() {
	const currentBabyId = babyId.value
	if (!currentBabyId) {
		console.warn('没有选择宝宝，无法停止计时器')
		return
	}

	try {
		console.log('自动停止左侧计时器')
		const response = await feedingTimerStop({
			babyId: currentBabyId,
			side: 'left'
		})
		console.log('自动停止左侧计时器成功:', response)
	} catch (error) {
		console.error('自动停止左侧计时器失败:', error)
		// 不显示错误提示，因为这是自动停止
	}
}

// 自动停止右侧计时器（调用后端接口）
async function autoStopRightTimer() {
	const currentBabyId = babyId.value
	if (!currentBabyId) {
		console.warn('没有选择宝宝，无法停止计时器')
		return
	}

	try {
		console.log('自动停止右侧计时器')
		const response = await feedingTimerStop({
			babyId: currentBabyId,
			side: 'right'
		})
		console.log('自动停止右侧计时器成功:', response)
	} catch (error) {
		console.error('自动停止右侧计时器失败:', error)
		// 不显示错误提示，因为这是自动停止
	}
}

// 停止所有计时器
async function stopAllTimers() {
	const currentBabyId = babyId.value
	if (!currentBabyId) {
		console.warn('没有选择宝宝，无法停止计时器')
		return
	}

	try {
		// 停止左侧计时器
		if (isLeftTimerRunning.value) {
			console.log('保存记录前停止左侧计时器')
			const leftResponse = await feedingTimerStop({
				babyId: currentBabyId,
				side: 'left'
			})
			console.log('停止左侧计时器成功:', leftResponse)
			isLeftTimerRunning.value = false
			stopLeftTimer()
		}

		// 停止右侧计时器
		if (isRightTimerRunning.value) {
			console.log('保存记录前停止右侧计时器')
			const rightResponse = await feedingTimerStop({
				babyId: currentBabyId,
				side: 'right'
			})
			console.log('停止右侧计时器成功:', rightResponse)
			isRightTimerRunning.value = false
			stopRightTimer()
		}
	} catch (error) {
		console.error('停止计时器失败:', error)
		// 不显示错误提示，因为这是正常的保存流程
		// 即使计时器停止失败，也要继续保存记录
	}
}

// 完成记录
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
	}


	if (selectedType.value === 'breastfeeding') {
		md.sensorLogTake({
			xcxClick: "小程序页面点击事件",
			pageName: "喂养工具首页",
			buttonName: "母乳亲喂完成记录",
		});
	}
	if (selectedType.value === 'bottle') {
		md.sensorLogTake({
			xcxClick: "小程序页面点击事件",
			pageName: "喂养工具首页",
			buttonName: "母乳瓶喂完成记录",
		});
	}
	if (selectedType.value === 'formula') {
		md.sensorLogTake({
			xcxClick: "小程序页面点击事件",
			pageName: "喂养工具首页",
			buttonName: "奶粉喂养完成记录",
		});
	}
	if (selectedType.value === 'food') {
		md.sensorLogTake({
			xcxClick: "小程序页面点击事件",
			pageName: "喂养工具首页",
			buttonName: "辅食完成记录",
		});
	}


	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)

		// 如果是计时器模式，先停止计时器
		if (selectedType.value === 'breastfeeding' && recordMethods.value.breastfeeding === 'timer') {
			console.log('保存记录前先停止计时器')
			await stopAllTimers()
		}

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

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

		// 刷新 home 数据
		await loadHomeData()

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

		// 显示成功弹窗
		successPopup.value.open()

		md.sensorPopLogTake({
			xcxPopExposure: "true",
			toolName: "喂养记录",
			popName: "添加成功弹窗"
		});




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

// 验证记录数据
function validateRecordData() {
	const currentBaby = userStore.babyInfo?.content

	// 验证宝宝信息
	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 = userStore.babyInfo?.content

	// 判断是否为语音模式，如果是则使用弹窗中的日期和时间
	let recordTime
	if (voiceRecognitionState.value.showResultPage && voiceRecognitionState.value.voiceDateTime) {
		// 语音模式：使用弹窗中的日期和时间，转换为ISO格式
		const dateTimeStr = voiceRecognitionState.value.voiceDateTime
		const date = new Date(dateTimeStr)
		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')
		recordTime = `${year}-${month}-${day} ${hours}:${minutes}`
	} else {
		// 其他模式：使用当前时间
		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() {
	// 检查是否正在录音
	if (recordingState.value.isRecording || voiceRecognitionState.value.isRecording) {
		uni.showToast({
			title: '录音进行中，不可切换页面',
			icon: 'none'
		})
		return
	}

	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "喂养工具首页",
		buttonName: "喂养记录",
	});

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

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

// 语音识别时间选择器显示
function showVoiceTimePicker() {
	// 使用与 formatCurrentTime() 一致的默认时间
	if (!voiceRecognitionState.value.voiceDateTime) {
		const defaultTimeString = formatCurrentTime()
		if (defaultTimeString) {
			voiceRecognitionState.value.voiceDateTime = `${defaultTimeString}:00`
		} else {
			const now = new Date()
			voiceRecognitionState.value.voiceDateTime = now.toISOString().slice(0, 19).replace('T', ' ')
		}
	}
	voiceTimePickerRef.value.show()
}

// 语音识别时间选择
function onVoiceTimeChange(value) {
	// 设置完整的日期时间字符串
	voiceRecognitionState.value.voiceDateTime = value

	// 解析日期和时间
	const date = new Date(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')

	// 设置分离的日期和时间
	voiceRecognitionState.value.recordDate = `${year}-${month}-${day}`
	voiceRecognitionState.value.recordTime = `${hours}:${minutes}`
}

// 格式化语音识别时间显示
function formatVoiceDateTime() {
	if (voiceRecognitionState.value.voiceDateTime) {
		const date = new Date(voiceRecognitionState.value.voiceDateTime)
		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')
		console.warn('formatVoiceDateTime', year, month, day, hours, minutes)
		return `${year}-${month}-${day} ${hours}:${minutes}`
	}
	return ''
}

// 关闭语音识别结果弹窗
function closeVoiceResult() {
	voiceRecognitionState.value.showResultPage = false
	voiceRecognitionState.value.recognizedText = ''
	voiceRecognitionState.value.recordDate = ''
	voiceRecognitionState.value.recordTime = ''
	voiceRecognitionState.value.voiceDateTime = ''

	// 重置防连点状态，确保用户可以重新录音
	resetRecordingCooldown()
}

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 feedingIndexRes.Tab_bottom_write
	} else if (currentMethod === 'timer') {
		return feedingIndexRes.Tab_bottom_timer
	} else {
		return feedingIndexRes.Tab_bottom_voice
	}
}

function getTabImage2() {
	const currentMethod = recordMethods.value[selectedType.value]
	if (currentMethod === 'manual') {
		return feedingIndexRes.Tab_bottom_muruandnaifen_write
	} else {
		return feedingIndexRes.Tab_bottom_muruandnaifen_voice
	}
}

// 格式化时间显示 (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 {
		md.sensorLogTake({
			xcxClick: "小程序页面点击事件",
			pageName: "喂养工具首页",
			buttonName: "辅食删除",
		});
		// 保存原始辅食数据，保持顺序
		foodSelectionState.value.originalFoodData = {
			selectedItems: [...feedingData.value.food.selectedItems],
			categories: {}
		}

		// 保存每个分类的原始数据
		Object.keys(foodCategories.value).forEach(categoryName => {
			foodSelectionState.value.originalFoodData.categories[categoryName] = {
				items: [...foodCategories.value[categoryName].items],
				customItems: [...foodCategories.value[categoryName].customItems]
			}
		})
		// 进入编辑模式
		foodSelectionState.value.isEditMode = true
		// 清空待删除列表
		foodSelectionState.value.pendingDeletes = []
	}
}

function cancelEditMode() {
	// 恢复原始辅食数据，保持原有顺序
	if (foodSelectionState.value.originalFoodData) {
		feedingData.value.food.selectedItems = [...foodSelectionState.value.originalFoodData.selectedItems]
	}

	// 恢复被删除的辅食到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)) {
				// 找到原来的位置并插入，而不是添加到末尾
				const originalIndex = item.originalIndex || 0

				// 根据原始位置判断应该添加到哪个数组
				// 如果原始位置在默认辅食范围内，添加到items；否则添加到customItems
				if (originalIndex >= 0 && originalIndex < category.items.length) {
					// 添加到默认辅食数组
					category.items.splice(originalIndex, 0, item.foodName)
				} else {
					// 添加到自定义辅食数组
					const customIndex = originalIndex - category.items.length
					if (customIndex >= 0 && customIndex <= category.customItems.length) {
						category.customItems.splice(customIndex, 0, item.foodName)
					} else {
						// 如果找不到原位置，则添加到自定义辅食末尾
						category.customItems.push(item.foodName)
					}
				}
			}
		}
	})

	// 清空待删除列表
	foodSelectionState.value.pendingDeletes = []
	// 退出编辑模式
	foodSelectionState.value.isEditMode = false
	// 清理原始数据
	foodSelectionState.value.originalFoodData = null
}

async function exitEditMode() {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "喂养工具首页",
		buttonName: "辅食删除完成",
	});
	// 防连点检查
	if (foodSelectionState.value.isDeletingFood) {
		console.log('防连点：删除完成按钮被阻止')
		return
	}
	foodSelectionState.value.isDeletingFood = true
	console.log('防连点：设置删除完成状态为true')

	// 如果有待删除的辅食，调用接口删除
	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'
			})

			// 删除失败时恢复数据
			console.log('删除失败，恢复原始数据')
			if (foodSelectionState.value.originalFoodData) {
				// 恢复原始辅食数据
				Object.keys(foodCategories.value).forEach(categoryName => {
					const originalCategory = foodSelectionState.value.originalFoodData.categories[categoryName]
					if (originalCategory) {
						foodCategories.value[categoryName].items = [...originalCategory.items]
						foodCategories.value[categoryName].customItems = [...originalCategory.customItems]
					}
				})

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

				console.log('数据恢复完成')
			}
		}
	}

	// 退出编辑模式
	foodSelectionState.value.isEditMode = false
	// 清理原始数据
	foodSelectionState.value.originalFoodData = null

	// 立即重置防连点状态
	foodSelectionState.value.isDeletingFood = false
	console.log('防连点：重置删除完成状态为false')
}

function showAddFoodPopup(categoryName) {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "喂养工具首页",
		buttonName: "辅食添加" + categoryName,
	});
	
	// 防连点检查
	if (foodSelectionState.value.isAddingFood) {
		console.log('防连点：添加辅食按钮被阻止')
		return
	}
	foodSelectionState.value.isAddingFood = true
	console.log('防连点：设置添加辅食状态为true')

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

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

	foodSelectionState.value.currentCategory = categoryName
	foodSelectionState.value.newFoodItem = ''
	// 显示弹窗
	addFoodPopup.value.open()
	md.sensorPopLogTake({
		xcxPopExposure: "true",
		toolName: "喂养记录",
		popName: "新增辅食弹窗",
	});
	// 立即重置防连点状态（弹窗显示后）
	setTimeout(() => {
		foodSelectionState.value.isAddingFood = false
		console.log('防连点：重置添加辅食状态为false')
	}, 100)
}

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

function cancelAddFood() {
	addFoodPopup.value.close()
	foodSelectionState.value.newFoodItem = ''
	md.sensorPopLogTake({
		xcxPopClick: "true",
		toolName: "喂养记录",
		popName: "新增辅食弹窗",
		buttonName: "取消"
	});
}

function confirmAddFood() {
	if (foodSelectionState.value.isAddingFood) {
		console.log('防连点：添加辅食按钮被阻止')
		return
	}
	md.sensorPopLogTake({
		xcxPopClick: "true",
		toolName: "喂养记录",
		popName: "新增辅食弹窗",
		buttonName: "添加"
	});
	foodSelectionState.value.isAddingFood = true
	console.log('防连点：设置添加辅食状态为true')

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

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

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

	// 2秒后重置防连点状态
	setTimeout(() => {
		foodSelectionState.value.isAddingFood = false
		console.log('防连点：重置添加辅食状态为false')
	}, 2000)
}

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

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

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

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

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

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

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

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

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

	} catch (error) {
		console.error('添加自定义辅食失败:', error)
		uni.showToast({
			title: '添加失败',
			icon: 'none'
		})
		// 失败时重置防连点状态
		foodSelectionState.value.isAddingFood = false
	}
}

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

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

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

	// 记录原始位置信息
	let originalIndex = -1

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

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

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

	// 添加到待删除列表，包含原始位置信息
	foodSelectionState.value.pendingDeletes.push({
		foodId: foodId,
		foodName: itemName,
		categoryName: categoryName,
		originalIndex: originalIndex
	})

	console.log('添加到待删除列表:', itemName, '原始位置:', originalIndex, '当前待删除:', 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'
			})
		}
	})
}

// 录音状态管理
const recordingState = ref({
	isInitialized: false, // 是否已初始化录音管理器
	isRecording: false, // 是否正在录音
	recordingStartTime: null, // 录音开始时间
	recordingDuration: 0, // 录音时长
	recordingTimer: null, // 录音时长定时器
	lastStopTime: 0, // 上次停止录音的时间戳
	canStartRecording: true // 是否可以开始录音（防连点）
})

// 初始化录音管理器（只初始化一次）
function initializeRecorderManager() {
	if (recordingState.value.isInitialized) {
		console.log('录音管理器已初始化，跳过')
		return
	}

	// 检查录音管理器是否可用
	if (!recorderManager) {
		console.error('录音管理器不可用')
		return
	}

	console.log('初始化录音管理器...')

	// 清理之前的回调（兼容性处理）
	try {
		if (typeof recorderManager.offStart === 'function') {
			recorderManager.offStart()
		}
		if (typeof recorderManager.offStop === 'function') {
			recorderManager.offStop()
		}
		if (typeof recorderManager.offError === 'function') {
			recorderManager.offError()
		}
	} catch (error) {
		console.warn('清理录音管理器回调时出错:', error)
	}

	// 绑定录音开始回调
	recorderManager.onStart(() => {
		console.log('录音开始成功')
		recordingState.value.isRecording = true
		recordingState.value.recordingStartTime = Date.now()
		voiceRecognitionState.value.isRecording = true
		voiceRecognitionState.value.recordingStartTime = Date.now()

		// 设置防连点状态
		recordingState.value.canStartRecording = false

		// 启动录音时长定时器
		recordingState.value.recordingTimer = setInterval(() => {
			if (recordingState.value.isRecording && recordingState.value.recordingStartTime) {
				const duration = Math.floor((Date.now() - recordingState.value.recordingStartTime) / 1000)
				recordingState.value.recordingDuration = duration
				voiceRecognitionState.value.recordingDuration = duration
			}
		}, 1000)
	})

	// 绑定录音停止回调
	recorderManager.onStop(async (res) => {
		console.log('录音停止回调触发，结果:', res)

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

		// 重置录音状态
		recordingState.value.isRecording = false
		recordingState.value.recordingStartTime = null
		voiceRecognitionState.value.isRecording = false
		voiceRecognitionState.value.recordingStartTime = null

		// 1秒后恢复防连点状态
		setTimeout(() => {
			recordingState.value.canStartRecording = true
			console.log('录音冷却结束，可以重新录音')
		}, 1000)

		// 检查录音文件路径
		const tempFilePath = res.tempFilePath
		if (!tempFilePath) {
			console.error('录音文件路径不存在，完整返回结果:', res)
			uni.hideLoading()
			uni.showToast({
				title: '录音文件获取失败，请检查录音权限',
				icon: 'none'
			})
			// 重置录音状态，让用户可以重新录音
			resetRecordingState()
			return
		}

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

		// 检查文件是否存在
		uni.getFileSystemManager().access({
			path: tempFilePath,
			success: () => {
				console.log('录音文件存在，开始处理')
				processVoiceFile(tempFilePath)
			},
			fail: (err) => {
				console.error('录音文件不存在:', err)
				uni.showToast({
					title: '录音文件不存在，请重新录音',
					icon: 'none'
				})
				// 重置录音状态，让用户可以重新录音
				resetRecordingState()
			}
		})
	})

	// 绑定录音错误回调
	recorderManager.onError((err) => {
		console.error('录音错误:', err)

		// 重置录音状态
		resetRecordingState()

		// 1秒后恢复防连点状态
		setTimeout(() => {
			recordingState.value.canStartRecording = true
			console.log('录音错误后冷却结束，可以重新录音')
		}, 1000)

		// uni.showToast({
		// 	title: '录音失败',
		// 	icon: 'none'
		// })
	})

	recordingState.value.isInitialized = true
	console.log('录音管理器初始化完成')
}

// 重置录音状态
function resetRecordingState() {
	console.log('重置录音状态')

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

	// 重置录音状态
	recordingState.value.isRecording = false
	recordingState.value.recordingStartTime = null
	recordingState.value.recordingDuration = 0

	// 重置语音识别状态
	voiceRecognitionState.value.isRecording = false
	voiceRecognitionState.value.recordingStartTime = null
	voiceRecognitionState.value.recordingDuration = 0
	voiceRecognitionState.value.recognitionStatus = 'idle'

	// 注意：这里不调用 recorderManager.stop()，因为调用方会处理
	// 避免重复调用导致的问题
}

// 重置防连点状态（立即恢复）
function resetRecordingCooldown() {
	recordingState.value.canStartRecording = true
	console.log('立即重置录音冷却状态')
}

// 检查录音管理器状态
function checkRecorderStatus() {
	console.log('检查录音管理器状态:', {
		isRecording: recordingState.value.isRecording,
		voiceIsRecording: voiceRecognitionState.value.isRecording,
		recognitionStatus: voiceRecognitionState.value.recognitionStatus,
		canStartRecording: recordingState.value.canStartRecording
	})
}

// 强制重置录音管理器状态
function forceResetRecorderManager() {
	console.log('强制重置录音管理器状态')

	// 重置录音状态
	resetRecordingState()

	// 尝试停止录音管理器
	try {
		if (recorderManager) {
			recorderManager.stop()
		}
	} catch (error) {
		console.warn('强制停止录音管理器时出错:', error)
	}

	// 等待一小段时间让录音管理器完全停止
	setTimeout(() => {
		console.log('录音管理器状态重置完成')
		// 重置防连点状态
		resetRecordingCooldown()
		// 确保状态完全重置
		recordingState.value.isRecording = false
		voiceRecognitionState.value.isRecording = false
		voiceRecognitionState.value.recognitionStatus = 'idle'

		// 检查重置后的状态
		checkRecorderStatus()
	}, 300)
}

// 开始录音
async function startRecording() {
	if (!recordingState.value.isRecording) {
		md.sensorLogTake({
			xcxClick: "小程序页面点击事件",
			pageName: "喂养工具首页",
			buttonName: "语音识别录制开始按钮",
		});
	}

	console.log('开始录音请求...')
	console.log('当前录音状态:', {
		isRecording: recordingState.value.isRecording,
		recordingStartTime: recordingState.value.recordingStartTime,
		recordingDuration: recordingState.value.recordingDuration,
		canStartRecording: recordingState.value.canStartRecording,
		voiceIsRecording: voiceRecognitionState.value.isRecording,
		voiceRecordingStartTime: voiceRecognitionState.value.recordingStartTime,
		voiceRecordingDuration: voiceRecognitionState.value.recordingDuration,
		recognitionStatus: voiceRecognitionState.value.recognitionStatus
	})

	// 检查录音管理器是否已初始化
	if (!recordingState.value.isInitialized) {
		console.log('录音管理器未初始化，尝试初始化...')
		initializeRecorderManager()
	}

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

			// 防止重复录音：检查是否正在录音
			if (recordingState.value.isRecording) {
				console.log('正在录音中，忽略重复请求')
				return
			}

			// 如果录音管理器状态异常，强制重置
			if (recordingState.value.isRecording !== voiceRecognitionState.value.isRecording) {
				console.log('录音状态不一致，强制重置')
				resetRecordingState()
			}

			// 防连点检查：检查是否可以开始录音
			if (!recordingState.value.canStartRecording) {
				console.log('录音冷却中，忽略请求')
				// uni.showToast({
				// 	title: '请稍后再试',
				// 	icon: 'none',
				// 	duration: 1000
				// })
				return
			}

			// 防止快速重复点击：检查距离上次停止的时间
			const now = Date.now()
			if (now - recordingState.value.lastStopTime < 1000) {
				console.log('距离上次停止时间太短，忽略请求')
				return
			}

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

			// 重置录音状态
			resetRecordingState()

			// 添加小延迟确保录音管理器状态正确
			await new Promise(resolve => setTimeout(resolve, 100))

			// 开始录音
			try {
				recorderManager.start({
					duration: 60000, // 最长录音时间60秒
					sampleRate: 16000, // 采样率
					numberOfChannels: 1, // 单声道
					encodeBitRate: 96000, // 编码码率
					format: 'mp3' // 音频格式
				})
			} catch (error) {
				console.error('开始录音失败:', error)
				// 如果开始录音失败，强制重置录音管理器状态
				forceResetRecorderManager()
				uni.showToast({
					title: '录音启动失败，请重试',
					icon: 'none'
				})
			}
		},
		fail: (err) => {
			console.error('检查录音权限失败', err)
			uni.showToast({
				title: '录音权限检查失败',
				icon: 'none'
			})
		}
	})
}

// 停止录音
async function stopRecording() {
	console.log('停止录音请求...')



	// 检查录音是否真正开始
	if (!recordingState.value.isRecording || !recordingState.value.recordingStartTime) {
		console.log('录音未开始或已停止，无需停止')
		return
	}


	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "喂养工具首页",
		buttonName: "语音识别录制结束按钮",
	});

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

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

		// 检查录音时长是否太短
		if (duration < 1) {
			uni.showToast({
				title: '录音时间太短，请重新录音',
				icon: 'none'
			})
			// 强制重置录音管理器状态
			forceResetRecorderManager()
			recordingState.value.lastStopTime = Date.now()
			return
		}

		// 检查录音时长是否太长
		if (duration > 60) {
			uni.showToast({
				title: '录音时间太长，请重新录音',
				icon: 'none'
			})
			// 强制重置录音管理器状态
			forceResetRecorderManager()
			recordingState.value.lastStopTime = Date.now()
			return
		}
	}

	// 记录停止时间
	recordingState.value.lastStopTime = Date.now()

	// 停止录音
	try {
		recorderManager.stop()
	} catch (error) {
		console.error('停止录音失败:', error)
		// 即使停止失败，也要强制重置录音管理器状态
		forceResetRecorderManager()
	}
}

// 处理语音文件
async function processVoiceFile(tempFilePath) {
	try {
		// 显示加载提示
		uni.showLoading({
			title: '正在转换并上传语音...',
			mask: true
		})

		// 上传语音文件（转换为base64）
		const uploadResponse = await uploadVoiceFile(tempFilePath)
		console.log('语音文件转换并上传成功:', uploadResponse)

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

	} catch (error) {
		handleVoiceRecognitionError(error)
	}
}

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

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

		// 先检查文件是否存在
		uni.getFileSystemManager().access({
			path: tempFilePath,
			success: () => {
				console.log('文件存在，开始获取文件信息')

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

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

						// 检查文件大小是否太小（可能录音失败）
						if (fileInfo.size < 1024) {
							console.warn('文件大小过小:', fileInfo.size, '字节')
							reject(new Error('录音文件过小，可能录音失败，请重新录音'))
							return
						}

						console.log('文件大小正常，开始读取文件为base64')

						// 读取文件为base64
						uni.getFileSystemManager().readFile({
							filePath: tempFilePath,
							encoding: 'base64',
							success: async (res) => {
								try {
									console.log('语音文件读取成功，base64长度:', res.data.length, '字符')

									// 检查base64数据是否有效
									if (!res.data || res.data.length < 100) {
										console.error('base64数据无效，长度:', res.data?.length)
										reject(new Error('语音文件数据无效，请重新录音'))
										return
									}

									// 验证base64格式
									if (!/^[A-Za-z0-9+/]*={0,2}$/.test(res.data)) {
										console.error('base64格式无效')
										reject(new Error('语音文件格式无效，请重新录音'))
										return
									}

									console.log('base64数据验证通过，开始上传')

									// 添加base64格式头
									const base64WithHeader = `data:audio/mp3;base64,${res.data}`

									// 调用上传接口，传递带格式头的base64数据
									const response = await feedingVoiceUpload({
										audioData: base64WithHeader
									})

									console.log('上传接口返回:', response)

									if (response && response.data && response.data.taskId) {
										resolve(response.data)
									} else {
										reject(new Error('上传失败：未获取到taskId，返回数据：' + JSON.stringify(response)))
									}
								} catch (error) {
									console.error('上传过程中发生错误:', error)
									reject(error)
								}
							},
							fail: (err) => {
								console.error('读取语音文件失败:', err)
								reject(new Error('读取语音文件失败：' + err.errMsg))
							}
						})
					},
					fail: (err) => {
						console.error('获取文件信息失败:', err)
						reject(new Error('获取文件信息失败：' + err.errMsg))
					}
				})
			},
			fail: (err) => {
				console.error('文件不存在:', tempFilePath, err)
				reject(new Error('录音文件不存在，请重新录音'))
			}
		})
	})
}

// 开始轮询识别结果
async function startPollingRecognitionResult(taskId) {
	console.log('开始轮询识别结果，taskId:', taskId)

	voiceRecognitionState.value.taskId = taskId
	voiceRecognitionState.value.isPolling = true
	voiceRecognitionState.value.recognitionStatus = 'processing'

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

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

			if (response && response.code === '000000' && response.data) {
				const result = response.data
				const status = result.flag // 0-处理中 1-成功 2-失败

				console.log('识别状态:', status)

				switch (status) {
					case 0: // 处理中
						console.log('语音识别处理中...')
						voiceRecognitionState.value.recognitionStatus = 'processing'
						// 继续轮询，不做任何处理
						break

					case 1: // 成功
						console.log('语音识别成功')
						voiceRecognitionState.value.recognitionStatus = 'success'
						clearPollingInterval()
						uni.hideLoading()

						// 立即重置防连点状态，让用户可以重新录音
						resetRecordingCooldown()

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

						// 使用与 formatCurrentTime() 一致的默认时间
						const defaultTimeString = formatCurrentTime()
						if (defaultTimeString) {
							// 解析时间字符串
							const [datePart, timePart] = defaultTimeString.split(' ')
							const [year, month, day] = datePart.split('-')
							const [hours, minutes] = timePart.split(':')

							voiceRecognitionState.value.recordDate = `${year}-${month}-${day}`
							voiceRecognitionState.value.recordTime = `${hours}:${minutes}`
							voiceRecognitionState.value.voiceDateTime = `${defaultTimeString}:00`
						} else {
							// 如果 formatCurrentTime() 返回空，使用当前时间
							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')

							voiceRecognitionState.value.recordDate = `${year}-${month}-${day}`
							voiceRecognitionState.value.recordTime = `${hours}:${minutes}`
							voiceRecognitionState.value.voiceDateTime = `${year}-${month}-${day} ${hours}:${minutes}:00`
						}
						voiceRecognitionState.value.showResultPage = true
						md.sensorPopLogTake({
							xcxPopExposure: "true",
							toolName: "喂养记录",
							popName: "语音识别结果弹窗"
						});
						// 显示识别成功提示
						uni.showToast({
							title: '语音识别成功',
							icon: 'success',
							duration: 2000
						})
						break

					case 2: // 失败
						console.log('语音识别失败')
						voiceRecognitionState.value.recognitionStatus = 'failed'
						clearPollingInterval()
						uni.hideLoading()
						// 强制重置录音管理器状态
						forceResetRecorderManager()
						uni.showToast({
							title: '语音识别失败',
							icon: 'none'
						})
						break

					default:
						console.log('未知的识别状态:', status)
						// 对于未知状态，继续轮询
						break
				}
			} else {
				console.log('接口返回异常:', response)
				// 如果接口返回异常，继续轮询
			}
		} catch (error) {
			console.error('轮询识别结果失败:', error)
			// 轮询失败时，如果连续失败次数过多，停止轮询并重置状态
			if (!voiceRecognitionState.value.pollingErrorCount) {
				voiceRecognitionState.value.pollingErrorCount = 0
			}
			voiceRecognitionState.value.pollingErrorCount++

			// 如果连续失败超过5次，停止轮询并重置状态
			if (voiceRecognitionState.value.pollingErrorCount >= 5) {
				console.log('轮询连续失败5次，停止轮询并重置状态')
				clearPollingInterval()
				uni.hideLoading()
				forceResetRecorderManager()
				uni.showToast({
					title: '识别服务异常，请重试',
					icon: 'none'
				})
			}
		}
	}, 2000) // 每2秒轮询一次

	// 设置最大轮询时间（30秒后停止）
	setTimeout(() => {
		if (voiceRecognitionState.value.isPolling) {
			console.log('轮询超时，停止轮询')
			clearPollingInterval()
			uni.hideLoading()
			// 强制重置录音管理器状态（超时时重置，让用户可以重新录音）
			forceResetRecorderManager()
			uni.showToast({
				title: '识别超时，请重试',
				icon: 'none'
			})
		}
	}, 30000)
}

// 清理轮询定时器
function clearPollingInterval() {
	console.log('清理轮询定时器')

	if (voiceRecognitionState.value.pollingInterval) {
		clearInterval(voiceRecognitionState.value.pollingInterval)
		voiceRecognitionState.value.pollingInterval = null
	}
	voiceRecognitionState.value.isPolling = false

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

	// 如果不是成功状态，重置识别状态和录音状态
	if (voiceRecognitionState.value.recognitionStatus !== 'success') {
		voiceRecognitionState.value.recognitionStatus = 'idle'
		resetRecordingState()
	}

	// 重置轮询错误计数
	voiceRecognitionState.value.pollingErrorCount = 0

	// 重置防连点状态，确保用户可以重新录音
	resetRecordingCooldown()
}

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

	// 强制重置录音管理器状态
	forceResetRecorderManager()

	// 根据错误类型显示不同的提示
	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() {
	console.log('重新识别...')
	md.sensorPopLogTake({
		xcxPopClick: "true",
		toolName: "喂养记录",
		popName: "语音识别结果弹窗",
		buttonName: "不对，重新识别"
	});
	// 清理轮询状态
	clearPollingInterval()

	// 强制重置录音管理器状态
	forceResetRecorderManager()

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

	// 重置识别状态
	voiceRecognitionState.value.showResultPage = false
	voiceRecognitionState.value.recognizedText = ''
	voiceRecognitionState.value.taskId = ''
	voiceRecognitionState.value.recordDate = ''
	voiceRecognitionState.value.recordTime = ''
	voiceRecognitionState.value.voiceDateTime = ''
}

async function completeVoiceRecord() {
	// 防止重复提交
	if (isSubmitting.value) {
		return
	}
	md.sensorPopLogTake({
		xcxPopClick: "true",
		toolName: "喂养记录",
		popName: "语音识别结果弹窗",
		buttonName: "完成记录"
	});

	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()

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

		// 不清空喂养数据，保持用户输入

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

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

		// 显示成功弹窗
		successPopup.value.open()

		md.sensorPopLogTake({
			xcxPopExposure: "true",
			toolName: "喂养记录",
			popName: "添加成功弹窗"
		});
	} catch (error) {
		console.error('保存语音记录失败:', error)
		// uni.hideLoading()
		uni.showToast({
			title: '保存失败',
			icon: 'none'
		})
	} finally {
		// 添加2秒防连点
		setTimeout(() => {
			isSubmitting.value = false
		}, 2000)
	}
}



// 记录成功弹窗相关方法
async function onSuccessJump() {
	// 检查是否正在录音
	if (recordingState.value.isRecording || voiceRecognitionState.value.isRecording) {
		uni.showToast({
			title: '录音进行中，不可切换页面',
			icon: 'none'
		})
		return
	}

	const res = await getHealthField();

	if (!res.success) {
		uni.showToast({
			title: "获取健康字段失败",
			icon: "none",
		});
		return;
	}

	const { sign, timestamp, appId, partnerUserId, env } = res.data;

	jump({
		type: JumpType.MINI,
		url: "/pages/partner/redirect",
		extra: {
			appId: "wx81ecfb5aa3fb512f",
			envVersion: env,
			extraData: {
				sign, // 参考 4.请求参数
				timestamp, // 参考 4.请求参数
				appId, // 参考 4.请求参数
				partnerUserId, // 参考 4.请求参数
				targetApp:
					"/h5/partner/shining-like-a-start/landing-free-consult?sysType=CRF",
			},
		},
	});	// 关闭弹窗
	successPopup.value.close()
	md.sensorPopLogTake({
		xcxPopClick: "true",
		toolName: "喂养记录",
		popName: "添加成功弹窗",
		buttonName: "咨询专家"
	});
}

function onSuccessClose() {
	// 关闭弹窗
	successPopup.value.close()
	md.sensorPopLogTake({
		xcxPopClick: "true",
		toolName: "喂养记录",
		popName: "添加成功弹窗",
		buttonName: "关闭"
	});
	// 跳转至记录页面
	uni.navigateTo({
		url: '/pages/feedingRecord/feedingRecord'
	})
}

// 检查是否有未完成的编辑操作
function hasUnfinishedEdit() {
	return foodSelectionState.value.isEditMode && foodSelectionState.value.pendingDeletes.length > 0
}

// 恢复未完成的编辑操作
function restoreUnfinishedEdit() {
	if (hasUnfinishedEdit()) {
		console.log('恢复未完成的辅食删除操作')
		// 显示提示
		uni.showModal({
			title: '提示',
			content: '检测到未完成的辅食删除操作，是否继续？',
			confirmText: '继续删除',
			cancelText: '取消编辑',
			success: (res) => {
				if (res.confirm) {
					// 用户选择继续删除，保持当前编辑状态
					console.log('用户选择继续删除')
				} else {
					// 用户选择取消编辑，恢复原始数据
					console.log('用户选择取消编辑')
					cancelEditMode()
				}
			}
		})
	}
}

// 宝宝切换相关方法
function showBabySwitch() {
	// 检查是否正在录音
	if (recordingState.value.isRecording || voiceRecognitionState.value.isRecording) {
		uni.showToast({
			title: '录音进行中，不可切换宝宝',
			icon: 'none'
		})
		return
	}

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

async function onBabyChange(baby, index) {
	// 切换宝宝
	await userStore.changeBabySelected(baby.id)
	console.log('切换到宝宝:', baby.babyName, '索引:', 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()

	// 按类型分组辅食 - API返回的都是自定义辅食
	foodsList.forEach(food => {
		const categoryName = foodTypeMap[food.foodType]
		if (categoryName && foodCategories.value[categoryName]) {
			// API返回的辅食都是自定义辅食，应该添加到customItems中
			foodCategories.value[categoryName].customItems.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: #ffffff;
	min-height: 100vh;
	padding: 0;
	position: relative;
}

/* ===== 可滚动内容区域 ===== */
// .scrollable-content {
// 	height: calc(100vh);
// 	// height: 100vh;
// 	background-color: #FFF8F1;
// 	/* 减去底部按钮的高度 */
// 	z-index: 200;
// 	position: absolute;
// 	width: 100vw;
// }

/* ===== 底部完成按钮 ===== */
.bottom_complete-btn {
	// padding-top: 20rpx;
	position: fixed;
	bottom: 0rpx;
	left: 0rpx;
	right: 0rpx;
	width: 750rpx;
	height: 218rpx;
	display: flex;
	background: #fff;
	z-index: 2;
	justify-content: center;
	align-items: center;

	.complete-btn-bg {
		width: 686rpx;
		height: 94rpx;
		display: block;
	}
}

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

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

/* ===== 喂养时间区域 ===== */
.feeding-time {
	position: relative;
	// margin-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;
		/* 移除点击高亮效果 */
		-webkit-tap-highlight-color: transparent;
		-webkit-touch-callout: none;
		-webkit-user-select: none;
		user-select: none;

		&: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;
			/* 移除点击高亮效果 */
			-webkit-tap-highlight-color: transparent;
			-webkit-touch-callout: none;
			-webkit-user-select: none;
			user-select: none;
		}

		.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: relative;
	// margin-top: 270rpx;
	left: 0;
	right: 0;
	display: flex;
	align-items: center;
	justify-content: flex-end;
	padding: 0rpx 30rpx 20rpx 30rpx;
	background: #FFF8F1;
	/* 移除点击高亮效果 */
	-webkit-tap-highlight-color: transparent;
	-webkit-touch-callout: none;
	-webkit-user-select: none;
	user-select: none;

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

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



/* ===== 喂养类型选择 ===== */
.feeding-types {
	position: relative;
	// margin-top: 320rpx;
	left: 0;
	right: 0;
	display: flex;
	background-color: #FFF8F1;
	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;
		/* 移除点击高亮效果 */
		-webkit-tap-highlight-color: transparent;
		-webkit-touch-callout: none;
		-webkit-user-select: none;
		user-select: none;

		.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: relative;
	// margin-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;
	background-color: #fff;
	// 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;
					/* 移除点击高亮效果 */
					-webkit-tap-highlight-color: transparent;
					-webkit-touch-callout: none;
					-webkit-user-select: none;
					user-select: none;

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

			.bubble-bg {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				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;
				transition: all 0.3s ease;

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

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

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

	.category-list {
		max-height: 550rpx;
		overflow-y: auto;
		padding-right: 10rpx;

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

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

			.add-section {
				display: flex;
				flex-direction: column;
				align-items: center;
				flex-shrink: 0;
				margin-right: 20rpx;
			}

			.add-btn {
				width: 80rpx;
				height: 60rpx;
				transition: all 0.3s ease;
				flex-shrink: 0;

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

			.limit-tip {
				font-size: 20rpx;
				color: #999;
				margin-top: 4rpx;
				text-align: center;
				white-space: nowrap;
			}

			.selected-tags {
				display: flex;
				flex-wrap: wrap;
				gap: 10rpx;
				flex: 1;
				align-items: flex-start;
				padding-right: 60rpx;

				.tag-item {
					display: inline-flex;
					align-items: center;
					background: #f6f8fa;
					color: #1d1e25;
					// padding: 8rpx 16rpx;
					padding-left: 32rpx;
					border-radius: 30rpx;
					height: 60rpx;
					font-size: 28rpx;
					// cursor: pointer;
					position: relative;
					transition: all 0.3s ease;
					border: none;
					/* 为删除按钮预留空间 */
					padding-right: 36rpx;
					flex-shrink: 0;

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

						.tag {
							color: #dcb477;
						}
					}

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

						.tag {
							color: #1d1e25;
						}
					}

					&.hidden {
						display: none;
					}

					.tag {
						font-size: 28rpx;
						text-align: center;
						transition: all 0.3s ease;
						/* 文字不被截断，根据内容自适应宽度 */
						white-space: nowrap;
					}

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


			}

			.expand-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 40rpx;
				height: 40rpx;
				// cursor: pointer;
				margin-left: 10rpx;
				flex-shrink: 0;
				align-self: flex-start;
				position: absolute;
				right: 20rpx;
				top: 0;
				z-index: 10;

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

/* ===== 添加辅食弹窗 ===== */
.add-food-popup-container {
	z-index: 10003 !important;
}

.add-food-popup {
	background: white;
	border-radius: 40rpx;
	width: 654rpx;
	min-height: 414rpx;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;

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

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

	.popup-content2 {
		flex: 1;
		padding: 0 40rpx;
		box-sizing: border-box;
		width: 100%;

		.input-container {
			position: relative;
			margin-bottom: 40rpx;
			width: 100%;
			box-sizing: border-box;

			.food-input {
				width: 100%;
				height: 88rpx;
				border: 2rpx solid #e5e5e5;
				border-radius: 12rpx;
				padding: 0 20rpx;
				font-size: 28rpx;
				color: #333;
				box-sizing: border-box;
				background: #fff;
			}

			.char-count {
				position: absolute;
				right: 20rpx;
				bottom: 20rpx;
				font-size: 24rpx;
				color: #999;
			}
		}
	}

	.popup-buttons {
		display: flex;
		justify-content: space-between;
		padding: 0 40rpx 40rpx;
		margin-top: auto;

		.cancel-btn,
		.confirm-btn {
			width: 284rpx;
			height: 94rpx;
			transition: opacity 0.3s;

			&.disabled {
				opacity: 0.5;
			}
		}
	}
}



/* ===== 记录成功弹窗 ===== */
.success-popup {
	position: relative;
	width: 654rpx;
	height: 436rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	// background: #ffffff;
	// border-radius: 20rpx;

	.success-bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 1;
	}

	.success-content {
		margin-top: 190rpx;
		position: relative;
		z-index: 2;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
		pointer-events: auto;

		.success-title {
			font-size: 36rpx;
			color: #1d1e25;
			font-weight: bold;
			margin-bottom: 60rpx;
		}

		.success-buttons {
			display: flex;
			gap: 40rpx;
			align-items: center;

			.success-btn {
				width: 284rpx;
				height: 94rpx;
				pointer-events: auto;
			}

		}
	}
}

/* ===== 记录方式选择 ===== */
.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%;
	z-index: 2;
	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: relative;
	left: 0;
	right: 0;
	width: 100%;
	height: 1008rpx;
	z-index: 1;
	background-color: #fff;

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



}


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

/* 全局时间选择器层级修复 */
::v-deep .uni-datetime-picker {
	z-index: 999999 !important;
}

::v-deep .uni-datetime-picker__mask {
	z-index: 999998 !important;
	position: fixed !important;
	top: 0 !important;
	left: 0 !important;
	right: 0 !important;
	bottom: 0 !important;
}

::v-deep .uni-datetime-picker__popup {
	z-index: 999999 !important;
	position: fixed !important;
	bottom: 218rpx !important;
	left: 50% !important;
	transform: translateX(-50%) !important;
	border-radius: 8px !important;
	padding: 30px !important;
	width: 270px !important;
	background-color: #fff !important;
}

::v-deep .uni-datetime-picker__content {
	z-index: 999999 !important;
	position: relative !important;
}

/* 确保时间选择器内部元素也有正确的层级 */
::v-deep .uni-datetime-picker__container {
	z-index: 999999 !important;
	position: relative !important;
}

::v-deep .uni-datetime-picker__timebox {
	z-index: 999999 !important;
	position: relative !important;
}

::v-deep .uni-datetime-picker__date {
	z-index: 999999 !important;
	position: relative !important;
}

::v-deep .uni-datetime-picker__time {
	z-index: 999999 !important;
	position: relative !important;
}

/* 修复时间选择器文本显示位置 */
::v-deep .uni-datetime-picker-text {
	position: relative !important;
	display: inline-block !important;
	line-height: 50px !important;
	font-size: 14px !important;
	text-align: center !important;
	vertical-align: middle !important;
}

/* 修复时间选择器内部布局 */
::v-deep .uni-datetime-picker__container-box {
	position: relative !important;
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
	margin-top: 40px !important;
}

::v-deep .uni-datetime-picker-item {
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
	height: 50px !important;
}

::v-deep .uni-datetime-picker-view {
	height: 150px !important;
}

/* ===== 语音识别结果弹窗 ===== */
.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;
	justify-content: center;
	overflow: hidden;
	touch-action: none;
	/* 为固定按钮留出空间 */
}



.popup-content {
	background: #f6f8fa;
	width: 750rpx;
	max-height: 80vh;
	border-radius: 20rpx 20rpx 0 0;
	padding: 40rpx 30rpx;
	animation: slideUp 0.3s ease-out;
	// overflow-y: auto;
	z-index: 1001;
	display: flex;
	flex-direction: column;
	/* 确保内容区域在按钮之上 */
	/* 时间选择器z-index为10002，确保显示在弹窗上面 */
	position: relative;

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

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

	.popup-close {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
	}

	.close-text {
		font-size: 40rpx;
		color: #999;
		font-weight: bold;
	}

	.form-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 40rpx;
		flex: 1;
		justify-content: flex-start;
		padding-bottom: 40rpx;
		/* 为底部按钮留出空间 */
	}

	.recognition-status {
		margin-bottom: 30rpx;

		.status-text {
			font-size: 24rpx;
			color: #666;
			background: #f0f0f0;
			padding: 8rpx 16rpx;
			border-radius: 20rpx;
		}
	}

	.form-item {
		width: 687rpx;
		height: 112rpx;
		position: relative;

		.voice-time-picker {
			position: absolute;
			width: 100%;
			height: 100%;
		}

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

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

		.picker,
		.input {
			width: 100%;
			height: 112rpx;
			padding: 0rpx 24rpx 0rpx 120rpx;
			background: #ffffff;
			border-radius: 12rpx;
			font-size: 28rpx;
			text-align: right;
			color: #333;
			pointer-events: none;
			border: 1rpx solid #e9ecef;
			box-sizing: border-box;

			&.disabled {
				background: #f5f5f5;
				color: #999;
				cursor: not-allowed;
			}
		}

		.picker {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			height: 100%;
		}
	}

	.popup-buttons {
		display: flex;
		gap: 20rpx;
		justify-content: center;
		margin-top: auto;
		padding-top: 40rpx;
		z-index: 999;
		/* 时间选择器z-index为10002，确保显示在按钮上面 */

		.cancel-btn,
		.confirm-btn {
			width: 331rpx;
			height: 94rpx;
			flex: none;
			transition: transform 0.1s ease-out;

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

	/* 确保语音识别时间选择器显示在最上层 */
	:deep(.voice-time-picker .uni-datetime-picker) {
		z-index: 999999 !important;
		width: 600rpx !important;
		max-width: 90vw !important;
		background: #ffffff !important;
		border-radius: 16rpx !important;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2) !important;
	}

	:deep(.voice-time-picker .uni-datetime-picker__container) {
		z-index: 999999 !important;
		width: 100% !important;
		background: #ffffff !important;
		border-radius: 16rpx !important;
	}

	/* 确保主时间选择器也能突破堆叠上下文 */
	:deep(.time-section .uni-datetime-picker) {
		z-index: 999999 !important;
		width: 600rpx !important;
		max-width: 90vw !important;
		background: #ffffff !important;
		border-radius: 16rpx !important;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2) !important;
	}

	:deep(.time-section .uni-datetime-picker__container) {
		z-index: 999999 !important;
		width: 100% !important;
		background: #ffffff !important;
		border-radius: 16rpx !important;
	}

	/* 修复时间选择器内部日期和时间重叠问题 */
	:deep(.voice-time-picker .uni-datetime-picker__container .uni-datetime-picker__timebox) {
		display: flex !important;
		flex-direction: column !important;
		gap: 20rpx !important;
		padding: 20rpx !important;
	}

	:deep(.voice-time-picker .uni-datetime-picker__container .uni-datetime-picker__timebox .uni-datetime-picker__time) {
		margin-top: 20rpx !important;
		border-top: 1rpx solid #e5e5e5 !important;
		padding-top: 20rpx !important;
	}

	/* 确保时间选择器内部元素不重叠 */
	:deep(.voice-time-picker .uni-datetime-picker__container .uni-datetime-picker__date) {
		margin-bottom: 20rpx !important;
	}

	:deep(.voice-time-picker .uni-datetime-picker__container .uni-datetime-picker__time) {
		margin-top: 20rpx !important;
		padding-top: 20rpx !important;
		border-top: 1rpx solid #e5e5e5 !important;
	}
}

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

	to {
		transform: translateY(0);
	}
}

// 语音模式提示样式
.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;
}

.food-input::placeholder {
	color: #bbb;
	line-height: 70rpx;
	/* 或 110rpx，和上面保持一致 */
}

.uni-date {
	z-index: 999999 !important;
}
</style>