import React from "react";
import "./index.css";
import {
DtmplData,
PageInfo,
QueryData,
SelectedRow, QueryTableProps, AggregateVO
} from "../tmpl/interface";
import HcserviceV3 from "../tmpl/hcservice-v3";
import Pagination from "./pagination";
import { TableRowSelection } from "antd/lib/table/interface";
import { SortableContainer, SortableElement } from "react-sortable-hoc";
import { arrayMoveImmutable } from "array-move";
import { LocaleContext } from "../locale/LocaleProvider";
import { init, merge, statistic } from "../utils/dsu";
import VerticalList from "../list/vertical-list";
import CardList from "../list/card-list";
import Gantt from "../list/gantt";
import Calendar from "../list/calendar";
import RealTimeCardList from "../list/real-time-card-list";
import SummaryBuilder from "./column/summary-builder";
import { Button, Card, Descriptions, message, Statistic, Empty } from "antd";
import Units from "../units";
import { DownOutlined, UpOutlined } from "@ant-design/icons";
import ResizableTable from "./resizable-table";
const SortableItem = SortableElement((props) => (
));
const SortableBody = SortableContainer((props) => );
interface CacheData {
dataSource: object[];
pageInfo: PageInfo;
}
interface QueryTableStat {
queryDataCache?: Map;
virtualEndPageNo?: number;
dataSource?: object[];
loading?: boolean;
touchEnd?: boolean;
aggregateVO?: AggregateVO;
beforeSelectedRows?: number;
errorText?: string;
localSorter?: { field: string, order: string };
}
class QueryTable extends React.PureComponent {
static defaultProps = {
pageInfo: {
pageNo: 1,
pageSize: 10,
virtualEndPageNo: undefined,
},
tableProps: {
size: "small",
clickDisplayTotal: false,
scrollY: 500,
},
hiddenRowCodes: [],
selectedRows: [],
viewModels: ["table"],
summaryConfigs: [],
cardListConfig: {},
ltmplConfig: {},
showPagination: true,
showEmpty: true,
bordered: true,
showHeader: true,
};
defaultAggregateShowSize = 7;
state = {
queryDataCache: undefined,
virtualEndPageNo: undefined,
dataSource: undefined,
loading: true,
touchEnd: undefined,
aggregateVO: undefined,
beforeSelectedRows: undefined,
errorText: undefined,
localSorter: undefined
};
static contextType = LocaleContext;
context: React.ContextType;
async componentDidMount() {
const { queryKey, pageInfo } = this.props;
if (queryKey) {
await this.loadData(queryKey.key, pageInfo);
} else {
this.setState({ loading: false });
}
}
componentWillUnmount() {
this.setState = () => false;
}
async componentDidUpdate(prevProps) {
const { queryKey: preQueryKey, pageInfo: prePageInfo } = prevProps;
const { queryKey, pageInfo, sourceId } = this.props;
if (queryKey) {
if (preQueryKey?.key != queryKey.key) {
await this.loadData(queryKey.key, pageInfo, true);
} else if (
prePageInfo?.pageNo != pageInfo.pageNo ||
prePageInfo?.pageSize != pageInfo.pageSize
) {
await this.loadData(queryKey.key, pageInfo, false);
}
}
}
DraggableContainer = (props) => (
);
DraggableBodyRow = ({ className, style, ...restProps }) => {
const { dataSource = [] } = this.state;
if (dataSource) {
const index = dataSource.findIndex(
(x) => x.key === restProps["data-row-key"]
);
// 处理嵌套子表格展开收起异常
const rowProps: any = { ...restProps, className, style };
return (
);
} else {
return <>>;
}
};
onSortEnd = ({ oldIndex, newIndex }) => {
const { dataSource } = this.state;
if (oldIndex !== newIndex) {
const newData = arrayMoveImmutable(
[].concat(dataSource),
oldIndex,
newIndex
).filter((el) => !!el);
//console.log('Sorted items: ', newData);
this.setState({ dataSource: newData });
}
};
loadData = async (
queryKey: string,
pageInfo: PageInfo,
cleanCache?: boolean
) => {
this.setState({ loading: true, errorText: undefined });
let { queryDataCache } = this.state;
const { translate } = this.context;
let { serverKey, tableProps, viewModels, ltmplConfig, loadDataCallback } = this.props;
let queryCache: Map;
if (cleanCache || !queryDataCache) {
queryCache = new Map();
this.setState({ aggregateVO: undefined });
} else {
queryCache = queryDataCache;
}
if (queryCache.has(pageInfo?.pageNo + "_" + pageInfo?.pageSize)) {
let cacheData = queryCache.get(
pageInfo?.pageNo + "_" + pageInfo?.pageSize
);
this.setState({
dataSource: cacheData.dataSource,
virtualEndPageNo: cacheData.pageInfo.virtualEndPageNo,
loading: false,
});
} else {
let queryData: QueryData = await HcserviceV3.requestQueryData(
serverKey,
queryKey,
pageInfo
);
if (queryData?.key !== queryKey) {
this.setState({ loading: false, errorText: translate("${查询异常}"), dataSource: [] });
if (loadDataCallback) loadDataCallback([]); // 请求数据回调函数
return;
} else {
let dataSource: object[] = [];
pageInfo = queryData?.pageInfo;
if (queryData?.entities) {
queryData.entities.forEach((item, index) => {
let row = {
key: item.code,
code: item.code, //增加code,为了删除操作
...item.fieldMap,
index,
};
dataSource.push(row);
});
}
let touchEnd = queryData?.touchEnd;
if (viewModels.includes("ganttChart") && ltmplConfig.gttSubOpenRatmplId) {
// 存在甘特图展示组件,并且存在树形结构,表格同步开启树形结构
dataSource = dataSource.map(item => ({ ...item, children: [] }));
}
//缓存数据
queryCache.set(pageInfo?.pageNo + "_" + pageInfo?.pageSize, {
dataSource,
pageInfo,
});
this.setState({
beforeSelectedRows: queryData.beforeSelectedRows,
dataSource,
virtualEndPageNo: pageInfo.virtualEndPageNo,
queryDataCache: queryCache,
touchEnd,
loading: false,
});
if (loadDataCallback) { // 请求数据回调函数
loadDataCallback(dataSource);
}
if (!tableProps.clickDisplayTotal) {
await this.queryTotal();
}
}
// }
}
};
pageTo = async (pageNo: number, pageSize: number) => {
const { onChangePage } = this.props;
// const { virtualEndPageNo } = this.state;
// let pageInfo = {
// pageNo,
// pageSize: pageSize ? pageSize : 10,
// virtualEndPageNo,
// };
//const { queryKey } = this.props;
//await this.loadData(queryKey.key, pageInfo);
onChangePage(pageNo, pageSize);
};
queryTotal = async () => {
const { queryKey, serverKey, queryTotal, onChangeAggregateVO } = this.props;
const { aggregateVO: stateAggregateVO } = this.state;
let aggregateVO;
if (stateAggregateVO && stateAggregateVO.queryKey == queryKey.key) {
return false;
} else {
if (queryTotal) {
aggregateVO = await queryTotal();
} else {
aggregateVO = await HcserviceV3.requestQueryAggregates(serverKey, queryKey.key);
}
onChangeAggregateVO && onChangeAggregateVO(aggregateVO);
this.setState({ aggregateVO });
}
};
getRowSelection = () => {
const {
columns,
onChangeRowSelection,
selectedRows,
maxSelectedRows,
primaryColumn,
} = this.props;
let { dataSource, beforeSelectedRows } = this.state;
let selectedRowKeys = [];
for (let row of selectedRows) {
selectedRowKeys.push(row.code);
}
const allRowKeys: string[] = [];
if (dataSource) {
for (let d of dataSource) {
allRowKeys.push(d.code);
}
}
let tmplMax = maxSelectedRows ? maxSelectedRows : 0;
if (beforeSelectedRows > 0) {
tmplMax = tmplMax - beforeSelectedRows;
}
const { translate } = this.context;
if (tmplMax <= -1) {
return null;
}
if (beforeSelectedRows > 0 && tmplMax <= 0) {
message.warning(translate("${已选超}"));
return null;
}
const rowSelection: TableRowSelection = {
fixed: true,
type: maxSelectedRows == 1 ? "radio" : "checkbox",
selectedRowKeys,
onChange: (selectedRowKeys, selectedRows) => {
if (tmplMax > 0 && selectedRowKeys.length > tmplMax) {
message.error(translate("${最多只能选择}") + " : " + tmplMax);
return;
}
let selectedRows_: SelectedRow[] = [];
let selectedDatas: DtmplData[] = [];
let titleColId = primaryColumn?.id;
if (!titleColId) {
columns.forEach((col) => {
if (col.title != "序号" && titleColId == null) {
titleColId = col.dataIndex;
return;
}
});
}
selectedRows.forEach((item) => {
selectedRows_.push({ code: item["code"], title: item[titleColId] });
selectedDatas.push(item);
});
if (onChangeRowSelection) {
onChangeRowSelection(selectedRows_, selectedDatas, allRowKeys);
}
},
};
return rowSelection;
};
getUnHidenDataSource = () => {
const { dataSource } = this.state;
const { hiddenRowCodes } = this.props;
let ds: object[] = [];
if (dataSource) {
for (let d of dataSource) {
if (!hiddenRowCodes.includes(d.code)) {
ds.push(d);
}
}
}
return ds;
};
mergeRowInCol(data, rowIdx, colIdx, mergeMp, calNum) {
const idx = rowIdx * calNum + colIdx;
// console.log(rowIdx, colIdx, mergeMp[idx]);
if (mergeMp[idx] !== undefined)
return {
rowSpan: mergeMp[idx].length,
};
return { rowSpan: 0 };
// return {};
}
sort_serial_number = new Date().getTime();
onChange(pagination, filters, sorter, extra) {
if (extra.action === "sort" && typeof sorter.column?.sorter !== "function") { // 非函数排序处理
let new_sort_serial_number = new Date().getTime();
if (new_sort_serial_number - this.sort_serial_number < 2000) {
const { translate } = this.context;
message.warning(translate("${系统忙,请稍后再试}"));
return;
} else {
this.sort_serial_number = new_sort_serial_number;
}
const extParams: Record = {};
const sortColumnData = JSON.parse(
JSON.stringify(this.props.sortColumnData)
);
if (sorter.order === "ascend") {
Object.assign(extParams, {
sortColIds: [sorter.field + "_" + "asc"],
});
} else if (sorter.order === "descend") {
Object.assign(extParams, {
sortColIds: [sorter.field + "_" + "desc"],
});
} else {
Object.assign(extParams, {
sortColIds: [],
});
}
this.props.doSearch(extParams);
} else if (typeof sorter.column?.sorter === "function") {
this.setState({ localSorter: sorter ? { field: sorter.field, order: sorter.order } : undefined });
}
}
// 更新树形结构子节点
updateChildrenById = (data, parentCode, childrenData) => {
const newData = data.map(node => {
const newNode = { ...node };
if (node.code === parentCode) {
// 找到目标节点,更新children
newNode.children = childrenData;
} else if (node.children && node.children.length > 0) {
// 递归更新子节点
newNode.children = this.updateChildrenById(node.children, parentCode, childrenData);
}
return newNode;
});
return newData;
}
// 懒加载子节点
getChildrenData = async (parentCode: string) => {
const { ltmplConfig, pageInfo } = this.props;
let { queryDataCache, dataSource } = this.state;
this.setState({ loading: true });
let res = await HcserviceV3.requestLtmplQueryTop(null, ltmplConfig?.gttSubOpenRatmplId, { mainCode: parentCode });
const childrenData = res?.entities?.map((r, index) => ({
key: r.code,
code: r.code,
...r.fieldMap,
index,
children: []
})) || [];
const newData = this.updateChildrenById(dataSource, parentCode, childrenData);
this.setState({ dataSource: newData, loading: false });
// 更新数据缓存
queryDataCache.set(pageInfo?.pageNo + "_" + pageInfo?.pageSize, {
dataSource,
pageInfo,
});
}
render() {
const {
pageInfo, queryKey,
columns,
viewModels,
summaryConfigs,
subtotalXColumn,
tableProps,
groupIColumns,
hiddenRowCodes,
columnConfigs,
serverKey,
cardListConfig,
ltmplConfig,
showView,
showPagination,
onChangeResize,
pageSizeOptions,
onChangePage,
showEmpty, expandable, hideOnSinglePage, bordered, showHeader
} = this.props;
//debugger
const { touchEnd, aggregateVO, loading, virtualEndPageNo, dataSource, errorText, localSorter } = this.state;
const isProSumarryTable = Boolean(subtotalXColumn);
// 是否是树形表格(存在甘特图视图展示且存在展开关系)
const isTreeTable = viewModels.includes("ganttChart") && ltmplConfig.gttSubOpenRatmplId;
const { translate } = this.context;
const {
proSummaryTableColumns,
proSummaryTableData,
} = SummaryBuilder.handleProSummaryTable({ subtotalXColumn, columns, data: this.getUnHidenDataSource(), translate, groupIColumns });
let current_cols = isProSumarryTable ? proSummaryTableColumns : columns ? columns : [];
let table_x = 20;
current_cols.forEach((c) => {
if (localSorter && localSorter.field === c["dataIndex"]) { // 存在本地排序
c["sortOrder"] = localSorter.order; // 设置页内排序
} else if (typeof c["sorter"] === "function") { // 其他页内排序清除
c["sortOrder"] = null;
}
table_x = table_x + (c.width ? c.width : 140);
});
let dat = this.getUnHidenDataSource();
const originData = isProSumarryTable ? proSummaryTableData : dat;
let summary = (pageData1) => {
return SummaryBuilder.summary({
translate, summaryConfigs,
pageData: dat, columns,
rowSelection: this.getRowSelection(), groupIColumns
});
}
// console.log("%crender data: ", "color: red", originData);
// console.log("%crender col: ", "color: red", current_cols);
if (ltmplConfig.displayTotal) { // 显示合计判断
const washOriginData = originData.map((i, idx) => {
const data = {};
current_cols.forEach((col) => {
data[col["dataIndex"]] = i[col["dataIndex"]];
});
data["1"] = idx;
return data;
});
// console.log("清洗原始数据: ", washOriginData);
// 一列中多行预处理
const dateOf2D = Array.from({ length: washOriginData.length })
.fill(0)
.map(() => Array.from({ length: current_cols.length }).fill(0));
washOriginData.forEach((row, rowIdx) => {
current_cols.forEach((col, colIdx) => {
dateOf2D[rowIdx][colIdx] = row[col["dataIndex"]];
});
});
console.log("dataOf2D: ", dateOf2D);
init(washOriginData.length * current_cols.length + 10);
for (let i = 1; i < dateOf2D.length; i++) {
let flag = false;
if (Array.isArray(groupIColumns) && groupIColumns.length > 0) {
groupIColumns.forEach(({ title, sourceId }) => {
if (
washOriginData[i][title] !== undefined &&
washOriginData[i][title] !== washOriginData[i - 1][title]
) {
return (flag = true);
}
if (
washOriginData[i][sourceId] !== undefined &&
washOriginData[i][sourceId] !== washOriginData[i - 1][sourceId]
) {
return (flag = true);
}
});
} else {
flag = true;
}
for (let j = 0; j < dateOf2D[i].length; j++)
if (dateOf2D[i][j] === "小计" || dateOf2D[i][j] === "合计") flag = true;
for (let j = 0; j < dateOf2D[i - 1].length; j++)
if (dateOf2D[i - 1][j] === "小计" || dateOf2D[i - 1][j] === "合计")
flag = true;
if (flag) continue;
for (let j = 0; j < dateOf2D[i].length; j++) {
if (dateOf2D[i][j] === dateOf2D[i - 1][j])
merge(i * dateOf2D[i].length + j, (i - 1) * dateOf2D[i].length + j);
}
}
const mergeMp = statistic();
//console.log("统计结果", mergeMp);
// 给 col 添加 mergeRowInCol
current_cols.forEach(
(col, colIdx) =>
(col.onCell = (_, rowIdx) =>
this.mergeRowInCol(_, rowIdx, colIdx, mergeMp, current_cols.length))
);
}
// 表格空状态显示
const renderEmptyText = () => {
if (showEmpty === false) {
return false;
}
if (errorText) {
return ;
}
if (!queryKey) {
return ;
}
return undefined;
}
return (
<>
{/*{viewModels.includes("table") ? (*/}
{/* */}
{/*) : (*/}
{/* ""*/}
{/*)}*/}
{viewModels.includes("table") ? (
{
if (expanded && !record.children?.length) { // 展开且没有子节点数据,请求子节点数据
this.getChildrenData(record.code);
}
}
} : expandable}
onChangeResize={onChangeResize}
bordered={bordered}
showHeader={showHeader}
/>
) : (
""
)}
{viewModels.includes("verticalList") ? (
) : (
""
)}
{/* showType */}
{viewModels.includes("cardList") ? (
) : (
""
)}
{viewModels.includes("RealTimeCard") ? : ""}
{viewModels.includes("ganttChart") ?
this.props.doSearch({})} serverKey={serverKey} sourceId={this.props.sourceId} loading={loading} dataSource={dataSource} ltmplConfig={ltmplConfig} errorText={errorText} getChildrenData={this.getChildrenData} /> : ""}
{viewModels.includes("calendar") ? : ""}
{showPagination ? : ""}
>
);
}
}
export default QueryTable;