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"; const defData = [ { value: 100, name: 'Value1', pct: 10 }, { value: 100, name: 'Value2', pct: 10 }, { value: 200, name: 'Value3', pct: 20 }, { value: 300, name: 'Value4', pct: 30 }, { value: 300, name: 'Value5', pct: 30 } ]; const defOption = { title: { text: '暂无数据', left: 'center', top: 'middle', show: false, // 无数据时显示 }, color: ["#5470c6", "#91cc75", "#fac858", "#ee6666", "#73c0de"], padAngle: 0, tooltip: { trigger: 'item' }, legend: { orient: 'vertical', left: 'left', textStyle: { fontSize: 0, color: "#ffffff", rich: { a: { fontSize: 12, width: 50, // 【关键】固定宽度,根据最长名字预估 align: 'left', // 左对齐 overflow: 'truncate', // 名字太长省略 ellipsis: '...', padding: [0, 10, 0, 0] // 右边距,作为列间隔 }, b: { fontSize: 12, width: 30, align: 'left', padding: [0, 10, 0, 0] }, c: { fontSize: 12, width: 30, align: 'left', padding: [0, 10, 0, 0] } }, }, }, series: [ { name: '数值', type: 'pie', radius: ["0%", "50%"], center: ['50%', '50%'], padAngle: 0, label: {}, labelLine: {}, data: defData } ], }; 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 }, }; const halfConifg = { startAngle: 180, endAngle: 360, }; // 处理关系字段显示 const handleRelationVal = (val: string) => { if (!val) { return val; } if (typeof val === "string" && val?.includes("@R@")) { return val.split("@R@")[1]; } else { return val; } } // 处理数据格式 const handleData = (data: { config: { [key: string]: string }, value: { [key: string]: any }[] }[]) => { if (!data?.length) { return []; } const temData = data.map((r) => { const { config, value } = r; const isD = Object.keys(config).some(r => r.includes("d")); if (isD) { const sum = value.reduce((total, item) => total + Number(item["v1"]), 0); return { name: config.v1, data: value.map(v => ({ name: handleRelationVal(v["d1"]), value: v["v1"], pct: sum ? parseFloat(Number(v["v1"] / sum * 100).toFixed(2)) : 0 })) } } else { const sum = Object.values(value[0]).reduce((total, item) => total + Number(item), 0); const vNames = Object.keys(config).filter((r) => r.startsWith("v") && !r.includes("-")).sort((a, b) => parseInt(a.substring(1)) - parseInt(b.substring(1))); return { name: "", data: vNames.map(v => ({ name: config[v], value: value[0][v], pct: sum ? parseFloat(Number(value[0][v] / sum * 100).toFixed(2)) : 0 })) }; } }); return temData || []; }; export interface ComponentStyle { tooltip?: { show: boolean }; color?: string[]; grid?: { top: number, let: number, right: number, bottom: number }; legend?: { [key: string]: any }; padAngle?: number; radius?: number; innerRadius?: number; label?: { [key: string]: any }; labelLine?: { [key: string]: any }; center?: { x: number, y: number }; roseType?: string; // 玫瑰图配置 renderer?: "canvas" | "svg"; isHalf?: boolean; // 是否半扇形/环形图 } 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 }[]>([]); 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 { translate } = useLocale(); const handleDestroy = () => { pollingIntervalRef.current && clearInterval(pollingIntervalRef.current); window.removeEventListener('resize', handleResize); chart.current && chart.current.dispose(); }; // 全局初始化请求数据处理 const handleInitData = (val: DataConfigProps) => { if (val.sourceType === "sourceId" && val.isInit && val.initData) { const { config, value } = val.initData; const temData = handleData(value); setData(temData); if (config?.requestMode === "polling") { pollingIntervalRef.current = setInterval(() => { getData() }, config?.pollingInterval || 60000); } } } // ws订阅数据更新 const handleWSData = (val: DataConfigProps) => { if (val.sourceType === "sourceId" && val.wsData) { const { value } = val.initData; const temData = handleData(value); 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); }, destroy: handleDestroy, updateSearchParams: (params) => { setInitSearchParams(params); }, })); // 窗口大小变化时重新调整图表大小 const handleResize = () => { chart.current.resize({ animation: { duration: 500 } }); }; useEffect(() => { return () => { handleDestroy(); } }, []); useEffect(() => { handleDestroy(); chart.current = echarts.init(chartRef.current, null, { renderer: renderType }); window.addEventListener('resize', handleResize); }, [renderType]); // 请求数据 const getData = async (params?: object) => { setLoading(true); const { data } = await HydrocarbonService.requestChartData(null, dataConfig?.sourceId, params) || {}; setLoading(false); const { config, value } = data || {}; const temData = handleData(value); setData(temData); return 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 legendFormatter = ({ name, formatter, unit }) => { if (!formatter || formatter === "a") { return `{a|${name}}`; } const temData = isDesignMode && !data?.length ? defData : data.map(r => r.data).flat(); const item = temData.find(r => r.name === name); if (!item) { return `{a|${name}}`; } const formatters = { "a-b": `{a|${name}} {b|${item.pct}%}`, "a-c": `{a|${name}} {b|${item.value}${unit ? ` (${unit})` : ""}}`, "a-c-b": `{a|${name}} {b|${item.value}${unit ? ` (${unit})` : ""}} {c|${item.pct}%}`, "a-b-c": `{a|${name}} {b|${item.pct}%} {c|${item.value}${unit ? ` (${unit})` : ""}}` }; return formatters[formatter] || `{a|${name}}`; } const renderChart = () => { const { legend, tooltip, radius, innerRadius, color, label, labelLine, padAngle, roseType, center, isHalf } = config; const option = _.cloneDeep(defOption); // 编辑态无数据显示默认数据 const temData = isDesignMode && !data?.length ? option.series : data; // formatter:a(名称)、b(百分比)、c(数值) const { position, formatter, textStyle, space, unit } = legend; const defLegendTextStyleRich = option?.legend?.textStyle?.rich; const temTextStyle = { fontSize: space || 0, color: textStyle.color, rich: { a: { ...(defLegendTextStyleRich?.a || {}), fontSize: textStyle.fontSize || 12, padding: [0, textStyle.padding || 0, 0, 0] }, b: { ...(defLegendTextStyleRich?.b || {}), fontSize: textStyle.fontSize || 12, padding: [0, textStyle.padding || 0, 0, 0] }, c: { ...(defLegendTextStyleRich?.c || {}), fontSize: textStyle.fontSize || 12, padding: [0, textStyle.padding || 0, 0, 0] }, }, }; option.legend = { ...legend, textStyle: temTextStyle, ...legends[position], formatter: (name) => legendFormatter({ name, formatter, unit }) }; option.tooltip = { trigger: "item", ...tooltip }; option.color = color; option.title.text = translate("${暂无数据}"); option.title.show = !temData?.length; option.series = temData.map(r => ({ ...r, ...(isHalf ? halfConifg : {}), type: "pie", radius: [`${innerRadius}%`, `${radius}%`], center: [`${center?.x}%`, `${center?.y}%`], padAngle, label, labelLine, roseType })); chart.current.setOption(option, true); } useEffect(() => { if (config) { renderChart(); } }, [config, data]); useEffect(() => { if (size) { handleResize(); } }, [size]); const renderChartDom = () =>
; if (isDesignMode) { return renderChartDom(); } return {renderChartDom()}; }); export default Index;