import * as echarts from 'echarts'; import React, { useEffect, useRef, useState, ForwardedRef, forwardRef, useImperativeHandle } from 'react'; import _ from 'lodash'; import { Spin } from "antd"; import ProgramConfig from "../../units"; import chinaJson from "../assets/china.json"; import HydrocarbonService from "../../tmpl/hcservice-v3"; import { DataConfigProps } from "../data"; // 处理提示框背景图片地址 const handleImgUrl = (basePath: string) => { if (!basePath) { return ""; } if (basePath.startsWith("http")) { return basePath; } const url = encodeURI(ProgramConfig.joinPath( ProgramConfig.joinPath(ProgramConfig.api(), "/v3/files"), basePath )) + `?@token=${ProgramConfig.hydrocarbonToken()}&@programToken=${ProgramConfig.programCode()}&@applicationToken=${ProgramConfig.applicationCode()}`; return url; } const defData = [{ name: '北京', value: [116.41, 40.19, 100] }]; const defOption = { animationDurationUpdate: 0, // 重要:禁用动画更新,防止缩放卡顿和不同步 tooltip: { trigger: 'item', triggerOn: "mousemove", }, geo: [ { // 边框 map zlevel: 6, map: "china", // 取消一些交互 select: { disabled: false }, emphasis: { disabled: true, }, silent: true, // 位置大小调整 layoutCenter: ["50%", "50%"], //位置 layoutSize: "125%", //大小 aspectScale: 0.84, // 框颜色 itemStyle: { color: "transparent", opacity: 1, borderWidth: 1, borderColor: "#92C1F0", borderCap: "round", shadowBlur: 20, shadowColor: "#92C1F0", borderType: "solid" }, label: { show: false } }, { // 顶层map map: "china", zlevel: 5, z: 4, select: { disabled: false }, emphasis: { disabled: true, }, silent: true, layoutCenter: ["50%", "50%"], //位置 layoutSize: "125%", //大小 aspectScale: 0.84, // 调整颜色 itemStyle: { areaColor: "#02142A" }, }, { // 第二层,下层地图,防3d效果 zlevel: 5, z: 3, map: "china", select: { disabled: false }, emphasis: { disabled: true, }, silent: true, layoutCenter: ["50%", "50.6%"], //位置 layoutSize: "125%", //大小 aspectScale: 0.84, // 颜色 itemStyle: { borderWidth: 0, borderCap: "round", areaColor: "#38609B", }, regions: [{ name: '南海诸岛', itemStyle: { opacity: 0 }, label: { show: false } }] }, { // 第三层,下层地图,防3d效果 zlevel: 5, z: 2, map: "china", select: { disabled: false }, emphasis: { disabled: true, }, silent: true, layoutCenter: ["50%", "51%"], //位置 layoutSize: "125%", //大小 aspectScale: 0.84, // 颜色 itemStyle: { borderWidth: 0, borderCap: "round", areaColor: "#38609B", }, regions: [{ name: '南海诸岛', itemStyle: { opacity: 0 }, label: { show: false } }] }, { // 第四层,下层地图,防3d效果 zlevel: 5, z: 1, map: "china", select: { disabled: false }, emphasis: { disabled: true, }, silent: true, layoutCenter: ["50%", "51.3%"], //位置 layoutSize: "124.5%", //大小 aspectScale: 0.84, // 颜色 itemStyle: { borderColor: "rgba(0, 0, 0, 0.3)", borderWidth: 1, borderCap: "round", areaColor: "#38609B", shadowBlur: 10, shadowColor: "rgba(0, 0, 0, 0.6)", }, regions: [{ name: '南海诸岛', itemStyle: { opacity: 0 }, label: { show: false } }] }, ], series: [ { type: 'effectScatter', coordinateSystem: "geo", showEffectOn: 'render', rippleEffect: { brushType: 'stroke' }, label: { formatter: '{b}', position: 'right', show: true, }, itemStyle: { color: '#f4e925', }, zlevel: 6, encode: { value: 2 }, data: defData } ] }; // 处理数据格式 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 temVal = value.filter(v => v["v2"]); return { name: config.v1, data: temVal.map(v => { const lonLat = v["v2"].split(",") || []; // 坐标经纬度;value:[经度,纬度,数值] return { name: v["d1"], value: [lonLat[0], lonLat[1], v["v1"]], itemData: { config, value: v } }; }) }; }); return temData[0]?.data || []; }; export interface ComponentStyle { tooltip?: { show: boolean, triggerOn: string, type: string, customize: { [key: string]: any } }; effectScatter?: { [key: string]: any }; areaColor?: string; backgroundColor?: string; borderColor?: string; borderWidth?: number; borderType?: string; label?: { [key: string]: any }; roam?: boolean; zoom?: number; } 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; } const Index = forwardRef((props: ComponentProps, ref: ForwardedRef) => { const { style, data: propsData, isDesignMode } = props; const [config, setConfig] = useState(style || {}); const [size, setSize] = useState<{ width: number, height: number }>(); const [dataConfig, setDataConfig] = useState({ ...propsData }); // 数据源配置 const [data, setData] = useState<{ name: string, value: number[] }[]>([]); 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 handleDestroy = () => { pollingIntervalRef.current && clearInterval(pollingIntervalRef.current); window.removeEventListener('resize', handleResize); 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); handleInitData(newDataConfig); setSearchParams(newDataConfig.searchParams); setInitSearchParams(newISParams); handleWSData(newDataConfig); }, destroy: handleDestroy, })); // 窗口大小变化时重新调整图表大小 const handleResize = () => { chart.current.resize({ animation: { duration: 500 } }); }; useEffect(() => { echarts.registerMap('china', chinaJson as any); chart.current = echarts.init(chartRef.current, null, { renderer: "svg" }); chart.current.on('georoam', () => { // 地图拖拽时,同步其他层级地图的缩放和中心点 const currentOption = chart.current.getOption(); // 获取主 geo (数组中的第一个) 当前的缩放和中心点 const masterZoom = currentOption.geo[0].zoom; const masterCenter = currentOption.geo[0].center; // 遍历并同步所有其他的 geo 组件(从第二个开始) for (let i = 1; i < currentOption.geo.length; i++) { currentOption.geo[i].zoom = masterZoom; // 同步缩放等级 currentOption.geo[i].center = masterCenter; // 同步中心位置 } // 使用 setOption 更新所有从 geo 的配置 // 注意:这里只更新需要变化的 geo 数组,避免不必要的重绘 chart.current.setOption({ geo: currentOption.geo }); }); window.addEventListener('resize', handleResize); return () => { handleDestroy(); } }, []); // 请求数据 const getData = async (params?: object) => { setLoading(true); const { data } = await HydrocarbonService.requestChartData(null, dataConfig?.sourceId, params) || {}; setLoading(false); const { config, value } = data || {}; setData(handleData(value)); 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(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 customizeTooltipConfig = (config) => { const { title, width, height, padding, backgroundColor, content } = config; const backgroundImage = handleImgUrl(config?.backgroundImage); let titleText = title.text; return { padding: 0, borderWidth: 0, enterable: true, backgroundColor: "rgba(0,0,0,0)", confine: false, appendTo: document.body, formatter: (params) => { const itemData = params.data.itemData; const dom = document.createElement("div"); if (title.titleType === "d1") { titleText = itemData?.value?.[title.titleType]; } const bgImg = `background-image: url(${backgroundImage});background-size: 100% 100%;background-repeat: no-repeat;background-position: center;`; dom.style = `z-index:9999;width:${width}px;height:${height}px;${backgroundImage ? bgImg : `background:${backgroundColor}`}`; dom.innerHTML = `
${title?.text ? `
${titleText}
` : ""} ${content?.value?.map(r => itemData?.config?.[r] && `
${itemData?.config?.[r] || ""}
${itemData?.value?.[r] || ""}
`)?.filter(Boolean)?.join("")}
`; return dom; } } }; const renderChart = () => { const { roam, zoom, tooltip, areaColor, backgroundColor, borderColor, borderWidth, borderType, label, effectScatter } = config; const option = _.cloneDeep(defOption); // 编辑态无数据显示默认数据 const temData = isDesignMode && !data?.length ? defData : data; option.tooltip = { trigger: "item", ...tooltip, ...(tooltip.type === "customize" ? customizeTooltipConfig(tooltip.customize || {}) : {}) }; option.geo = option.geo.map((r, index) => { switch (index) { case 0: return { ...r, roam, zoom, label, itemStyle: { ...r.itemStyle, borderWidth, borderColor, shadowColor: borderColor, borderType } }; case 1: return { ...r, roam: false, zoom, itemStyle: { areaColor } }; case 2: case 3: case 4: return { ...r, roam: false, zoom, itemStyle: { ...r.itemStyle, areaColor: backgroundColor } }; default: return { ...r, roam: false, zoom }; } }) as any; option.series = option.series.map((item: any) => ({ ...item, ...effectScatter, data: temData })); 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;