<template>
	<view v-if="bmi_history" class="content">
		<!-- 折线-开始 -->
		<view class="chart-con gap">
			<view class="chart-wrap">
				<view class="title" style="height: 18px;">
					<view class="ver-line"></view>
					<view @click="showDropdown = !showDropdown" class="title-desc">
						<text>平均值 </text>
						<text class="t-sm">{{type}}<text class="cuIcon-triangledownfill"></text></text>
						<!-- 下拉选择器 -->
					</view>
					<view v-show="showDropdown" class="dropdown-container flex justify-between">
						<view class="dropdown-item" @click="selectItem('year')">年</view>
						<view class="dropdown-item" @click="selectItem('month')">月</view>
						<view class="dropdown-item" @click="selectItem('day')">日</view>
					  <!-- <view class="dropdown-item" @click="selectItem('hour')">时</view> -->
					</view>
				</view>
				<view class="line-chart-con">
					<l-echart id="123" class="line-chart" ref="lineChart"></l-echart>
				</view>
				<!-- <text class="margin-left t-sm">注：数据只保留一年</text> -->
			</view>
		</view>
		<!-- 折线-结束 -->
		<view class="chart-con gap">
			<view class="chart-wrap">
				<view class="title">
					<view class="ver-line"></view>
					<view @click="openDatetimePicker" class="title-desc">
						<text>详细记录</text>
						<text class="t-sm">
							{{selectDate.year}} 年 {{selectDate.month}} 月 <!-- {{selectDate.day}} 日 -->
							<text class="cuIcon-triangledownfill"></text>
						</text>
					</view>
				</view>
				
				<uv-swipe-action v-if="refresh">
					<uv-swipe-action-item @click="delData($event,key)" v-for="(value, key) in select_history" :key="key" :options="options">
						<view @longpress="check_delDatag({'index':0},key)" class="swipe-action uv-border-top uv-border-bottom">
							<view class="swipe-action__content">
								<view class="margin-left margin-right">
									<view class="margin-bottom-xs flex justify-between">
										<view class="flex">
											<text class="margin-right" style="font-size: 24px;font-weight: 600;">{{value.bmi}}</text>
											<div style="display: flex;font-weight: 600;align-items: center;justify-content: center;">
												<span style="color: #57bff6;" v-if="value.bmi < 18.5">偏瘦</span>
												<span style="color: #13d080;" v-else-if="value.bmi >= 18.5 && value.bmi < 24.0">正常</span>
												<span style="color: #ffb951;" v-else-if="value.bmi >= 24.0 && value.bmi < 28.0">偏重</span>
												<span style="color: #ff7433;" v-else-if="value.bmi >= 28.0">肥胖</span>
											</div>
										</view>
										<text style="color:#999;display: flex;align-items: center;justify-content: center;">{{value.time}}</text>
									</view>
									<view style="color:#666;" class="flex justify-start">
										<text class="margin-right">身高：{{value.height}}cm</text>
										<text>体重：{{value.weight}}kg</text>
									</view>
								</view>
							</view>
						</view>
						<!-- <uv-divider v-if="key != lastKey" style="margin:0 ;padding: 0;height: 1px;"></uv-divider> -->
						<view v-if="key != lastKey" style="background-color: #ccc;bottom: 0;height: 1px;margin:0 10px;"></view>
					</uv-swipe-action-item>
				</uv-swipe-action>
				<view v-else style="height: 3000px;"></view>
			</view>
			<uv-datetime-picker :formatter="formatter" :minDate="firstkey" :maxDate="lastKey" ref="datetimePicker" v-model="dateValue" mode="year-month" @confirm="confirm"></uv-datetime-picker>
		</view>
	</view>
	<view v-else class="no_data"></view>
</template>

<script>
	import * as echarts from '@/uni_modules/lime-echart/static/echarts.min.js';
	export default {
		onPullDownRefresh() {
			let bmi_history = uni.getStorageSync('bmi_history');
			this.bmi_history = null;
			if(bmi_history && Object.keys(bmi_history).length != 0) this.bmi_history = bmi_history;
			else uni.showToast({duration:1500,icon:"error",title: '暂无数据 !'});
			this.$forceUpdate();
			setTimeout(() => {uni.stopPullDownRefresh();}, 1000);
		},
		onLoad() {
			let bmi_history = uni.getStorageSync('bmi_history');
			if(bmi_history && Object.keys(bmi_history).length != 0) this.bmi_history = bmi_history;
			else uni.showToast({duration:1500,icon:"error",title: '暂无数据 !'});
		},
		mounted() {
			if(this.bmi_history){
				this.loadLineData("month");
			}
			
			// 获取对象的所有键
			const keys = Object.keys(this.bmi_history);
			// 获取最后一个键
			const lastKey = keys[keys.length - 1];
			this.lastKey = lastKey;
			this.firstkey = keys[0];
			this.confirm({'value': lastKey});
		},
		data() {
			return {
				selectDate: {
					year: null,
					month: null,
					day: null
				},
				dateValue: Number(new Date()),
				month: null,
				bmi_history: null,
				select_history: null,
				showDropdown: false,
				type: null,
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				firstkey: null,
				lastKey: null,
				refresh: true
			}
		},
		methods: {
			check_delDatag(e,key){
				uni.showModal({
					title: '删除此纪录',
					content: '是否要删除此纪录？',
					success: (res) => { 
						if (res.confirm) 
							this.delData(e,key); 
					}  
				})
			},
			delData(e,key){
				console.log('e: ',e);
				console.log('key: ',key);
				if(e['index'] === 0){
					let bmi_history = uni.getStorageSync('bmi_history');
					if (bmi_history.hasOwnProperty(key)) {
						delete bmi_history[key];
						uni.setStorageSync('bmi_history',bmi_history);
					}
					if (this.select_history.hasOwnProperty(key)) {
						delete this.select_history[key];
					}
					this.$forceUpdate();
					this.refresh = false;
					setTimeout(() => this.refresh = true,1);
				}
			},
			openDatetimePicker() {
				this.$refs.datetimePicker.open();
			},
			confirm(e) {
				console.log('confirm', e);
				const date = new Date(parseInt(e.value));
				this.selectDate.year = date.getFullYear();
				this.selectDate.month = date.getMonth() + 1;
				// this.selectDate.day = date.getDate();
				
				this.select_history =this.$util.reversedObject(filterByDate(this.selectDate,this.bmi_history));
				
				this.$forceUpdate();
				this.refresh = false;
				setTimeout(() => this.refresh = true,1);
				
				function filterByDate(dateObj, timestampObj) {
				    const { year, month } = dateObj;
				    const result = {};
				
				    for (const [timestamp, value] of Object.entries(timestampObj)) {
				        const date = new Date(parseInt(timestamp));
				        if ((year === null || date.getFullYear() === year) &&
				            (month === null || date.getMonth() + 1 === month)) {
				            const day = date.getDate().toString().padStart(2, '0');
				            const hours = date.getHours().toString().padStart(2, '0');
				            const minutes = date.getMinutes().toString().padStart(2, '0');
				            result[timestamp] = { ...value, time: `${day}日 ${hours}时 ${minutes}分` };
				        }
				    }
				    return result;
				}

			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			selectItem(item) {
				this.showDropdown = false; // 关闭下拉选择器
				this.loadLineData(item);
			},
			loadLineData(type) {
				let res = this.handle_data(type);
				
				let option = {
					xAxis: {
						type: 'category',
						// x轴数据文字颜色
						axisLabel: {
							color: '#a7a7a7'
						},
						// x轴那天坐标轴线的颜色
						axisLine: {
							lineStyle: {
								color: '#f1f1f1',
							}
						},
						//x轴上面刻度线隐藏
						axisTick: {
							show: false,
						},
						//这里是x轴数据
						data: res.xData
					},
					//设置网格
					grid: {
						top: 40,
						bottom: 30,
					},
					//y轴设置
					yAxis: {
						type: 'value',
						//y轴标签文字颜色
						axisLabel: {
							color: '#a7a7a7'
						},
						// y轴分割线设置为虚线
						splitLine: {
							show: true,
							lineStyle: {
								type: 'dashed'
							}
						}
					},
					//设置提示为点击时
					tooltip: {
						trigger: 'axis',
						triggerOn: 'click',
						formatter: '{b} \n 数据: {c}'
					},
					//设置曲线的颜色
					color: ['#4e9d77'],
					series: [{
						//这里是数据
						data: res.yData,
						type: 'line',
						//设置为平滑，默认为折线
						smooth: true,
					}],
					//设置数据缩放，手指缩放
					dataZoom:{
						type:'inside',//inside移动端就是手指缩放，slider
						id:'123',
					}
				};
			
				this.$refs.lineChart.init(echarts, chart => {
					chart.setOption(option);
				});
			},
			handle_data(type = null){
				
				let xData;
				if(type === null) xData = this.formatTimestamps(this.bmi_history);
				else xData = this.formatTimestamps_typeB(this.bmi_history,type);
				
				let yData = this.extractBmis(this.bmi_history);
				
				console.log('xData: ',xData);
				console.log('yData: ',yData);
				
				let res = averageData(xData, yData)
				return {
					xData: res.newXData, 
					yData: res.newYData
				}
				
				function averageData(xData, yData) {
				    // 创建一个Map来存储每个时间点的总和和计数
				    const dataMap = new Map();
				
				    // 遍历xData和yData
				    for (let i = 0; i < xData.length; i++) {
				        const time = xData[i];
				        const value = parseFloat(yData[i]);
				
				        if (dataMap.has(time)) {
				            // 如果时间点已经存在，更新总和和计数
				            const [sum, count] = dataMap.get(time);
				            dataMap.set(time, [sum + value, count + 1]);
				        } else {
				            // 如果时间点不存在，初始化总和和计数
				            dataMap.set(time, [value, 1]);
				        }
				    }
				
				    // 创建新的xData和yData
				    const newXData = [];
				    const newYData = [];
				
				    // 遍历Map计算平均值
				    for (const [time, [sum, count]] of dataMap) {
				        newXData.push(time);
				        newYData.push((sum / count).toFixed(2)); // 保留两位小数
				    }
				
				    return { newXData, newYData };
				}
			},
			extractBmis(obj) {
			    const bmis = [];
			    function traverse(object) {
			        for (let key in object) {
			            if (object.hasOwnProperty(key)) {
			                const value = object[key];
			                if (typeof value === 'object' && value !== null) {
			                    if (value.bmi !== undefined) {
			                        bmis.push(value.bmi);
			                    }
			                    traverse(value); // 递归遍历子对象
			                }
			            }
			        }
			    }
			
			    traverse(obj);
			    return bmis;
			},
			formatTimestamps(obj) {
				
				return this.formatTimestamps_typeB(obj, getTimeGranularity(obj));
				
				function getTimeGranularity(timestamps) {
				    const dates = Object.keys(timestamps).map(ts => new Date(parseInt(ts)));
				
				    const allSameYear = dates.every(date => date.getFullYear() === dates[0].getFullYear());
				    if (!allSameYear) return 'year';
				
				    const allSameMonth = dates.every(date => date.getMonth() === dates[0].getMonth());
				    if (!allSameMonth) return 'month';
				
				    const allSameDay = dates.every(date => date.getDate() === dates[0].getDate());
				    if (!allSameDay) return 'day';
				}
			},
			formatTimestamps_typeB(obj, type) {
				
				if(type === 'year')this.type = '年';
				if(type === 'month')this.type = '月';
				if(type === 'day')this.type = '日';
				if(type === 'hour')this.type = '时';
				
			    const timestamps = Object.keys(obj).map(ts => new Date(parseInt(ts)));
			
			    return timestamps.map(ts => {
			        switch (type) {
			            case 'year':
			                return ts.getFullYear().toString();
			            case 'month':
			                return (ts.getMonth() + 1).toString();
			            case 'day':
							return (ts.getMonth() + 1) + '/' + ts.getDate().toString().padStart(2, '0');
			                // return ts.getDate().toString();
			            case 'hour':
			                return ts.getHours() + ':' + ts.getMinutes().toString().padStart(2, '0');
			            default:
			                throw new Error('Invalid granularity');
			        }
			    });
			}
		}
	}
</script>

<style>
	
	.dropdown-item {
	  padding: 3px;
	  color: #5e5e5e;
	  border-radius: 10px;
	  cursor: pointer;
	}
	
	.dropdown-item:hover {
		background-color: #e0e0e0;
	}
	
	.dropdown-container {
	  padding: 3px;
	  font-size: 18px;
	  position: relative;
	  top: 3px; /* 根据实际需求调整距离 */
	  background-color: #f3f5f4;
	  border-radius: 10px;
	  // box-shadow: 0 2px 10px rgba(0, 0, 0, 0.8);
	  z-index: 100; /* 确保选择器在其他内容之上 */
	}
</style>

<style lang="scss">
	.uv-page {
		padding: 0;
	}
	.uv-demo-block__title {
		padding: 10px 0 2px 15px;
	}
	.swipe-action {
		&__content {
			padding: 25rpx 0;
			&__text {
				font-size: 15px;
				color: #222;
				padding-left: 30rpx;
			}
		}
	}
</style>

<style lang="scss" scoped>
	
	.content {
		width: 100%;
		min-height: 100vh;
		background-color: #f1f3f2;
		padding: 20rpx 0rpx 100rpx;
	}
	.t-sm{
		font-size: 22rpx;
		color: #6e6e6e;
		padding-left: 10rpx;
	}
	.chart-con {
		width: 100%;
		box-sizing: border-box;
		padding: 0rpx 28rpx;

		.chart-wrap {
			width: 100%;
			box-sizing: border-box;
			background-color: #ffffff;
			padding: 32rpx 0rpx;
			border-radius: 20rpx;

			.title {
				box-sizing: border-box;
				width: 100%;
				padding: 0rpx 28rpx;
				display: flex;
				flex-direction: row;
				justify-content: flex-start;
				align-items: center;
			}

			.ver-line {
				height: 30rpx;
				width: 8rpx;
				border-radius: 10rpx;
				background-color: #4e9d77;
			}

			.title-desc {
				font-size: 30rpx;
				color: #222222;
				margin-left: 22rpx;
				font-weight: bold;
			}

			
			.line-chart-con {
				width: 100%;
				box-sizing: border-box;
				padding: 0rpx 28rpx;

				.fun-tabs {
					margin-top: 42rpx;
					display: flex;
					flex-direction: row;
					justify-content: space-between;
					align-self: center;
					width: 100%;
					box-sizing: border-box;

					.tab-item {
						width: 200rpx;
						height: 120rpx;
						border-radius: 10rpx;
						padding-left: 20rpx;
						background: #ffffff;
						border: 1rpx solid #ececec;
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: flex-start;
						box-sizing: border-box;

						.item-name {
							color: #6e6e6e;
							font-size: 20rpx;
						}

						.item-val {
							color: #222222;
							font-size: 24rpx;
							font-weight: bold;
							margin-top: 20rpx;
						}
					}

					.selected {
						background: #edf5f1 !important;
						border: 1rpx solid #4e9d77 !important;

						.item-name {
							color: #4e9d77 !important;
						}

						.item-val {
							color: #4e9d77 !important;
						}
					}
				}

				.line-chart {
					margin-top: 30rpx;
					height: 380rpx;
				}
			}
		}
	}
	.gap {
		margin-top: 30rpx;
	}
	
</style>

