import React, { useMemo, useEffect, useState, useRef } from "react"; import { Spin, Empty, theme, Popconfirm, message, Popover, Descriptions, DescriptionsProps } from "antd"; import { Gantt, VTable } from '@visactor/vtable-gantt'; import dayjs, { OpUnitType } from "dayjs"; import cloneDeep from "lodash/cloneDeep"; import HcserviceV3 from "../../tmpl/hcservice-v3"; import { LtmplConfig, ShowViewParam, ColumnConfig } from "../../tmpl/interface"; import { useLocale } from "../../locale/useLocale"; import loadingIcon from "./img/loading-circle.gif"; import "./index.less"; // 注册树形表格懒加载loading图标 const registerLoadingIcon = () => { VTable.register.icon('loading', { type: 'image', width: 16, height: 16, src: loadingIcon, name: 'loading', //定义图标的名称,在内部会作为缓存的key值 positionType: VTable.TYPES.IconPosition.absoluteRight, // 指定位置,可以在文本的前后,或者在绝对定位在单元格的左侧右侧 marginLeft: 0, // 左侧内容间隔 在特定位置position中起作用 marginRight: 4, // 右侧内容间隔 在特定位置position中起作用 visibleTime: 'always', // 显示时机, 'always' | 'mouseover_cell' | 'click_cell' hover: { // 热区大小 width: 22, height: 22, bgColor: 'rgba(101,117,168,0.1)' }, isGif: true }); } // 配置标题,用于提示未配置 const configTitle = { gttBeginTime: "开始时间", gttEndTime: "结束时间", gttProgress: "进度", gttTimeUint: "时间单位" }; const timeFormat = { "year": "YYYY", "month": "YYYY-MM", "day": "YYYY-MM-DD", "hour": "YYYY-MM-DD HH:mm", "minute": "YYYY-MM-DD HH:mm" }; // 动态设置任务条背景色 const handleProgressBgColor = (args: { startDate?: string, endDate: string, taskRecord: { [key: string]: any }, gttLatestProgressTime: ColumnConfig; gttProgress: ColumnConfig, timeType: OpUnitType }) => { const { startDate, endDate, taskRecord, gttProgress, timeType, gttLatestProgressTime } = args; const progress = Number(taskRecord[gttProgress?.id] || 0); let cBarColor = undefined; // 任务条已完成颜色,默认主题色 let state = "-"; if (taskRecord[gttLatestProgressTime?.id] && progress >= 100) { // 任务延迟完成(任务完成时间>任务结束时间) const progressTime = dayjs(taskRecord[gttLatestProgressTime?.id]).unix(); const endTime = dayjs(endDate).unix(); if (progressTime > endTime) { cBarColor = "#ad6800"; state = "延期完成"; } } if (progress >= 100) return { barColor: undefined, cBarColor, state: state || "已完成" }; // 已完成 const startTime = dayjs(startDate).startOf(timeType).unix(); const endTime = dayjs(endDate).endOf(timeType).unix(); const progressTime = (endTime - startTime) * progress / 100 + startTime; const curStartTime = dayjs().startOf(timeType).unix(); // 当前时间开始 const curEndTime = dayjs().endOf(timeType).unix(); // 当前时间结束 if (endTime < curEndTime) return { barColor: "#990000", cBarColor, state: "延期未完成" }; // 延期已结束(未完成,当前时间>任务结束时间) if (progress > 0) { if (curEndTime < progressTime) return { barColor: "#52c41a", cBarColor, state: "进度领先" }; // 进度快 if (curStartTime > progressTime) return { barColor: "#faad14", cBarColor, state: "进度滞后" }; // 延期已开始(未完成,当前时间<任务结束时间) } else if (startTime < curEndTime) { // 延期未开始 return { barColor: "#ff0000", cBarColor, state: "延期未开始" }; } return { barColor: undefined, cBarColor, state: progress > 0 ? "进行中" : "未开始" }; }; // 时间刻度配置 const timeScales = { year: [{ unit: "year", format: "YYYY年" }], month: [{ unit: "year", format: "YYYY年" }, { unit: "month", format: "MM月" }], day: [{ unit: "month", format: "MM月" }, { unit: "day", format: "DD日" }], hour: [{ unit: "day", format: "MM月DD日" }, { unit: "hour", format: "HH:mm" }], minute: [{ unit: "hour", format: "MM-DD HH:mm" }, { unit: "minute", format: "mm" }] }; // 智能缩放配置 const zoomScale = ({ translate, colorText }) => { const timeTypes = ["year", "month", "day", "hour", "minute"]; const levels = timeTypes.map(t => timeScales[t].map(r => ({ unit: r.unit, step: 1, format: date => translate("$" + `{${dayjs(date.startDate).format(r.format)}}`), style: { fontSize: 14, fontWeight: 500, color: colorText } }))); return { enabled: true, levels } }; type Props = { dataSource?: any[]; serverKey?: string; sourceId?: string; loading?: boolean; ltmplConfig?: LtmplConfig; onRefresh?: () => void; // 刷新数据 showView?: (showVievParam: ShowViewParam) => void; errorText?: string; getChildrenData?: (code?: string) => void; }; const Index = (props: Props) => { const { dataSource, serverKey, sourceId, loading, ltmplConfig, onRefresh, showView, errorText, getChildrenData } = props; const { extDisplayConfig, gttTableProportion, gttBeginTime, gttEndTime, gttEditable, gttHideTable, gttProgress, gttTableColumns, gttTimeUint, gttType, gttSubOpenRatmplId, gttLatestProgressTime } = ltmplConfig || {}; const { primaryColumn } = extDisplayConfig || {}; const [ganttHeight, setGanttHeight] = useState(120); const [ganttInstance, setGanttInstance] = useState(); const [popconfirmOpen, setPopconfirmOpen] = useState(false); const [popconfirmRect, setPopconfirmRect] = useState<{ top: number, left: number }>({ top: 0, left: 0 }); const [currentData, setCurrentData] = useState(null); const [currentChangeData, setCurrentChangeData] = useState(null); const [ganttData, setGanttData] = useState([]); const [detailOpen, setDetailOpen] = useState(false); const [detailRect, setDetailRect] = useState<{ top: number, left: number }>({ top: 0, left: 0 }); const [expandedCodes, setExpandedCodes] = useState([]); const { translate } = useLocale(); const ganttRef = useRef(null); const isEditRef = useRef(true); // 甘特图是否编辑Ref const { token: ganttTheme } = theme.useToken(); const version = localStorage.getItem("version"); useEffect(() => { // option 中使用,当前存在编辑项,其他项不可编辑 isEditRef.current = !popconfirmOpen; }, [popconfirmOpen]); // 提示信息 const warnMessage = useMemo(() => { const warnList = ["gttBeginTime", "gttEndTime", "gttProgress", "gttTimeUint"].map((item) => { if (ltmplConfig[item]) { return ""; } return configTitle[item]; }).filter(Boolean).join("、"); return warnList ? `${warnList}${translate("${未配置}")}` : ""; }, [ltmplConfig]); // 处理数据 const handleChangeData = (data) => data?.map(r => ({ ...r, hierarchyState: expandedCodes.includes(r.code) ? "expand" : "collapse", type: r[gttType?.id] || "task", children: r.children?.length ? handleChangeData(r.children) : !!gttSubOpenRatmplId })); // 数据处理,存在表格类型配置,默认任务条类型 const handleInitData = () => { let data = dataSource; if (!gttType?.id && !gttSubOpenRatmplId) { data = dataSource; } else { // 存在任务类型配置、存在子任务模板id data = handleChangeData(dataSource); } setGanttData(data); } useEffect(() => { handleInitData(); }, [dataSource]); // 甘特图配置 const option: any = useMemo(() => { const { buttons } = ltmplConfig; const { colorBorderSecondary, colorFillQuaternary, colorText, colorPrimaryBorder, colorPrimary } = ganttTheme; const defStyle = { borderColor: colorBorderSecondary, bgColor: colorFillQuaternary } const styleMap = { v2: defStyle, v3: { borderColor: "#15325b", bgColor: "#0e346a" }, v4: { ...defStyle, bgColor: "#0a3155" }, v5: defStyle }; const { borderColor, bgColor } = styleMap[version] || defStyle; const leftColumns = []; // 表格左侧固定列 const rightColumns = []; // 表格右侧固定列 let tableColumns = []; // 表格列 gttTableColumns?.forEach((col, index) => { const item = { field: col.id, title: col.title, width: col.colWidth || 'auto', tree: index === 0, }; if (col.colFixed === "left") { leftColumns.push(item); return; } if (col.colFixed === "right") { rightColumns.push(item); return; } tableColumns.push(item); }); tableColumns = [...leftColumns, ...tableColumns, ...rightColumns]; const isEdit = buttons.includes("dtmplEdit") && gttEditable; // 任务条是否可编辑 return { overscrollBehavior: 'auto', records: [], underlayBackgroundColor: "transparent", taskListTable: { tableWidth: (gttHideTable || gttTableProportion === 0) ? 0 : (gttTableProportion || "auto"), // 隐藏表格宽度设置0 columns: tableColumns, select: { disableSelect: true }, hover: { disableHover: true }, theme: { headerStyle: { borderColor, color: colorText, borderLineWidth: 1, fontSize: 14, fontWeight: 500, bgColor }, bodyStyle: { borderColor, borderLineWidth: 1, fontSize: 14, color: colorText, bgColor: "transparent" } }, frozenColCount: leftColumns.length, // 左侧固定列数 rightFrozenColCount: rightColumns.length, // 右侧固定列数 }, frame: { outerFrameStyle: { borderLineWidth: 1, borderColor, cornerRadius: 8 }, verticalSplitLine: { lineColor: borderColor, lineWidth: 1 }, horizontalSplitLine: { lineColor: borderColor, lineWidth: 1 }, verticalSplitLineMoveable: !gttHideTable, // 是否可移动垂直分割线(隐藏表格则不可移动) verticalSplitLineHighlight: { lineWidth: 1 } }, grid: { verticalLine: { lineWidth: 1, lineColor: borderColor }, horizontalLine: { lineWidth: 1, lineColor: borderColor }, }, headerRowHeight: 38, rowHeight: 38, taskBar: { startDateField: gttBeginTime?.id, endDateField: gttEndTime?.id, progressField: gttProgress?.id, resizable: () => isEdit ? isEditRef.current : false, // 存在编辑任务条时其他任务不可编辑 moveable: () => isEdit ? isEditRef.current : false, progressAdjustable: () => isEdit ? isEditRef.current : false, hoverBarStyle: { barOverlayColor: 'rgba(99, 144, 0, 0)' }, labelText: `{${primaryColumn?.id}} {${gttProgress?.id}}%`, labelTextStyle: { fontFamily: 'Arial', fontSize: 12, textAlign: 'left', textOverflow: 'ellipsis', color: "#ffffff" }, barStyle: (args) => { const { startDate, endDate, taskRecord } = args; const { barColor, cBarColor } = handleProgressBgColor({ startDate, endDate, taskRecord, gttLatestProgressTime, gttProgress, timeType: gttTimeUint as OpUnitType }) || {}; return { width: 20, barColor: barColor || colorPrimaryBorder, completedBarColor: cBarColor || colorPrimary, cornerRadius: 8, } }, milestoneStyle: { borderColor, borderLineWidth: 1, fillColor: colorPrimary, width: 15 } }, markLine: { scrollToMarkLine: true, position: "right", date: dayjs().format(timeFormat[gttTimeUint]), style: { lineDash: [4, 4] }, }, timelineHeader: { colWidth: 100, backgroundColor: bgColor, horizontalLine: { lineWidth: 1, lineColor: borderColor }, verticalLine: { lineWidth: 1, lineColor: borderColor }, zoomScale: zoomScale({ translate, colorText }) }, scrollStyle: { scrollRailColor: "transparent", visible: 'scrolling', width: 6, scrollSliderCornerRadius: 4, scrollSliderColor: colorPrimaryBorder, } }; }, [version, ltmplConfig]); // 计算甘特图高度 const handleGanttHeight = () => { const itemHeight = 38; const temHieght = (dataSource.length + timeScales[gttTimeUint]?.length || 2) * itemHeight + 3; setGanttHeight(temHieght); }; // 设置甘特图时间范围,处理甘特图默认显示范围 const handleUpdateDateRange = () => { const times = [dayjs().valueOf()]; dataSource.forEach(r => { const sTime = r[gttBeginTime.id]; const eTime = r[gttEndTime.id]; if (sTime && eTime) { times.push(dayjs(sTime).valueOf(), dayjs(eTime).valueOf()); } }); const minTime = Math.min(...times); const maxTime = Math.max(...times); const minDate = dayjs(minTime).subtract(2, gttTimeUint as any).format(timeFormat[gttTimeUint]); const maxDate = dayjs(maxTime).add(2, gttTimeUint as any).format(timeFormat[gttTimeUint]); ganttInstance.updateDateRange(minDate, maxDate); // 更新甘特图时间范围 }; // 更新甘特图任务时间、进度 const handleUpdateTask = async () => { if (!currentChangeData) { return; } let res = await HcserviceV3.postLtmplData( serverKey, sourceId, currentChangeData, message ); if (res.status === "success") { setPopconfirmOpen(false); setCurrentChangeData(null); onRefresh(); } }; // 甘特图时间变化处理 const changeDateRange = (event, gantt) => { const { index, record, startDate, endDate, oldEndDate, oldStartDate } = event; const { top, left, width } = gantt.getTaskBarRelativeRect(index); const canvasWidth = gantt.getElement().clientWidth; setPopconfirmOpen(true); const format = timeFormat[gttTimeUint]; const changeStart = dayjs(oldStartDate).format(format) !== dayjs(startDate).format(format); const changeEnd = dayjs(oldEndDate).format(format) !== dayjs(endDate).format(format); const temLeft = (changeStart && changeEnd) ? (left + width / 2) : changeEnd ? (left + width) : left; setPopconfirmRect({ top: top - 86, left: (temLeft > canvasWidth - 200 || temLeft < 0) ? canvasWidth / 2 : temLeft - 40 }); const dtmplData = { "唯一编码": record.code, [gttBeginTime.id]: startDate, [gttEndTime.id]: endDate }; setCurrentChangeData(dtmplData); } // 甘特图进度变化处理 const changeProgress = (event, gantt) => { const { index, record, progress } = event; const { top, left, width } = gantt.getTaskBarRelativeRect(index); setPopconfirmOpen(true); setPopconfirmRect({ top: top - 86, left: width * progress / 100 + left - 40 }); const dtmplData = { "唯一编码": record.code, [gttProgress.id]: progress }; setCurrentChangeData(dtmplData); } // 任务条点击查看详情 const handleClickTaskBar = (event) => { if (!showView) return; const { buttons } = ltmplConfig; const { record } = event; if (buttons.includes("customDetail")) { showView({ code: record.code, toCustomPage: true }); return; } if (buttons.includes("detail")) { showView({ code: record.code }); return; } } // 懒加载子节点 const getTaskTreeData = async (event, gantt) => { const { originData, col, row, hierarchyState } = event; const itemData = gantt.taskListTableInstance.getRecordByCell(col, row); // 获取当前单元格对应的完整数据 setExpandedCodes(val => hierarchyState === "collapse" ? val.filter(c => c !== itemData.code) : [...val, originData.code]); if (hierarchyState === "collapse" || originData.children !== true) return; gantt.taskListTableInstance.setLoadingHierarchyState(col, row); await getChildrenData(originData.code); } useEffect(() => { if (dataSource?.length && !ganttInstance && !warnMessage) { const gantt = new Gantt(ganttRef.current, option); gantt.zoomScaleManager.setZoomPosition({ minUnit: gttTimeUint, step: 1, colWidth: 100 }); // 设置默认缩放状态 setGanttInstance(gantt); gantt.on('click_task_bar', handleClickTaskBar); // 任务时间变化监听 gantt.on('change_date_range', (event) => changeDateRange(event, gantt)); // 任务进度更新监听 gantt.on('progress_update', (event) => changeProgress(event, gantt)); // 鼠标移入任务条事件,显示详情 gantt.on("mouseenter_task_bar", (event) => { const { x, y } = event.federatedEvent.canvas as any || {}; const { canvasWidth } = gantt.taskListTableInstance || {}; setCurrentData(event.record); setDetailRect({ top: y + 10, left: x + canvasWidth - 112 }); setDetailOpen(true); }); // 鼠标移出,隐藏详情弹窗 gantt.on("mouseleave_task_bar", () => { setCurrentData(undefined); setDetailOpen(false); }); // 任务树懒加载 gantt.taskListTableInstance.on("tree_hierarchy_state_change", (event) => getTaskTreeData(event, gantt)); } }, [dataSource, option]); useEffect(() => { if (ganttInstance && ganttData?.length) { handleGanttHeight(); // 计算甘特图高度 handleUpdateDateRange(); ganttInstance.updateOption({ ...option, // 处理展开分组表格出现空白异常(重绘整个甘特图) records: cloneDeep(ganttData) // 更新数据 }); // 重置缩放最大值最小值范围(由于官方 updateOption BUG,默认缩放范围异常,暂时处理方法) ganttInstance.zoomScaleManager.updateZoomLimits(); } }, [ganttInstance, ganttData]); useEffect(() => { registerLoadingIcon(); return () => { ganttInstance?.release(); } }, []); // 任务条详情 const renderDetail = () => { if (!currentData) return ""; const startDate = currentData[gttBeginTime.id]; const endDate = currentData[gttEndTime.id]; const { state } = handleProgressBgColor({ startDate, endDate, taskRecord: currentData, gttLatestProgressTime, gttProgress, timeType: gttTimeUint as OpUnitType }) || {}; const items: DescriptionsProps['items'] = [ primaryColumn && { key: primaryColumn.id, label: primaryColumn.title, children: currentData[primaryColumn.id], }, gttBeginTime && { key: "startTime", label: "开始时间", children: dayjs(startDate).format(timeFormat[gttTimeUint]) }, gttEndTime && { key: "endTime", label: "结束时间", children: dayjs(endDate).format(timeFormat[gttTimeUint]) }, gttProgress && { key: "progress", label: "进度", children: `${currentData[gttProgress.id] || 0}%` }, { key: "state", label: "状态", children: state } ].filter(Boolean); return ; } return (
{(dataSource?.length && !warnMessage) ?
: } { setPopconfirmOpen(false); setCurrentChangeData(null); ganttInstance.setRecords(cloneDeep(ganttData)); }} okText={translate("${确定}")} cancelText={translate("${取消}")} open={popconfirmOpen} getPopupContainer={() => ganttRef.current} destroyOnHidden={true} /> renderDetail()} open={detailOpen} placement="bottom" autoAdjustOverflow={false} destroyOnHidden={true} getPopupContainer={() => ganttRef.current} />
); }; export default Index;