<template>
	<view class="shengzhang-tools-container">
		<swiper class="banner-swiper" :indicator-dots="swiperData?.length > 1" :autoplay="swiperData?.length > 1"
			:circular="swiperData?.length > 1" indicator-color="#dfddd9" indicator-active-color="#b27c1e"
			:indicator-top="596" v-if="swiperData && swiperData?.length > 0">
			<swiper-item v-for="(item, index) in swiperData" :key="index">
				<image class="banner-img" :src="`${$baseUrl}${item?.img}`" mode="aspectFill"
					@click="bannerHandler(item, index)" />
			</swiper-item>
		</swiper>

		<!-- <image @tap="backHandler" class="btnback" :src="$baseUrl + `shengzhangTool/1001/backBtn.png`"></image>
		<text class="title">生长测评</text> -->
		<view class="info-container">
			<!-- 顶部宝宝信息区域 -->
			<view class="baby-info-section">
				<view class="baby-avatar">
					<image class="avatar-img"
						:src="babyAvatar ? babyAvatar : `https://course.feihe.com/momclub-picture/common/default_avatar.png`"
						mode="aspectFill"></image>
				</view>
				<view class="baby-details">
					<view class="baby-name-row">
						<text class="baby-name">{{ babyName }}</text>
						<image class="change-baby-btn" @click="changeBaby"
							:src="`${$baseUrl}shengzhangTool/1001/changeBaby.png`" mode="aspectFit"></image>
					</view>
					<view class="baby-info-row">
						<view class="gender-age">
							<image class="gender-icon"
								:src="babyGender == 'M' ? `${$baseUrl}shengzhangTool/1001/sex1.png` : `${$baseUrl}shengzhangTool/1001/sex0.png`"
								mode="aspectFit"></image>
							<text class="age-text">{{ babyAge }}</text>
						</view>
						<text class="birth-date">{{ formatDate(babyBirthday) }}</text>
					</view>
				</view>
				<view class="record-btn" @click="viewRecords">
					<text class="record-text">测评记录</text>
					<image class="arrow-icon" :src="`${$baseUrl}shengzhangTool/1001/close.png`" mode="aspectFit">
					</image>
				</view>
			</view>

			<!-- 分割线 -->
			<image class="divider-line" :src="`${$baseUrl}shengzhangTool/1001/line.png`" mode="aspectFit"></image>

			<!-- 测评信息区域 -->
			<view class="test-info-section">
				<view class="test-date-row">
					<text class="label">本次测评日期</text>
					<view class="date-container" @click="showDatePicker">
						<text class="date-value">{{ selectedDate }}</text>
						<image class="edit-icon" :src="`${$baseUrl}shengzhangTool/1001/editIcon.png`" mode="aspectFit">
						</image>
					</view>
				</view>
				<!-- 分割线 -->
				<image class="divider-line" :src="`${$baseUrl}shengzhangTool/1001/line.png`" mode="aspectFit"></image>

				<view class="feeding-row">
					<text class="label">宝宝喂养方式</text>
					<view class="feeding-select" @click="showFeedingPopup">
						<text class="feeding-value">{{ selectedFeedText }}</text>
						<image class="dropdown-icon" :src="`${$baseUrl}shengzhangTool/1001/close.png`" mode="aspectFit">
						</image>
					</view>
				</view>
			</view>

			<!-- 测量数据区域 -->
			<view class="measurement-section">
				<view class="measurement-header">
					<view class="measurement-item">
						<text class="measurement-title">宝宝身高</text>
					</view>
					<view class="measurement-item">
						<text class="measurement-title">宝宝体重</text>
					</view>
					<view class="measurement-item">
						<text class="measurement-title">宝宝头围</text>
					</view>
				</view>

				<!-- 替换输入框区域为picker-view -->
				<view class="input-section">
					<view class="input-item">
						<view class="input-container">
							<image class="input-bg" :src="`${$baseUrl}shengzhangTool/1001/numBg.png`" mode="aspectFit">
							</image>
							<picker-view class="measurement-picker"
								:class="{ 'measurement-picker-disabled': isHeightTipActive }" :value="heightPickerValue"
								@change="onHeightChange" :indicator-style="indicatorStyle"
								indicator-class="date-picker">
								<picker-view-column>
									<view v-for="(item, index) in heightRange" :key="index" class="picker-item">
										{{ item }}
									</view>
								</picker-view-column>
							</picker-view>
							<!-- 身高输入框 -->
							<input class="measurement-input" type="number" :value="height" @input="onHeightInput"
								@blur="onHeightBlur" @focus="onHeightFocus" :disabled="isHeightTipActive"
								:style="`background-image: url(${$baseUrl}shengzhangTool/1001/numBg.png); background-size: 100% 100%; background-repeat: no-repeat;`" />
							<text class="unit">cm</text>
						</view>
					</view>
					<view class="input-item">
						<view class="input-container">
							<image class="input-bg" :src="`${$baseUrl}shengzhangTool/1001/numBg.png`" mode="aspectFit">
							</image>
							<picker-view class="measurement-picker"
								:class="{ 'measurement-picker-disabled': isWeightTipActive }" :value="weightPickerValue"
								@change="onWeightChange" :indicator-style="indicatorStyle"
								indicator-class="date-picker">
								<picker-view-column>
									<view v-for="(item, index) in weightRange" :key="index" class="picker-item">
										{{ item }}
									</view>
								</picker-view-column>
							</picker-view>
							<!-- 体重输入框 -->
							<input class="measurement-input" type="number" :value="weight" @input="onWeightInput"
								@blur="onWeightBlur" @focus="onWeightFocus" :disabled="isWeightTipActive"
								:style="`background-image: url(${$baseUrl}shengzhangTool/1001/numBg.png); background-size: 100% 100%; background-repeat: no-repeat;`" />
							<text class="unit">kg</text>
						</view>
					</view>
					<view class="input-item">
						<view class="input-container">
							<image class="input-bg" :src="`${$baseUrl}shengzhangTool/1001/numBg.png`" mode="aspectFit">
							</image>
							<picker-view class="measurement-picker"
								:class="{ 'measurement-picker-disabled': isHeadTipActive }" :value="headPickerValue"
								@change="onHeadChange" :indicator-style="indicatorStyle" indicator-class="date-picker">
								<picker-view-column>
									<view v-for="(item, index) in headRange" :key="index" class="picker-item">
										{{ item }}
									</view>
								</picker-view-column>
							</picker-view>
							<!-- 头围输入框 -->
							<input class="measurement-input" type="number" :value="headCircumference"
								@input="onHeadInput" @blur="onHeadBlur" @focus="onHeadFocus" :disabled="isHeadTipActive"
								:style="`background-image: url(${$baseUrl}shengzhangTool/1001/numBg.png); background-size: 100% 100%; background-repeat: no-repeat;`" />
							<text class="unit">cm</text>
						</view>
					</view>
				</view>

				<!-- 底部提示 -->
				<view class="tips-section">
					<!-- <view class="tip-item0" @click="toggleHeightTip">
						<text class="tip-text" :class="{ 'tip-text-active': isHeightTipActive }">暂无数据</text>
					</view>
					<view class="tip-item1" @click="toggleWeightTip">
						<text class="tip-text" :class="{ 'tip-text-active': isWeightTipActive }">暂无数据</text>
					</view> -->
					<view class="tip-item2" @click="toggleHeadTip">
						<text class="tip-text" :class="{ 'tip-text-active': isHeadTipActive }">暂无数据</text>
					</view>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-section">
				<view class="submit-btn" @click="submitData">
					<image class="submit-bg" :src="`${$baseUrl}shengzhangTool/1001/submitBtn.png`" mode="aspectFit">
					</image>
					<!-- <text class="submit-text">确认提交</text> -->
				</view>
				<view class="bottom-tip" @click="onClickTips">
					<image class="tip-icon" :src="`${$baseUrl}shengzhangTool/1001/tips.png`" mode="aspectFit"></image>
					<!-- <text class="tip-desc">如何选择你的宝宝身高、体重、头围</text> -->
				</view>
			</view>
		</view>
		<view class="guide-container" v-if="guideIndex != -1" @click="guideHandler">
			<image v-if="guideIndex == 0" class="guide-img0" :src="`${$baseUrl}shengzhangTool/1001/guide0.png`"
				mode="aspectFit"></image>
			<image v-if="guideIndex == 1" class="guide-img1" :src="`${$baseUrl}shengzhangTool/1001/guide1-2.png`"
				mode="aspectFit"></image>
			<image v-if="guideIndex == 2" class="guide-img2" :src="`${$baseUrl}shengzhangTool/1001/guide2.png`"
				mode="aspectFit"></image>
		</view>
		<view class="loading-container" v-if="showLoading">
			<view class="loading-content">
				<view class="star-container">
					<image class="loading-star" :src="`${$baseUrl}shengzhangTool/1001/loadingActImg.png`"
						mode="aspectFit"></image>
				</view>
				<view class="loading-text">
					<text class="loading-title">正在计算宝宝的生长测评得分</text>
					<text class="loading-subtitle">请耐心等待~</text>
				</view>
			</view>
		</view>
	</view>

	<!-- 在页面底部添加弹窗组件 -->
	<BabySwitchPopup v-model:visible="showBabySwitchPopup" :babyList="babyList" v-model:selectedIndex="currentBabyIndex"
		@change="onBabyChange" />

	<!-- 喂养方式弹窗 -->
	<BabyFeedSwitchPopup v-model:visible="showFeedSwitchPopup" v-model:selectedIndex="currentFeedIndex"
		@change="onFeedChange" />

	<!-- 日期选择弹窗 -->
	<DatePickerPopup v-model:visible="showDatePickerPopup" v-model:selectedDate="selectedDate"
		v-model:babyBirthday="babyBirthday" @change="onDateChange" />

	<!-- 宝宝测评提示弹窗 -->
	<BabyTestTipsPopup v-model:visible="showBabyTestTipsPopup" />
	<popup-tip v-if="isTip" type="1" @statusChange="onBabyChange1" @afterPhone="isShowRegisterLayer = true"
		@close="isTip = false" :isNotLogin="isNotLogin"></popup-tip>
	<RegisterLayer v-model="isShowRegisterLayer" @confirm="onRegisterConfirm" />
</template>

<script setup>
import { onMounted, ref, getCurrentInstance, watch } from 'vue'
import BabySwitchPopup from '@/components/BabySwitchPopup.vue'
import BabyFeedSwitchPopup from '@/components/BabyFeedSwitchPopup.vue'
import DatePickerPopup from '@/components/DatePickerPopup.vue'
import BabyTestTipsPopup from '@/components/BabyTestTipsPopup.vue'
import { growthHome, guideCompleted, getGrowthCurveData, fetchShengzhangToolsJSON } from '../../api/shengzhangTools'
import { onLoad, onShow, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { throttleTap, jump, JumpType, formatDate } from '../../utils/index.js';
import { useShengzhangStore } from '../../stores/shengzhangResult.js';
import { useUserStore } from "@/stores/user";
import md from '../../md';
import { RegisterLayer } from '@/components/RegisterLayer.vue';
import { storeToRefs } from 'pinia'

const isTip = ref(false);
const isNotLogin = ref(false);
const isShowRegisterLayer = ref(false);

const babyName = ref('宝宝名称')
const babyAge = ref('8月龄')
const babyBirthday = ref('')
const babyGender = ref('M')
const babyAvatar = ref(`https://course.feihe.com/momclub-picture/common/default_avatar.png`);

const shengzhangStore = useShengzhangStore();

const guideFlag = ref(false);
const showLoading = ref(false);

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

const bannerHandler = (item, index) => {
	console.log(item)
	let buttonName = '';
	switch (index) {
		case 0:
			buttonName = '第一张焦点图';
			break;
		case 1:
			buttonName = '第二张焦点图';
			break;
		case 2:
			buttonName = '第三张焦点图';
			break;
		case 3:
			buttonName = '第四张焦点图';
			break;
	}

	md.sensorLogTake({
		xcxClick: "生长曲线首页-banner资源位",
		pageName: "生长曲线首页",
		buttonName: buttonName,
	});

	if (item?.url != "") {
		jump({
			type: item.type,
			url: item.url,
			extra: item.extra
		})
	}
}

// 首页组件逻辑
const backHandler = () => {
	try {
		uni.navigateBack({
			success: () => {
				console.log('返回成功')
			},
			fail: backFailHandler
		})
	} catch (error) {
		console.log('error=', error)
		jump({
			type: JumpType.INNER,
			url: "/pages/index/index"
		})
	}
}

const backFailHandler = (err) => {
	console.log('backFailHandler=', err)
	jump({
		type: JumpType.INNER,
		url: "/pages/index/index"
	})
}

// 替换原有的变量
const height = ref('50.3')
const weight = ref('3.32')
const headCircumference = ref('34.5')
const babyId = ref(0);
const assessmentDate = ref('');
const feedingType = ref('');
// 添加picker-view相关数据
const indicatorStyle = `height: 40px; border: none;`

// 生成数值范围
const generateRange = (min, max, step = 0.1) => {
	const range = []
	for (let i = min; i <= max; i += step) {
		if (step < 0.1) {
			range.push(parseFloat(i.toFixed(2)))
		} else {
			range.push(parseFloat(i.toFixed(1)))
		}
	}

	console.log('range=', range)
	return range
}

// 日期选择器相关状态
const showDatePickerPopup = ref(false)
const selectedDate = ref()

const showDatePicker = () => {
	md.sensorLogTake({
		xcxClick: "生长曲线首页-本次测评日期",
		pageName: "生长曲线首页",
		buttonName: "生长曲线首页-本次测评日期-点击",
	});

	console.log('显示日期选择器')
	md.sensorPopLogTake({
		xcxPopExposure: "true",
		toolName: "生长曲线",
		popName: "选择本次测评日期弹窗"
	});
	showDatePickerPopup.value = true
}

// 处理日期选择变化
const onDateChange = (date) => {
	console.log('选择了日期:', date)
	selectedDate.value = date;
	assessmentDate.value = selectedDate.value;
}

const showFeedingPopup = () => {
	md.sensorLogTake({
		xcxClick: "生长曲线首页-宝宝喂养方式选择",
		pageName: "生长曲线首页",
		buttonName: "生长曲线首页-宝宝喂养方式选择-点击",
	});

	console.log('显示喂养方式弹窗')
	showFeedSwitchPopup.value = true
	currentFeedIndex.value = 1 // 默认选中"母乳+奶粉混合喂养"
}

// 身高范围 (40-80cm)
const heightRange = generateRange(40, 170, 0.1)
const heightPickerValue = ref([heightRange.indexOf(parseFloat(height.value))])

// 体重范围 (2-10kg)
const weightRange = generateRange(0, 50, 0.01)
const weightPickerValue = ref([weightRange.indexOf(parseFloat(weight.value))])

// 头围范围 (30-50cm)
const headRange = generateRange(20, 60.1, 0.1)
const headPickerValue = ref([headRange.indexOf(parseFloat(headCircumference.value))])

// picker-view change事件处理
const onHeightChange = (e) => {
	const index = e.detail.value[0]
	height.value = heightRange[index].toString()
	heightPickerValue.value = [index]
}

const onWeightChange = (e) => {
	const index = e.detail.value[0]
	weight.value = weightRange[index].toString()
	weightPickerValue.value = [index]
}

const onHeadChange = (e) => {
	const index = e.detail.value[0]
	headCircumference.value = headRange[index].toString()
	headPickerValue.value = [index]
}

// 输入框事件处理方法
const onHeightInput = (e) => {
	const value = e.detail.value
	height.value = value
	// 同步更新 picker 的选中位置
	const numValue = parseFloat(value)
	if (!isNaN(numValue) && numValue >= 40 && numValue <= 170) {
		const index = heightRange.findIndex(item => item >= numValue)
		if (index !== -1) {
			heightPickerValue.value = [index]
		}
	}
}

const onHeightBlur = (e) => {
	const value = parseFloat(e.detail.value)
	if (isNaN(value) || value < 40 || value > 170) {
		uni.showToast({
			title: '请输入40-170之间的身高值',
			icon: 'none'
		})
		height.value = '50.3' // 重置为默认值
		heightPickerValue.value = [heightRange.indexOf(50.3)]
	} else {
		height.value = value.toFixed(1)
	}
}

const onHeightFocus = () => {
	height.value = '' // 清空输入框
}

const onWeightInput = (e) => {
	const value = e.detail.value
	weight.value = value
	// 同步更新 picker 的选中位置
	const numValue = parseFloat(value)
	if (!isNaN(numValue) && numValue >= 0 && numValue <= 50) {
		const index = weightRange.findIndex(item => item >= numValue)
		if (index !== -1) {
			weightPickerValue.value = [index]
		}
	}
}

const onWeightBlur = (e) => {
	const value = parseFloat(e.detail.value)
	if (isNaN(value) || value < 0 || value > 50) {
		uni.showToast({
			title: '请输入0-50之间的体重值',
			icon: 'none'
		})
		weight.value = '3.32' // 重置为默认值
		weightPickerValue.value = [weightRange.indexOf(3.32)]
	} else {
		weight.value = value.toFixed(2)
	}
}

const onWeightFocus = () => {
	weight.value = '' // 清空输入框
}

const onHeadInput = (e) => {
	const value = e.detail.value
	headCircumference.value = value
	// 同步更新 picker 的选中位置
	const numValue = parseFloat(value)
	if (!isNaN(numValue) && numValue >= 20 && numValue <= 60.1) {
		const index = headRange.findIndex(item => item >= numValue)
		if (index !== -1) {
			headPickerValue.value = [index]
		}
	}
}

const onHeadBlur = (e) => {
	const value = parseFloat(e.detail.value)
	if (isNaN(value) || value < 20 || value > 60.1) {
		uni.showToast({
			title: '请输入20-60.1之间的头围值',
			icon: 'none'
		})
		headCircumference.value = '34.5' // 重置为默认值
		headPickerValue.value = [headRange.indexOf(34.5)]
	} else {
		headCircumference.value = value.toFixed(1)
	}
}

const onHeadFocus = () => {
	headCircumference.value = '' // 清空输入框
}

// 其他方法保持不变
const changeBaby = () => {
	md.sensorLogTake({
		xcxClick: "生长曲线首页-切换宝宝",
		pageName: "生长曲线首页",
		buttonName: "生长曲线首页-切换宝宝-点击",
	});
	console.log('切换宝宝')
	showBabySwitchPopup.value = true
	// currentBabyIndex.value = 0 // 默认选中第一个宝宝
}

//测评记录
const viewRecords = () => {
	md.sensorLogTake({
		xcxClick: "生长曲线首页-测评记录",
		pageName: "生长曲线首页",
		buttonName: "生长曲线首页-测评记录-点击",
	});

	jump({
		type: JumpType.INNER,
		url: "/pages/shengzhangTestResult/shengzhangTestResult?isRecords=false"
	})
}

const convertFeedingType = (type) => {
	if (type == '纯母乳') {
		return 'BREAST_MILK'
	} else if (type == '母乳+奶粉混合喂养') {
		return 'MIXED'
	} else if (type == '奶粉') {
		return 'FORMULA'
	} else if (type == '母乳+辅食') {
		return 'BREAST_MILK_CF'
	} else if (type == '奶粉+辅食') {
		return 'FORMULA_CF'
	}
}
const submitData = throttleTap(async () => {
	console.log('submitData')
	md.sensorLogTake({
		xcxClick: "生长曲线首页-确认提交",
		pageName: "生长曲线首页",
		buttonName: "生长曲线首页-确认提交-点击",
	});

	showLoading.value = true;

	if (headCircumference.value == 0) {
		headCircumference.value = null;
	}
	const submitData = {
		babyId: babyId.value,
		height: height.value,
		weight: weight.value,
		headCircumference: headCircumference.value,
		assessmentDate: assessmentDate.value,
		feedingType: convertFeedingType(selectedFeedText.value)
	};



	await shengzhangStore.assessmentSave(submitData);
	if (shengzhangStore.shengzhangInfo.success) {
		babyId.value = shengzhangStore.shengzhangInfo.babyId;
	} else {
		showLoading.value = false;

		uni.showToast({
				title: '宝宝已经超龄啦，不支持记录了哦～',
				icon: "none",
			});
		return;
	}

	const babyDataHeight = {
		babyId: babyId.value,
		curveType: 'HEIGHT',
		startMonth: 0,
		endMonth: 36,
	};

	await shengzhangStore.getGrowthCurveData(babyDataHeight);

	const babyDataWeight = {
		babyId: babyId.value,
		curveType: 'WEIGHT',
		startMonth: 0,
		endMonth: 36,
	};
	await shengzhangStore.getGrowthCurveData(babyDataWeight);

	const babyDataHead = {
		babyId: babyId.value,
		curveType: 'HEAD',
		startMonth: 0,
		endMonth: 36,
	};
	await shengzhangStore.getGrowthCurveData(babyDataHead);


	//跳转测评结果页
	if (shengzhangStore.shengzhangInfo.success) {
		jump({
			type: JumpType.INNER,
			url: "/pages/shengzhangTestResult/shengzhangTestResult"
		})
	}
	showLoading.value = false;
}, 1000)

// 添加以下数据
const showBabySwitchPopup = ref(false)
const currentBabyIndex = ref(0)

// 喂养方式弹窗相关状态
const showFeedSwitchPopup = ref(false)
const currentFeedIndex = ref(1) // 默认选中"母乳+奶粉混合喂养"
const selectedFeedText = ref('母乳+奶粉混合喂养')

// 示例宝宝列表数据
const babyList = ref([
])

// 处理宝宝选择变化
const onBabyChange = async (baby) => {
	console.log('选择了宝宝:', baby)
	// 这里可以更新页面上的宝宝信息
	// 比如更新宝宝名称、性别、生日等

	await refreshBabyInfo();
}

// 处理喂养方式选择变化
const onFeedChange = (feedOption, index) => {
	console.log('选择了喂养方式:', feedOption, index)
	selectedFeedText.value = feedOption.name
	currentFeedIndex.value = index

	// 这里可以更新页面上显示的喂养方式
	// 比如更新 feeding-select 中的文本
}

// 身高提示状态管理
const isHeightTipActive = ref(false)

// 处理身高提示点击
const toggleHeightTip = () => {
	if (!canClick(0)) return

	pushCount(0)
	isHeightTipActive.value = !isHeightTipActive.value
	console.log('身高提示状态:', isHeightTipActive.value)
}

// 体重提示状态管理
const isWeightTipActive = ref(false)

// 处理体重提示点击
const toggleWeightTip = () => {
	if (!canClick(1)) return

	pushCount(1)
	isWeightTipActive.value = !isWeightTipActive.value
	console.log('体重提示状态:', isWeightTipActive.value)
}

// 头围提示状态管理
const isHeadTipActive = ref(false)

// 处理头围提示点击
const tempHeadCircumference = ref(0);
const toggleHeadTip = () => {
	if (!canClick(2)) return

	pushCount(2)
	isHeadTipActive.value = !isHeadTipActive.value
	if (isHeadTipActive.value) {
		// 不改变输入框的值，只标记为暂无数据状态
		tempHeadCircumference.value = headCircumference.value;
		headCircumference.value = 0;
	} else {
		// 恢复原来的值
		headCircumference.value = tempHeadCircumference.value;
	}
	console.log('头围提示状态:', isHeadTipActive.value)
}

const selectCountArr = ref([])

// 数组内存在当前索引可以点击，如果不存在，在判断是不是已经选择两个了，如果已经选择两个，则不能点击
const canClick = (val) => {
	if (selectCountArr.value.indexOf(val) == -1) {
		if (selectCountArr.value.length >= 2) {
			return false
		}
		return true
	} else {
		return true
	}
}

const pushCount = (val) => {
	if (selectCountArr.value.indexOf(val) == -1) {
		selectCountArr.value.push(val)
	} else {
		selectCountArr.value.splice(selectCountArr.value.indexOf(val), 1)
	}
}

// 宝宝测评提示弹窗状态
const showBabyTestTipsPopup = ref(false)

const onClickTips = () => {
	md.sensorLogTake({
		xcxClick: "生长曲线首页-（如何确认身高、体重、头围）",
		pageName: "生长曲线首页",
		buttonName: "生长曲线首页-（如何确认身高、体重、头围）-点击",
	});

	console.log('显示宝宝测评提示弹窗')
	showBabyTestTipsPopup.value = true
}

const guideIndex = ref(-1);

const guideHandler = async () => {
	guideIndex.value++
	if (guideIndex.value > 2) {

		const data = await guideCompleted();
		if (data.success) {
			guideFlag.value = true;
			guideIndex.value = -1;
		} else {
			//引导页完成失败，提示用户
		}
	}
}

const userStore = useUserStore();
const { babyInfo } = storeToRefs(userStore)
// 获取页面参数
onLoad((options) => {
	if (options.babyId) {
		babyId.value = parseInt(options.babyId)
		console.log('获取到的babyId:', babyId.value)
	}

})
watch(babyInfo, async (newVal, oldVal) => {
	console.log(oldVal,'-----babyId发生变化，重新获取数据', newVal)
	if((!oldVal || !oldVal?.content?.id) && newVal?.content?.id){
		console.log('start重新获取数据', newVal)
		await babyRefresh();
	}
	

})

onShow(async () => {
	await babyRefresh();

})

const onRegisterConfirm = async () => {
	isShowRegisterLayer.value = false;
	await babyRefresh();
}
// 提示弹窗回调
const onBabyChange1 = async () => {
	await babyRefresh();
}

const refreshBabyInfo = async () => {
	const userStore = useUserStore();
	babyId.value = userStore.babyInfo?.content?.id;
	console.log('babyId.value=', babyId.value);

	// babyList.value = userStore.babyInfo?.allBabyBaseInfo;
	// if(babyList.value === null){
	// 	babyList.value = [];
	// }

	//切换宝宝默认选中处理
	// selectedIndex.value = userStore.babyInfo?.allBabyBaseInfo.findIndex(
	// 	(item) => item.selected
	// );

	const { data } = await growthHome(babyId.value);

	selectedDate.value = formatDate(new Date());
	// const data = {"babyId":1234,"babyName":"小强","gender":"M","monthAge":3,"avatar":"https://momclub.feihe.com/pmall/momclub-picture/integral/1009/yuerBtn.png","birthDate":"2018-10-28 14:06:45","guideFlag":false};

	babyName.value = data.babyName
	babyAge.value = data.monthAge + '月龄'
	babyBirthday.value = data.birthDate
	babyGender.value = data.gender;
	babyAvatar.value = data.avatar

	assessmentDate.value = selectedDate.value;
	feedingType.value = selectedFeedText.value;

	//暂时隐藏引导
	// guideFlag.value = data.guideFlag;

	// // guideFlag.value = false;//测试用代码
	// if (guideFlag.value) {
	// 	guideIndex.value = -1;
	// }else{
	// 	guideIndex.value = 0;
	// }
}

const babyRefresh = async () => {


	const userStore = useUserStore();
	await userStore.loadBabyInfo();
	const babyInfo = userStore.babyInfo;
	isNotLogin.value = false;
	isTip.value = false
	if (
		userStore?.userInfo?.memberId &&
		userStore?.userInfo?.memberId == "not_login" || !userStore.userInfo
	) {
		isNotLogin.value = true;
	}

	console.log(babyInfo?.babyStage + '--------------------', babyInfo)
	if (babyInfo && babyInfo.babyStage == 2) {
		isTip.value = false
		await refreshBabyInfo();
	} else {
		isTip.value = true;
	}

}

const shengzhangToolsData = ref({
	activeInfo: [
		{
			"img": "shengzhangTool/1001/banner1.png",
			"url": "subPackages/shopMainList/topicNew/index?id=1000911",
			"type": 2,
			"extra": {
				"appId": "wx4205ec55b793245e",
				"envVersion": "release"
			}
		}
	]
});

const swiperData = ref([]);
onMounted(async () => {

	md.sensorLogTake({
		xcxPage: "生长曲线首页",
		pageName: "生长曲线首页"
	});

	const { data } = await fetchShengzhangToolsJSON();
	if (data) {
		shengzhangToolsData.value = { ...data };
	} else {
		shengzhangToolsData.value = { activeInfo: [] };
	}

	swiperData.value = shengzhangToolsData?.value?.activeInfo || [];
})


onShareAppMessage(() => {

	return {
		title: "生长测评：精准评估宝宝发育水平",
		path: "/pages/shengzhangTools/shengzhangTools",
		imageUrl: $baseUrl + "share/shengzhang.png",
	}
});

onShareTimeline(() => {
	return {
		title: "生长测评：精准评估宝宝发育水平",
		path: "/pages/shengzhangTools/shengzhangTools",
		imageUrl: $baseUrl + "share/shengzhang.png",
	}
});

</script>

<style lang="less" scoped>
.shengzhang-tools-container {
	width: 100%;
	overflow-x: hidden;
	overflow-y: auto;
	background-color: #fdf6eb;
	display: flex;
	flex-flow: column;


	.banner-swiper {
		position: relative;
		width: 687rpx;
		margin-left: 32rpx;
		height: 176rpx;
		padding-bottom: 50rpx;

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

	.btnback {
		position: absolute;
		top: 119rpx;
		left: 30rpx;
		width: 29rpx;
		height: 29rpx;
	}

	.title {
		position: absolute;
		top: 111rpx;
		left: 50%;
		transform: translateX(-50%);
		font-size: 34rpx;
		color: #000;
		font-weight: 600;
	}

	.info-container {
		width: 750rpx;
		height: 1210rpx;
		// margin: 414rpx auto 0;
		background-color: #ffffff;
		border-top-left-radius: 32rpx;
		border-top-right-radius: 32rpx;
		padding: 40rpx 30rpx;
		box-sizing: border-box;
		overflow: hidden;

		.baby-info-section {
			display: flex;
			align-items: center;
			padding: 0 10rpx;

			.baby-avatar {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				overflow: hidden;
				margin-right: 20rpx;

				.avatar-img {
					width: 100%;
					height: 100%;
				}
			}

			.baby-details {
				flex: 1;

				.baby-name-row {
					display: flex;
					align-items: center;
					margin-bottom: 8rpx;

					.baby-name {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
						margin-right: 20rpx;
					}

					.change-baby-btn {
						width: 139rpx;
						height: 37rpx;
					}
				}

				.baby-info-row {
					display: flex;
					align-items: center;

					.gender-age {
						display: flex;
						align-items: center;
						margin-right: 30rpx;

						.gender-icon {
							width: 24rpx;
							height: 24rpx;
							margin-right: 8rpx;
						}

						.age-text {
							font-size: 26rpx;
							color: #666;
						}
					}

					.birth-date {
						font-size: 26rpx;
						color: #666;
					}
				}
			}

			.record-btn {
				display: flex;
				align-items: center;

				.record-text {
					font-size: 26rpx;
					color: #666;
					margin-right: 8rpx;
				}

				.arrow-icon {
					width: 20rpx;
					height: 20rpx;
				}
			}
		}

		.divider-line {
			width: 100%;
			height: 2rpx;
			margin: 20rpx 0;
		}

		.test-info-section {
			.test-date-row {
				display: flex;
				align-items: center;
				justify-content: space-between;

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

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

					.date-value {
						font-size: 28rpx;
						color: #666;
						margin-right: 10rpx;
					}

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

			.feeding-row {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 25rpx;

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

				.feeding-select {
					display: flex;
					align-items: center;

					.feeding-value {
						font-size: 28rpx;
						color: #666;
						margin-right: 8rpx;
					}

					.dropdown-icon {
						width: 20rpx;
						height: 20rpx;
					}
				}
			}
		}

		.measurement-section {
			margin-bottom: 40rpx;
			margin-top: 80rpx;


			.measurement-header {
				display: flex;
				margin-bottom: 25rpx;

				.measurement-item {
					flex: 1;
					text-align: center;

					.measurement-title {
						font-size: 28rpx;
						color: #333;
						font-weight: bold;
					}
				}
			}

			.input-section {
				display: flex;

				.input-item {
					flex: 1;
					display: flex;
					justify-content: center;

					.input-container {
						position: relative;
						display: flex;
						align-items: center;
						justify-content: center;

						.input-bg {
							position: absolute;
							width: 105rpx;
							height: 44rpx;
							z-index: 1;
						}

						.measurement-picker {
							position: relative;
							z-index: 2;
							width: 70rpx;
							height: 370rpx;
							background: transparent;

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

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

							&.measurement-picker-disabled {
								opacity: 0.4;
								pointer-events: none;
							}

							.picker-item {
								display: flex;
								align-items: center;
								justify-content: center;
								font-size: 28rpx;
								color: #333;
								font-weight: bold;
								height: 40rpx;
								line-height: 40rpx;
							}
						}

						.measurement-input {
							position: absolute;
							z-index: 3;
							width: 105rpx;
							height: 44rpx;

							margin-top: 2rpx;
							// background: #ffffff;
							border: none;
							font-size: 28rpx;
							color: #333;
							text-align: center;
							font-weight: bold;
							margin-left: 0rpx;

							&:disabled {
								opacity: 0.4;
								pointer-events: none;
							}

							&::placeholder {
								color: #999;
								font-size: 20rpx;
							}
						}

						.unit {
							position: absolute;
							z-index: 2;
							font-size: 24rpx;
							color: #666;
							margin-left: 162rpx;
							font-weight: 600;
						}
					}
				}
			}

			.tips-section {
				display: flex;

				.tip-item0 {
					flex: 1;
					text-align: center;

					&:hover {
						opacity: 0.8;
					}

					.tip-text {
						font-size: 24rpx;
						color: #1d1e26;
						text-decoration: underline;

						&.tip-text-active {
							color: red !important;
						}
					}
				}

				.tip-item1 {
					flex: 1;
					text-align: center;

					&:hover {
						opacity: 0.8;
					}

					.tip-text {
						font-size: 24rpx;
						color: #1d1e26;
						text-decoration: underline;

						&.tip-text-active {
							color: red !important;
						}
					}
				}

				.tip-item2 {
					// flex: 1;
					position: absolute;
					// text-align: center;
					right: 97rpx;

					&:hover {
						opacity: 0.8;
					}

					.tip-text {
						font-size: 24rpx;
						color: #1d1e26;
						text-decoration: underline;

						&.tip-text-active {
							color: red !important;
						}
					}
				}
			}
		}

		.submit-section {
			position: relative;
			margin-top: 130rpx;
			// bottom: 50rpx;
			// z-index: 666;

			.submit-btn {
				position: relative;
				width: 681rpx;
				height: 98rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 20rpx;

				.submit-bg {
					position: absolute;
					width: 100%;
					height: 100%;
					z-index: 1;
				}

				.submit-text {
					position: relative;
					z-index: 2;
					font-size: 32rpx;
					color: #fff;
					font-weight: bold;
				}
			}

			.bottom-tip {
				display: flex;
				align-items: center;
				justify-content: center;

				.tip-icon {
					width: 424rpx;
					height: 23rpx;
				}
			}
		}
	}

	.guide-container {
		position: absolute;
		top: 0;
		bottom: 0;
		width: 100%;
		height: 100%;
		z-index: 1000;

		.guide-img0 {
			width: 100%;
			height: 1624rpx;
			position: absolute;
			top: 0;
			left: 0;
		}

		.guide-img1 {
			width: 100%;
			height: 1624rpx;
			position: absolute;
			top: 0;
			left: 0;
		}

		.guide-img2 {
			width: 100%;
			height: 1624rpx;
			position: absolute;
			top: 0;
			left: 0;
		}
	}

	.loading-container {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.7);
		z-index: 9999;
		display: flex;
		align-items: center;
		justify-content: center;

		.loading-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			.star-container {
				margin-bottom: 60rpx;
				position: relative;

				.loading-star {
					width: 750rpx;
					height: 1624rpx;
					animation: breathe 2s ease-in-out infinite;
				}
			}

			.loading-text {
				// background-color: rgba(128, 59, 59, 0.7);
				position: absolute;
				width: 100%;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				top: 850rpx;

				.loading-title {
					font-size: 32rpx;
					color: #ffffff;
					font-weight: 500;
					line-height: 1.4;
				}

				.loading-subtitle {
					top: 40rpx;
					font-size: 32rpx;
					color: #ffffff;
					font-weight: 500;
					line-height: 1.4;
				}
			}
		}
	}

	@keyframes breathe {
		0% {
			opacity: 0.6;
		}

		50% {
			opacity: 1;
		}

		100% {
			opacity: 0.6;
		}
	}
}
</style>