import * as echarts from 'echarts'; import React, { useEffect, useRef, useState, ForwardedRef, forwardRef, useImperativeHandle } from 'react'; import _ from 'lodash'; import { Spin } from "antd"; import { useLocale } from "../../locale/useLocale"; import HydrocarbonService from "../../tmpl/hcservice-v3"; import { DataConfigProps } from "../data"; import { handleTimeDataSort, formatNumberUnit } from "../line-chart"; const defOption = { title: { text: '暂无数据', left: 'center', top: 'middle', show: false, // 无数据时显示 }, tooltip: { trigger: "axis" }, grid: { top: 30, left: 30, right: 20, bottom: 30 }, xAxis: { type: 'category', boundaryGap: true, axisTick: { show: true }, axisLabel: {} }, yAxis: { type: 'value', axisLabel: {} }, legend: { show: false }, barMaxWidth: 20, dataZoom: [], series: [ { data: [["1990", 225], ["1991", 359], ["1992", 57], ["1993", 214], ["1994", 134], ["1995", 250], ["1996", 156]], type: 'line', }, { data: [["1990", 325], ["1991", 259], ["1992", 157], ["1993", 314], ["1994", 234], ["1995", 150], ["1996", 256]], type: 'bar', } ] }; const legends = { top: { top: 0 }, bottom: { bottom: 0 }, left: { left: 5, top: "center" }, right: { right: 5, top: "center" }, leftTop: { left: 5 }, rightTop: { right: 5 }, leftBottom: { left: 5, bottom: 0 }, rightBottom: { right: 5, bottom: 0 }, }; // 处理数据格式 nullSetZero(是否空值置0) const handleData = (data: { config: { [key: string]: string }, value: { [key: string]: any }[] }[], nullSetZero?: boolean) => { if (!data?.length) { return []; } const temData = data.map((r) => { const { config, value } = r; const isD = Object.keys(config).some(r => r.includes("d")); const vNames = Object.keys(config).filter((r) => r.startsWith("v") && !r.includes("-")).sort((a, b) => parseInt(a.substring(1)) - parseInt(b.substring(1))); // 过滤只有t1、t2等数据 const tNames = Object.keys(config).filter((r) => r.startsWith("t") && !r.includes("-")).sort((a, b) => parseInt(a.substring(1)) - parseInt(b.substring(1))); return isD ? { name: config.d1, data: [ ...vNames.map((r) => ({ name: config[r], data: handleTimeDataSort(value, r, nullSetZero), })), ...tNames.map((r) => ({ vLength: vNames.length, isMarkLine: true, name: config[r], data: handleTimeDataSort(value, r, nullSetZero) })) ] } : { data: value.map((r, index) => ({ name: `数值${index || ""}`, data: vNames.map(v => [config[v], nullSetZero ? (r[v] || 0) : r[v]]) })) }; }); return temData[0]?.data || []; }; export interface ComponentStyle { tooltip?: { show: boolean }; color?: string[]; grid?: { top: number, left: number, right: number, bottom: number }; xAxis?: { [key: string]: any }; yAxis?: { [key: string]: any }; legend?: { [key: string]: any }; markPoint?: { [key: string]: any }; smooth?: boolean; lineStyle?: { [key: string]: any }; symbol?: { [key: string]: any }; step?: boolean; // 是否为阶梯折线图 isArea?: boolean; // 是否面积图 isGradient?: boolean; // 面积图是否渐变 areaStyle?: { opacity: number }; // 面积图样式 renderer?: "canvas" | "svg"; barMaxWidth?: number; //柱状图最大宽度 dataZoom?: boolean; slider?: boolean; // 区域缩放是否显示滑动条 connectNulls?: boolean; // 是否连接空值 nullSetZero?: boolean; // 空值是否置0 markLineColor?: string[]; // 标记线颜色 groupType?: string; // 图表分组类型(用于图表联动) } export interface ComponentProps { style?: ComponentStyle; base?: { width: number, height: number }; data?: DataConfigProps; isDesignMode?: boolean; // 是否编辑模式 initSearchParams?: { [key: string]: any }; // 全局初始化外部参数,例:传参包含设备id,则在查询时带上设备id } export interface ComponentRef { updateConfig: (newConfig: ComponentProps) => void; destroy: () => void; updateSearchParams: (params: { [key: string]: any }) => void; } const Index = forwardRef((props: ComponentProps, ref: ForwardedRef) => { const { style, data: propsData, isDesignMode } = props; const [config, setConfig] = useState(style || {}); const [renderType, setRenderType] = useState<"canvas" | "svg">(style?.renderer || "svg"); // 渲染模式 const [size, setSize] = useState<{ width: number, height: number }>(); const [dataConfig, setDataConfig] = useState({ ...propsData }); // 数据源配置 const [data, setData] = useState<{ name: string, data: any, isMarkLine?: boolean }[]>([]); const [searchParams, setSearchParams] = useState<{ [key: string]: any }>(); const [initSearchParams, setInitSearchParams] = useState<{ [key: string]: any }>(); const [loading, setLoading] = useState(false); const chartRef = useRef(null); const chart = useRef(null); const pollingIntervalRef = useRef(null); const resizeObserverRef = useRef(null); const dataRef = useRef<{ name: string, data: any, isMarkLine?: boolean }[]>([]); // 数据Ref const { translate } = useLocale(); const handleDestroy = () => { pollingIntervalRef.current && clearInterval(pollingIntervalRef.current); resizeObserverRef.current && resizeObserverRef.current.disconnect(); chart.current && chart.current.dispose(); }; // 全局初始化请求数据处理 const handleInitData = (val: DataConfigProps) => { if (val.sourceType === "sourceId" && val.isInit && val.initData) { const { config: dataConfig, value } = val.initData; const { nullSetZero } = config || {}; const temData = handleData(value, nullSetZero); setData(temData); if (dataConfig?.requestMode === "polling") { pollingIntervalRef.current = setInterval(() => { getData() }, dataConfig?.pollingInterval || 60000); } } } // ws订阅数据更新 const handleWSData = (val: DataConfigProps) => { if (val.sourceType === "sourceId" && val.wsData) { const { value } = val.initData; const { nullSetZero } = config || {}; const temData = handleData(value, nullSetZero); setData(temData); } } useImperativeHandle(ref, () => ({ updateConfig: (newConfig) => { const { base, style: newStyle, data: newDataConfig, initSearchParams: newISParams } = newConfig; setConfig({ ...(newStyle || {}) }); setSize({ width: base.width, height: base.height }); setDataConfig(newDataConfig); setRenderType(newStyle?.renderer || "svg"); handleInitData(newDataConfig); setSearchParams(newDataConfig.searchParams); setInitSearchParams(newISParams); handleWSData(newDataConfig); }, updateSearchParams: (params) => { setInitSearchParams(params); }, destroy: handleDestroy, })); // 窗口大小变化时重新调整图表大小 const handleResize = () => { const container = chartRef.current; if (!container || container.offsetWidth === 0 || container.offsetHeight === 0) return; if (chart.current) { requestAnimationFrame(() => { const isMarkLine = dataRef.current?.some(r => r.isMarkLine); // 存在标记线需要重绘图表(标记线计算有使用容器宽度,因此需要重绘) if (isMarkLine) renderChart(dataRef.current); chart.current.resize({ animation: { duration: 500 } }); }); } }; useEffect(() => { return () => { handleDestroy(); } }, []); useEffect(() => { dataRef.current = data; // 数据变化更新ref }, [data]); useEffect(() => { handleDestroy(); chart.current = echarts.init(chartRef.current, null, { renderer: renderType, useDirtyRect: true }); // 监听容器尺寸变化:页面从隐藏(如切到其他 tab)变为可见时,图表自动重新适应 resizeObserverRef.current = new ResizeObserver(() => handleResize()); resizeObserverRef.current.observe(chartRef.current); }, [renderType]); // 请求数据 const getData = async (params?: object) => { const { nullSetZero } = config || {}; setLoading(true); const { data } = await HydrocarbonService.requestChartData(null, dataConfig?.sourceId, params) || {}; setLoading(false); const temData = handleData(data?.value, nullSetZero); setData(temData); return data?.config; }; // 初始化请求数据 const getInitData = async (params?: object) => { pollingIntervalRef.current && clearInterval(pollingIntervalRef.current); const config = await getData(params); if (config?.requestMode === "polling") { pollingIntervalRef.current = setInterval(() => getData(params), config?.pollingInterval || 60000); } }; // 静态数据处理 useEffect(() => { if (dataConfig?.sourceType === 'staticData') { setData(handleData(dataConfig.staticData)); } }, [dataConfig?.sourceType, dataConfig?.staticData]); /** * 数据源数据请求 * 1、编辑态不请求数据 */ useEffect(() => { if (!isDesignMode && dataConfig?.sourceType === 'sourceId' && dataConfig?.sourceId && !dataConfig?.isInit && dataConfig?.isDefRequest !== false) { if (dataConfig?.isInitParams) { // 组件数据源接收外部参数 initSearchParams && getInitData(initSearchParams); } else { getInitData(); } } else if (dataConfig?.sourceType === 'sourceId') { setData([]); } }, [dataConfig?.sourceType, dataConfig?.sourceId, initSearchParams]); // 搜索参数变化时重新请求数据 useEffect(() => { if (searchParams) { const params = { ...(initSearchParams || {}), ...searchParams }; if (dataConfig?.isInitParams) { // 数据源接收外部参数,则参数存在再请求 initSearchParams && getInitData(params); } else { getInitData(params); } } }, [searchParams, initSearchParams]); const renderChart = (tData) => { const { grid, legend, tooltip, color, xAxis, yAxis, smooth, lineStyle, step, isArea, isGradient, areaStyle, barMaxWidth, symbol, dataZoom, slider, connectNulls, markLineColor, groupType } = config; const option = _.cloneDeep(defOption); const yAxisLabel = yAxis?.axisLabel; const xAxisLabel = xAxis?.axisLabel; // 编辑态无数据显示默认数据 const temData = isDesignMode && !tData?.length ? option.series : tData; option.barMaxWidth = barMaxWidth; option.grid = grid; option.legend = { ...legend, ...legends[legend?.position], data: temData?.filter((item: any) => !item.isMarkLine && item.name).map((r: any) => r.name) }; option.tooltip = { trigger: "axis", ...tooltip }; option.xAxis = { ...option.xAxis, ...xAxis, axisTick: { show: xAxis?.axisLine?.show }, axisLabel: xAxisLabel.numFormat && xAxis.type === "value" ? { ...xAxisLabel, formatter: formatNumberUnit } : xAxisLabel }; option.yAxis = { ...option.yAxis, ...yAxis, axisLabel: yAxisLabel.numFormat && yAxis.type === "value" ? { ...yAxisLabel, formatter: formatNumberUnit } : yAxisLabel }; option.dataZoom = dataZoom ? [slider ? { type: "slider" } : undefined, { type: "inside", disabled: false }].filter(Boolean) : []; option.title.text = translate("${暂无数据}"); option.title.show = !temData?.length; option.series = temData.map((r, index) => { if (!r.isMarkLine) { return (index === 0 ? { type: "line", ...r, ...symbol, step, smooth, itemStyle: symbol.showSymbol ? { color: color[index] } : undefined, lineStyle: { ...lineStyle, color: color[index] }, areaStyle: isArea ? { ...areaStyle, color: isGradient ? new echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: color[index] }, { offset: 1, color: 'rgba(0, 0, 0, 0)' } ]) : color[index] } : undefined, connectNulls } : { type: "bar", ...r, itemStyle: { color: color[index] }, }); } else { // 标记线显示配置 const temData = r.data.filter(r => r[1] || r[1] === 0); // 过滤掉无数据的值 const startData = temData[0]; const lastData = temData[temData.length - 1]; const temColor = markLineColor?.[index - r.vLength]; if (!(startData && lastData)) { return undefined; } return { type: "line", ...r, data: r.data, step: 'end', showSymbol: false, tooltip: { show: false }, lineStyle: { width: 1, color: temColor, type: 'dashed' }, connectNulls: true, markLine: { // 拼接标记线以显示箭头 symbol: ['none', 'arrow'], // 起点无箭头,终点显示箭头 symbolSize: 6, silent: true, // 不触发鼠标事件 lineStyle: { color: temColor }, label: { show: true, color: temColor, position: 'insideEndTop', formatter: lastData[1] }, data: [ [ { coord: startData, }, { coord: startData, x: grid.left, symbol: "none", label: { show: false } }, ], [ { coord: lastData }, { coord: lastData, x: chartRef.current.clientWidth - grid.right } ] ] } } } }).filter(Boolean); if (groupType) chart.current.group = groupType; chart.current.setOption(option, true); }; useEffect(() => { if (config) { renderChart(data); } }, [config, data]); useEffect(() => { if (size) { handleResize(); } }, [size]); const renderChartDom = () =>
; if (isDesignMode) { return renderChartDom(); } return {renderChartDom()}; }); export default Index;