import React, { ReactNode } from "react"; import { Button, Drawer, FormInstance, Modal, Popconfirm, Space, Card, } from "antd"; import { DtmplBaseProps, DtmplConfig, DtmplData, PageType, } from "../tmpl/interface"; import DtmplForm from "../form/dtmpl-form"; import HCDataSource from "../tmpl/hc-data-source"; import Units from "../units"; import HcserviceV3 from "../tmpl/hcservice-v3"; import Action from "../controls/action"; import Scrollbars from "react-custom-scrollbars"; import Draggable from 'react-draggable'; import DraggableModal from "./draggable-modal"; import TmplConfigAnalysis from "../tmpl/tmpl-config-analysis"; import { LocaleContext } from "../locale/LocaleProvider"; import { relValueFieldExtControlType } from "../controls/entry-control"; // 缓存 getSubDtmplData 的请求结果(防止多次请求) const subDtmplDataCache: Map = new Map(); interface ModalEditorProps extends DtmplBaseProps { height?: any; bodyWidth?: number | string; width?: number; open: boolean; onOk: (code: string, isContinueSave?: boolean) => void; onCancel: () => void; pageType: PageType; placement?: "top" | "right" | "bottom" | "left"; title?: ReactNode; extendButtons?: ReactNode[]; isCopy?: boolean; isAudit?: boolean; // 是否审计编辑页 } interface ModalEditorState { id?: string; queryingCode?: string; dtmplConfig?: DtmplConfig; loading?: boolean; serial?: number; dtmplData?: DtmplData; valueFieldMap?: { [key: string]: any }; isContinueSave?: boolean; // 是否连续保存 btnLoading?: string; // 按钮loading控制 drawerSize?: number | string; // 抽屉组件尺寸 } export default class DtmplEditPage extends React.PureComponent< ModalEditorProps, ModalEditorState > { formRef = React.createRef(); autoSaveTimer = -1000000000000000; autoSaveInterval = undefined; static contextType = LocaleContext; context: React.ContextType; onClickBody = (e) => { // console.log(e); //console.log("点击了我" + this.autoSaveTimer); this.autoSaveTimer = 0; }; static defaultProps = { showConfirm: true, height: "76vh", width: "76vw", bodyWidth: "100%", //antd modal forceRender: true, style: { maxWidth: "calc(100vw - 60px)", maxHeight: "calc(100vh - 50px)" }, okText: "确定", cancelText: "取消", pageType: "modal", placement: "left", }; state = { id: "modelDtmplEdit" + Units.getRandomNum(6), dtmplConfig: undefined, queryingCode: undefined, loading: false, serial: 1, dtmplData: undefined, valueFieldMap: {}, isContinueSave: false, // 是否连续保存 btnLoading: "", drawerSize: 0, isCopy: false, }; async componentDidMount() { const { height, width } = this.props; const placement = this.props.placement || 'left'; this.setState({ drawerSize: ["top", "bottom"].includes(placement) ? height : width }); if (this.props.open) { await this.loadConfigData(); } } async componentDidUpdate(prevProps) { const { dtmplConfig } = this.state; //debugger if (prevProps && prevProps != this.props) { if ( prevProps.sourceId != this.props.sourceId || prevProps.code != this.props.code || prevProps.addTmplId != this.props.addTmplId || !dtmplConfig || dtmplConfig == 'null' ) { await this.loadConfigData(); } else { await this.loadData(dtmplConfig); } } } componentWillUnmount(): void { if (this.autoSaveInterval) { clearInterval(this.autoSaveInterval); } } loadConfigData = async () => { const { sourceId, open, code, serverKey, addTmplId, isCopy } = this.props; this.setState({ loading: true, }); let dtmplConfig = undefined; if (code) { dtmplConfig = await HCDataSource.requestDtmplConfig( serverKey, sourceId, code ); } else { dtmplConfig = await HCDataSource.requestAddDtmplConfig( serverKey, sourceId, addTmplId ); } this.handleRelValueField(dtmplConfig); // 直接复制 if (dtmplConfig?.entity && dtmplConfig?.entity?.code == code) { let dtmplData = dtmplConfig.entity; dtmplConfig.entity = undefined; if (isCopy) { // 是否复制 this.setState({ dtmplData: { ...dtmplData, code: undefined }, loading: false }); } else { this.setState({ dtmplData, id: code, loading: false }); } setTimeout(() => this.handleBuildInFuncFields(), 300); } else { await this.loadData(dtmplConfig); } this.setState({ dtmplConfig, loading: false }); }; // 表单关联项secondCriterion处理start getSubDtmplData = async (valueField, code) => { const { serverKey } = this.props; let dtmplData = null; const cacheKey = `${valueField.extRefPageId || valueField.id}_${code.split("@R@")[0]}`; //缓存Key const cacheData = subDtmplDataCache.get(cacheKey); if (cacheData !== undefined) { // 存在缓存使用缓存,减少请求次数 dtmplData = cacheData; } else { if (valueField.extRefPageId) { // 存在extRefPageId(扩展关联页面),则优先使用extRefPageId(例如:枚举值无指向页面,使用扩展关联页面) const { entities } = await HcserviceV3.requestLtmplQueryTop(null, valueField.extRefPageId, { top: 1, secondCriterion: code.split("@R@")[0] }) || {}; dtmplData = entities?.[0]; } else { // 查询字段指向页面的数据 dtmplData = await HcserviceV3.requestDtmplData(serverKey, valueField.id, code.split("@R@")[0], null); } subDtmplDataCache.set(cacheKey, dtmplData || false); } if (!dtmplData) return null; const subField = valueField.subRelValueField; const subData = dtmplData.fieldMap[subField.id]; if (subField.subRelValueField && subData) { // 存在下级关联项 return this.getSubDtmplData(subField, subData); } return subData; } getSecondCriteria = async (field) => { const { parentFormInstance } = this.props; const { relValueField, relValueField3, baseCriteria = {}, relMinValueField, relMaxValueField } = field; const temForm = parentFormInstance || this.formRef.current; if (relValueField && temForm) { // 设置默认值或查询次条件 let relValueData = temForm.getFieldValue(relValueField.id); if (relValueField.subRelValueField && relValueData) { relValueData = await this.getSubDtmplData(relValueField, relValueData); } if (!relValueFieldExtControlType.includes(field.extControlType)) { field.defaultValue = relValueData; // 非关系型字段填充默认值 } else { field.baseCriteria = { ...(baseCriteria || {}), "secondCriterion": relValueData }; } field.configChanged = true; } if (relValueField3 && temForm) { // 设置查询三条件 let relValueData = temForm.getFieldValue(relValueField3.id); if (relValueField3.subRelValueField && relValueData) { relValueData = await this.getSubDtmplData(relValueField3, relValueData); } field.baseCriteria = { ...(field.baseCriteria || {}), "thirdCriterion": relValueData }; field.configChanged = true; } if (relMinValueField && temForm) { // 设置最小值 let relValueData = temForm.getFieldValue(relMinValueField.id); if (relMinValueField.subRelValueField && relValueData) { relValueData = await this.getSubDtmplData(relMinValueField, relValueData); } field.min = relValueData; field.configChanged = true; } if (relMaxValueField && temForm) { // 设置最大值 let relValueData = temForm.getFieldValue(relMaxValueField.id); if (relMaxValueField.subRelValueField && relValueData) { relValueData = await this.getSubDtmplData(relMaxValueField, relValueData); } field.max = relValueData; field.configChanged = true; } return field; } // 表单关联项secondCriterion处理end loadData = async (dtmplConfig: DtmplConfig) => { const { sourceId, code: propsCode, defaultDtmplData, open, serverKey, codeSource, isCopy } = this.props; if (!open) { return; } if (dtmplConfig?.autoSaveInterval && dtmplConfig?.autoSaveInterval > 0) { if (this.autoSaveInterval) { clearInterval(this.autoSaveInterval); } this.autoSaveInterval = setInterval(() => { if (this.autoSaveTimer >= dtmplConfig.autoSaveInterval) { //console.log('执行自动保存'); this.autoSaveTimer = -1000000000000000; this.setState({ btnLoading: "saveLoading" }); this.doSubmit(undefined); } else { this.autoSaveTimer = this.autoSaveTimer + 1; } }, 1000); } let code = propsCode; if (!code && codeSource) { code = await HcserviceV3.queryCode(sourceId, codeSource, serverKey); } if (code) { this.setState({ loading: true, queryingCode: code, dtmplData: undefined, }); const dtmplData_: DtmplData = await HcserviceV3.getDtmplData( dtmplConfig, serverKey, sourceId, code ); if ((!this.state.queryingCode || this.state.queryingCode == dtmplData_.code) && (!dtmplData_.sourceId || (this.props.sourceId == dtmplData_.sourceId))) { if (isCopy) { this.setState({ dtmplData: { ...dtmplData_, code: undefined }, id: undefined }); } else { this.setState({ dtmplData: dtmplData_, id: code }); } } this.setState({ loading: false, }); } else if (defaultDtmplData) { this.setState({ dtmplData: defaultDtmplData, loading: false, }); } else { this.setState({ dtmplData: { code: undefined, title: undefined, fieldMap: {}, arrayMap: {}, }, loading: false, }); } setTimeout(() => this.onValuesChange(), 300); }; /** * 处理表单关联项 * 匹配关联项的字段,实现值更新关联字段值变化 */ handleRelValueField = (dtmplConfig: DtmplConfig) => { if (!dtmplConfig) { return; } const { groups } = dtmplConfig; const valueFieldMap = groups.reduce((total, item) => { if (item.fields) { item.fields.forEach(field => { if (field.relValueField) { // 关联取值字段 const temArr = total[field.relValueField.id] || []; const isSameGroup = item.fields.some(f => f.id === field.relValueField.id); const temField = isSameGroup ? field : item; const isItem = temArr.find(r => r.id === temField.id); if (!isItem) { total[field.relValueField.id] = [...temArr, temField]; } } if (field.relValueField3) { // 关联取值字段扩1 const temArr = total[field.relValueField3.id] || []; const isSameGroup = item.fields.some(f => f.id === field.relValueField3.id); const temField = isSameGroup ? field : item; const isItem = temArr.find(r => r.id === temField.id); if (!isItem) { total[field.relValueField3.id] = [...temArr, temField]; } } }) } return total; }, {}); this.setState({ valueFieldMap }); }; //关联取值:根据 parentFormInstance / this.formRef 完善 dtmplConfig handleBuildInFuncFields = async (tDtmplConfig?: DtmplConfig) => { const dtmplConfig = tDtmplConfig || this.state.dtmplConfig; if (dtmplConfig) { if (!dtmplConfig.buildInFuncFields) { dtmplConfig.buildInFuncFields = TmplConfigAnalysis.buildInFuncFields(dtmplConfig); } dtmplConfig.buildInFuncFields = await Promise.all(dtmplConfig.buildInFuncFields.map(field => this.getSecondCriteria(field))); } } onValuesChange = (changedValues?: any, allValues?: any) => { const { dtmplData, valueFieldMap, dtmplConfig } = this.state; this.handleBuildInFuncFields(); const { groups } = dtmplConfig; const changeValKey = Object.keys(changedValues || {})[0]; const clearValues = {}; // 清空关联字段值 if (changeValKey && valueFieldMap[changeValKey]) { // 处理关联字段值变化, 表单值变化,处理关联字段值为空 const temArrayMap = valueFieldMap[changeValKey].reduce((total, item) => { if (groups.some(g => g.id === item.id)) { total[item.id] = []; // 清空关联字段组 } else { clearValues[item.id] = undefined; } return total; }, {}); this.setState({ dtmplData: { ...dtmplData, fieldMap: { ...allValues, ...clearValues }, arrayMap: { ...dtmplData.arrayMap, ...temArrayMap } } }); } this.setState({ serial: this.state.serial + 1 }); }; doSubmit = (actionId?: number, codes?: string[], params?: object, isContinue?: boolean) => { const { mainCode } = this.props; //if (actionId) { this.formRef.current.setFieldsValue({ actionId: actionId }); // } if (mainCode) { this.formRef.current.setFieldsValue({ mainCode: mainCode }); } if (params) { this.formRef.current.setFieldsValue(params); } this.formRef.current.submit(); this.setState({ isContinueSave: isContinue }); }; getFooter = () => { const { onCancel, serverKey } = this.props; const { dtmplData, serial, loading, btnLoading } = this.state; const footerButtons = []; const { dtmplConfig } = this.state; const { saveBtnTitle, continueSaveBtnTitle } = dtmplConfig || {}; const { translate } = this.context; if (dtmplConfig?.buttons?.includes("dtmplSave")) { if (continueSaveBtnTitle) { footerButtons.unshift( ); } else { footerButtons.unshift( ); } } //处理action if (dtmplConfig) { dtmplConfig.actions.forEach((ac, index) => { footerButtons.unshift( { this.setState({ btnLoading: `actionLoading${index}` }); this.doSubmit(...val); }} loading={loading || btnLoading === `actionLoading${index}`} /> ); }); } footerButtons.unshift( ); return footerButtons; }; onFinish = (code) => { const { code: propsCode } = this.props; const { isContinueSave } = this.state; this.setState({ loading: false, btnLoading: "" }); if (code) { if (propsCode && isContinueSave) { this.loadConfigData(); } this.props.onOk(code, isContinueSave); } } render() { const { height, onCancel, sourceId, open, mainCode, code, width, pageType, maxColsOnRow, title, serverKey, parentFormInstance, isAudit } = this.props; const { dtmplConfig, id, dtmplData, valueFieldMap, drawerSize } = this.state; const placement = this.props.placement || "left"; const maxSize = ["top", "bottom"].includes(placement) ? document.documentElement.clientHeight : document.documentElement.clientWidth * 0.9; let title1 = title ? title : dtmplConfig ? dtmplConfig.title : ""; const { translate } = this.context; //判断是不是 字符串 if (typeof title1 === "string") { title1 = translate("${" + title1 + "}"); } return ( <> {pageType === "modal" ? ( //
} >
//
) : pageType === "drawer" ? ( this.setState({ drawerSize: newSize })) }} size={drawerSize} maxSize={maxSize} closable={true} destroyOnHidden={true} mask={false} onClose={onCancel} open={open} style={{ border: "2px solid #d9d9d9" }} extra={{this.getFooter()}} styles={{ body: { minWidth: width ? width - 4 : 0 } }} >
) : ( )} ); } }