<template>
	<view class="shengzhang-test-result-container">
		<view class="result-bg">
			<image class="result-bg-img0" src="/static/shengzhangTestResult/resultBg0.jpg" mode="aspectFit"></image>
			<image class="result-bg-img1" src="/static/shengzhangTestResult/resultBg1.jpg" mode="aspectFit"></image>
		</view>
		<!-- 返回按钮 -->
		<!-- <view class="back-btn" @click="backHandler">
			<text class="back-text">←</text>
		</view> -->
		<text class="title">生长测评</text>
		<image @tap="backHandler" class="back-btn" :src="`/static/shengzhangTool/backBtn.png`"></image>

		
		<view class="content-wrapper">
		
			<!-- 顶部导航标签 -->
			<view class="nav-tabs">
				<view class="tab-item" :class="{ 'active': activeTab === 'latest' }" @click="switchTab('latest')">
					<text class="tab-text">最新</text>
				</view>
				<view class="tab-item" :class="{ 'active': activeTab === 'history' }" @click="switchTab('history')">
					<text class="tab-text">历史</text>
				</view>
				<!-- <view class="tab-decoration">
					<text class="star">★</text>
					<text class="star">★</text>
					<text class="star">★</text>
				</view> -->
			</view>

			<!-- 最新内容容器 -->
			<view class="latest-content" :class="{ 'active': activeTab === 'latest' }">
				<!-- 宝宝信息卡片 -->
				<view class="baby-info-card">
					<view class="card-header">
						<image class="name-icon" src="/static/shengzhangTestResult/nameIcon.png" mode="aspectFit"></image>
						<text class="card-title">{{babyInfo.babyName}}</text>
					</view>
					<view class="baby-basic-info">
						<text class="gender">{{babyInfo.gender == 'M' ? '男' : '女'}}</text>
						<text class="age">{{babyInfo.monthAge}}月</text>
						<text class="test-date">测评于{{babyInfo.assessmentDate}}</text>
					</view>
					<view class="measurement-summary">
						<view class="values-row">
							<text class="measurement-value">{{assessmentData.height}}cm</text>
							<text class="measurement-value">{{assessmentData.weight}}kg</text>
							<text class="measurement-value">{{assessmentData.headCircumference}}cm</text>
							<text class="measurement-value">{{assessmentData.bmi}}</text>
						</view>
						<view class="labels-row">
							<view class="measurement-item">
								<text class="measurement-label">身高</text>
								<text class="measurement-status normal">{{statusMap[analysisData.heightStatus]}}</text>
							</view>
							<view class="measurement-item">
								<text class="measurement-label">体重</text>
								<text class="measurement-status normal">{{statusMap[analysisData.weightStatus]}}</text>
							</view>
							<view class="measurement-item">
								<text class="measurement-label">头围</text>
								<text class="measurement-status normal">{{statusMap[analysisData.headStatus]}}</text>
							</view>
							<view class="measurement-item">
								<text class="measurement-label">BMI</text>
								<text class="measurement-status normal">{{statusMap[analysisData.bmiStatus]}}</text>
							</view>
						</view>
					</view>
					<view class="growth-evaluation">
						<text class="evaluation-text">{{contentText.evaluation}}</text>
					</view>
				</view>

				<!-- 生长情况卡片 -->
				<view class="growth-status-card">
					<view class="card-header">
						<image class="status-icon" src="/static/shengzhangTestResult/shengzhangqingkuangIcon.png" mode="aspectFit"></image>
						<text class="card-title">生长情况</text>
					</view>
					<view class="legend">
						<view class="legend-item">
							<view class="legend-color too-low"></view>
							<text class="legend-text">偏低</text>
						</view>
						<view class="legend-item">
							<view class="legend-color slightly-low"></view>
							<text class="legend-text">略低</text>
						</view>
						<view class="legend-item">
							<view class="legend-color normal"></view>
							<text class="legend-text">正常</text>
						</view>
						<view class="legend-item">
							<view class="legend-color slightly-high"></view>
							<text class="legend-text">略高</text>
						</view>
						<view class="legend-item">
							<view class="legend-color too-high"></view>
							<text class="legend-text">偏高</text>
						</view>
					</view>
					<view class="measurement-bars">
						<view class="bar-item" >
							<view class="value-triangle-container" :style="{marginLeft: statusBarPercentileMap[analysisData.heightStatus] + 'rpx'}">
								<text class="bar-value">{{assessmentData.height}}cm {{statusMap[analysisData.heightStatus]}}</text>
								<image class="triangle" src="/static/shengzhangTestResult/triangle.png" mode="aspectFit"></image>
							</view>
							<view class="bar-row">
								<text class="measurement-label">身高</text>
								<image class="value-bar" src="/static/shengzhangTestResult/valueBar.png" mode="aspectFit"></image>
								<text class="bar-percentage">超过{{analysisData.heightPercentile}}%同龄宝宝</text>
							</view>
						</view>
						<view class="bar-item">
							<view class="value-triangle-container" :style="{marginLeft: statusBarPercentileMap[analysisData.weightStatus] + 'rpx'}">
								<text class="bar-value">{{assessmentData.weight}}kg {{statusMap[analysisData.weightStatus]}}</text>
								<image class="triangle" src="/static/shengzhangTestResult/triangle.png" mode="aspectFit"></image>
							</view>
							<view class="bar-row">
								<text class="measurement-label">体重</text>
								<image class="value-bar" src="/static/shengzhangTestResult/valueBar.png" mode="aspectFit"></image>
								<text class="bar-percentage">超过{{analysisData.weightPercentile}}%同龄宝宝</text>
							</view>
						</view>
						<view class="bar-item">
							<view class="value-triangle-container" :style="{marginLeft: statusBarPercentileMap[analysisData.headStatus] + 'rpx'}">
								<text class="bar-value">{{assessmentData.headCircumference}}cm {{statusMap[analysisData.headStatus]}}</text>
								<image class="triangle" src="/static/shengzhangTestResult/triangle.png" mode="aspectFit"></image>
							</view>
							<view class="bar-row">
								<text class="measurement-label">头围</text>
								<image class="value-bar" src="/static/shengzhangTestResult/valueBar.png" mode="aspectFit"></image>
								<text class="bar-percentage">超过{{analysisData.headPercentile}}%同龄宝宝</text>
							</view>
						</view>
						<view class="bar-item">
							<view class="value-triangle-container" :style="{marginLeft: statusBarPercentileMap[analysisData.bmiStatus] + 'rpx'}">
								<text class="bar-value">{{assessmentData.bmi}} {{statusMap[analysisData.bmiStatus]}}</text>
								<image class="triangle" src="/static/shengzhangTestResult/triangle.png" mode="aspectFit"></image>
							</view>
							<view class="bar-row">
								<text class="measurement-label">BMI</text>
								<image class="value-bar" src="/static/shengzhangTestResult/valueBar.png" mode="aspectFit"></image>
								<text class="bar-percentage">超过{{analysisData.bmiPercentile}}%同龄宝宝</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 生长曲线卡片 -->
				<view class="growth-curve-card">
					<view class="card-header">
						<text class="card-title">生长曲线</text>
					</view>
					<view class="curve-tabs">
						<view class="curve-tab" :class="{ 'active': activeCurveTab === 'height' }" @click="switchCurveTab('height')">
							<image v-if="activeCurveTab === 'height'"class="tab-icon" src="/static/shengzhangTestResult/shengaoTab0.png" mode="aspectFit"></image>
							<image v-else class="tab-icon" src="/static/shengzhangTestResult/shengaoTab1.png" mode="aspectFit"></image>
						</view>
						<view class="curve-tab" :class="{ 'active': activeCurveTab === 'weight' }" @click="switchCurveTab('weight')">
							<image v-if="activeCurveTab === 'weight'" class="tab-icon" src="/static/shengzhangTestResult/tizhongTab0.png" mode="aspectFit"></image>
							<image v-else class="tab-icon" src="/static/shengzhangTestResult/tizhongTab1.png" mode="aspectFit"></image>
						</view>
						<view class="curve-tab" :class="{ 'active': activeCurveTab === 'head' }" @click="switchCurveTab('head')">
							<image v-if="activeCurveTab === 'head'" class="tab-icon" src="/static/shengzhangTestResult/touweiTab0.png" mode="aspectFit"></image>
							<image v-else class="tab-icon" src="/static/shengzhangTestResult/touweiTab1.png" mode="aspectFit"></image>
						</view>
					</view>
					<view class="graph-legend">
						<view class="legend-item">
							<view class="legend-color slightly-low"></view>
							<text class="legend-text">略低</text>
						</view>
						<view class="legend-item">
							<view class="legend-color normal"></view>
							<text class="legend-text">正常</text>
						</view>

						<view class="legend-item">
							<view class="legend-color slightly-high"></view>
							<text class="legend-text">略高</text>
						</view>
						<view class="legend-item">
							<view class="legend-color baby-record"></view>
							<text class="legend-text">宝宝记录</text>
						</view>
					</view>
					<view class="graph-title-y">
						<text class="graph-title-text">{{getYAxisLabel()}}</text>
					</view>
					<view class="graph-container">
						<scroll-view class="graph-scroll" scroll-x="true" :scroll-left="scrollLeft" @scroll="onScroll">
							<view class="graph-content" :style="{ width: totalWidth + 'px' }">
								<canvas class="curve-canvas" canvas-id="growthCurve" :style="{ width: totalWidth + 'px', height: '100%' }"></canvas>
							</view>
						</scroll-view>
					</view>
				</view>

				<view class="curve-tips" @click="showCurveTips">
					<image class="tips-icon" src="/static/shengzhangTestResult/shengzhangTips.png" mode="aspectFit"></image>
				</view>
				
			</view>
		</view>

		<!-- 历史内容容器 -->
		<view class="history-content" :class="{ 'active': activeTab === 'history' }">
			<view class="history-list">
				<view class="history-item" v-for="(item, index) in historyList" :key="index" @click="selectHistoryItem(item)">
					<view class="history-card">
						<view class="card-header">
							<image class="name-icon" src="/static/shengzhangTestResult/nameIcon.png" mode="aspectFit"></image>
							<text class="card-title">宝宝名称</text>
						</view>
						<view class="baby-basic-info">
							<text class="gender">{{item.gender}}</text>
							<text class="age">{{item.age}}</text>
							<text class="test-date">测评于{{item.testDate}}</text>
						</view>
						<view class="measurement-summary">
							<view class="values-row">
								<text class="measurement-value">{{item.height}}cm</text>
								<text class="measurement-value">{{item.weight}}kg</text>
								<text class="measurement-value">{{item.head}}cm</text>
								<text class="measurement-value">{{item.bmi}}</text>
							</view>
							<view class="labels-row">
								<view class="measurement-item">
									<text class="measurement-label">身高</text>
									<text class="measurement-status normal">正常</text>
								</view>
								<view class="measurement-item">
									<text class="measurement-label">体重</text>
									<text class="measurement-status normal">正常</text>
								</view>
								<view class="measurement-item">
									<text class="measurement-label">头围</text>
									<text class="measurement-status normal">正常</text>
								</view>
								<view class="measurement-item">
									<text class="measurement-label">BMI</text>
									<text class="measurement-status normal">正常</text>
								</view>
							</view>
						</view>
						<view class="growth-evaluation">
							<text class="evaluation-text">{{item.evaluation}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

<!-- 专家咨询按钮 -->
				<view class="expert-consult-btn" @click="consultExpert">
					<image class="consult-bg" src="/static/shengzhangTestResult/zhuanjiazixunBtn.png" mode="aspectFit"></image>
				</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useShengzhangStore } from '../../stores/shengzhangResult.js';
import { formatDate, jump, JumpType } from '../../utils/index.js';
import { getGrowthHistoryList } from '../../api/shengzhangTools';

// 导航标签状态
const activeTab = ref('latest') // 默认显示最新内容

// 生长曲线标签状态
const activeCurveTab = ref('height')

// 滑动相关状态
const scrollLeft = ref(0)
const totalWidth = ref(1080) // 36个月 * 10px
const babyInfo = ref({
	babyName: '宝宝名称',
	gender: 'M',
	monthAge: '12',
	avatar: '',
	assessmentDate: '1749139200000',
})

const analysisData = ref({
	bmiPercentile: 0,
	bmiStatus: "LOW",
	headPercentile: 0,
	headStatus: "LOW",
	heightPercentile: 0,
	heightStatus: "LOW",
	weightPercentile: 0,
	weightStatus: "LOW"
	
})

const assessmentData = ref({
	bmi: 13.12,
	feedingType: "MIXED",
	headCircumference: 34.5,
	height: 50.3,
	weight: 3.32
})

const contentText = ref({
	evaluation: "描述",
	shareText: "描述",
	summary: "描述"
});

const statusBarPercentileMap = {
	NORMAL: 177,
	SLIGHT_LOW: 110,
	SLIGHT_HIGH: 247,
	LOW: 43,
	HIGH: 314
}

// 历史数据列表
const historyList = ref([
	{
		gender: '男',
		age: '2月21天',
		testDate: '2025年06月06日',
		height: '60.6',
		weight: '5.8',
		head: '39.0',
		bmi: '16.0',
		evaluation: '宝宝发育的非常棒,身高、体重和头围都处于正常的发育水平。TA与大多数宝宝一样,正在健康苗壮地成长。建议定期观察和记录宝宝的体格发育数据,这样有利于评估宝宝的生长发育情况,能够及时发现宝宝生长发育过程中的存在的问题和异常。'
	},
	{
		gender: '男',
		age: '1月15天',
		testDate: '2025年05月01日',
		height: '55.2',
		weight: '4.5',
		head: '36.8',
		bmi: '14.8',
		evaluation: '宝宝发育良好,各项指标都在正常范围内。建议继续保持良好的喂养习惯,定期进行生长发育监测。'
	},
	{
		gender: '男',
		age: '3月05天',
		testDate: '2025年07月20日',
		height: '62.1',
		weight: '6.2',
		head: '40.5',
		bmi: '16.1',
		evaluation: '宝宝生长发育稳定,身高、体重增长符合预期。头围发育正常,整体健康状况良好。'
	}
])



// 生长曲线数据
const curveData = ref([
	{ month: 1.5, height: 56 },
	{ month: 3.5, height: 67 },
	{ month: 7, height: 72 }
])

const curveDataPostHeight = ref([]);
const curveDataPostWeight = ref([]);
const curveDataPostHead = ref([]);
// 生成0-36个月的数据点
/**
 * @param {number} startValue - 起始值（0个月时的数值）
 * @param {number} endValue - 结束值（36个月时的数值）
 * @param {string} type - 数据类型（'height'|'weight'|'head'）
 * @returns {Array} 包含36个月数据点的数组
 */
const generateCurveData = (startValue, endValue, type) => {
	const data = []
	for (let i = 0; i <= 36; i++) {
		const value = startValue + (endValue - startValue) * (i / 36)
		const point = { month: i }
		point[type] = Math.round(value * 10) / 10
		data.push(point)
	}
	return data
}

//获取宝宝曲线数据范围4条线，用于绘制曲线
const generateCurveData1 = (lineData, type, arrayName, minOrMax) =>{
	const data = [];
	lineData.forEach(element => {
		const point = { month: element.monthAge }
		point[type] = minOrMax === 'min' ? element?.[arrayName]?.min : element?.[arrayName]?.max
		data.push(point);
	});

	console.log('data888888=', data);
	return data;
}
// slightHighRange
// slightLowRange
// 标准生长曲线数据（多条线，延长到36个月）
const standardCurves = ref({
	height: {
		slightlyLow: generateCurveData1(curveDataPostHeight.value, 'height', 'slightLowRange', 'min'),
		// normal: generateCurveData(50, 110, 'height'),
		normal: generateCurveData1(curveDataPostHeight.value, 'height', 'normalRange', 'min'),
		normal2: generateCurveData1(curveDataPostHeight.value, 'height', 'normalRange', 'max'), // 新增的a8e6cf颜色曲线
		slightlyHigh: generateCurveData1(curveDataPostHeight.value, 'height', 'slightHighRange', 'max')
	},
	weight: {
		slightlyLow: generateCurveData1(curveDataPostWeight.value, 'weight', 'slightLowRange', 'min'),
		normal: generateCurveData1(curveDataPostWeight.value, 'weight', 'normalRange', 'min'),
		normal2: generateCurveData1(curveDataPostWeight.value, 'weight', 'normalRange', 'max'), // 新增的a8e6cf颜色曲线
		slightlyHigh: generateCurveData1(curveDataPostWeight.value, 'weight', 'slightHighRange', 'max')
	},
	head: {
		slightlyLow: generateCurveData1(curveDataPostHead.value, 'head', 'slightLowRange', 'min'),
		normal: generateCurveData1(curveDataPostHead.value, 'head', 'normalRange', 'min'),
		normal2: generateCurveData1(curveDataPostHead.value, 'head', 'normalRange', 'max'), // 新增的a8e6cf颜色曲线
		slightlyHigh: generateCurveData1(curveDataPostHead.value, 'head', 'slightHighRange', 'max')
	}
})

const statusMap = {
	NORMAL: '正常',
	SLIGHT_LOW: '略低',
	SLIGHT_HIGH: '略高',
	LOW: '偏低',
	HIGH: '偏高'
}

// 切换导航标签
/**
 * @param {string} tab - 要切换的标签名称（'latest'|'history'）
 */
const switchTab = (tab) => {
	activeTab.value = tab
	console.log('切换到标签:', tab)
}

// 选择历史记录项
/**
 * @param {Object} item - 选中的历史记录项
 */
const selectHistoryItem = (item) => {
	console.log('选择历史记录:', item)
	// 这里可以添加跳转到详情页或更新当前显示数据的逻辑
	uni.showToast({
		title: '已选择历史记录',
		icon: 'success'
	})
}

// 切换生长曲线标签
/**
 * @param {string} tab - 要切换的曲线类型（'height'|'weight'|'head'）
 */
const switchCurveTab = (tab) => {
	activeCurveTab.value = tab
	console.log('切换到曲线标签:', tab)
	
	// 根据不同的标签更新曲线数据
	if (tab === 'height') {
		curveData.value = [
			{ month: 1.5, height: 56 },
			{ month: 3.5, height: 67 },
			{ month: 7, height: 72 }
		]
	} else if (tab === 'weight') {
		curveData.value = [
			{ month: 1.5, weight: 4.2 },
			{ month: 3.5, weight: 6.8 },
			{ month: 7, weight: 8.5 }
		]
	} else if (tab === 'head') {
		curveData.value = [
			{ month: 1.5, head: 36 },
			{ month: 3.5, head: 41 },
			{ month: 7, head: 44 }
		]
	}
	
	// 重新绘制曲线
	setTimeout(() => {
		drawGrowthCurve()
	}, 100)
}

//获取当前宝宝曲线数据，用于绘制曲线
const generateCurveData2 = (lineData, type, arrayName, minOrMax) =>{
	const data = [];
	lineData.forEach(element => {
		const point = { month: element.monthAge }
		point[type] = minOrMax === 'min' ? element?.[arrayName]?.min : element?.[arrayName]?.max
		data.push(point);
	});
	return data;
}

// 获取Y轴标签
/**
 * @returns {string} 根据当前曲线类型返回对应的Y轴标签
 */
const getYAxisLabel = () => {
	if (activeCurveTab.value === 'height') {
		return '身高 (cm)'
	} else if (activeCurveTab.value === 'weight') {
		return '体重 (kg)'
	} else if (activeCurveTab.value === 'head') {
		return '头围 (cm)'
	}
	return '身高 (cm)'
}

// 获取Y轴刻度
/**
 * @returns {Array<number>} 根据当前曲线类型返回对应的Y轴刻度数组
 */
const getYTicks = () => {
	if (activeCurveTab.value === 'height') {
		return [40, 50, 60, 70, 80, 90, 100]
	} else if (activeCurveTab.value === 'weight') {
		return [0, 3, 6, 9, 12, 15, 18]
	} else if (activeCurveTab.value === 'head') {
		return [0, 3, 6, 9, 12, 15, 18]
	}
	return [40, 50, 60, 70, 80, 90, 100]
}

// 显示生长曲线提示
/**
 * 显示生长曲线说明弹窗
 */
const showCurveTips = () => {
	console.log('显示生长曲线提示')
	uni.showModal({
		title: '生长曲线说明',
		content: '生长曲线是根据大量同龄宝宝的生长发育数据绘制的标准曲线，用于评估宝宝的生长发育是否正常。',
		showCancel: false
	})
}

// 专家咨询
/**
 * 处理专家咨询按钮点击事件
 */
const consultExpert = () => {
	console.log('专家在线咨询')
	uni.showToast({
		title: '正在连接专家...',
		icon: 'loading'
	})
}

// 首页组件逻辑
/**
 * 处理返回按钮点击事件，尝试返回上一页或跳转到首页
 */
const backHandler = () => {
	console.log('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 = () => {
	console.log('backFailHandler');
}

onMounted(async () => {
	// 初始化绘制曲线
	setTimeout(() => {
		drawGrowthCurve()
	}, 100)

	//分析结果处理
	const shengzhangStore = useShengzhangStore();
	const data = {...shengzhangStore.shengzhangInfo.babyInfo};
	data.assessmentDate = formatDate(shengzhangStore.shengzhangInfo.assessmentDate);
	babyInfo.value = data;


	analysisData.value = shengzhangStore.shengzhangInfo.analysis;
	assessmentData.value = shengzhangStore.shengzhangInfo.assessmentData;


	contentText.value = shengzhangStore.shengzhangInfo.content;

	//生长曲线处理
	curveDataPostHeight.value = shengzhangStore.getGrowthCurveDataInfoHeight.curveData;
	curveDataPostWeight.value = shengzhangStore.getGrowthCurveDataInfoWeight.curveData;
	curveDataPostHead.value = shengzhangStore.getGrowthCurveDataInfoHead.curveData;
	console.log('curveDataPostHeight.value=', curveDataPostHeight.value);

	standardCurves.value = {
		height: {
			// slightlyLow: generateCurveData(45, 105, 'height'),
			// normal: generateCurveData(50, 110, 'height'),
			slightlyLow: generateCurveData1(curveDataPostHeight.value, 'height', 'slightLowRange', 'min'),
			normal: generateCurveData1(curveDataPostHeight.value, 'height', 'normalRange', 'min'),
			normal2: generateCurveData1(curveDataPostHeight.value, 'height', 'normalRange', 'max'), // 新增的a8e6cf颜色曲线
			slightlyHigh: generateCurveData1(curveDataPostHeight.value, 'height', 'slightHighRange', 'max'),
			// slightlyHigh: generateCurveData(55, 115, 'height')slightHighRange
		},
		weight: {
			// slightlyLow: generateCurveData(2.5, 15.0, 'weight'),
			// normal: generateCurveData(3.0, 16.5, 'weight'),
			// normal2: generateCurveData(3.2, 17.0, 'weight'), // 新增的a8e6cf颜色曲线
			// slightlyHigh: generateCurveData(3.5, 18.0, 'weight')

			slightlyLow: generateCurveData1(curveDataPostWeight.value, 'weight', 'slightLowRange', 'min'),
			normal: generateCurveData1(curveDataPostWeight.value, 'weight', 'normalRange', 'min'),
			normal2: generateCurveData1(curveDataPostWeight.value, 'weight', 'normalRange', 'max'), // 新增的a8e6cf颜色曲线
			slightlyHigh: generateCurveData1(curveDataPostWeight.value, 'weight', 'slightHighRange', 'max'),
		},
		head: {
			// slightlyLow: generateCurveData(32, 52, 'head'),
			// normal: generateCurveData(34, 54, 'head'),
			// normal2: generateCurveData(35, 55, 'head'), // 新增的a8e6cf颜色曲线
			// slightlyHigh: generateCurveData(36, 56, 'head')

			slightlyLow: generateCurveData1(curveDataPostHead.value, 'head', 'slightLowRange', 'min'),
			normal: generateCurveData1(curveDataPostHead.value, 'head', 'normalRange', 'min'),
			normal2: generateCurveData1(curveDataPostHead.value, 'head', 'normalRange', 'max'), // 新增的a8e6cf颜色曲线
			slightlyHigh: generateCurveData1(curveDataPostHead.value, 'head', 'slightHighRange', 'max'),
		}
	};

	debugger;
	const historyListData = await getGrowthHistoryList();
	console.log('historyListData=', historyListData);
})

// 绘制生长曲线
/**
 * 绘制完整的生长曲线图表，包括坐标轴、标准曲线和宝宝记录曲线
 */
const drawGrowthCurve = () => {
	const query = uni.createSelectorQuery()
	query.select('.curve-canvas').boundingClientRect((rect) => {
		if (rect) {
			const ctx = uni.createCanvasContext('growthCurve')
			const width = rect.width
			const height = rect.height
			
			// 清空画布
			ctx.clearRect(0, 0, width, height)
			
			// 设置画布边距
			const margin = { top: 20, right: 20, bottom: 25, left: 30 }
			const chartWidth = width - margin.left - margin.right
			const chartHeight = height - margin.top - margin.bottom
			
			// 获取当前数据类型
			const currentType = activeCurveTab.value
			const currentCurves = standardCurves.value[currentType]
			
			// 绘制坐标轴
			drawAxes(ctx, width, height, margin, chartWidth, chartHeight, currentType)
			
			// 绘制标准曲线
			drawStandardCurves(ctx, currentCurves, margin, chartWidth, chartHeight, currentType)
			
			// 绘制宝宝记录曲线
			drawBabyCurve(ctx, curveData.value, margin, chartWidth, chartHeight, currentType)
			
			ctx.draw()
		}
	}).exec()
}

// 绘制坐标轴
/**
 * @param {Object} ctx - Canvas上下文对象
 * @param {number} width - Canvas总宽度
 * @param {number} height - Canvas总高度
 * @param {Object} margin - 边距对象 {top, right, bottom, left}
 * @param {number} chartWidth - 图表区域宽度
 * @param {number} chartHeight - 图表区域高度
 * @param {string} type - 数据类型（'height'|'weight'|'head'）
 */
const drawAxes = (ctx, width, height, margin, chartWidth, chartHeight, type) => {
	console.log('drawAxes', width, height, margin, chartWidth, chartHeight, type);
	// 绘制X轴
	ctx.beginPath()
	ctx.setStrokeStyle('#000')
	ctx.setLineWidth(2)
	ctx.moveTo(margin.left, height - margin.bottom)
	ctx.lineTo(width - margin.right, height - margin.bottom)
	ctx.stroke()
	
	// 先绘制水平网格线
	const yTicks = getYTicks()
	yTicks.forEach((tick, index) => {
		const y = margin.top + (1 - index / (yTicks.length - 1)) * chartHeight
		
		// 绘制水平网格线
		ctx.beginPath()
		ctx.setStrokeStyle('#faf2e7')
		ctx.setLineWidth(1)
		ctx.moveTo(margin.left, y)
		ctx.lineTo(width - margin.right, y)
		ctx.stroke()
	})
	
	// 绘制Y轴
	ctx.beginPath()
	ctx.setStrokeStyle('#000')
	ctx.setLineWidth(1)
	ctx.moveTo(margin.left, margin.top - 8)
	ctx.lineTo(margin.left, height - margin.bottom)
	ctx.stroke()
	
	// 绘制X轴箭头
	ctx.beginPath()
	ctx.moveTo(width - margin.right, height - margin.bottom)
	ctx.lineTo(width - margin.right - 8, height - margin.bottom - 4)
	ctx.lineTo(width - margin.right - 8, height - margin.bottom + 4)
	ctx.closePath()
	ctx.setFillStyle('#000')
	ctx.fill()
	
	// 绘制Y轴箭头
	ctx.beginPath()
	ctx.moveTo(margin.left, margin.top - 16)
	ctx.lineTo(margin.left - 4, margin.top + 8 - 16)
	ctx.lineTo(margin.left + 4, margin.top + 8 - 16)
	ctx.closePath()
	ctx.fill()
	
	// 绘制X轴刻度（每个月都显示）
	const xTicks = []
	for (let i = 0; i <= 36; i++) {
		xTicks.push(i)
	}
	xTicks.forEach((tick) => {
		const x = margin.left + (tick / 36) * chartWidth
		const y = height - margin.bottom
		// 刻度线
		// ctx.beginPath()
		// ctx.setStrokeStyle('#000')
		// ctx.setLineWidth(1)
		// ctx.moveTo(x, y)
		// ctx.lineTo(x, y) // 缩短为原来的30%
		// ctx.stroke()
		// 刻度标签
		ctx.setFillStyle('#000')
		ctx.setFontSize(12)
		ctx.setTextAlign('center')
		ctx.fillText(tick.toString(), x, y + 20)
	})
	
	// 绘制Y轴刻度和标签
	yTicks.forEach((tick, index) => {
		const x = margin.left
		const y = margin.top + (1 - index / (yTicks.length - 1)) * chartHeight
		
		// 刻度线
		// ctx.beginPath()
		// ctx.setStrokeStyle('#999')
		// ctx.setLineWidth(1)
		// ctx.moveTo(x, y)
		// ctx.lineTo(x - 5, y)
		// ctx.stroke()
		
		// 刻度标签
		ctx.setFillStyle('#000')
		ctx.setFontSize(12)
		ctx.setTextAlign('right')
		ctx.fillText(tick.toString(), x - 10, y + 4)
	})
	
	// 绘制坐标轴标签
	ctx.setFillStyle('#000')
	ctx.setFontSize(14)
	ctx.setTextAlign('center')
	ctx.fillText('月龄', width / 2, height - 10)
	
	// ctx.setTextAlign('center')
	// ctx.setFontSize(14)
	// const yLabel = getYAxisLabel()
	// ctx.save()
	// ctx.translate(20, height / 2)
	// // ctx.rotate(-Math.PI / 2)
	// ctx.fillText(yLabel, 0, -100)
	// ctx.restore()
}

// 绘制标准曲线
/**
 * @param {Object} ctx - Canvas上下文对象
 * @param {Object} curves - 标准曲线数据对象 {slightlyLow, normal, slightlyHigh}
 * @param {Object} margin - 边距对象 {top, right, bottom, left}
 * @param {number} chartWidth - 图表区域宽度
 * @param {number} chartHeight - 图表区域高度
 * @param {string} type - 数据类型（'height'|'weight'|'head'）
 */
const drawStandardCurves = (ctx, curves, margin, chartWidth, chartHeight, type) => {
	// 绘制略低曲线 - 黄色
	drawCurve(ctx, curves.slightlyLow, margin, chartWidth, chartHeight, type, '#ffeaa7', 2)
	
	// 绘制正常曲线 - 浅绿色
	drawCurve(ctx, curves.normal, margin, chartWidth, chartHeight, type, '#a8e6cf', 2)
	
	// 绘制新增的正常曲线2 - 浅绿色（不重合）
	drawCurve(ctx, curves.normal2, margin, chartWidth, chartHeight, type, '#a8e6cf', 2)
	
	// 绘制略高曲线 - 紫色
	drawCurve(ctx, curves.slightlyHigh, margin, chartWidth, chartHeight, type, '#d4a5f5', 2)
}

// 绘制单条曲线
/**
 * @param {Object} ctx - Canvas上下文对象
 * @param {Array} data - 曲线数据点数组，每个元素包含 {month, height/weight/head}
 * @param {Object} margin - 边距对象 {top, right, bottom, left}
 * @param {number} chartWidth - 图表区域宽度
 * @param {number} chartHeight - 图表区域高度
 * @param {string} type - 数据类型（'height'|'weight'|'head'）
 * @param {string} color - 曲线颜色（十六进制颜色值）
 * @param {number} lineWidth - 曲线线宽
 */
const drawCurve = (ctx, data, margin, chartWidth, chartHeight, type, color, lineWidth) => {
	ctx.beginPath()
	ctx.setStrokeStyle(color)
	ctx.setLineWidth(lineWidth)
	
	data.forEach((point, index) => {
		const x = margin.left + (point.month / 36) * chartWidth
		let y = 0
		
		// 根据不同的数据类型计算y坐标
		if (type === 'height') {
			y = margin.top + (1 - (point.height - 40) / 80) * chartHeight
		} else if (type === 'weight') {
			y = margin.top + (1 - (point.weight - 2) / 16) * chartHeight
		} else if (type === 'head') {
			y = margin.top + (1 - (point.head - 30) / 30) * chartHeight
		}
		
		if (index === 0) {
			ctx.moveTo(x, y)
		} else {
			ctx.lineTo(x, y)
		}
	})
	
	ctx.stroke()
}

// 绘制宝宝记录曲线
/**
 * @param {Object} ctx - Canvas上下文对象
 * @param {Array} data - 宝宝记录数据点数组，每个元素包含 {month, height/weight/head}
 * @param {Object} margin - 边距对象 {top, right, bottom, left}
 * @param {number} chartWidth - 图表区域宽度
 * @param {number} chartHeight - 图表区域高度
 * @param {string} type - 数据类型（'height'|'weight'|'head'）
 */
const drawBabyCurve = (ctx, data, margin, chartWidth, chartHeight, type) => {
	// 绘制折线
	ctx.beginPath()
	ctx.setStrokeStyle('#8b4513')
	ctx.setLineWidth(1)
	
	data.forEach((point, index) => {
		const x = margin.left + (point.month / 36) * chartWidth
		let y = 0
		
		// 根据不同的数据类型计算y坐标
		if (type === 'height') {
			y = margin.top + (1 - (point.height - 40) / 80) * chartHeight
		} else if (type === 'weight') {
			y = margin.top + (1 - (point.weight - 2) / 16) * chartHeight
		} else if (type === 'head') {
			y = margin.top + (1 - (point.head - 30) / 30) * chartHeight
		}
		
		if (index === 0) {
			ctx.moveTo(x, y)
		} else {
			ctx.lineTo(x, y)
		}
	})
	
	ctx.stroke()
	
	// 绘制数据点
	data.forEach((point) => {
		const x = margin.left + (point.month / 36) * chartWidth
		let y = 0
		
		// 根据不同的数据类型计算y坐标
		if (type === 'height') {
			y = margin.top + (1 - (point.height - 40) / 80) * chartHeight
		} else if (type === 'weight') {
			y = margin.top + (1 - (point.weight - 2) / 16) * chartHeight
		} else if (type === 'head') {
			y = margin.top + (1 - (point.head - 30) / 30) * chartHeight
		}
		
		ctx.beginPath()
		ctx.setFillStyle('#8b4513')
		ctx.arc(x, y, 6, 0, 2 * Math.PI)
		ctx.fill()
	})
}

// 获取X轴刻度
/**
 * @returns {Array<number>} 返回0-36个月的X轴刻度数组
 */
// const getXTicks = () => {
// 	const ticks = []
// 	for (let i = 0; i <= 36; i++) {
// 		ticks.push(i)
// 	}
// 	return ticks
// }

// 处理滑动事件
/**
 * @param {Object} e - 滑动事件对象
 * @param {number} e.detail.scrollLeft - 当前滑动位置
 */
const onScroll = (e) => {
	scrollLeft.value = e.detail.scrollLeft
}
</script>

<style lang="less" scoped>
.shengzhang-test-result-container {
	width: 100%;
	height: 2700rpx;
	// box-sizing: border-box;
	position: relative;
	overflow: hidden;

	
	.result-bg{
		top: 0rpx;
		width: 100%;
		height: 2700rpx;
		position: absolute;
		.result-bg-img0{
			position: absolute;
			top: 0rpx;
			width: 100%;
			height: 1300rpx;
		}
		.result-bg-img1{
			position: absolute;
			top: 1300rpx;
			width: 100%;
			height: 1400rpx;
		}
	}
	
	// 内容容器
	.content-wrapper {
		padding-left: 30rpx;
		padding-right: 30rpx;
	}

	// 最新内容容器
	.latest-content {
		display: none;
		
		&.active {
			display: block;
		}
	}

	// 历史内容容器
	.history-content {
		padding-left: 30rpx;
		padding-right: 30rpx;
		display: none;
		
		&.active {
			display: block;
		}

		.history-list {
			margin-top: 46rpx;
		}

		.history-item {
			margin-bottom: 30rpx;
		}

		.history-card {
			background-color: #fff;
			border-radius: 24rpx;
			padding: 50rpx 35rpx 35rpx 35rpx;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
			position: relative;
			transition: all 0.3s ease;

			&:active {
				transform: scale(0.98);
				opacity: 0.8;
			}

			.card-header {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;

				.name-icon,
				.status-icon {
					width: 32rpx;
					height: 32rpx;
					margin-right: 10rpx;
				}

				.card-title {
					font-size: 32rpx;
					color: #333;
					font-weight: bold;
				}
			}

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

				.gender {
					font-size: 24rpx;
					color: #000;
					margin-right: 20rpx;
				}

				.age {
					font-size: 24rpx;
					color: #000;
					margin-right: 20rpx;
				}

				.test-date {
					font-size: 24rpx;
					color: #000;
				}
			}

			.measurement-summary {
				display: flex;
				flex-direction: column;
				margin-bottom: 30rpx;

				.values-row {
					display: flex;
					justify-content: space-between;
					margin-bottom: 15rpx;

					.measurement-value {
						font-size: 32rpx;
						color: #333;
						font-weight: bold;
						flex: 1;
						text-align: center;
					}
				}

				.labels-row {
					display: flex;
					justify-content: space-between;

					.measurement-item {
						display: flex;
						flex-direction: row;
						align-items: center;
						flex: 1;
						justify-content: center;

						.measurement-label {
							font-size: 24rpx;
							color: #666;
							margin-right: 8rpx;
						}

						.measurement-status {
							font-size: 22rpx;
							color: #52c41a;
							display: flex;
							align-items: center;

							&.normal {
								&::before {
									content: "";
									width: 16rpx;
									height: 16rpx;
									background-image: url('/static/shengzhangTestResult/duihaoIcon.png');
									background-size: contain;
									background-repeat: no-repeat;
									margin-right: 6rpx;
								}
							}
						}
					}
				}
			}

			.growth-evaluation {
				.evaluation-text {
					font-size: 26rpx;
					color: #666;
					line-height: 1.6;
				}
			}
		}
	}
	
	// 返回按钮
	.back-btn {
		position: absolute;
		top: 119rpx;
		left: 30rpx;
		width: 29rpx;
		height: 29rpx;
	}

	.title{
		position: absolute;
		top: 112rpx;
		font-size: 34rpx;
		font-weight: 500;
		width: 100%;
		text-align: center;
	}

	// 顶部导航标签
	.nav-tabs {
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		margin-top: 202rpx;
		width: 260rpx;
		margin-left: 5rpx;

		.tab-item {
			width: 116rpx;
			height: 51rpx;
			// padding: 20rpx 40rpx;
			margin-right: 30rpx;
			border-radius: 25rpx;
			background-color: #fffbed;
			transition: all 0.3s ease;

			&.active {
				background-color: #b27c1e;
				.tab-text {
					color: #ffffff;
				}
			}

			.tab-text {
				font-size: 28rpx;
				color: #b27c1e;
				font-weight: 500;
				align-items: center;
				justify-content: center;
				display: flex;
				width: 100%;
				height: 100%;
			}
		}

		// .tab-decoration {
		// 	position: absolute;
		// 	right: 20rpx;
		// 	top: 50%;
		// 	transform: translateY(-50%);

		// 	.star {
		// 		font-size: 20rpx;
		// 		color: #b27c1e;
		// 		margin-left: 10rpx;
		// 		opacity: 0.6;
		// 	}
		// }
	}

	// 宝宝信息卡片
	.baby-info-card {
		background-color: #fff;
		border-radius: 24rpx;
		padding: 50rpx 35rpx 35rpx 35rpx;
		margin-top: 46rpx;
		// height: 100%;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		position: relative;

		.card-header {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;

			.name-icon,
			.status-icon {
				width: 32rpx;
				height: 32rpx;
				margin-right: 10rpx;
			}

			.card-title {
				font-size: 32rpx;
				color: #333;
				font-weight: bold;
			}
		}

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

			.gender {
				font-size: 24rpx;
				color: #000;
				margin-right: 20rpx;
			}

			.age {
				font-size: 24rpx;
				color: #000;
				margin-right: 20rpx;
			}

			.test-date {
				font-size: 24rpx;
				color: #000;
			}
		}

		.measurement-summary {
			display: flex;
			flex-direction: column;
			margin-bottom: 30rpx;

			.values-row {
				display: flex;
				justify-content: space-between;
				margin-bottom: 15rpx;

				.measurement-value {
					font-size: 32rpx;
					color: #333;
					font-weight: bold;
					flex: 1;
					text-align: center;
				}
			}

			.labels-row {
				display: flex;
				justify-content: space-between;

				.measurement-item {
					display: flex;
					flex-direction: row;
					align-items: center;
					flex: 1;
					justify-content: center;

					.measurement-label {
						font-size: 24rpx;
						color: #666;
						margin-right: 8rpx;
					}

					.measurement-status {
						font-size: 22rpx;
						color: #52c41a;
						display: flex;
						align-items: center;

						&.normal {
							&::before {
								content: "";
								width: 16rpx;
								height: 16rpx;
								background-image: url('/static/shengzhangTestResult/duihaoIcon.png');
								background-size: contain;
								background-repeat: no-repeat;
								margin-right: 6rpx;
							}
						}
					}
				}
			}
		}

		.growth-evaluation {
			.evaluation-text {
				font-size: 26rpx;
				color: #666;
				line-height: 1.6;
			}
		}
	}

	// 生长情况卡片
	.growth-status-card {
		background-color: #fff;
		border-radius: 24rpx;
		padding: 50rpx 35rpx 15rpx 35rpx;
		margin-top: 40rpx;
		// box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		position: relative;

		.card-header {
			display: flex;
			align-items: center;

			.name-icon,
			.status-icon {
				width: 32rpx;
				height: 32rpx;
				margin-right: 10rpx;
			}

			.card-title {
				font-size: 32rpx;
				color: #000;
				font-weight: bold;
			}
		}

		.legend {
			display: flex;
			justify-content: space-between;
			margin-top: 46rpx;

			.legend-item {
				display: flex;
				align-items: center;

				.legend-color {
					width: 20rpx;
					height: 20rpx;
					border-radius: 4rpx;
					margin-right: 8rpx;

					&.too-low {
						background-color: #ffede0;
					}

					&.slightly-low {
						background-color: #fde0a5;
					}

					&.normal {
						background-color: #89caa2;
					}

					&.slightly-high {
						background-color: #f3d1e9;
					}

					&.too-high {
						background-color: #a78dbc;
					}
				}

				.legend-text {
					font-size: 22rpx;
					color: #000;
				}
			}
		}

		.measurement-bars {
			margin-top: 26rpx;
			.bar-item {
				display: flex;
				flex-direction: column;
				margin-bottom: 20rpx;

				.value-triangle-container {
					display: flex;
					flex-direction: column;
					width: 150rpx;
					align-items: center;

					.bar-value {
						font-size: 24rpx;
						color: #b27c1e;
					}

					.triangle {
						// position: relative;
						top:8rpx;
						// margin-left: 20rpx;
						width: 20rpx;
						height: 20rpx;
						// align-self: center;
					}
				}

				.bar-row {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.measurement-label {
						font-size: 28rpx;
						color: #000;
						width: 80rpx;
						// margin-top: 3rpx;
					}

					.value-bar {
						flex: 1;
						height: 30rpx;
					}

					.bar-percentage {
						font-size: 24rpx;
						color: #000;
						width: 200rpx;
						text-align: right;
					}
				}
			}
		}
	}

	// 生长曲线卡片
	.growth-curve-card {
		background-color: #fff;
		border-radius: 24rpx;
		padding: 30rpx;
		margin-top: 40rpx;
		// box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		position: relative;

		.card-header {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;

			.name-icon,
			.status-icon {
				width: 32rpx;
				height: 32rpx;
				margin-right: 10rpx;
			}

			.card-title {
				font-size: 32rpx;
				color: #333;
				font-weight: bold;
			}
		}

		.curve-tabs {
			display: flex;
			justify-content: space-around;
			// justify-items: center;
			width: 466rpx;
			height: 141rpx;
			margin-bottom: 37rpx;
			margin-top: 37rpx;
			margin-left: 78rpx;
			background-color: #f6f8fa;
			border-radius: 70rpx;

			.curve-tab {
				margin-top: 8rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 132rpx;
				height: 131rpx;
				border-radius: 50%;
				// transition: all 0.3s ease;
				// background-color: #ffffff;
				// box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
				position: relative;

				&.active {
					// background-color: #e0e0e0;
					// box-shadow: none;
				}

				.tab-icon {
					width: 100%;
					height: 100%;
				}
			}
		}

		.graph-legend {
			display: flex;
			justify-content: space-around;

			.legend-item {
				display: flex;
				align-items: center;

				.legend-color {
					width: 20rpx;
					height: 20rpx;
					border-radius: 4rpx;
					margin-right: 6rpx;

					&.slightly-low {
						background-color: #fde0a5; // 黄色
					}

					&.normal {
						background-color: #89caa2; // 浅绿色
					}

					&.normal2 {
						background-color: #a8e6cf; // 浅绿色（第二条线）
					}

					&.slightly-high {
						background-color: #f3d1e9; // 紫色
					}

					&.baby-record {
						background-color: #b27c1e; // 棕色
					}
				}

				.legend-text {
					font-size: 20rpx;
					color: #000;
				}
			}
		}
		.graph-title-y{
			position: relative;
			margin-top: 30rpx;
			margin-left: 20rpx;
			.graph-title-text{
				font-size: 20rpx;
				color: #000;
			}
		}

		.graph-container {
			position: relative;
			height: 400rpx;
			background-color: #fff;
			border-radius: 10rpx;
			overflow: hidden;

			.graph-scroll {
				width: 100%;
				height: 100%;
				white-space: nowrap;
			}

			.graph-content {
				height: 100%;
				display: inline-block;
			}

			.curve-canvas {
				height: 100%;
				display: block;
			}
		}

		
	}

	.curve-tips {
		position: relative;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 60rpx;
			margin-bottom: 60rpx;
			width: 100%;
			height: 24rpx;
			.tips-icon{
				width: 198rpx;
				height: 100%;
			}
		}
	// 专家咨询按钮
	.expert-consult-btn {
		position: fixed;
		bottom: 60rpx;
		left: 0;
		width: 100%;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.consult-bg {
			position: absolute;
			width: 100%;
			height: 100%;
			z-index: 1;
		}
	}
}
</style> 