WholeProcessPlatform/frontend/src/modules/waterQuality/index.vue

1013 lines
29 KiB
Vue
Raw Normal View History

2026-05-12 14:34:58 +08:00
<!-- SidePanelItem.vue -->
<template>
<SidePanelItem
title="沿程水质变化"
:iconmap="iconmap"
:select="select"
:datetimePicker="datetimePicker"
@update-values="handlePanelChange1"
>
<div class="chart-wrapper">
<a-spin :spinning="loading">
<!-- 始终渲染图表容器确保有固定宽高 -->
<div ref="chartRef" class="chart-container"></div>
<!-- 无数据时显示Empty但不影响容器尺寸 -->
<div v-if="!loading && !hasData" class="empty-overlay">
<a-empty description="暂无数据" />
2026-06-01 08:37:38 +08:00
</div>
</a-spin>
</div>
</SidePanelItem>
2026-05-12 14:34:58 +08:00
</template>
<script lang="ts" setup>
2026-07-31 11:13:49 +08:00
import { ref, onMounted, onBeforeUnmount, nextTick, watch, inject, computed } from 'vue';
2026-05-12 14:34:58 +08:00
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';
import SidePanelItem from '@/components/SidePanelItem/index.vue';
2026-07-15 18:24:05 +08:00
import { qgcGetKendoListCust } from '@/api/sz';
import { getMonitorDataWaterQualityDetail } from '@/api/mapModal/index';
import { useJidiSelectEventStore } from '@/store/modules/jidiSelectEvent';
import { useModelStore } from '@/store/modules/model';
import {
WATER_QUALITY_INDICATORS,
type WaterQualityIndicator
} from '@/modules/waterQuality/padig';
2026-06-02 14:52:44 +08:00
const indicators = WATER_QUALITY_INDICATORS;
2026-05-12 14:34:58 +08:00
// 定义组件名(便于调试和递归)
defineOptions({
name: 'waterQuality'
2026-05-12 14:34:58 +08:00
});
2026-06-01 08:37:38 +08:00
const modelStore = useModelStore();
const JidiSelectEventStore = useJidiSelectEventStore();
2026-05-15 18:08:29 +08:00
const iconmap = ref({
show: true,
value: '',
icon: 'iconfont icon-time'
2026-05-15 18:08:29 +08:00
});
2026-05-12 14:34:58 +08:00
// ==================== 响应式数据 ====================
const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;
2026-06-01 08:37:38 +08:00
// Loading 状态和数据状态
const loading = ref(false);
const hasData = ref(true); // 初始化为 true因为 initChart 会使用 mockData 渲染
2026-05-12 14:34:58 +08:00
// 获取当天早上8:00的时间
const now = new Date();
const todayAtEightAM = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
8,
0,
0
);
const defaultValue = `${todayAtEightAM.getFullYear()}-${String(
todayAtEightAM.getMonth() + 1
).padStart(2, '0')}-${String(todayAtEightAM.getDate()).padStart(
2,
'0'
)} ${String(todayAtEightAM.getHours()).padStart(2, '0')}:00`;
2026-06-02 14:52:44 +08:00
// 👆 注意这里分钟固定为 :00与 timeFormat: 'HH' 配置保持一致
2026-05-12 14:34:58 +08:00
const datetimePicker = ref({
show: true,
value: defaultValue,
format: 'YYYY-MM-DD HH:mm', // 显示格式:包含分钟
picker: 'date',
timeFormat: 'HH', // 新增:选择格式:只选择小时
options: []
2026-05-12 14:34:58 +08:00
});
2026-06-01 08:37:38 +08:00
const select = ref({
show: true,
value: '',
options: [],
picker: undefined,
format: undefined
2026-06-01 08:37:38 +08:00
});
2026-05-12 14:34:58 +08:00
// ==================== 可见系列队列最多2个====================
const visibleSeriesQueue = ref<string[]>([]);
2026-06-02 14:52:44 +08:00
// ==================== 动态指标配置 ====================
const indicatorConfig = ref<
Array<{
key: string;
name: string;
unit: string;
color: string;
sort: number;
}>
>([]);
2026-06-02 14:52:44 +08:00
// ==================== 指标颜色 ====================
// 参考 MonitorInfo.vue 的固定色板,按指标顺序循环取色,颜色稳定可预期
const COLOR_PALETTE = [
'#56C2E3',
'#7399C6',
'#4B79AB',
'#78C300',
'#00A050',
'#F7A737'
];
2026-06-02 14:52:44 +08:00
const generateRandomColor = (index: number): string => {
return COLOR_PALETTE[index % COLOR_PALETTE.length];
2026-06-02 14:52:44 +08:00
};
// 指标颜色映射(来自水质参数接口 showControl.lineColorkey 为指标小写编码)
const indicatorColorMap = ref<Record<string, string>>({});
2026-06-02 14:52:44 +08:00
// ==================== 动态指标筛选和配置生成 ====================
const generateIndicatorConfig = (data: StationData[]) => {
if (!data || data.length === 0) {
indicatorConfig.value = [];
return;
}
// 定义需要排除的元数据字段
const excludeKeys = new Set([
'stcd',
'stcd2',
'stnm',
'rstcd',
'sttp',
'tm',
'SORT',
'limits',
'minTm',
'wwqtg',
'wqgrd',
'wqgrdName',
'min',
'max',
'_tls',
'id',
'recordUser',
'recordTime',
'modifyTime',
'displayRecordUser',
'departmentId',
'displayDepartment'
]);
// 收集所有有效指标的 key
const validKeysSet = new Set<string>();
data.forEach(station => {
Object.keys(station).forEach(key => {
// 跳过排除字段
if (excludeKeys.has(key)) return;
const value = station[key as keyof typeof station];
// 检查是否为有效数值(不为 null 且不是 NaN
if (
value !== null &&
value !== undefined &&
typeof value === 'number' &&
!isNaN(value)
) {
// 在 indicators 中查找匹配的项(小写比较)
const matchedIndicator = indicators.find(
ind => ind.key.toLowerCase() === key.toLowerCase()
);
if (matchedIndicator) {
validKeysSet.add(matchedIndicator.key);
}
}
2026-06-02 14:52:44 +08:00
});
});
// 如果没有有效指标,返回空数组
if (validKeysSet.size === 0) {
indicatorConfig.value = [];
return;
}
// 根据 indicators 中的 sort 排序,并生成配置
const validIndicators = indicators
.filter(ind => validKeysSet.has(ind.key))
.sort((a, b) => a.sort - b.sort);
// 生成最终配置:颜色优先取接口配置,缺失时回退到色板
indicatorConfig.value = validIndicators.map((ind, index) => ({
key: ind.key,
name: ind.name,
unit: ind.description || '',
color: indicatorColorMap.value[ind.key] || generateRandomColor(index),
sort: ind.sort
}));
2026-05-12 14:34:58 +08:00
};
2026-06-02 14:52:44 +08:00
// 定义数据类型接口
interface StationData {
stnm: string;
stcd: string;
type: string;
tm: string;
SORT: number;
limits: Record<string, { min?: number; max?: number }>;
// 水质指标字段为动态生成,通过索引签名访问
[key: string]: any;
2026-06-02 14:52:44 +08:00
}
2026-05-12 14:34:58 +08:00
2026-06-02 14:52:44 +08:00
const mockData = ref<StationData[]>([]);
2026-05-12 14:34:58 +08:00
// ==================== 图表配置生成 ====================
const getChartOption = (): EChartsOption => {
const data = mockData.value;
if (!data || data.length === 0 || indicatorConfig.value.length === 0) {
return {};
}
// X轴数据站点名称
const xData = data.map((item, index) => {
// 去除站点名称中的"出库水质监测站"或"坝上水质监测站"后缀
let stnm = item.stnm || '-';
if (stnm.includes('出库水质监测站')) {
stnm = stnm.replace('出库水质监测站', '');
} else if (stnm.includes('坝上水质监测站')) {
stnm = stnm.replace('坝上水质监测站', '');
2026-05-12 14:34:58 +08:00
}
return {
value: stnm,
textStyle: {
padding: index % 2 !== 0 ? [16, 0, 0, 0] : 0
}
};
});
2026-06-01 08:37:38 +08:00
// 电站标记线数据
const markLineData: any[] = [];
data.forEach((item, index) => {
if (item.type === '1') {
markLineData.push({ xAxis: index });
}
});
// 图例数据
const legendData = indicatorConfig.value.map(item => item.name);
// 根据可见队列构建选中状态
const selectedState: Record<string, boolean> = {};
indicatorConfig.value.forEach(config => {
selectedState[config.name] = visibleSeriesQueue.value.includes(config.name);
});
// Series 数据
const seriesData = indicatorConfig.value.map((config, index) => {
const _key = config.key === 'dox' ? 'do' : config.key;
return {
name: config.name,
type: 'line' as const,
yAxisIndex: index,
smooth: true,
connectNulls: true,
symbol: 'circle' as const,
symbolSize: 6,
itemStyle: {
color: config.color
},
data: data.map(item => {
const value = item[config.key as keyof typeof item];
return typeof value === 'number' && !isNaN(value) ? value : null;
}),
markLine:
index === 0
? {
symbol: ['none', 'none'],
label: { show: false },
lineStyle: {
color: '#ccc',
type: 'dashed' as const
},
data: markLineData
2026-06-01 08:37:38 +08:00
}
: undefined
};
});
2026-06-01 08:37:38 +08:00
// 计算每个Y轴的数据范围用于自适应使用整数
const calculateYAxisRange = (configIndex: number) => {
if (!selectedState[indicatorConfig.value[configIndex].name]) {
return null;
}
2026-05-12 14:34:58 +08:00
const values = data
.map(
item =>
item[indicatorConfig.value[configIndex].key as keyof typeof item]
)
.filter((val): val is number => typeof val === 'number' && !isNaN(val));
2026-05-12 14:34:58 +08:00
if (values.length === 0) {
return { min: 0, max: 10 };
}
2026-06-01 08:37:38 +08:00
const min = Math.min(...values);
const max = Math.max(...values);
2026-06-01 08:37:38 +08:00
// Y轴使用整数向下取整-1向上取整+1
return {
min: Math.floor(min) - 1,
max: Math.ceil(max) + 1
};
};
// Y轴配置左1右1原则最多显示2个Y轴
const yAxisData = indicatorConfig.value.map((config, index) => {
const isShow = selectedState[config.name];
// 如果不显示,直接返回隐藏配置
if (!isShow) {
return {
type: 'value' as const,
name: config.name,
show: false
};
}
2026-06-01 08:37:38 +08:00
// 计算当前是第几个显示的Y轴
let displayIndex = 0;
for (let i = 0; i < index; i++) {
if (selectedState[indicatorConfig.value[i].name]) {
displayIndex++;
}
}
2026-06-01 08:37:38 +08:00
// 最多只显示2个Y轴索引0和1
if (displayIndex >= 2) {
return {
type: 'value' as const,
name: config.name,
show: false
};
}
2026-06-01 08:37:38 +08:00
const isLeft = displayIndex === 0;
const offset = displayIndex === 1 ? 0 : 0;
const range = calculateYAxisRange(index);
return {
type: 'value' as const,
name: config.name,
position: isLeft ? ('left' as const) : ('right' as const),
offset,
min: range ? range.min : undefined,
max: range ? range.max : undefined,
axisLine: {
show: true,
lineStyle: {
color: config.color
2026-06-02 14:52:44 +08:00
}
},
axisLabel: {
color: config.color,
formatter: (value: number) => {
// Y轴刻度使用整数显示
return Math.round(value).toString();
2026-06-02 14:52:44 +08:00
}
},
splitLine: {
show: true,
lineStyle: {
color: '#e0e0e0',
type: 'solid' as const
2026-06-02 14:52:44 +08:00
}
},
show: true
};
});
const option: EChartsOption = {
tooltip: {
trigger: 'axis',
confine: true,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
borderColor: 'transparent',
textStyle: {
color: '#ffffff'
},
formatter: (params: any) => {
if (!params || params.length === 0) return '';
// 在最上面显示用户选择的时间
let result = `<div style="font-weight: bold; margin-bottom: 8px;">${datetimePicker.value.value}</div>`;
const tm = data.find(item => item.stnm === params[0].name)?.tm;
result += `${params[0].name}<br/>`;
// 判断是否只显示一个系列
const showOnlyOneSeries = visibleSeriesQueue.value.length === 1;
params.forEach((param: any) => {
const config = indicatorConfig.value.find(
c => c.name === param.seriesName
);
const unit = config?.unit || '';
if (param.value !== null && param.value !== undefined) {
// 折线数据保留一位小数
const numValue = Number(param.value);
let displayValue = param.value;
if (!isNaN(numValue)) {
displayValue = numValue.toFixed(1);
2026-06-01 08:37:38 +08:00
}
result += `${param.marker}${param.seriesName}${displayValue}${unit}`;
// 如果只显示一个系列,且该指标有限值,则显示限值
if (showOnlyOneSeries && config) {
// 从 data 中获取当前站点的限值
const stationData = data.find(item => item.stnm === param.name);
if (stationData && stationData.limits) {
const limitKey = config.key; // 如 'ph', 'dox'
const limits = stationData.limits[limitKey];
if (limits) {
// 构建限值显示字符串
let limitText = '';
const unit = config.unit || ''; // 获取单位
if (limits.min !== undefined && limits.max !== undefined) {
// 既有上限又有下限
limitText = `&nbsp;&nbsp;&nbsp;&nbsp;限值: ${limits.min}-${
limits.max
}${unit ? unit : ''}`;
} else if (limits.min !== undefined) {
// 只有下限
limitText = `&nbsp;&nbsp;&nbsp;&nbsp;限值: ${limits.min}${
unit ? unit : ''
}`;
} else if (limits.max !== undefined) {
// 只有上限
limitText = `&nbsp;&nbsp;&nbsp;&nbsp;限值: ${limits.max}${
unit ? unit : ''
}`;
}
result += '<br/>' + limitText;
2026-05-12 14:34:58 +08:00
}
}
2026-05-12 14:34:58 +08:00
}
result += '<br/>';
}
});
return result;
}
},
legend: {
type: 'scroll',
top: 0,
right: 10, // 右侧留白,避免箭头按钮被遮挡
data: legendData,
selected: selectedState,
inactiveColor: '#ccc',
itemWidth: 16,
itemHeight: 12,
itemGap: 8,
pageButtonItemGap: 5, // 分页按钮与图例项的间距
pageIconColor: '#2f4554', // 分页按钮颜色
pageIconInactiveColor: '#aaa', // 分页按钮禁用时的颜色
pageIconSize: 12, // 分页按钮大小
pageFormatter: '{current}/{total}', // 分页格式:当前页/总页数
textStyle: {
fontSize: 14
}
},
// 添加 dataZoom 组件实现X轴滚轮缩放仅内置类型无滑动条
dataZoom: [
{
type: 'inside', // 内置型数据区域缩放组件(支持鼠标滚轮)
xAxisIndex: 0, // 控制第一个X轴
start: 0, // 默认显示全部数据
end: 100,
zoomOnMouseWheel: true, // 开启鼠标滚轮缩放
moveOnMouseMove: true, // 开启鼠标移动平移
filterMode: 'filter' // 过滤模式
}
],
grid: {
top: 60,
bottom: 50,
left: '20px',
right: '20px',
containLabel: true
},
xAxis: {
type: 'category',
data: xData,
axisLabel: {
interval: 0,
color: '#333',
fontSize: 12
},
axisLine: {
lineStyle: {
color: '#8f8f8f'
}
},
splitLine: {
show: true,
lineStyle: {
color: '#e0e0e0',
type: 'solid' as const
}
}
},
yAxis: yAxisData,
series: seriesData
};
return option;
2026-05-12 14:34:58 +08:00
};
// ==================== 图例选择事件处理最多2个系列====================
const handleLegendSelectChanged = (params: any) => {
if (!chartInstance) return;
const { selected, name } = params;
const clickedName = name;
const isNowSelected = selected[clickedName];
if (isNowSelected) {
// 用户想要显示这个系列
if (visibleSeriesQueue.value.length >= 2) {
// 已满2个移除最早的队列头部
visibleSeriesQueue.value.shift();
}
// 添加到队列尾部
if (!visibleSeriesQueue.value.includes(clickedName)) {
visibleSeriesQueue.value.push(clickedName);
}
} else {
// 用户想要隐藏这个系列
const index = visibleSeriesQueue.value.indexOf(clickedName);
if (index > -1) {
visibleSeriesQueue.value.splice(index, 1);
}
}
// 基于最新队列重新生成完整配置(所有 y 轴都带颜色/formatter/min-max
// 避免从 getOption() 快照激活隐藏 y 轴时丢失样式导致颜色消失、宽度变化)
try {
const option = getChartOption();
chartInstance.setOption(option, true);
} catch (error) {
console.error('图表更新失败:', error);
}
2026-05-12 14:34:58 +08:00
};
2026-06-02 14:52:44 +08:00
// ==================== 数据点点击事件处理 ====================
const handleDataPointClick = (params: any) => {
// dataIndex 为 0 时不能直接取反判断,必须判断 null/undefined
if (!params || params.dataIndex == null) return;
// 获取点击的数据点对应的站点信息
const dataIndex = params.dataIndex;
const stationData = mockData.value[dataIndex];
if (stationData && stationData.stcd) {
modelStore.modalVisible = true;
modelStore.params.sttp = 'WQFB';
modelStore.title = stationData.stnm;
modelStore.params.stcd = stationData.stcd;
modelStore.filter.rangeTm = [
dayjs(datetimePicker.value.value)
.startOf('month')
.format('YYYY-MM-DD HH:mm:ss'),
dayjs(datetimePicker.value.value)
.endOf('month')
.format('YYYY-MM-DD HH:mm:ss')
];
}
2026-05-12 14:34:58 +08:00
};
2026-06-02 14:52:44 +08:00
// ==================== 图表初始化 ====================
2026-06-01 08:37:38 +08:00
//获取图参数
const getecharts = async () => {
if (!select.value.value) {
console.warn('选择器值为空,无法获取图表数据');
loading.value = false;
2026-06-01 08:37:38 +08:00
hasData.value = false;
chartInstance?.clear();
return;
}
// 设置 loading 状态
loading.value = true;
hasData.value = false;
let params = {
filter: {
logic: 'and',
filters: [
{
field: 'baseId',
operator: 'eq',
dataType: 'string',
value: select.value.value
},
{
field: 'tm',
operator: 'gte',
dataType: 'date',
value: getStartTime()
},
{
field: 'tm',
operator: 'lte',
dataType: 'date',
value: getEndTime()
2026-06-01 08:37:38 +08:00
}
]
},
sort: [
{
field: 'sort',
dir: 'asc'
}
]
};
try {
console.log('请求参数:', params);
let res = await qgcGetKendoListCust(params);
console.log('接口返回数据:', res);
// 处理返回的数据 - 兼容多种数据结构
let apiData: any[] = [];
if (res && res.data) {
// 情况1: res.data.data 是数组(当前实际情况)
if (Array.isArray(res.data.data)) {
apiData = res.data.data;
}
// 情况2: res.data.data.data 是数组
else if (res.data.data && Array.isArray(res.data.data.data)) {
apiData = res.data.data.data;
}
// 情况3: res.data 直接是数组
else if (Array.isArray(res.data)) {
apiData = res.data;
}
}
2026-06-01 08:37:38 +08:00
// 过滤出有水质数据的站点sttp === 'WQ'并按sort排序
const filteredData = apiData
.filter((item: any) => item.sttp === 'WQ')
.sort((a: any, b: any) => {
// 如果有sort字段则使用否则按索引排序
return (a.sort || 0) - (b.sort || 0);
});
console.log('过滤后水质数据条数:', filteredData.length);
// 转换为图表所需的数据格式
const chartData = filteredData.map((item: any, index: number) => {
// 去除站点名称中的"出库水质站"后缀
let stnm = item.stnm || '-';
if (stnm.includes('出库水质站')) {
stnm = stnm.replace('出库水质站', '');
}
if (stnm.includes('出库水质_')) {
stnm = stnm.replace('出库水质_', '');
}
// 解析 min 和 max 数组,构建限值对象
const limits: Record<string, { min?: number; max?: number }> = {};
// 处理下限
if (item.min && Array.isArray(item.min)) {
item.min.forEach((limitItem: any) => {
Object.keys(limitItem).forEach(key => {
// key 是大写,如 "PH", "DOX",转为小写以匹配 indicatorConfig
const lowerKey = key.toLowerCase();
limits[lowerKey] = limits[lowerKey] || {};
limits[lowerKey].min = limitItem[key];
});
});
}
// 处理上限
if (item.max && Array.isArray(item.max)) {
item.max.forEach((limitItem: any) => {
Object.keys(limitItem).forEach(key => {
const lowerKey = key.toLowerCase();
limits[lowerKey] = limits[lowerKey] || {};
limits[lowerKey].max = limitItem[key];
});
});
}
2026-06-01 08:37:38 +08:00
// 动态收集指标字段(基于 indicators 配置,避免硬编码 30+ 个字段映射)
const indicatorValues: Record<string, number | null> = {};
indicators.forEach(ind => {
const val = item[ind.key];
indicatorValues[ind.key] = val != null ? Number(val) : null;
});
return {
stnm: stnm,
stcd: item.stcd || '',
type: item.rstcd ? '1' : '0', // 有rstcd表示是电站出库站
tm: item.tm || '',
SORT: index + 1,
...indicatorValues,
limits: limits // 新增:存储该站点的所有限值
};
});
2026-06-02 14:52:44 +08:00
// 更新模拟数据
mockData.value = chartData;
2026-06-01 08:37:38 +08:00
// 判断是否有数据
hasData.value = chartData.length > 0;
console.log('hasData 设置为:', hasData.value);
2026-06-01 08:37:38 +08:00
if (!hasData.value) {
// 无数据时清空图表
console.log('无数据,清空图表');
chartInstance?.clear();
indicatorConfig.value = [];
loading.value = false;
return;
}
2026-06-01 08:37:38 +08:00
// 获取水质参数配置showControl.lineColor用于指标颜色
// 参考 WaterQuality.vue颜色来自接口返回的每个参数配置
try {
const configStcd = modelStore.params.stcd || chartData[0]?.stcd;
if (configStcd) {
const detailRes = await getMonitorDataWaterQualityDetail({
stcd: configStcd,
tbCode: 'WQ_R',
startTime: getStartTime(),
endTime: getEndTime()
});
const detailData = detailRes?.data?.data || detailRes?.data || [];
const map: Record<string, string> = {};
detailData.forEach((param: any) => {
if (!param.ys) return;
try {
const config = JSON.parse(param.showControl || '{}');
if (config.lineColor) {
map[param.ys.toLowerCase()] = config.lineColor;
}
} catch {
// 解析失败忽略该参数
}
});
indicatorColorMap.value = map;
}
} catch (error) {
// 配置获取失败不影响主流程,颜色走色板回退
console.error('获取水质参数配置失败:', error);
}
// 动态生成指标配置
generateIndicatorConfig(chartData);
2026-06-02 14:52:44 +08:00
// 如果没有有效指标,显示空状态
if (indicatorConfig.value.length === 0) {
hasData.value = false;
chartInstance?.clear();
loading.value = false;
return;
}
2026-06-02 14:52:44 +08:00
// 重新渲染图表 - 使用 nextTick 确保 DOM 更新完成
await nextTick();
2026-06-02 14:52:44 +08:00
if (chartInstance) {
// 如果图表已存在,更新配置
requestAnimationFrame(() => {
const option = getChartOption();
chartInstance?.setOption(option, true);
chartInstance?.resize();
console.log(
'图表数据已更新,共',
chartData.length,
'个站点,',
indicatorConfig.value.length,
'个指标'
);
});
} else {
// 如果图表不存在,初始化图表
await initChart();
2026-06-01 08:37:38 +08:00
}
} catch (error) {
console.error('获取图表数据失败:', error);
hasData.value = false;
indicatorConfig.value = [];
} finally {
// 关闭 loading 状态 - 使用 nextTick 确保在下一个 tick 关闭
await nextTick();
console.log('关闭 loading 状态');
loading.value = false;
}
};
2026-06-01 08:37:38 +08:00
// 获取起始时间(当前选择日期前一个月)
const getStartTime = () => {
const currentDate = new Date(datetimePicker.value.value);
const oneMonthAgo = new Date(currentDate);
oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
const year = oneMonthAgo.getFullYear();
const month = String(oneMonthAgo.getMonth() + 1).padStart(2, '0');
const day = String(oneMonthAgo.getDate()).padStart(2, '0');
const hours = String(oneMonthAgo.getHours()).padStart(2, '0');
const minutes = String(oneMonthAgo.getMinutes()).padStart(2, '0');
const seconds = String(oneMonthAgo.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
2026-06-01 08:37:38 +08:00
};
// 获取结束时间(当前选择日期的当天 23:59:59
const getEndTime = () => {
const currentDate = new Date(datetimePicker.value.value);
2026-06-01 08:37:38 +08:00
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const day = String(currentDate.getDate()).padStart(2, '0');
2026-06-01 08:37:38 +08:00
return `${year}-${month}-${day} 23:59:59`;
2026-06-01 08:37:38 +08:00
};
2026-06-02 14:52:44 +08:00
// ==================== 图表初始化 ====================
const initChart = async () => {
if (!chartRef.value) {
console.warn('图表容器未就绪');
return;
}
// 检查容器尺寸
const rect = chartRef.value.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) {
console.warn('图表容器尺寸为0等待渲染...');
// 使用 requestAnimationFrame 确保在浏览器下一重绘帧再初始化
return new Promise(resolve => {
requestAnimationFrame(() => {
setTimeout(() => {
initChart().then(resolve);
}, 50);
});
});
}
2026-06-02 14:52:44 +08:00
// 如果图表实例已存在,先销毁
if (chartInstance) {
chartInstance.dispose();
chartInstance = null;
}
2026-06-02 14:52:44 +08:00
// 如果没有有效指标配置,不初始化图表
if (indicatorConfig.value.length === 0) {
console.warn('没有有效的指标配置,跳过图表初始化');
hasData.value = false;
return;
}
2026-06-02 14:52:44 +08:00
// 初始化可见队列默认只显示第一个系列按sort排序后的第一个
visibleSeriesQueue.value = [indicatorConfig.value[0].name];
2026-06-02 14:52:44 +08:00
// 初始化 ECharts 实例
chartInstance = echarts.init(chartRef.value);
2026-06-02 14:52:44 +08:00
// 设置初始配置
const option = getChartOption();
chartInstance.setOption(option);
2026-06-02 14:52:44 +08:00
// 监听图例选择变化事件
chartInstance.on('legendselectchanged', handleLegendSelectChanged);
2026-06-02 14:52:44 +08:00
// 监听数据点点击事件
chartInstance.on('click', handleDataPointClick);
2026-06-02 14:52:44 +08:00
// 强制 resize 确保正确渲染
setTimeout(() => {
chartInstance?.resize();
}, 50);
2026-06-02 14:52:44 +08:00
console.log('图表初始化成功');
2026-06-02 14:52:44 +08:00
};
// ==================== 窗口大小变化处理 ====================
const handleResize = () => {
chartInstance?.resize();
2026-06-02 14:52:44 +08:00
};
// ==================== 生命周期钩子 ====================
onMounted(async () => {
await nextTick();
// 不再立即初始化图表,等待数据加载完成
window.addEventListener('resize', handleResize);
2026-06-02 14:52:44 +08:00
});
onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize);
if (chartInstance) {
chartInstance.off('legendselectchanged', handleLegendSelectChanged);
chartInstance.off('click', handleDataPointClick);
chartInstance.dispose();
chartInstance = null;
}
2026-06-02 14:52:44 +08:00
});
2026-06-01 08:37:38 +08:00
//监听子组件的数据变化
const handlePanelChange1 = async data => {
console.log('当前所有控件状态:', data);
// 当选择器或日期变化时,重新加载图表数据
if (data.datetime || data.select) {
select.value.value = data.select;
datetimePicker.value.value = data.datetime;
getecharts();
}
};
2026-06-02 14:52:44 +08:00
// 监听 datetimePicker 变化,更新 iconmap 中的时间显示
watch(
() => datetimePicker.value.value,
newVal => {
if (newVal) {
iconmap.value.value = `注:最新数据时间为${newVal}`;
}
},
{ immediate: true }
2026-06-02 14:52:44 +08:00
);
2026-07-31 11:13:49 +08:00
// 监听电站变化(优先使用父组件 provide 的电站上下文,兜底 jidiStore
const injectedStation = inject<any>('dianZhanStation', null);
const stationSource = computed(() => injectedStation?.value || JidiSelectEventStore.selectedItem);
2026-06-01 08:37:38 +08:00
const wbsCode = ref('');
watch(
2026-07-31 11:13:49 +08:00
() => stationSource.value,
newVal => {
wbsCode.value = newVal.wbsCode;
2026-07-15 18:24:05 +08:00
select.value.value = newVal.wbsCode;
getecharts();
},
{ deep: true, immediate: true }
);
// 监听 JidiSelectEventStore.jidiData 变化,同步下拉框选项(过滤掉"当前全部"项)
watch(
() => JidiSelectEventStore.jidiData,
newVal => {
const filtered = newVal.filter(item => item.wbsCode !== 'all');
select.value.options = filtered.map(item => ({
value: item.wbsCode,
label: item.wbsName
}));
},
{ deep: true, immediate: true }
2026-06-01 08:37:38 +08:00
);
// 图例切换时 handleLegendSelectChanged 已基于最新队列重建完整配置,此处无需再监听
2026-05-12 14:34:58 +08:00
</script>
<style lang="scss" scoped>
2026-06-01 08:37:38 +08:00
.chart-wrapper {
width: 100%;
height: 280px;
min-height: 231px;
position: relative;
/* 为empty-overlay提供定位上下文 */
.chart-container {
width: 100% !important;
height: 100% !important;
min-width: 100%;
min-height: 280px;
}
.empty-overlay {
position: absolute;
top: 0;
left: 0;
2026-05-12 14:34:58 +08:00
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.9);
z-index: 10;
}
2026-05-12 14:34:58 +08:00
}
</style>