<template>
	<div class="table_item">
		<a-page-header sub-title="趋势图" @back="goBack" style="padding: 0 0 20px">
			<template #title>
				<span style="font-size: 18px; cursor: pointer" @click="goBack">返回</span>
			</template>
		</a-page-header>

		<div class="table_head">
			<div class="head_name">{{ data.regionName }}</div>
			<div class="head_row">
				<div class="label">
					<img src="/src/assets/images/monitor/01.png" v-if="data.sensorData && data.sensorData.temperature" />
					<img src="/src/assets/images/monitor/01-1.png" v-else />
				</div>
				<div class="value">
					<div>温度</div>
					<div class="num" v-if="data.sensorData && data.sensorData.temperature">
						{{ data.sensorData.temperature + '℃' }}
					</div>
				</div>
			</div>
			<div class="head_row">
				<div class="label">
					<img src="/src/assets/images/monitor/02.png" v-if="data.sensorData && data.sensorData.humidity" />
					<img src="/src/assets/images/monitor/02-2.png" v-else />
				</div>
				<div class="value">
					<div>湿度</div>
					<div class="num" v-if="data.sensorData && data.sensorData.humidity">{{ data.sensorData.humidity + '%' }}</div>
				</div>
			</div>
			<div class="head_row">
				<div class="label">
					<img src="/src/assets/images/monitor/03.png" v-if="data.sensorData && data.sensorData.co2" />
					<img src="/src/assets/images/monitor/03-3.png" v-else />
				</div>
				<div class="value">
					<div>二氧化碳</div>
					<div class="num" v-if="data.sensorData && data.sensorData.co2">{{ data.sensorData.co2 + 'ppm' }}</div>
				</div>
			</div>

			<div class="head_time">
				{{ '更新时间 ：' + data.updateTime }}
			</div>
		</div>

		<div class="table_search">
			<div class="search_left">
				<span>查询范围：</span>
				<a-range-picker
					v-model:value="timeValue"
					style="width: 250px"
					format="YYYY-MM-DD"
					value-format="YYYY-MM-DD"
					:disabled-date="disabledDate"
					:allowClear="false"
					@change="getEchartData"
				/>

				<a-radio-group v-model:value="periodValue" button-style="solid">
					<a-radio-button value="week">最近一周</a-radio-button>
					<a-radio-button value="halfaMonth">最近半月</a-radio-button>
					<a-radio-button value="oneMonth">最近一月</a-radio-button>
					<a-radio-button value="threeMonths">最近三月</a-radio-button>
				</a-radio-group>
			</div>

			<div class="search_right">
				<span>数据维度：</span>
				<a-radio-group v-model:value="radioValue" button-style="solid">
					<a-radio-button value="null">系统默认</a-radio-button>
					<a-radio-button value="1m">分钟</a-radio-button>
					<a-radio-button value="1h">小时</a-radio-button>
					<a-radio-button value="1d">天</a-radio-button>
					<a-radio-button value="1w">自然周</a-radio-button>
					<a-radio-button value="1mo">月度</a-radio-button>
					<a-radio-button value="3mo">季度</a-radio-button>
				</a-radio-group>
				<a-button class="xn-mg08">
					<template #icon><download-outlined /></template>导出
				</a-button>
			</div>
		</div>

		<!-- 折线图 -->
		<div class="chart">
			<div class="echart" id="temperature"></div>
			<div class="echart" id="humidity"></div>
			<div class="echart" id="CO2"></div>
		</div>
	</div>
</template>
<script setup>
	import * as echarts from 'echarts'
	import alarmTrendApi from '@/api/coldchain/alarmTrendApi.js'
	import { useRoute } from 'vue-router'
	import router from '@/router'
	import dayjs from 'dayjs' // 用于处理日期和时间
	const Route = useRoute()
	const queryValue = ref({}) //监控对象的参数
	const radioValue = ref('null') //时间段

	const data = ref({})
	const periodValue = ref('week')
	const timeValue = ref([])

	onBeforeMount(() => {
		calculateDateRange()
		if (Route.query.id) {
			queryValue.value = { ...Route.query }
		}
	})
	onMounted(() => {
		if (queryValue.value.id) {
			getData()
			getEchartData()
		}
	})

	// 监听 查询范围 变化，重新计算日期范围
	watch(periodValue, () => {
		calculateDateRange()
		getEchartData()
	})

	// 监听 数据维度 变化，重新计算日期范围
	watch(radioValue, () => {
		getEchartData()
	})

	// 计算时间范围
	const calculateDateRange = () => {
		const now = new Date()
		let startDate
		const endDate = new Date(now)
		endDate.setHours(23, 59, 59, 999) // 设置结束时间为当天的23:59:59

		// 根据不同的选择设置开始时间
		switch (periodValue.value) {
			case 'week':
				startDate = new Date(now)
				startDate.setDate(now.getDate() - 6) // 最近一周
				break
			case 'halfaMonth':
				startDate = new Date(now)
				startDate.setDate(now.getDate() - 14) // 最近半个月
				break
			case 'oneMonth':
				startDate = new Date(now)
				startDate.setMonth(now.getMonth() - 1) // 最近一个月
				break
			case 'threeMonths':
				startDate = new Date(now)
				startDate.setMonth(now.getMonth() - 3) // 最近三个月
				break
			default:
				startDate = new Date(now) // 默认值是今天
		}
		startDate.setHours(0, 0, 0, 0) // 设置开始时间为当天的00:00:00
		timeValue.value = [formatDate(startDate), formatDate(endDate)]
	}

	const today = dayjs() // 获取当前时间和90天前的时间
	const ninetyDaysAgo = today.subtract(90, 'day') // 90天前的日期

	// 禁用超过90天之前的日期和今天之后的日期
	const disabledDate = (current) => {
		if (!current) return false
		// 禁用当前日期早于90天之前的日期或今天之后的日期
		return current.isBefore(ninetyDaysAgo, 'day') || current.isAfter(today, 'day')
	}

	// 格式化日期为 "YYYY-MM-DD"
	const formatDate = (date) => {
		const year = date.getFullYear()
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		return `${year}-${month}-${day}`
	}

	// 获取基础信息
	const getData = () => {
		const parameter = {
			deviceId: queryValue.value.id,
			roads: queryValue.value.roads
		}
		alarmTrendApi.realTimeData(parameter).then((res) => {
			data.value = res
		})
	}

	// 获取折线图数据
	const getEchartData = () => {
		const parameter = {
			deviceId: queryValue.value.id,
			roads: queryValue.value.roads,
			startTime: timeValue.value[0],
			endTime: timeValue.value[1],
			aggregationWindow: radioValue.value === 'null' ? null : radioValue.value
		}
		alarmTrendApi
			.pointDataTrend(parameter)
			.then((res) => {
				if (res) {
					// 温度
					if (
						res.sensorEchartDataResult.temperature &&
						res.sensorEchartDataResult.temperature.x &&
						res.sensorEchartDataResult.temperature.x.length
					) {
						getEcharts1({
							up: res.temperatureUp,
							down: res.temperatureDown,
							data: res.sensorEchartDataResult.temperature
						})
					}

					// 湿度
					if (
						res.sensorEchartDataResult.humidity &&
						res.sensorEchartDataResult.humidity.x &&
						res.sensorEchartDataResult.humidity.x.length
					) {
						getEcharts2({
							up: res.humidityUp,
							down: res.humidityDown,
							data: res.sensorEchartDataResult.humidity
						})
					}

					// co2
					if (
						res.sensorEchartDataResult.co2 &&
						res.sensorEchartDataResult.co2.x &&
						res.sensorEchartDataResult.co2.x.length
					) {
						getEcharts3({
							up: res.co2Up,
							down: res.co2Down,
							data: res.sensorEchartDataResult.co2
						})
					}
				}
			})
			.finally(() => {})
	}

	// 温度
	const getEcharts1 = (val) => {
		let EchartsA = echarts.init(document.getElementById('temperature'))
		const option = {
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'cross',
					crossStyle: {
						color: '#999'
					},
					label: {
						show: false
					}
				},
				formatter: function (params) {
					let date = params[0].axisValueLabel
					let value = params[0].value
					return `${date}<br/>温度 ：${value} °C`
				}
			},
			grid: {
				top: '15%',
				left: '5%',
				right: '7%',
				bottom: '25%'
			},
			xAxis: {
				type: 'category',
				data: val.data.x,
				axisLine: {
					show: true,
					lineStyle: {
						color: '#7e848e'
					}
				},
				axisLabel: {
					color: '#A1A7B3',
					interval: 0,
					rotate: '10'
				},
				axisTick: {
					show: false
				},
				splitLine: {
					show: true
				},
				name: '日期',
				nameTextStyle: {
					color: '#484848',
					fontSize: 14,
					fontWeight: 'bold'
				}
			},
			yAxis: {
				type: 'value',
				scale: true,
				minInterval: 1,
				axisLabel: {
					formatter: '{value} °C'
				},
				splitLine: {
					show: true
				},
				name: '温度',
				nameTextStyle: {
					color: '#484848',
					fontSize: 14,
					fontWeight: 'bold',
					align: 'left',
					padding: [0, 0, 0, -50]
				}
			},
			dataZoom: [
				{
					show: true,
					height: 10,
					xAxisIndex: [0],
					left: '10%',
					right: '10%',
					bottom: '6%',
					start: 70,
					end: 100,
					handleIcon:
						'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
					handleSize: '110%',
					handleStyle: {
						color: '#d3dee5'
					},
					textStyle: {
						color: '#000'
					},
					borderColor: '#90979c'
				},
				{
					type: 'inside',
					show: true,
					height: 15,
					start: 1,
					end: 35
				}
			],
			series: [
				{
					name: '温度',
					data: val.data.y,
					type: 'line',
					symbol: 'circle',
					lineStyle: {
						color: '#4362f0',
						cap: 'round'
					},
					itemStyle: {
						normal: {
							color: 'transparent',
							borderColor: '#4362f0',
							borderWidth: 3
						}
					},
					areaStyle: {
						color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
							{
								offset: 0,
								color: '#4362f0'
							},
							{
								offset: 1,
								color: '#fff'
							}
						])
					},
					symbolSize: 6,
					label: {
						show: false
					},
					markLine: {
						data: [
							{
								name: '温度上限',
								yAxis: val.up,
								lineStyle: {
									color: '#f3956e',
									width: 2,
									type: 'solid',
									shadowColor: 'rgba(243, 149, 110, 1)',
									shadowBlur: 5
								},
								label: {
									formatter: '温度上限: {c}°C',
									color: '#f3956e'
								}
							},
							{
								name: '温度下限',
								yAxis: val.down,
								lineStyle: {
									color: '#41b982',
									width: 2,
									type: 'solid',
									shadowColor: 'rgba(4, 188, 111, 1)',
									shadowBlur: 5
								},
								label: {
									formatter: '温度下限: {c}°C',
									color: '#41b982'
								}
							}
						]
					}
				}
			]
		}

		// 绘制图表
		EchartsA.setOption(option)
		// 自适应大小
		EchartsA.resize()
		window.addEventListener('resize', () => {
			EchartsA.resize()
		})
	}
	// 湿度
	const getEcharts2 = (val) => {
		let EchartsB = echarts.init(document.getElementById('humidity'))
		const option = {
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'cross',
					crossStyle: {
						color: '#999'
					},
					label: {
						show: false
					}
				},
				formatter: function (params) {
					let date = params[0].axisValueLabel
					let value = params[0].value
					return `${date}<br/>湿度 ：${value} %`
				}
			},
			grid: {
				top: '15%',
				left: '5%',
				right: '7%',
				bottom: '25%'
			},
			xAxis: {
				type: 'category',
				data: val.data.x,
				axisLine: {
					show: true,
					lineStyle: {
						color: '#7e848e'
					}
				},
				axisTick: {
					show: false
				},
				splitLine: {
					show: true
				},
				axisLabel: {
					color: '#A1A7B3',
					interval: 0,
					rotate: '10'
				},
				name: '日期',
				nameTextStyle: {
					color: '#484848',
					fontSize: 14,
					fontWeight: 'bold'
				}
			},
			yAxis: {
				type: 'value',
				scale: true,
				minInterval: 1,
				axisLabel: {
					formatter: '{value} %'
				},
				splitLine: {
					show: true
				},
				name: '湿度',
				nameLocation: 'end',
				nameGap: 15,
				nameTextStyle: {
					color: '#484848',
					fontSize: 14,
					fontWeight: 'bold',
					align: 'left',
					padding: [0, 0, 0, -50]
				}
			},
			dataZoom: [
				{
					show: true,
					height: 10,
					xAxisIndex: [0],
					left: '10%',
					right: '10%',
					bottom: '6%',
					start: 70,
					end: 100,
					handleIcon:
						'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
					handleSize: '110%',
					handleStyle: {
						color: '#d3dee5'
					},
					textStyle: {
						color: '#000'
					},
					borderColor: '#90979c'
				},
				{
					type: 'inside',
					show: true,
					height: 15,
					start: 1,
					end: 35
				}
			],
			series: [
				{
					name: '湿度',
					data: val.data.y,
					type: 'line',
					symbol: 'circle',
					lineStyle: {
						color: '#11def7',
						cap: 'round'
					},
					itemStyle: {
						normal: {
							color: 'transparent',
							borderColor: '#11def7',
							borderWidth: 3
						}
					},
					areaStyle: {
						color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
							{
								offset: 0,
								color: '#11def7'
							},
							{
								offset: 1,
								color: '#fff'
							}
						])
					},
					symbolSize: 6,
					label: {
						show: false
					},
					markLine: {
						data: [
							{
								name: '湿度上限',
								yAxis: val.up,
								lineStyle: {
									color: '#f3956e',
									width: 2,
									type: 'solid',
									shadowColor: 'rgba(243, 149, 110, 1)',
									shadowBlur: 5
								},
								label: {
									formatter: '湿度上限: {c}%',
									color: '#f3956e'
								}
							},
							{
								name: '湿度下限',
								yAxis: val.down,
								lineStyle: {
									color: '#41b982',
									width: 2,
									type: 'solid',
									shadowColor: 'rgba(4, 188, 111, 1)',
									shadowBlur: 5
								},
								label: {
									formatter: '湿度下限: {c}%',
									color: '#41b982'
								}
							}
						]
					}
				}
			]
		}
		// 绘制图表
		EchartsB.setOption(option)
		// 自适应大小
		EchartsB.resize()
		window.addEventListener('resize', () => {
			EchartsB.resize()
		})
	}
	// CO2
	const getEcharts3 = (val) => {
		let EchartsC = echarts.init(document.getElementById('CO2'))
		const option = {
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'cross',
					crossStyle: {
						color: '#999'
					},
					label: {
						show: false
					}
				},
				formatter: function (params) {
					let date = params[0].axisValueLabel
					let value = params[0].value
					return `${date}<br/>二氧化碳 ：${value} ppm`
				}
			},
			grid: {
				top: '15%',
				left: '5%',
				right: '7%',
				bottom: '25%'
			},
			xAxis: {
				type: 'category',
				data: val.data.x,
				axisLine: {
					show: true,
					lineStyle: {
						color: '#7e848e'
					}
				},
				axisLabel: {
					color: '#A1A7B3',
					interval: 0,
					rotate: '10'
				},
				axisTick: {
					show: false
				},
				splitLine: {
					show: true
				},
				name: '日期',
				nameTextStyle: {
					color: '#484848',
					fontSize: 14,
					fontWeight: 'bold'
				}
			},
			yAxis: {
				type: 'value',
				scale: true,
				minInterval: 1,
				axisLabel: {
					formatter: '{value} ppm'
				},
				splitLine: {
					show: true
				},
				name: '二氧化碳',
				nameLocation: 'end',
				nameGap: 15,
				nameTextStyle: {
					color: '#484848',
					fontSize: 14,
					fontWeight: 'bold',
					align: 'left',
					padding: [0, 0, 0, -50]
				}
			},
			dataZoom: [
				{
					show: true,
					height: 10,
					xAxisIndex: [0],
					left: '10%',
					right: '10%',
					bottom: '6%',
					start: 70,
					end: 100,
					handleIcon:
						'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
					handleSize: '110%',
					handleStyle: {
						color: '#d3dee5'
					},
					textStyle: {
						color: '#000'
					},
					borderColor: '#90979c'
				},
				{
					type: 'inside',
					show: true,
					height: 15,
					start: 1,
					end: 35
				}
			],
			series: [
				{
					name: '二氧化碳',
					data: val.data.y,
					type: 'line',
					symbol: 'circle',
					lineStyle: {
						color: '#7f3fd5',
						cap: 'round'
					},
					itemStyle: {
						normal: {
							color: 'transparent',
							borderColor: '#7f3fd5',
							borderWidth: 3
						}
					},
					areaStyle: {
						color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
							{
								offset: 0,
								color: '#7f3fd5'
							},
							{
								offset: 1,
								color: '#fff'
							}
						])
					},
					symbolSize: 6,
					label: {
						show: false
					},
					markLine: {
						data: [
							{
								name: '二氧化碳上限',
								yAxis: val.up,
								lineStyle: {
									color: '#f3956e',
									width: 2,
									type: 'solid',
									shadowColor: 'rgba(243, 149, 110, 1)',
									shadowBlur: 5
								},
								label: {
									formatter: '二氧化碳上限: {c}ppm',
									color: '#f3956e'
								}
							},
							{
								name: '二氧化碳下限',
								yAxis: val.down,
								lineStyle: {
									color: '#41b982',
									width: 2,
									type: 'solid',
									shadowColor: 'rgba(4, 188, 111, 1)',
									shadowBlur: 5
								},
								label: {
									formatter: '二氧化碳下限: {c}ppm',
									color: '#41b982'
								}
							}
						]
					}
				}
			]
		}
		// 绘制图表
		EchartsC.setOption(option)
		// 自适应大小
		EchartsC.resize()
		window.addEventListener('resize', () => {
			EchartsC.resize()
		})
	}

	// 返回上一页
	const goBack = () => {
		router.go(-1)
	}
</script>

<style lang="less" scoped>
	.table_item {
		padding: 15px 20px;
		background-color: #ffffff;

		.table_head {
			width: 100%;
			height: 100px;
			padding: 0 10px;
			background-image: url('/src/assets/images/monitor/bg.png');
			background-size: cover;
			background-position: center;
			border-radius: 10px;
			display: flex;
			align-items: center;
			.head_name,
			.head_time {
				flex: 2;
				text-align: center;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
			.head_name {
				font-size: 20px;
				font-weight: bold;
				color: #4362f0;
			}
			.head_row {
				flex: 3;
				display: flex;
				align-items: center;
				justify-content: center;

				.label {
					img {
						width: 50px;
						height: 50px;
					}
				}

				.value {
					padding: 0 20px;
					display: flex;
					align-items: center;

					.num {
						font-weight: bold;
						font-size: 26px;
						padding: 0 20px;
						width: 180px;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}
				}
			}
		}

		.table_search {
			width: 100%;
			margin: 20px 0;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.search_left {
				:deep(.ant-radio-button-wrapper) {
					margin: 0 10px;
				}
			}
		}

		// 图表
		.chart {
			width: 100%;
			height: 950px;
			.echart {
				width: 100%;
				height: 30%;
				margin-bottom: 50px;
			}
		}
	}
</style>
