import React, { useEffect, useRef, useCallback, useState } from 'react'; import { Space, Button, Spin } from "antd"; import { ExpandOutlined } from '@ant-design/icons'; import chunk from "lodash/chunk"; import HcserviceV3 from "../tmpl/hcservice-v3"; import WebSocket from "../tmpl/web-socket"; import { Render } from '../draw-canvas-edit/components/render'; import { useLocale } from "../index"; import './index.less'; // 数据源请求结果 interface DataSource { config: { [key: string]: any }; value: { config: { [key: string]: any }; value: { [key: string]: any }[] }[]; } interface ViewerProps { data?: string; // 画布 JSON 数据 viewId?: string; // 画面ID recordCode: string; // 画面关联实例Code,用于数据源请求过滤 width?: number | string; height?: number | string; // 组件数据源初始化查询参数;公共参数、指定组件参数:例:{公共参数key:value,指定组件Id(编辑页获取):{参数key:value}} initSearchParams?: { [key: string]: any }, } const Index = (props: ViewerProps) => { const { recordCode, viewId, data, width = '100%', height = '100%' } = props; const boardRef = useRef(null); const stageRef = useRef(null); const renderRef = useRef(null); const observerRef = useRef(null); const wsRef = useRef(undefined); // 实时数据websocket连接 const subscribeRef = useRef(undefined); // 实时数据订阅 const [loading, setLoading] = useState(false); const { getLocale } = useLocale(); // 初始化渲染器(只读模式) const initRender = useCallback( (width: number, height: number) => { if (renderRef.current || !stageRef.current) return; const locale = getLocale(); const render = new Render(stageRef.current, { width, height, showRuler: false, // 不需要标尺 showRefLine: false, // 不需要参考线 showPreview: false, // 不需要预览框 showContextmenu: false, // 不需要右键菜单 showBg: true, readonly: true, // 只读模式 locale }); renderRef.current = render; // 如果有数据,恢复画布 if (data) { loadData(render, data); } }, [data] ); // 更新指定组件设置 const updateComponentSetting = (node: { [key: string]: any }, data: DataSource, pageId: string) => { const { componentType, id, settings } = node; let temSetting; switch (componentType) { case "workstation": // 工位(v1:工位状态枚举颜色,d1:工位编号) const temVals = data.value?.[0]?.value; const value = temVals.find(r => r.d1 === settings.workstationNumber)?.v1; temSetting = value ? { fill: value } : undefined; break; default: break; } temSetting && renderRef.current.updateAssetById(id, { ...temSetting, pageId }); } // 更新组件数据->更新画面 const updateAssetSettings = async (nodes: { [key: string]: any }[], data: DataSource) => { if (!renderRef.current || !nodes?.length || !data) return; nodes.forEach(node => updateComponentSetting(node, data, data.config?.pageId)); }; // 整理组件数据源 const handleDataSourceParams = (nodes: { [key: string]: any }[]) => { const dataSourceConfigs = nodes.reduce((total, item) => { const { dataSource } = item.settings || {}; if (dataSource && total[dataSource]) { total[dataSource].nodes.push(item); } else if (dataSource) { total[dataSource] = { params: { sourceId: dataSource, chartCode: dataSource, secondCriterion: recordCode }, nodes: [item] }; } return total; }, {}); return dataSourceConfigs; } // 获取初始化组件数据 const getInitComponentData = async (dataSourceConfigs: { [key: string]: any }) => { const dataSources = Object.keys(dataSourceConfigs).map(r => dataSourceConfigs[r].params); if (!dataSources.length) return; const temSourceConfigs = chunk(dataSources, 10); // 每批处理10个数据源 temSourceConfigs.forEach(i => { HcserviceV3.requestCharMultitData(null, JSON.stringify(i)).then(rs => { const { status, ...data } = rs || {}; if (status === "success") { for (const item in data) { // 更新组件数据 updateAssetSettings(dataSourceConfigs[item].nodes, data[item]); } } }) }) }; // 获取当前画面数据源配置 const getCharWSConfig = async (dataSourceConfigs: { [key: string]: any }) => { const dataSourceIds = Object.keys(dataSourceConfigs).map(r => dataSourceConfigs[r].params.sourceId); if (!dataSourceIds.length) return; const res = await HcserviceV3.requestCharWSConfig(null, dataSourceIds); const wsSourceIds = Object.keys(res?.config || {}); if (!wsSourceIds?.length) { return; } return wsSourceIds.map(r => dataSourceConfigs[r].params); } // 实时订阅组件数据 const webSocketComponentData = async (dataSourceConfigs: { [key: string]: any }) => { if (subscribeRef.current) { subscribeRef.current.unsubscribe(); } const temArr = await getCharWSConfig(dataSourceConfigs); if (!viewId || !temArr?.length) { return; } wsRef.current = WebSocket.getInstance("v3/kk-ws"); // 订阅数据 subscribeRef.current = await wsRef.current.subscribe(`/user/queue/chart-data/${viewId}`, { dataSourceConfigs: JSON.stringify(temArr) }, (data) => { for (const item in data) { // 更新组件数据 updateAssetSettings(dataSourceConfigs[item].nodes, data[item]); } }); } // 获取所有组件-更新数据 const onAssetsLoaded = () => { if (!renderRef.current) return; const assets = renderRef.current.getAllAssets(); if (!assets?.length) return; const allDataSource = handleDataSourceParams(assets); getInitComponentData(allDataSource); // 初始化请求 webSocketComponentData(allDataSource); // ws订阅数据 } // 加载画布数据 const loadData = useCallback(async (render: Render, jsonData: string) => { setLoading(true); try { await render.importExportTool.restore(jsonData); // 数据加载完成后自适应居中 render.positionTool.positionFit(); onAssetsLoaded(); } catch (e) { console.error('Failed to load canvas data:', e); } setLoading(false); }, []); // 监听容器尺寸变化 useEffect(() => { if (!boardRef.current) return; const observer = new ResizeObserver(() => { if (!boardRef.current) return; const { width, height } = boardRef.current.getBoundingClientRect(); if (renderRef.current) { renderRef.current.resize(width, height); // 更新尺寸 renderRef.current.positionTool.positionFit(); // 自适应居中 } else { initRender(width, height); } }); observer.observe(boardRef.current); observerRef.current = observer; return () => { observer.disconnect(); }; }, []); // 当外部 data 更新时,重新加载 useEffect(() => { if (renderRef.current && data) { loadData(renderRef.current, data); } }, [data, loadData]); const handleFit = useCallback(() => { if (!renderRef.current) return; renderRef.current.positionTool.positionFit(); }, []); // 清理 useEffect(() => { return () => { if (renderRef.current) { renderRef.current.stage.destroy(); renderRef.current = null; } if (observerRef.current) { observerRef.current.disconnect(); observerRef.current = null; } if (subscribeRef.current) { // 清理订阅 subscribeRef.current.unsubscribe(); } }; }, []); return (
{/* 画布区域 */}
); }; export default Index;