import * as echarts from '../../ec-canvas/echarts';


// 渐变圆环
let chartCircularProgressBar;//圈圈
let chartOutOfBed;//离床
let chartBodyMovementsLine;//体动
let chartCardiacSystemLine;//心脏系统
let chartRespiratoryLine;//平均呼吸率
let chartSnoringLine;//打鼾
let chartApneaLine;//呼吸暂停
let chartTimeWaterfall;//深浅睡眠

// 圈圈>90分极好(绿色)
// > 75分，(浅绿色)良好
// 各项睡眠监测数据统计 > 60分，较差(黄色)
// 	< 60分，很差(红色)
function setChartCircularProgressBarOption(chart, data = {}) {
	var rscore_value = data?.rscore_value || 0;
	var checkList = [{
		title: "极好",
		titleColor: "#0BC3AA",
		startColor: "#0AB1C3",
		centerColor: "#0BC3AA",
		endColor: "#36E1CA",
	}, {
		title: "良好",
		titleColor: "#9C43FF",
		startColor: "#8D25FF",
		centerColor: "#A631FF",
		endColor: "#FF8FF0",
	}, {
		title: "较差",
		titleColor: "#FF8F4E",
		startColor: "#EE8B52",
		centerColor: "#FAA472",
		endColor: "#FAA472",
	}, {
		title: "很差",
		titleColor: "#FB717B",
		startColor: "#FB717B",
		centerColor: "#FB717B",
		endColor: "#FF98A0",
	}];
	var checkData = checkList[0];
	if (rscore_value >= 90 && rscore_value <= 100) {
		checkData = checkList[0];
	} else if (rscore_value >= 75 && rscore_value < 90) {
		checkData = checkList[1];
	} else if (rscore_value >= 60 && rscore_value < 75) {
		checkData = checkList[2];
	} else {
		checkData = checkList[3];
	}

	var option = {
		series: [
			{
				type: 'gauge',
				startAngle: -270,
				endAngle: 90,
				legendHoverLink: true,
				min: 0,
				max: 100,
				itemStyle: {
					color: '#58D9F9',
					shadowColor: 'rgba(0,138,255,0.45)',
					shadowBlur: 5,
					shadowOffsetX: 1,
					shadowOffsetY: 1
				},
				progress: {
					show: true,
					roundCap: true,
					width: 10,
					itemStyle: {
						// 进度条样式
						color: {
							// 自定义渐变色
							type: 'linear',
							x: 0.75,
							y: 0.75,
							x2: 0,
							y2: 0.75,
							colorStops: [
								{
									offset: 0,
									color: checkData.startColor // 0% 处的颜色
								},

								{
									offset: 0.5,
									color: checkData.centerColor // 100% 处的颜色
								},
								{
									offset: 1,
									color: checkData.endColor // 100% 处的颜色
								}
							],
							global: false // 缺省为 false
						}
					}
				},
				pointer: {
					show: false,
				},
				axisLine: {
					roundCap: true,
					lineStyle: {
						width: 10,
					}
				},
				axisTick: {
					show: false // 是否显示分隔线
				},
				splitLine: {
					show: false // 是否显示分隔线
				},
				axisLabel: {
					show: false,
				},
				title: {
					color: checkData.titleColor,
					offsetCenter: [0, '-36%'],
					lineHeight: 15,
					fontSize: 15,
				},
				detail: {
					backgroundColor: '#fff',
					width: '60%',
					lineHeight: 40,
					height: 40,
					color: '#333333',
					offsetCenter: [0, "24%"],
					valueAnimation: true,
					formatter: function (value) {
						return '{value|' + value.toFixed(0) + '}';
					},
					rich: {
						value: {
							fontSize: 30,
							fontWeight: 'bolder',
							color: checkData.titleColor
						},
					}
				},
				data: [
					{
						name: data?.rscore_desc || checkData.title || '无',
						value: data?.rscore_value || 0
					}
				]
			}
		]
	};

	chart.setOption(option, true);
}


function initChartHumidifier(canvas, width, height, dpr) {
	// this.selectComponent('#mychart-dom-bar00').init((canvas, width, height, dpr) => {
	// 获取组件的 canvas、width、height 后的回调函数
	// 在这里初始化图表
	const chart = echarts.init(canvas, null, {
		width: width,
		height: height,
		devicePixelRatio: dpr // new
	});
	canvas.setChart(chart);
	setChartCircularProgressBarOption(chart);

	// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
	chartCircularProgressBar = chart;

	// 注意这里一定要返回 chart 实例，否则会影响事件处理等
	return chart;
	// });
};

function updateChartCircularProgressBarOption(rscore_desc, rscore_value, that) {
	if (chartCircularProgressBar) {
		setChartCircularProgressBarOption(chartCircularProgressBar, { rscore_desc, rscore_value });

	} else {
		that.selectComponent('#mychart-dom-CircularProgressBar').init((canvas, width, height, dpr) => {
			const chart = echarts.init(canvas, null, {
				width: width,
				height: height,
				devicePixelRatio: dpr // new
			});
			canvas.setChart(chart);
			setChartCircularProgressBarOption(chart, { rscore_desc, rscore_value });

			// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
			chartCircularProgressBar = chart;

			// 注意这里一定要返回 chart 实例，否则会影响事件处理等
			return chart;
		});
	}
}
//离床

function initChartOutOfBed(canvas, width, height, dpr) {
	// this.selectComponent('#mychart-dom-bar00').init((canvas, width, height, dpr) => {
	// 获取组件的 canvas、width、height 后的回调函数
	// 在这里初始化图表
	const chart = echarts.init(canvas, null, {
		width: width,
		height: height,
		devicePixelRatio: dpr // new
	});
	canvas.setChart(chart);
	setChartOutOfBedOption(chart);

	// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
	chartOutOfBed = chart;

	// 注意这里一定要返回 chart 实例，否则会影响事件处理等
	return chart;
	// });
};



function setChartOutOfBedOption(chart, data1 = [], data2 = [],) {
	var option = option = {
		tooltip: {
			show: true,
			trigger: 'axis',
			formatter: function (param) {
				return `${param[0] && param[0].value == 1 ? '在床' : '离床'}`
			}
		},
		dataZoom: [
			{ // 第一个 dataZoom 组件
				type: 'inside',
			},
		],
		grid: {
			top: '40rpx',
			left: 0,
			right: '20rpx',
			bottom: 0,
			containLabel: true
		},
		xAxis: {
			type: 'category',
			axisLabel: {
				color: '#6C6970',// 设置 x 轴标签颜色为白色  
				fontSize: 10
			},
			boundaryGap: false,
			splitLine: {
				show: false, // 是否显示刻度线  

			},
			axisTick: {
				// 不显示Y轴刻度线  
				show: false
			},
			data: data1,
			axisLine: {
				// 不显示X轴轴线  
				show: false
			}
		},
		yAxis: {
			// Y 轴配置
			type: 'value',
			show: false
		},
		series: [{
			type: 'line',
			name: '睡眠状态',
			smooth: true,
			lineStyle: {
				width: 1,
				color: '#54C68B'
			},
			emphasis: {
				disabled: true,
				scale: false,
				lineStyle: {
					width: 1,
					color: '#54C68B'
				},
			},
			showSymbol: false,
			areaStyle: {
				opacity: 0.8,
				color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
					{
						offset: 0,
						color: '#B8EBD0'
					},
					{
						offset: 1,
						color: 'rgba(255, 255, 255, 0)'
					}
				])
			},
			data: data2,
		}]
	};

	chart.setOption(option, true);
}


function updateOutOfBed(data1, data2, startSleepTime, endSleepTime, that) {
	if (chartOutOfBed) {
		setChartOutOfBedOption(chartOutOfBed, data1, data2);
	} else {
		that.selectComponent('#chartOutOfBed-dom').init((canvas, width, height, dpr) => {
			const chart = echarts.init(canvas, null, {
				width: width,
				height: height,
				devicePixelRatio: dpr // new
			});
			canvas.setChart(chart);
			setChartOutOfBedOption(chart, data1, data2);

			// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
			chartOutOfBed = chart;

			// 注意这里一定要返回 chart 实例，否则会影响事件处理等
			return chart;
		});
	}
}


//体动

function initChartBodyMovementsLine(canvas, width, height, dpr) {
	// 在这里初始化图表
	const chart = echarts.init(canvas, null, {
		width: width,
		height: height,
		devicePixelRatio: dpr // new
	});
	canvas.setChart(chart);
	setBodyMovementsOption(chart);

	// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
	chartBodyMovementsLine = chart;

	// 注意这里一定要返回 chart 实例，否则会影响事件处理等
	return chart;
};


function setBodyMovementsOption(chart, data1 = [], data2 = [],) {
	var option = option = {
		tooltip: {
			show: true,
			trigger: 'axis',
			formatter: function (param) {
				return `${param[0] && param[0].value == 1 ? '体动' : '否'}`
			}
		},
		dataZoom: [
			{ // 第一个 dataZoom 组件
				type: 'inside',
			},
		],
		grid: {
			top: '40rpx',
			left: 0,
			right: '20rpx',
			bottom: 0,
			containLabel: true
		},
		xAxis: {
			type: 'category',
			axisLabel: {
				color: '#6C6970',// 设置 x 轴标签颜色为白色  
				fontSize: 10
			},
			boundaryGap: false,
			splitLine: {
				show: false, // 是否显示刻度线  

			},
			axisTick: {
				// 不显示Y轴刻度线  
				show: false
			},
			data: data1,
			axisLine: {
				// 不显示X轴轴线  
				show: false
			}
		},
		yAxis: {
			// Y 轴配置
			type: 'value',
			show: false
		},
		series: [{
			name: '睡眠状态',
			type: 'line',
			smooth: true,
			lineStyle: {
				width: 1,
				color: '#5582FF'
			},
			emphasis: {
				disabled: true,
				scale: false,
				lineStyle: {
					width: 1,
					color: '#5582FF'
				},
			},
			showSymbol: false,
			areaStyle: {
				opacity: 0.8,
				color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
					{
						offset: 0,
						color: 'rgba(85, 130, 255, 0.5)'
					},
					{
						offset: 1,
						color: 'rgba(149, 177, 255, 0.3)'
					}
				])
			},
			data: data2,
		}]
	};

	chart.setOption(option, true);
}

function updateBodyMovements(data1, data2, startSleepTime, endSleepTime, that) {
	if (chartBodyMovementsLine) {
		setBodyMovementsOption(chartBodyMovementsLine, data1, data2);
	} else {
		that.selectComponent('#chartBodyMovementsLine-dom').init((canvas, width, height, dpr) => {
			const chart = echarts.init(canvas, null, {
				width: width,
				height: height,
				devicePixelRatio: dpr // new
			});
			canvas.setChart(chart);
			setBodyMovementsOption(chart, data1, data2);

			// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
			chartBodyMovementsLine = chart;

			// 注意这里一定要返回 chart 实例，否则会影响事件处理等
			return chart;
		});
	}
}


//心脏系统

function initChartCardiacSystemLine(canvas, width, height, dpr) {
	// 在这里初始化图表
	const chart = echarts.init(canvas, null, {
		width: width,
		height: height,
		devicePixelRatio: dpr // new
	});
	canvas.setChart(chart);
	setCardiacSystemOption(chart);

	// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
	chartCardiacSystemLine = chart;

	// 注意这里一定要返回 chart 实例，否则会影响事件处理等
	return chart;
};


function setCardiacSystemOption(chart, data1 = [], data2 = [],) {
	var option = option = {
		tooltip: {
			show: true,
			trigger: 'axis',
			formatter: function (param) {
				return `${(param[0].value || 0) + '次'}`
			}
		},
		dataZoom: [
			{ // 第一个 dataZoom 组件
				type: 'inside',
			},
		],
		grid: {
			top: '20rpx',
			left: '20rpx',
			right: '20rpx',
			bottom: '10rpx',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			axisLabel: {
				color: '#6C6970',// 设置 x 轴标签颜色为白色  
				fontSize: 10
			},
			boundaryGap: false,
			splitLine: {
				show: false, // 是否显示刻度线  

			},
			axisTick: {
				// 不显示Y轴刻度线  
				show: false
			},
			data: data1,
			axisLine: {
				// 不显示X轴轴线  
				show: false
			}
		},
		yAxis: {
			type: 'value',
			max: 100,
			min: 0,
			show: true,
			offset: 10,
			splitLine: {
				show: false
			},
			axisLabel: {
				hideOverlap: true,
				fontSize: 10,
			}
		},
		series: [{
			type: 'line',
			smooth: true,
			lineStyle: {
				width: 1,
				color: '#F47893'
			},
			emphasis: {
				disabled: true,
				scale: false,
				lineStyle: {
					width: 1,
					color: '#F47893'
				},
			},
			showSymbol: false,
			areaStyle: {
				opacity: 0.8,
				color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
					{
						offset: 0,
						color: 'rgba(244, 120, 147, 0.5)'
					},
					{
						offset: 1,
						color: 'rgba(250, 140, 164, 0.3)'
					}
				])
			},
			data: data2,
		}]
	};

	chart.setOption(option, true);
}

function updateCardiacSystem(data1, data2, that) {
	if (chartCardiacSystemLine) {
		setCardiacSystemOption(chartCardiacSystemLine, data1, data2);
	} else {
		that.selectComponent('#chartCardiacSystemLine-dom').init((canvas, width, height, dpr) => {
			const chart = echarts.init(canvas, null, {
				width: width,
				height: height,
				devicePixelRatio: dpr // new
			});
			canvas.setChart(chart);
			setCardiacSystemOption(chart, data1, data2);

			// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
			chartBodyMovementsLine = chart;

			// 注意这里一定要返回 chart 实例，否则会影响事件处理等
			return chart;
		});
	}
}

//平均呼吸率

function initChartRespiratoryLine(canvas, width, height, dpr) {
	// 在这里初始化图表
	const chart = echarts.init(canvas, null, {
		width: width,
		height: height,
		devicePixelRatio: dpr // new
	});
	canvas.setChart(chart);
	setRespiratoryOption(chart);

	// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
	chartRespiratoryLine = chart;

	// 注意这里一定要返回 chart 实例，否则会影响事件处理等
	return chart;
};


function setRespiratoryOption(chart, data1 = [], data2 = [],) {
	var option = option = {
		tooltip: {
			show: true,
			trigger: 'axis',
			formatter: function (param) {
				return `${(param[0].value || 0) + '次'}`
			}
		},
		dataZoom: [
			{ // 第一个 dataZoom 组件
				type: 'inside',
			},
		],
		grid: {
			top: '20rpx',
			left: '20rpx',
			right: '20rpx',
			bottom: '10rpx',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			axisLabel: {
				color: '#6C6970',// 设置 x 轴标签颜色为白色  
				fontSize: 10
			},
			boundaryGap: false,
			splitLine: {
				show: false, // 是否显示刻度线  

			},
			axisTick: {
				// 不显示Y轴刻度线  
				show: false
			},
			data: data1,
			axisLine: {
				// 不显示X轴轴线  
				show: false
			}
		},
		yAxis: {
			type: 'value',
			max: 24,
			min: 0,
			show: true,
			offset: 10,
			splitLine: {
				show: false
			},
			axisLabel: {
				hideOverlap: true,
				fontSize: 10,
			}
		},
		series: [{
			type: 'line',
			smooth: true,
			lineStyle: {
				width: 1,
				color: '#06A9AD'
			},
			emphasis: {
				disabled: true,
				scale: false,
				lineStyle: {
					width: 1,
					color: '#06A9AD'
				},
			},
			showSymbol: false,
			areaStyle: {
				opacity: 0.8,
				color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
					{
						offset: 0,
						color: 'rgba(186, 246, 231, 1)'
					},
					{
						offset: 1,
						color: 'rgba(255, 255, 255, 0)'
					}
				])
			},
			data: data2,
		}]
	};

	chart.setOption(option, true);
}

function updateRespiratory(data1, data2, startSleepTime, endSleepTime, that) {
	if (chartRespiratoryLine) {
		setRespiratoryOption(chartRespiratoryLine, data1, data2);
	} else {
		that.selectComponent('#chartRespiratoryLine-dom').init((canvas, width, height, dpr) => {
			const chart = echarts.init(canvas, null, {
				width: width,
				height: height,
				devicePixelRatio: dpr // new
			});
			canvas.setChart(chart);
			setRespiratoryOption(chart, data1, data2);

			// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
			chartRespiratoryLine = chart;

			// 注意这里一定要返回 chart 实例，否则会影响事件处理等
			return chart;
		});
	}
}

//打鼾

function initSnoringLine(canvas, width, height, dpr) {
	// 在这里初始化图表
	const chart = echarts.init(canvas, null, {
		width: width,
		height: height,
		devicePixelRatio: dpr // new
	});
	canvas.setChart(chart);
	setSnoringOption(chart);

	// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
	chartSnoringLine = chart;

	// 注意这里一定要返回 chart 实例，否则会影响事件处理等
	return chart;
};


function setSnoringOption(chart, data1 = [], data2 = [],) {
	var option = option = {
		tooltip: {
			show: true,
			trigger: 'axis',
			formatter: function (param) {
				return `${param[0] && param[0].value == 1 ? '打鼾' : '否'}`
			}
		},
		dataZoom: [
			{ // 第一个 dataZoom 组件
				type: 'inside',
			},
		],
		grid: {
			top: '40rpx',
			left: 0,
			right: '20rpx',
			bottom: 0,
			containLabel: true
		},
		xAxis: {
			type: 'category',
			axisLabel: {
				color: '#6C6970',// 设置 x 轴标签颜色为白色  
				fontSize: 10
			},
			boundaryGap: false,
			splitLine: {
				show: false, // 是否显示刻度线  

			},
			axisTick: {
				// 不显示Y轴刻度线  
				show: false
			},
			data: data1,
			axisLine: {
				// 不显示X轴轴线  
				show: false
			}
		},
		yAxis: {
			type: 'value',
			show: false,
		},
		series: [{
			type: 'line',
			smooth: true,
			lineStyle: {
				width: 1,
				color: '#EE8B52'
			},
			emphasis: {
				disabled: true,
				scale: false,
				lineStyle: {
					width: 1,
					color: '#EE8B52'
				},
			},
			showSymbol: false,
			areaStyle: {
				opacity: 0.8,
				color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
					{
						offset: 0,
						color: 'rgba(249, 211, 189, 1)'
					},
					{
						offset: 1,
						color: 'rgba(255, 255, 255, 0)'
					}
				])
			},
			data: data2,
		}]
	};

	chart.setOption(option, true);
}

function updateSnoring(data1, data2, startSleepTime, endSleepTime, that) {
	if (chartSnoringLine) {
		setSnoringOption(chartSnoringLine, data1, data2);
	} else {
		that.selectComponent('#chartSnoringLine-dom').init((canvas, width, height, dpr) => {
			const chart = echarts.init(canvas, null, {
				width: width,
				height: height,
				devicePixelRatio: dpr // new
			});
			canvas.setChart(chart);
			setSnoringOption(chart, data1, data2);

			// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
			chartSnoringLine = chart;

			// 注意这里一定要返回 chart 实例，否则会影响事件处理等
			return chart;
		});
	}
}

//呼吸暂停

function initApneaLine(canvas, width, height, dpr) {
	// 在这里初始化图表
	const chart = echarts.init(canvas, null, {
		width: width,
		height: height,
		devicePixelRatio: dpr // new
	});
	canvas.setChart(chart);
	setApneaOption(chart);

	// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
	chartApneaLine = chart;

	// 注意这里一定要返回 chart 实例，否则会影响事件处理等
	return chart;
};


function setApneaOption(chart, data1 = [], data2 = [],) {
	var option = option = {
		tooltip: {
			show: true,
			trigger: 'axis',
			formatter: function (param) {
				return `${param[0] && param[0].value == 1 ? '停止' : '否'}`
			}
		},
		dataZoom: [
			{ // 第一个 dataZoom 组件
				type: 'inside',
			},
		],
		grid: {
			top: '40rpx',
			left: 0,
			right: '20rpx',
			bottom: 0,
			containLabel: true
		},
		xAxis: {
			type: 'category',
			axisLabel: {
				color: '#6C6970',// 设置 x 轴标签颜色为白色  
				fontSize: 10
			},
			boundaryGap: false,
			splitLine: {
				show: false, // 是否显示刻度线  

			},
			axisTick: {
				// 不显示Y轴刻度线  
				show: false
			},
			data: data1,
			axisLine: {
				// 不显示X轴轴线  
				show: false
			}
		},
		yAxis: {
			type: 'value',
			show: false,
		},
		series: [{
			type: 'line',
			smooth: true,
			lineStyle: {
				width: 1,
				color: '#6086EF'
			},
			emphasis: {
				disabled: true,
				scale: false,
				lineStyle: {
					width: 1,
					color: '#6086EF'
				},
			},
			showSymbol: false,
			areaStyle: {
				opacity: 0.8,
				color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
					{
						offset: 0,
						color: 'rgba(96, 134, 239, 1)'
					},
					{
						offset: 1,
						color: 'rgba(255, 255, 255, 0)'
					}
				])
			},
			data: data2,
		}]
	};

	chart.setOption(option, true);
}

function updateApnea(data1, data2, startSleepTime, endSleepTime, that) {
	if (chartApneaLine) {
		setApneaOption(chartApneaLine, data1, data2);
	} else {
		that.selectComponent('#chartApneaLine-dom').init((canvas, width, height, dpr) => {
			const chart = echarts.init(canvas, null, {
				width: width,
				height: height,
				devicePixelRatio: dpr // new
			});
			canvas.setChart(chart);
			setApneaOption(chart, data1, data2);

			// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
			chartApneaLine = chart;

			// 注意这里一定要返回 chart 实例，否则会影响事件处理等
			return chart;
		});
	}
}


//深浅睡眠

function timestampToHHMM(timestamp) {
	let date = new Date(timestamp); // 注意：JavaScript中的Date是以毫秒为单位的
	let hours = date.getHours().toString().padStart(2, '0'); // 获取小时数，并补零
	let minutes = date.getMinutes().toString().padStart(2, '0'); // 获取分钟数，并补零
	return hours + ':' + minutes;
}

// 自定义图形
function renderItem(params, api) {
	var categoryIndex = api.value(0);
	var startX = api.coord([api.value(1), categoryIndex])[0];
	var endX = api.coord([api.value(2), categoryIndex])[0];
	var centerY = api.coord([
		api.value(1) + (api.value(2) - api.value(1)) / 2,
		categoryIndex
	])[1]; // 取中间点的y坐标
	var height = api.size([0, 1])[1] * 1;
	var width = endX - startX;

	// 创建一个矩形
	var rect = {
		x: startX,
		y: centerY - height / 2,
		r: 2,
		width: width,
		height: height
	};

	// 返回的图形对象
	return {
		type: 'rect',
		shape: rect,
		style: api.style()
	};
}

function initChartTimeWaterfall(canvas, width, height, dpr) {
	// 在这里初始化图表
	const chart = echarts.init(canvas, null, {
		width: width,
		height: height,
		devicePixelRatio: dpr // new
	});
	canvas.setChart(chart);
	setTimeWaterfallOption(chart, null, [{ "name": "清醒", "value": [2, 0, 0, 0], "itemStyle": { "normal": { "color": { "colorStops": [{ "offset": 0, "color": "#AAD09F" }, { "offset": 1, "color": "#AAD09F" }], "x": 0, "y": 0, "x2": 0, "y2": 1, "type": "linear", "global": false } } } }]);

	// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
	chartTimeWaterfall = chart;

	// 注意这里一定要返回 chart 实例，否则会影响事件处理等
	return chart;
};


function setTimeWaterfallOption(chart, startTime = new Date().getTime(), data = [], categories = ['深睡', '中睡', '浅睡', '清醒']) {
	var option =
		option = {
			tooltip: {
				show: true,
				formatter: function (params) {
					return params.marker + params.name + ': ' + params.value[3] + ' m';
				}
			},
			dataZoom: [
				{
					type: 'inside',
					filterMode: 'weakFilter'
				}
			],
			grid: {
				top: 0,
				bottom: 0,
				height: 160,
				containLabel: false
			},
			xAxis: {
				type: 'value',
				scale: true,
				min: startTime,
				splitLine: {
					show: false // 是否显示刻度线
				},
				axisLabel: {
					color: '#6C6970',// 设置 x 轴标签颜色为白色  
					fontSize: 10,
					formatter: function (val) {
						return timestampToHHMM(val || startTime);
					}
				}
			},
			yAxis: {
				show: false,
				data: categories
			},
			series: [
				{
					type: 'custom',
					renderItem: renderItem,
					itemStyle: {
						opacity: 1
					},
					encode: {
						x: [1, 2],
						y: 0
					},
					data: data
				}
			]
		};


	chart.setOption(option, true);
}

function updateTimeWaterfall(startTime = new Date().getTime(), data, that) {
	console.log("updateTimeWaterfall========>", data);
	if (chartTimeWaterfall) {
		setTimeWaterfallOption(chartTimeWaterfall, startTime, data);
	} else {
		that.selectComponent('#chartTimeWaterfall-dom').init((canvas, width, height, dpr) => {
			const chart = echarts.init(canvas, null, {
				width: width,
				height: height,
				devicePixelRatio: dpr // new
			});
			canvas.setChart(chart);
			setTimeWaterfallOption(chart, startTime, data);

			// 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
			chartTimeWaterfall = chart;

			// 注意这里一定要返回 chart 实例，否则会影响事件处理等
			return chart;
		});
	}
}

function addZero(str) {
	if (String(str).length == 1) {
		return "0" + String(str);
	} else {
		return String(str);
	}
}



const aipushApi = "https://aipush.aidsleep.cn";
const token_push = "b74fd5754c5ef24cf600c39194abdaeb";
const token_today_push = "89835e65993fee4a6a6cbbe4c271da51e5521822934e13769e61cadabaed72c3";

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		ecCircularProgressBar: {
			// lazyLoad: true, // 懒加载
			onInit: initChartHumidifier
		},
		ecOutOfBed: {
			// lazyLoad: true, // 懒加载
			onInit: initChartOutOfBed
		},
		ecBodyMovements: {
			// lazyLoad: true, // 懒加载
			onInit: initChartBodyMovementsLine
		},
		ecCardiacSystemLine: {
			// lazyLoad: true, // 懒加载
			onInit: initChartCardiacSystemLine
		},
		ecChartRespiratoryLine: {
			// lazyLoad: true, // 懒加载
			onInit: initChartRespiratoryLine
		},
		// ecSnoringLine: {
		// 	// lazyLoad: true, // 懒加载
		// 	onInit: initSnoringLine
		// },
		// ecApneaLine: {
		// 	// lazyLoad: true, // 懒加载
		// 	onInit: initApneaLine
		// },
		ecTimeWaterfall: {
			// lazyLoad: true, // 懒加载
			onInit: initChartTimeWaterfall
		},
		showAuthorizedDialog: false,
		status: "",
		isToDay: false,

		year: addZero(new Date().getFullYear()),
		month: addZero(new Date().getMonth()),
		date: addZero(new Date().getDate()),
		hours: addZero(new Date().getHours()),

		rdt_arr: [],
		rrh_arr: [],
		rhx_arr: [],
		rsnoring_arr: [],
		routbed_arr: [],
		rmove_arr: [],
		rhxstop_arr: [],
		rsleep_arr: [],

		rdt_arrNew: [],//睡眠时间轴数据集合
		rrh_arrNew: [],//睡眠心率数据集合
		rhx_arrNew: [],//睡眠呼吸数据集合
		rmove_arrNew: [],//体动状态数据集合,0-否,1-体动状态
		rsleep_arrNew: [],//睡眠状态数据集合,0-清醒,10-浅睡,20-中睡,30-深睡
		rsleep_arr_all_New: [],//睡眠状态数据集合,0-清醒,10-浅睡,20-中睡,30-深睡
		durationData: [], //睡眠时长
		sleep_duration: [], //睡眠和清醒对比
		rdeep_durationFormatA: {},
		rdeep_duration: 0,
		rlight_duration: 0,
		rin_duration: 0,
		rawake_duration: 0,

		rrs_duration: 0,//入睡时长
		routbed_count_value: 0,//离床次数
		rsleep_eff_value: '',//睡眠效率

		rdeep_durationFormat: '',
		rlight_durationFormat: '',
		rin_durationFormat: '',
		rawake_durationFormat: '',

		ravg_hx_value: 0,
		ravg_hx_desc: '',
		ravg_rh_value: 0,
		ravg_rh_desc: '',
		rscore_value: 0,
		rscore_desc: '',
		sleep_efficiency: '',//睡眠效率
		zdPoint: [],
		rsn: '',
		rdate: '',
		total_duration: 0,
		rtotal_duration: 0,
		rinbed_duration: 0,
		rgobed_time: 0,
		routbed_time: 0,
		rgobed_routbed: 0,
		sleepHourSub: 0,
		routbed_count_value: 0,
		reportDate: '',
		currentDate: '',
		currentTime: '',
		rmove_arrFrequency: 0,//体动次数
		routbed_arrFrequency: 0,//离床次数
		rsnoring_arrFrequency: 0,//打鼾次数
		rhxstop_arrFrequency: 0,//呼吸暂停次数
		sleep_durationCountA: 0,//睡眠时间

		tvEntityIds: [],
		ifOneMoreTV: false,//数据推送是否有多于一台电视

		hotelcode: '',//酒店编码
		roomcode: '',//房间编码

		rdeep_duration_efficiency: '',//深睡比例
		rlight_duration_efficiency: '',//浅睡比例
		rin_duration_efficiency: '',//中睡比例
		rawake_duration_efficiency: '',//清醒比例
		isLoading: false,
		reportId: '',
		hotelname: '',
		roomname: '',
		bedname: '',
		pushReportId: '',//推送用：reportId
		sn: '',//今日报告切换用
		sns: [],//床
		dateData: [],//日期
		dateTimeData: [],//时间段
		selectTitleList: [],//床垫
		showSelect: false,
		showSelectSn: false,
		showSelectDate: false,
		showSelectDateTime: false,
		isNoReportToday: false,
		isShowTz: false,
		tzTitle: '',
		tzSubTitle: '',
	},
	toWarmReminder(e) {
		const tabName = e.currentTarget.dataset.index || 1;
		wx.navigateTo({
			url: '/subpages/warmReminder/warmReminder?id=' + tabName
		})
	},

	getRsleep_arr(list) {
		if (list) {
			console.log("getRsleep_arr_list1==" + JSON.stringify(list));
			for (let i = 0; i < list.length; i++) {
				if (list[i] == '0') {
					list[i] = '清醒';
				} else if (list[i] == '10') {
					list[i] = '浅睡';
				} else if (list[i] == '20') {
					list[i] = '中睡';
				} else if (list[i] == '30') {
					list[i] = '深睡';
				} else {
					list[i] = '其他';
				}
			}
		}
		console.log("getRsleep_arr_list2==" + JSON.stringify(list));
	},
	getFrequency(list) {//获取
		if (list) {
			console.log("getRsleep_arr_list1==" + JSON.stringify(list));
			for (let i = 0; i < list.length; i++) {
				if (list[i] == '0') {
					list[i] = '清醒';
				} else if (list[i] == '10') {
					list[i] = '浅睡';
				} else if (list[i] == '20') {
					list[i] = '中睡';
				} else if (list[i] == '30') {
					list[i] = '深睡';
				} else {
					list[i] = '其他';
				}
			}
		}
		console.log("getRsleep_arr_list2==" + JSON.stringify(list));
	},
	splitN(originalArray, n) {
		if (!originalArray) return [];
		// 计算每份的大小  
		// let chunkSize = Math.ceil(originalArray.length / n);

		// 分割数组并获取每份的最后一个元素  
		// let lastElements = [];
		// for (let i = 0; i < originalArray.length; i += chunkSize) {
		// 	let chunk = originalArray.slice(i, i + chunkSize);
		// 	lastElements.push(chunk[chunk.length - 1]);
		// }
		// 输出每份的最后一个元素  
		// console.log('lastElements=' + lastElements);
		return originalArray;
	},
	//获取次数
	getFrequency(list, o) {
		if (!list) return 0;
		let frequency = 0;
		for (let i = 0; i < list.length; i++) {
			if (list[i] == o) frequency++;
		}
		console.log('frequency=' + frequency);
		return frequency;
	},
	getTimeDiffInHours: function (startTimeStr, endTimeStr) {
		// 假设两个时间都是同一天的，这里我们使用当前日期作为基准  
		if (!startTimeStr || !endTimeStr) return null;
		const now = new Date();
		const startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), ...startTimeStr.split(':').map(Number));
		const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), ...endTimeStr.split(':').map(Number));

		// 处理跨天的情况  
		if (endDate < startDate) {
			endDate.setDate(endDate.getDate() + 1); // 将结束时间设置为第二天的同一时间  
		}

		// 计算时间差（毫秒）  
		const diffInMs = endDate - startDate;

		// 转换为小时  
		const diffInHours = diffInMs / (1000 * 60 * 60);

		return diffInHours;
	},
	// 时间格式化
	convertTimeToHoursAndMinutes: function (timeWithText, flag = 0) {
		if (!timeWithText) return;
		// 移除'分钟'两个字  
		var minutesStr = timeWithText.replace('分钟', '');
		var minutes = parseInt(minutesStr); // 将字符串转换为整数  

		if (isNaN(minutes)) {
			// 如果转换失败，则可能是输入的不是有效的数字  
			console.error('Invalid minutes format');
			return;
		}

		var hours = Math.floor(minutes / 60); // 整除60得到小时数  
		var remainingMinutes = minutes % 60; // 取余得到剩余的分钟数  

		// 如果小时数或分钟数小于10，前面补0  
		// var formattedHours = hours < 10 ? '0' + hours : hours;  
		var formattedHours = hours;
		// var formattedMinutes = remainingMinutes < 10 ? '0' + remainingMinutes : remainingMinutes;
		var formattedMinutes = remainingMinutes;

		// 拼接小时和分钟，形成HH:mm格式 
		var formattedTime = '';
		if (flag == 1) {
			formattedTime = formattedHours + 'H ' + formattedMinutes + 'M';
		} else if (flag == 2) {
			formattedTime = formattedHours + '{units|小时}' + formattedMinutes + '{units|分钟}';
		} else {
			formattedTime = {
				formattedHours,
				formattedMinutes
			};
		}

		// 更新数据  
		// this.setData({  
		//   formattedTime: formattedTime  
		// });  
		return formattedTime;
	},
	// 组装深度睡眠数据
	calculateTheDurationOfDeepSleep() {
		var that = this;
		// var totalDuration = this.data.total_duration;
		// var timePeriod = this.data.rdt_arrNew;
		var sleepData = this.data.rsleep_arr;//睡眠状态数据集合,0-清醒,10-浅睡,20-中睡,30-深睡

		// console.log("睡眠总时长=>", totalDuration);
		// console.log("睡眠时间片段=>", timePeriod);
		// console.log("睡眠时间片段=>", timePeriod.length);
		// console.log("睡眠数据=>", sleepData);
		// console.log("睡眠数据=>", sleepData.length);
		var awakeColor = [{ offset: 0, color: '#F7E3BA' }, { offset: 1, color: '#F7E3BA' }];;
		var lightSleepColor = [{ offset: 0, color: '#AAD09F' }, { offset: 1, color: '#AAD09F' }];
		var sleptInColor = [{ offset: 0, color: '#75BDE0' }, { offset: 1, color: '#75BDE0' }];
		var deepSleepColor = [{ offset: 0, color: '#3D7299' }, { offset: 1, color: '#3D7299' }];
		// var linearGradient = new echarts.graphic.LinearGradient(
		// 	0, 0, 0, 1, // 方向从左到右  
		// 	[
		// 		{ offset: 0, color: '#FDBE25' }, // 渐变开始的颜色  
		// 		{ offset: 1, color: '#FD7778' } // 渐变结束的颜色  
		// 	]
		// );
		// var item = {
		// 	name: { name: '清醒', color: '#7b9ce1' },
		// 	value: [index, baseTime, (baseTime += duration), duration],
		// 	itemStyle: {
		// 		normal: {
		// 			color: linearGradient,
		// 		}
		// 	}
		// };

		// var sleepData = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "10", "10", "10", "10", "10", "10", "10", "10", "10", "10", "10", "10", "10", "10", "10", "0", "0", "0", "0", "0", "0", "0", "0", "0", "10", "10", "10", "10", "10", "10", "10", "20", "20", "20", "20", "20", "20", "20", "20", "30", "30", "30", "30", "30", "30", "30", "30", "30"];//睡眠状态数据集合,0-清醒,10-浅睡,20-中睡,30-深睡

		// 状态映射  
		const statusMap = {
			"0": "清醒",
			"10": "浅睡",
			"20": "中睡",
			"30": "深睡"
		};
		// 状态映射  
		const statusColorMap = {
			"20": awakeColor,
			"0": lightSleepColor,
			"10": sleptInColor,
			"30": deepSleepColor
		};
		// 状态映射  
		const statusIndexMap = {
			"20": 3,
			"0": 2,
			"10": 1,
			"30": 0
		};
		// 初始化变量  reportDate
		// let dateString = '2024/09/14 23:20:00';
		let dateString = `${that.data.reportDate.replaceAll("-", "/")} ${that.data.rgobed_time + ":00"}`;
		let date = new Date(dateString);
		let startTime = date.getTime(); // 基准时间，这里设为午夜开始 
		console.log("时间=》", timestampToHHMM(startTime));

		let oldTime = startTime;
		let currentTime = startTime;
		let currentState = sleepData[0];
		let timePeriods = [];

		// 遍历睡眠数据数组  
		for (let i = 0; i < sleepData.length; i++) {
			// 如果当前状态与前一个状态不同，则记录前一个时间段  
			if (i > 0 && sleepData[i] !== sleepData[i - 1]) {
				// 计算前一个时间段的结束时间（注意这里不需要减去一分钟，因为 currentTime 还未递增）  
				let endTime = currentTime;
				// 计算前一个时间段的持续时间（分钟）  
				let duration = Math.floor((endTime - startTime) / (1000 * 60));
				// 记录时间段  
				if (duration > 0) {
					var linearGradient = new echarts.graphic.LinearGradient(
						0, 0, 0, 1, // 方向从左到右  
						statusColorMap[sleepData[i - 1]]
					);
					timePeriods.push({
						name: statusMap[sleepData[i - 1]],// 使用前一个状态 
						value: [statusIndexMap[sleepData[i - 1]], startTime, endTime, duration],
						itemStyle: {
							normal: {
								color: linearGradient,
							}
						},
						// startTime: new Date(startTime), // 转换为 Date 对象以便更易于阅读  
						// endTime: new Date(endTime),
						// durationMinutes: duration
					});
				}
				// 更新当前状态和开始时间  
				currentState = sleepData[i];
				startTime = currentTime;
			}
			// 递增时间（每分钟）  
			currentTime += 1000 * 60;
			// 处理最后一个时间段（如果数组不是以状态变化结束的话）  
			if (i === sleepData.length - 1) {
				let endTime = currentTime;
				let duration = Math.floor((endTime - startTime) / (1000 * 60));
				if (duration > 0) {
					var linearGradient = new echarts.graphic.LinearGradient(
						0, 0, 0, 1, // 方向从左到右  
						statusColorMap[currentState]
					);
					timePeriods.push({
						name: statusMap[currentState],// 使用前一个状态 
						value: [statusIndexMap[currentState], startTime, endTime, duration],
						itemStyle: {
							normal: {
								color: linearGradient,
							}
						},
						// startTime: new Date(startTime), // 转换为 Date 对象以便更易于阅读  
						// endTime: new Date(endTime),
						// durationMinutes: duration
					});
				}
			}
		}

		wx.nextTick(() => {
			setTimeout(() => {
				updateTimeWaterfall(oldTime, timePeriods, that)
			}, 1000);
		});
		// console.log("睡眠数据最终=>", dateString);
		// console.log("睡眠数据最终=>", startTime);
		console.log("睡眠数据最终=>", JSON.stringify(timePeriods));
	},
	// 授权成功
	authorizationSuccessful() {
		console.log("授权成功");
		this.setData({ showAuthorizedDialog: false })
		this.showData();
	},
	onReady() {

	},
	showData() {
		let hotelcodeTemp = wx.getStorageSync("hotelEmpower");
		let roomcodeTemp = wx.getStorageSync("roomEmpower");
		// hotelcodeTemp = wx.getStorageSync('res').result.split('|')[0];
		// roomcodeTemp = wx.getStorageSync('res').result.split('|')[1];
		// 设置canvas的宽高  
		this.setData({
			hotelcode: hotelcodeTemp,
			roomcode: roomcodeTemp,
		});
		if (this.data.isToDay) {
			this.getToDayReportData();
		} else {
			this.getReportData();
		}
		this.getTzData();
	},
	/**			
	 * 生命周期函数--监听页面加载
	 */
	onShow: function () {
		if (!wx.getStorageSync('hasAuth')) {
			this.setData({ showAuthorizedDialog: true })
		} else {
			this.showData();
		}
	},
	onLoad(options) {
		var that = this;
		if (options.rpids) {
			that.setData({
				reportId: options.rpids,
				isToDay: false
			})
			wx.setNavigationBarTitle({
				title: "历史睡眠报告"
			})
		} else {
			wx.setNavigationBarTitle({
				title: "最新睡眠报告" || "今日睡眠报告"
			})
			that.setData({
				isToDay: true
			})

		}

	},
	onTitleChange(event) {
		const { picker, value, index } = event.detail;
		console.log(`当前值：${value.rpid}, 当前索引：${index}`);
		console.log(`当前值：${value.bedname}, 当前索引：${index}`);
		console.log(`当前值：${value.hotelname}, 当前索引：${index}`);
		console.log(`当前值：${value.roomname}, 当前索引：${index}`);
		this.setData({
			reportId: value.rpid,
			hotelname: value.hotelname,
			roomname: value.roomname,
			bedname: value.bedname,
		});
		this.closePicker();
		this.getReportData();//更新报告
	},
	onSnChange(event) {
		const { picker, value, index } = event.detail;
		console.log(`当前值：${value.sn}, 当前索引：${index}`);
		this.closePicker();
		this.getDateData(value.sn);//自动获取日期
		// 
		// this.getDateTimeData(this.data.reportDate);//如果不能修改日期 自动获取时间段
	},
	onDateChange(event) {
		const { picker, value, index } = event.detail;
		console.log(`当前值：${value.rdate}, 当前索引：${index}`);
		this.closePicker();
		this.getDateTimeData(value.rdate);//自动获取时间段
	},
	onDateTimeChange(event) {
		const { picker, value, index } = event.detail;
		console.log(`当前值：${value.rpids}, 当前索引：${index}`);
		this.setData({
			reportId: value.rpids
		});
		this.closePicker();
		this.getReportData();//更新报告
	},
	showPicker(e) {
		// return //暂时不开放
		// 不是今天不让选择
		if (!this.data.isToDay) {
			return
		}
		var type = e.currentTarget.dataset.type;
		console.log(type);

		if (type == 'sn' && this.data.selectTitleList.length) {
			this.setData({
				showSelect: true,
			});
		} else if (type == 'sn' && this.data.sns.length) {
			// this.setData({
			// 	showSelectSn: true,
			// });
		} else if (type == 'date' && this.data.dateData.length) {
			return
			// this.setData({
			// 	showSelectDate: true,
			// });
		} else if (type == 'dateTime' && this.data.dateTimeData.length) {
			return
			// this.setData({
			// 	showSelectDateTime: true,
			// });
		}
	},
	closePicker() {
		this.setData({
			showSelect: false,
			showSelectSn: false,
			showSelectDate: false,
			showSelectDateTime: false
		});
	},
	getAllUnionidList() {
		var that = this;
		wx.request({
			url: `${aipushApi}` + '/allunionidlist',
			data: {
				"udi": wx.getStorageSync("unionid"),
				"token": token_today_push
			},
			method: 'POST',
			success(res) {
				try {
					const tempList = res.data.data || []
					that.setData({
						selectTitleList: tempList,
					});
					
				} catch (error) {
					console.error(error);
				}

			},
		})
	},
	getSnData() {
		var that = this;
		wx.request({
			url: `${aipushApi}` + '/getsn',
			data: {
				// "hotelcode": "lab",
				// "roomcode": "labs",
				"hotelcode": that.data.hotelcode ? that.data.hotelcode : "club",
				"roomcode": that.data.roomcode ? that.data.roomcode : "nuange",
				"token": token_push
			},
			method: 'POST',
			success(res) {
				try {
					if (res && res.data && res.data[0]) {
						that.setData({
							hotelname: res.data[0].hn,
							roomname: res.data[0].rn,
							sn: res.data[0].sn,
							sns: res.data //床的数组
						});
						that.getDateData(res.data[0].sn, false);//根据 sn  获取可以用的时间段 
						// console.log("res.data=sn=" + JSON.stringify(res.data));
					}

				} catch (error) {
					console.error(error);
				}

			},
		})
	},
	toReport() {
		wx.navigateTo({
			url: '/subpages/constitutionDiagnosis/constitutionDiagnosis'
		})
	},
	getTzData() {
		var that = this;
		var userId = wx.getStorageSync("unionid");
		wx.request({
			url: `https://fare.somnisix.top/system/constitutionDiagnosis/user/${userId}`,
			data: {
				"token": "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6Ijk5YzI3MjI2LTdkOWQtNDhiOC1hYjlhLWM4YjVjYWZiZGNkNyIsInVzZXJuYW1lIjoiYWRtaW4ifQ.zITQOINFkHs19_1RAgHS4I9YMaVxVq0Dsn3t6r_K7rv3rXvJy0sMtodejIMi_PNa_m4uQYxnU-6k3wC2LZht_Q"
			},
			header: {
				'Authorization': 'Bearer ' + "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6Ijk5YzI3MjI2LTdkOWQtNDhiOC1hYjlhLWM4YjVjYWZiZGNkNyIsInVzZXJuYW1lIjoiYWRtaW4ifQ.zITQOINFkHs19_1RAgHS4I9YMaVxVq0Dsn3t6r_K7rv3rXvJy0sMtodejIMi_PNa_m4uQYxnU-6k3wC2LZht_Q" // 在头部设置Bearer Token
			},
			method: 'GET',
			success(res) {
				try {
					if (res && res.data && res.data.data) {
						console.log("睡眠数据最终33=>", res.data);
						if (res.data.data.value2) {
							console.log("睡眠数据最终444=>", res.data.data.value2);
							var data = JSON.parse(res.data.data.value2);
							console.log("睡眠数据最终555=>", data);

							var ratingResultsMap = {
								A: {
									index: 0,
									title: "气虚型",
									tips: "（体力和气力都低下，需要规律性的生活方式）",
									subTitle: "累啊』『真倒霉』成了口头语",
									desc: "一般来说气虚型的人，就是被称作生命力的“气”整体不足。因为体力和气力的整体下降，无论做什么都会感到“真倒霉”“真麻烦”，饮食和运动也是马马虎虎地应付。结果，陷入生活越不规律，“气”就越衰弱的恶性循环。特点就是免疫力降低，易患感冒，而且很难一次性治愈。\n\n为了改善气虚，最重要的就是要有规律性的生活方式。晚上早睡，早上早起。日常食物也要以应季的食材为主，促进胃肠的蠕动，尽量多食用可以提升体温的豆类、薯类等食材。\n\n适度的运动是必要的，但因体力下降，所以万不可强求大的运动量，可以从散步呀、瑜伽呀等轻负荷的运动练起。\n\n特征：驼背。显老像；稍一运动就出汗；手脚发冷；易疲劳，总有困意与疲倦感；下半身易发胖。"
								}, B: {
									index: 1,
									title: "气滞型",
									tips: "（常常紧张、焦虑～要有意识地放松自己）",
									subTitle: "感情起伏剧烈",
									desc: "“气”本来是在体内正常循环的，但是因紧张和压力等使气滞留，就造成了气滞型。“气’一旦滞留，就表现为腹胀、肿胀、疼痛等症状。而且，感情起伏剧烈也是其特征。一旦情绪低落，很快就会焦虑起来，给人以“易发怒”歇斯底里”的感觉。更年期出现气滞的人也不在少数。\n\n养生法无疑是减轻压力的最好办法，但暴饮暴食则会适得其反。值得注意的是体重的增加会影响气的循环。香草和香味蔬菜有促进气循环和防止暴饮暴食的作用。除此之外，每天的日常安排中应留出自我放松的时间，也可以进行深呼吸，这些都有助于改善气滞。\n\n气滞型：入睡困难；眼睛充血；肚子容易生赘肉；焦虑，易怒，皮肤油腻，发红；易打嗝，矢气。"
								}, C: {
									index: 2,
									title: "血虚型",
									tips: "（饮食生活无规律～可能也有气虚或气滞的原因）",
									subTitle: "头发散乱，皮肤无光泽",
									desc: "你是否为了减肥极端地限制饮食，或者光在外边吃快餐？如果一直这样，就会使营养失去平衡，引起“血”的不足，陷入血虚状态。\n\n为此，日常饮食重要的是要注意营养的平衡，特别要多食用有造血作用的羊栖菜、动物肝脏、梅干等。“血”增加了，头发散乱、皮肤无光泽这些血虚型的症状自然就消失了。夜间是人体的造血时间，因此不要熬夜。还要控制电脑和手机的使用，也要控制看电视的时间。中医学以为用眼是消耗“血”的。\n\n特征：头发脆弱，脱发；常常眩晕，站起时头晕；脸色不好，皮肤干燥；指甲偏薄，易裂；耳鸣；冷静，认真型。"
								}, D: {
									index: 3,
									title: "淤血型",
									tips: "（血流不畅～更要注意减压，慎食生冷食品）",
									subTitle: "常常感到肩凝、头痛",
									desc: "血流不顺畅，易在体内形成血块（瘀血）。其原因有喜食生冷食品、压力大、过劳、睡眠不足等等。也有因气虚和血虚造成的瘀血。\n\n对这个型的人，首先是必须使其血行畅通，提高代谢。要多食用牛蒡、蒟蒻（魔芋）、黑醋等有化解瘀血作用的食品，也要多食用生姜和韭菜、葱等有香味的蔬菜。饮料也要尽量选择热你，偏冷会影响血循环。\n\n要养成运动的习惯。运动可以促进血行，缓解瘀血引起的肩凝和腰痛。当然，按摩下半身也可以有效地改善脸部的气色。\n\n特征：容易被晒伤；容易长色斑，雀斑；容易出现黑眼圈；常常为肩凝和腰痛烦恼；经血中有动物肝脏样血块；基本上自制力较强，但偶尔也会感情爆发。"
								}, E: {
									index: 4,
									title: "水虚型",
									tips: "（身体如同干枯一般～避免食用香辛食物和剧烈运动）",
									subTitle: "常为头晕眼花、身体发热而烦恼",
									desc: "体内水分不足称为水虚。皮肤、毛发、大便干燥的入水虚的可能性较大。而且，这类人因为给身体起到降温作用的水分不足，所以，常常感到头晕眼花或者身体发热。\n\n作为养生法，就是要通过食物的摄取，有效地补充水分。其中，苹果和香蕉、白菜可以有效地滋润身体，要有意识地多多食用。而且，因为睡眠中容易出汗，水分会在不知不觉中流失，因此，要在枕边预备下温开水，醒来后先饮水。\n\n另一方面，要尽量避免食用香辛食材。因为香辛料有温暖身体的作用，可能会加重头晕眼花和身体发热的症状。水虚的人还要避免剧烈的运动。因为他们的关节水分不足，剧烈运动会引发疼痛。\n\n特征：睡眠浅，盗汗；关节运动不灵活；不明原因的消沉，情绪低落；毛发和皮肤脆弱，口腔和咽喉干燥；便秘，尿量少。"
								}, F: {
									index: 5,
									title: "痰湿型",
									tips: "（体内多余的水分～常常引发各种“不调”，要慎食味重食品）",
									subTitle: "体型胖墩墩的",
									desc: "现代职场女性多为痰湿型。所谓痰湿就是生活不规律、压力大等原因造成身体内形成多余的水分块（痰湿）的状态。因为我们的身体70%是由水构成的，所以痰湿的影响不容忽视，会造成我们的身心状态出现各种各样的“不调”。\n\n首先，有氧运动能够增加肌肉的弹力，促进血行和代谢。肌肉弹力的提高、血行和代谢的改善，就可以通过汗和取把多余的水分排出体外。\n\n第二要注意减少冷饮和味重食品的摄入量，因为它们会造成水分的滞留。\n\n第三要多食用黄瓜和西瓜、梨等有较好利尿作用的食物。也要多食红豆、薏米。\n\n特征：整个身体容易浮肿；容易发胖；早晨起床后脸上有枕头的痕迹；皮肤发白。胖墩墩的；爱生湿乎乎的疙瘩；性格自我，爱慕虚荣。"
								}
							};
							var key = that.findKeyWithMaxValue(data);
							console.log("睡眠数据最终555=>", ratingResultsMap[key]);
							console.log("睡眠数据最终555=>", key);
							that.setData({
								tzTitle: ratingResultsMap[key]?.title ?? "健康型",
								tzSubTitle: ratingResultsMap[key]?.subTitle ?? "太棒了，您的身体非常健康，请继续保持",
								isShowTz: true
							})

						}
					}

				} catch (error) {
					console.error(error);
				}

			},
		})
	},

	/**
	 * A、B、C、D、E、F 最后积累的数量对比，按数量多少来判断，6个分别对应：气虚型、气滞型、血虚型、淤血型、水虚型、痰湿型
 * 找出对象中值最大的键
 * @param {Object} obj - 包含键值对的对象
 * @returns {string|null} - 值最大的键，如果没有找到则返回null
 */
	findKeyWithMaxValue(obj) {
		if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
			throw new Error('Input must be a plain object');
		}

		let maxKey = null;
		let maxValue = 0;

		for (let key in obj) {
			if (obj.hasOwnProperty(key)) {
				if (obj[key] > maxValue) {
					maxValue = obj[key];
					maxKey = key;
				}
			}
		}

		return maxKey;
	},

	// 可选择的日期
	getDateData: function (sn, isRefresh = true) {
		var that = this;
		var sourceFourthTemp = [];
		wx.request({
			url: `${aipushApi}/getdatefromsn`, //
			method: 'POST',
			//   header: {
			// 	  'content-type': 'application/json', // 默认值
			// 	  'Authorization': 'Bearer ' + token // 在头部设置认证信息，例如使用Bearer Token
			// },
			data: {
				"sn": sn, "token": token_push
			},
			success(res) {
				if (!res || !res.data || !res.data.results || !res.data.results.length) {
					that.setData({
						isNoReportToday: true
					})
					return;
				}
				that.setData({
					dateData: res.data.results //床的数组
				});
				// {"results": [{ "rdate": "2024-10-08" }]}
				that.getDateTimeData(res.data.results[0].rdate, isRefresh);
				// var resDataSn = res.data.results
			},
			fail: function (error) {
				console.error('error', error);
				that.setData({
					isNoReportToday: true
				})
			},
			complete: function (e) {
			}
		});
	},
	// 可选择的时间 可自动选择 更改 reportId
	getDateTimeData: function (rdate, isRefresh = true) {
		var that = this;
		wx.request({
			url: `${aipushApi}/getimefromsn`, //
			method: 'POST',
			//   header: {
			// 	  'content-type': 'application/json', // 默认值
			// 	  'Authorization': 'Bearer ' + token // 在头部设置认证信息，例如使用Bearer Token
			// },
			data: {
				"sn": that.data.sn, "date": rdate, "token": token_push
			},
			success(res) {
				// { "results": [{ "rpids": "459857", "durations": "14:17-17:55" }] }
				if (!res || !res.data || !res.data.results || !res.data.results.length) {
					that.setData({
						isNoReportToday: true
					})
					return;
				}

				that.setData({
					dateTimeData: res.data.results, //床的数组
				});
				if (isRefresh) {
					that.setData({
						isNoReportToday: false,
						reportId: res.data.results[0].rpids
					});
					that.getReportData();
				}

			},
			fail: function (error) {
				console.error('error', error);
				that.setData({
					isNoReportToday: true
				})
			}
		});
	},
	// 新版
	getReportData() {
		const that = this;
		wx.request({
			url: `${aipushApi}` + '/getsingle',
			data: {
				"token": token_push,
				"rpids": this.data.reportId,
				"udi": wx.getStorageSync("unionid")
			},
			method: 'POST',
			success(ress) {
				try {
					if (ress && ress.data) {
						console.log('ress.data-getsingle=' + JSON.stringify(ress.data.results));

						if (!ress.data.results || ress.data.results == '') {
							// wx.showModal({
							// 	title: '提示',
							// 	content: '无数据',
							// 	showCancel: false
							// });
							that.setData({
								isNoReportToday: true
							})
							return;
						}

						wx.nextTick(() => {
							setTimeout(() => {
								//初始化数据
								that.initReportData(ress.data.results);
								that.initChartCircle(ress.data.results);
								that.initOutOfBed(ress.data.results);
								that.initBodyMovements(ress.data.results);
								that.initCardiacSystem(ress.data.results);
								that.initChartRespiratory(ress.data.results);
								// that.initChartSnoring(ress.data.results);
								// that.initChartApnea(ress.data.results);
								that.initTimeWaterfall(ress.data.results);
							}, 1000);
						});

					} else {
						// wx.showModal({
						// 	title: '提示',
						// 	content: '无数据',
						// 	showCancel: false
						// });
						that.setData({
							isNoReportToday: true
						})
					}
				} catch (error) {
					console.error(error);
				}
			},
			fail: function (error) {
				// wx.showToast({
				// 	title: "无数据",
				// 	icon: "error",
				// 	mask: true,
				// });
				that.setData({
					isNoReportToday: true
				})
			}
		});
	},
	// 新版
	getToDayReportData() {
		const that = this;
		wx.request({
			url: `${aipushApi}` + '/getunionsingle',
			data: {
				"token": token_today_push,
				"udi": wx.getStorageSync("unionid")
			},
			method: 'POST',
			success(ress) {
				try {
					if (ress && ress.data) {
						console.log('ress.data-getunionsingle=' + JSON.stringify(ress.data));

						if (ress.data == {} || ress.data.data == {} || ress.data.data == [] || !ress.data.data) {
							// wx.showModal({
							// 	title: '提示',
							// 	content: '无数据',
							// 	showCancel: false
							// });
							that.setData({
								isNoReportToday: true
							})
							return;
						}
						//初始化数据
						wx.nextTick(() => {
							setTimeout(() => {
								that.initReportData(ress.data.data);
								that.initChartCircle(ress.data.data);
								that.initOutOfBed(ress.data.data);
								that.initBodyMovements(ress.data.data);
								that.initCardiacSystem(ress.data.data);
								that.initChartRespiratory(ress.data.data);
								// that.initChartSnoring(ress.data.data);
								// that.initChartApnea(ress.data.data);
								that.initTimeWaterfall(ress.data.data);
							}, 1000);
						});

						that.getSnData();//需要筛选的 要获取sn
						that.getAllUnionidList();
					} else {
						// wx.showModal({
						// 	title: '提示',
						// 	content: '无数据',
						// 	showCancel: false
						// });

						that.setData({
							isNoReportToday: true
						})
					}
				} catch (error) {
					console.error(error);
				}
			},
			fail: function (error) {
				// wx.showToast({
				// 	title: "无数据",
				// 	icon: "error",
				// 	mask: true,
				// });

				that.setData({
					isNoReportToday: true
				})
			}
		});
	},
	// 初始化的数据
	initReportData(ress) {
		const that = this;

		let durationDataTemp = [];
		let obj = {};
		obj.name = '深睡';
		obj.value = ress.rdeep_duration;
		durationDataTemp.push(obj);
		obj = {};
		obj.name = '浅睡';
		obj.value = ress.rlight_duration;
		durationDataTemp.push(obj);
		obj = {};
		obj.name = '中睡';
		obj.value = ress.rin_duration;
		durationDataTemp.push(obj);
		obj = {};
		obj.name = '清醒';
		obj.value = ress.rawake_duration;
		durationDataTemp.push(obj);

		let sleep_durationCount = 0;
		if (ress.rdeep_duration) {
			sleep_durationCount += parseFloat(ress.rdeep_duration)
		}
		if (ress.rlight_duration) {
			sleep_durationCount += parseFloat(ress.rlight_duration)
		}
		if (ress.rin_duration) {
			sleep_durationCount += parseFloat(ress.rin_duration)
		}

		let sleep_efficiency_temp = ress.rtotal_duration ? (Math.ceil((sleep_durationCount / ress.rtotal_duration) * 100) + '%') : '%'

		let rdeep_duration_efficiency_temp = ress.rtotal_duration ? (Math.ceil(((ress.rdeep_duration ? parseFloat(ress.rdeep_duration) : 0) / ress.rtotal_duration) * 100) + '%') : '%'
		let rlight_duration_efficiency_temp = ress.rtotal_duration ? (Math.ceil(((ress.rlight_duration ? parseFloat(ress.rlight_duration) : 0) / ress.rtotal_duration) * 100) + '%') : '%'
		let rin_duration_efficiency_temp = ress.rtotal_duration ? (Math.ceil(((ress.rin_duration ? parseFloat(ress.rin_duration) : 0) / ress.rtotal_duration) * 100) + '%') : '%'
		let rawake_duration_efficiency_temp = ress.rtotal_duration ? (Math.ceil(((ress.rawake_duration ? parseFloat(ress.rawake_duration) : 0) / ress.rtotal_duration) * 100) + '%') : '%'

		// let rdeep_duration_efficiency_temp = ress.darktrate;
		// let rlight_duration_efficiency_temp = ress.lightrate;
		// let rin_duration_efficiency_temp = ress.midrate;
		// let rawake_duration_efficiency_temp = ress.awakenrate;



		let sleep_durationTemp = [];
		let obj1 = {};
		obj1.name = '睡眠时间';
		obj1.value = Math.ceil(sleep_durationCount / 60);
		sleep_durationTemp.push(obj1);
		obj1 = {};
		obj1.name = '清醒时间';
		obj1.value = Math.ceil(parseFloat(ress.rawake_duration) / 60);
		sleep_durationTemp.push(obj1);

		let zdPointTemp = [];
		let rdt_arrTemp = [];

		let rrh_arrTemp = [];

		let rhx_arrTemp = [];


		let rmove_arrTemp = [];

		let rsleep_arrTemp = [];

		let rsleep_arr_all_Temp = [];

		if (ress.rrh_arr) {
			rdt_arrTemp = that.splitN(ress.rdt_arr.split(","), 100);
		}

		if (ress.rrh_arr) {
			rrh_arrTemp = that.splitN(ress.rrh_arr.split(","), 100);
		}
		if (ress.rhx_arr) {
			rhx_arrTemp = that.splitN(ress.rhx_arr.split(","), 100);
		}
		if (ress.rmove_arr) {
			rmove_arrTemp = that.splitN(ress.rmove_arr.split(","), 100);
		}
		if (ress.rsleep_arr) {
			rsleep_arrTemp = that.splitN(ress.rsleep_arr.split(","), 100);
		}

		if (ress.rsleep_arr) {
			rsleep_arr_all_Temp = ress.rsleep_arr.split(",");
		}



		that.setData({

			rdt_arr: ress.rdt_arr ? ress.rdt_arr.split(',') : [],
			rrh_arr: ress.rrh_arr ? ress.rrh_arr.split(',') : [],
			rhx_arr: ress.rhx_arr ? ress.rhx_arr.split(',') : [],
			rsnoring_arr: ress.rsnoring_arr ? ress.rsnoring_arr.split(',') : [],
			routbed_arr: ress.routbed_arr ? ress.routbed_arr.split(',') : [],
			rmove_arr: ress.rmove_arr ? ress.rmove_arr.split(',') : [],
			rhxstop_arr: ress.rhxstop_arr ? ress.rhxstop_arr.split(',') : [],
			rsleep_arr: ress.rsleep_arr ? ress.rsleep_arr.split(',') : [],//睡眠状态数据集合,0-清醒,10-浅睡,20-中睡,30-深睡

			rsnoring_arrFrequency: that.getFrequency(ress.rsnoring_arr ? ress.rsnoring_arr.split(',') : [], 1),
			routbed_arrFrequency: that.getFrequency(ress.routbed_arr ? ress.routbed_arr.split(',') : [], 0),
			rmove_arrFrequency: that.getFrequency(ress.rmove_arr ? ress.rmove_arr.split(',') : [], 1),
			rhxstop_arrFrequency: that.getFrequency(ress.rhxstop_arr ? ress.rhxstop_arr.split(',') : [], 1),

			rdeep_durationFormatA: that.convertTimeToHoursAndMinutes(ress.rdeep_duration),
			rlight_duration: ress.rlight_duration,
			rin_duration: ress.rin_duration,
			rawake_duration: ress.rawake_duration,
			ravg_hx_value: ress.ravg_hx_value,
			ravg_hx_desc: ress.ravg_hx_desc,
			ravg_rh_value: ress.ravg_rh_value,
			ravg_rh_desc: ress.ravg_rh_desc,
			rscore_value: ress.rscore_value,
			rscore_desc: ress.rscore_desc,

			rsn: ress.rsn,
			rdate: ress.rdate,
			total_duration: ress.rtotal_duration,
			rtotal_duration: that.convertTimeToHoursAndMinutes(ress.rtotal_duration),//睡眠总时长,单位小时分钟
			rinbed_duration: that.convertTimeToHoursAndMinutes(ress.rinbed_duration),//在床时长,单位小时分钟
			rgobed_time: ress.rgobed_time,//上床时间
			routbed_time: ress.routbed_time,//离床时间
			rgobed_routbed: ress.rgobed_time + '~' + ress.routbed_time,
			sleepHourSub: that.getTimeDiffInHours(ress.rgobed_time, ress.routbed_time),
			routbed_count_value: ress.routbed_count_value,//离床次数
			zdPointT: zdPointTemp,
			rdt_arrNew: rdt_arrTemp,
			rrh_arrNew: rrh_arrTemp,
			rhx_arrNew: rhx_arrTemp,
			rmove_arrNew: rmove_arrTemp,
			rsleep_arrNew: rsleep_arrTemp,
			rsleep_arr_all_New: rsleep_arr_all_Temp,
			durationData: durationDataTemp,
			sleep_duration: sleep_durationTemp,
			sleep_efficiency: sleep_efficiency_temp,
			sleep_durationCountA: that.convertTimeToHoursAndMinutes(sleep_durationCount ? sleep_durationCount.toString() : '0'),
			tvEntityIds: wx.getStorageSync('tvEntityIds'),
			ifOneMoreTV: (wx.getStorageSync('tvEntityIds') && wx.getStorageSync('tvEntityIds').length > 1),
			rdeep_duration_efficiency: rdeep_duration_efficiency_temp,
			rlight_duration_efficiency: rlight_duration_efficiency_temp,
			rin_duration_efficiency: rin_duration_efficiency_temp,
			rawake_duration_efficiency: rawake_duration_efficiency_temp,
			pushReportId: ress.rdid,
			isNoReportToday: false,
			rrs_duration: that.convertTimeToHoursAndMinutes(ress.rrs_duration ? ress.rrs_duration.toString() : '0'),
			routbed_count_value: ress.routbed_count_value,
			rsleep_eff_value: ress.rsleep_eff_value,
			hotelname: ress.hotelname,
			roomname: ress.roomname,
			bedname: ress.bedname,
		});
	},
	// 香睡指数
	initChartCircle(ress) {
		var that = this;
		try {
			let rscore_descTemp = [];
			if (ress.rscore_desc) {
				rscore_descTemp = ress.rscore_desc;
			}
			let rscore_valueTemp = [];
			if (ress.rscore_value) {
				rscore_valueTemp = ress.rscore_value;
			}
			that.setData({
				rscore_desc: rscore_descTemp,
				rscore_value: rscore_valueTemp,
			});
			updateChartCircularProgressBarOption(rscore_descTemp, rscore_valueTemp, that);
		} catch (error) {
			console.error(error);
		}

	},
	// 心脏 系统
	initCardiacSystem(ress) {
		var that = this;
		try {
			let rdt_arrTemp = [];
			if (ress.rrh_arr) {
				rdt_arrTemp = that.splitN(ress.rdt_arr.split(","), 100);
			}
			if (ress.rdate) {
				that.setData({
					reportDate: ress.rdate
				});
			}
			let rrh_arrTemp = [];
			if (ress.rrh_arr) {
				rrh_arrTemp = that.splitN(ress.rrh_arr.split(","), 100);
			}
			that.setData({
				rdt_arrNew: rdt_arrTemp,
				rrh_arrNew: rrh_arrTemp,
			});
			console.log("that.data.rdt_arrNew,that.data.rrh_arrNew=" + that.data.rdt_arrNew + "," + that.data.rrh_arrNew);
			updateCardiacSystem(that.data.rdt_arrNew, that.data.rrh_arrNew, that);
		} catch (error) {
			console.error(error);
		}
	},
	initTimeWaterfall(ress) {//深浅睡眠
		var that = this;
		try {
			let rdt_arrTemp = [];
			if (ress.rrh_arr) {
				// rdt_arrTemp = that.splitN(ress.rdt_arr.split(","), 100);
				rdt_arrTemp = ress.rdt_arr.split(",");
			}
			// console.log('深浅睡眠11111=======' + JSON.stringify(rdt_arrTemp));
			let rsleep_arr_Temp = [];
			if (ress.rsleep_arr) {
				// rsleep_arr_Temp = that.splitN(ress.rsleep_arr.split(","), 100);
				rsleep_arr_Temp = ress.rsleep_arr.split(",");
			}
			// console.log('深浅睡眠222222=======' + JSON.stringify(rsleep_arr_Temp));
			that.setData({
				rdt_arrNew: rdt_arrTemp,
				rsleep_arr: rsleep_arr_Temp,
				rdeep_duration: ress.rdeep_duration,
				rlight_duration: ress.rlight_duration,
				rin_duration: ress.rin_duration,
				rawake_duration: ress.rawake_duration,
				rdeep_durationFormat: that.convertTimeToHoursAndMinutes(ress.rdeep_duration),
				rlight_durationFormat: that.convertTimeToHoursAndMinutes(ress.rlight_duration),
				rin_durationFormat: that.convertTimeToHoursAndMinutes(ress.rin_duration),
				rawake_durationFormat: that.convertTimeToHoursAndMinutes(ress.rawake_duration),
			});

			that.calculateTheDurationOfDeepSleep();
		} catch (error) {
			console.error(error);
		}
		console.log("that.data.rsleep_arr=" + that.data.rsleep_arr);

	},
	initOutOfBed(ress) {//离床次数
		var that = this;

		try {
			var routbed_arr_Temp = [];
			if (ress.routbed_arr) {
				routbed_arr_Temp = ress.routbed_arr.split(",");
			}

			that.setData({
				rdt_arr: ress.rdt_arr ? ress.rdt_arr.split(',') : [],
				routbed_arr: routbed_arr_Temp,
				rgobed_time: ress.rgobed_time,
				routbed_time: ress.routbed_time,
				rgobed_routbed: ress.rgobed_time + '~' + ress.routbed_time,
			});
			updateOutOfBed(that.data.rdt_arr, that.data.routbed_arr, that.data.rgobed_time, that.data.routbed_time, that)
		} catch (error) {
			console.error(error);
		}
		console.log("that.data.routbed_arr=" + that.data.routbed_arr);
	},
	initBodyMovements(ress) {//体动次数
		var that = this;

		try {
			var rmove_arr_Temp = [];
			if (ress.rmove_arr) {
				rmove_arr_Temp = ress.rmove_arr.split(",");
			}

			that.setData({
				// rdt_arr: that.splitN(ress.rdt_arr ? ress.rdt_arr.split(',') : [], 100),
				// rmove_arr: that.splitN(rmove_arr_Temp, 100),
				rdt_arr: ress.rdt_arr ? ress.rdt_arr.split(',') : [],
				rmove_arr: rmove_arr_Temp,
				rgobed_time: ress.rgobed_time,
				routbed_time: ress.routbed_time,
				rgobed_routbed: ress.rgobed_time + '~' + ress.routbed_time,
			});
			updateBodyMovements(that.data.rdt_arr, that.data.rmove_arr, that.data.rgobed_time, that.data.routbed_time, that)
		} catch (error) {
			console.error(error);
		}
		console.log("c8_that.data.rmove_arr=" + that.data.rmove_arr);
	},
	initChartRespiratory(ress) {//平均呼吸率
		var that = this;

		try {
			var rhx_arr_Temp = [];
			if (ress.rhx_arr) {
				rhx_arr_Temp = ress.rhx_arr.split(",");
			}

			that.setData({
				rdt_arr: that.splitN(ress.rdt_arr ? ress.rdt_arr.split(',') : [], 100),
				rhx_arr: that.splitN(rhx_arr_Temp, 100),
				rgobed_time: ress.rgobed_time,
				routbed_time: ress.routbed_time,
				rgobed_routbed: ress.rgobed_time + '~' + ress.routbed_time,
			});
			updateRespiratory(that.data.rdt_arr, that.data.rhx_arr, that.data.rgobed_time, that.data.routbed_time, that)
		} catch (error) {
			console.error(error);
		}
		console.log("c81_that.data.ravg_hx_value=" + that.data.ravg_hx_value);
	},
	initChartSnoring(ress) {//打鼾
		var that = this;

		try {
			var rsnoring_arr_Temp = [];
			if (ress.rsnoring_arr) {
				rsnoring_arr_Temp = ress.rsnoring_arr.split(",");
			}

			that.setData({
				rdt_arr: that.splitN(ress.rdt_arr ? ress.rdt_arr.split(',') : [], 100),
				rsnoring_arr: that.splitN(rsnoring_arr_Temp, 100),
				rgobed_time: ress.rgobed_time,
				routbed_time: ress.routbed_time,
				rgobed_routbed: ress.rgobed_time + '~' + ress.routbed_time,
			});
			updateSnoring(that.data.rdt_arr, that.data.rsnoring_arr, that.data.rgobed_time, that.data.routbed_time, that)
		} catch (error) {
			console.error(error);
		}
		console.log("c8_that.data.rmove_arr=" + that.data.rmove_arr);
	},
	initChartApnea(ress) {//呼吸暂停
		var that = this;
		try {
			var rhxstop_arr_Temp = [];
			if (ress.rhxstop_arr) {
				rhxstop_arr_Temp = ress.rhxstop_arr.split(",");
			}

			that.setData({
				rdt_arr: that.splitN(ress.rdt_arr ? ress.rdt_arr.split(',') : [], 100),
				rhxstop_arr: that.splitN(rhxstop_arr_Temp, 100),
				rgobed_time: ress.rgobed_time,
				routbed_time: ress.routbed_time,
				rgobed_routbed: ress.rgobed_time + '~' + ress.routbed_time,
			});
			updateApnea(that.data.rdt_arr, that.data.rhxstop_arr, that.data.rgobed_time, that.data.routbed_time, that)
		} catch (error) {
			console.error(error);
		}
		console.log("c8_that.data.rhxstop_arr=" + that.data.rhxstop_arr);

	},
	mounted() {

	},
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {
	},
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})