diff --git a/.umirc.ts b/.umirc.ts index 32cf163..2a964c8 100644 --- a/.umirc.ts +++ b/.umirc.ts @@ -4,7 +4,11 @@ export default defineConfig({ routes: [ { path: '/', redirect: '/login' }, { path: '/login', component: '@/routes/login/login' }, - { path: '/indexPage', component: '@/routes/indexPage' }, + { + path: '/indexPage', + component: '@/routes/indexPage', + routes: [{ path: '/indexPage/CommonList' }], + }, ], npmClient: 'pnpm', diff --git a/package.json b/package.json index 4ef02a2..37f6e3f 100644 --- a/package.json +++ b/package.json @@ -11,10 +11,21 @@ "dependencies": { "@ant-design/compatible": "^1.1.2", "@ant-design/icons": "^5.6.1", + "@js-preview/docx": "^1.6.4", + "@js-preview/excel": "^1.7.14", "antd": "^5.24.3", + "antd-mobile": "2.3.4", "antd-v4": "npm:antd@4.24.16", + "braft-editor": "^2.3.9", + "immutability-helper": "^3.1.1", "lodash": "^4.17.21", "moment": "^2.30.1", + "react-dnd": "^14.0.5", + "react-dnd-html5-backend": "^14.1.0", + "react-highlight-words": "^0.21.0", + "react-pdf": "^9.2.1", + "react-resizable": "^3.0.5", + "react-sortable-hoc": "^2.0.0", "umi": "^4.4.6" }, "devDependencies": { diff --git a/src/components/Common/AffixMenu.js b/src/components/Common/AffixMenu.js new file mode 100644 index 0000000..5c0ff0b --- /dev/null +++ b/src/components/Common/AffixMenu.js @@ -0,0 +1,507 @@ +/* eslint-disable */ +import React, { Component } from 'react'; +import { Affix, Table, Checkbox, Input, Select, message, Tabs, Alert } from 'antd-v4'; +import styles from '@/index.less'; +import lodash from 'lodash'; +import * as commonUtils from '@/utils/utils'; +import config from '@/utils/config'; +import * as commonFunc from '@/components/Common/commonFunc'; +import AntdDraggableModal from '@/components/Common/AntdDraggableModal'; +import SvgIcon from '../SvgIcon'; + +const { Option } = Select; +const { TabPane } = Tabs; + +class AffixMenuComponent extends Component { + constructor(props) { + super(props); + const UserPersonalization = commonFunc.showMessage(props.app.commonConst, 'UserPersonalization');/* 用户个性化配置 */ + this.state = { + top: 10, + modalPanel: { title: UserPersonalization }, + modalVisible: false, + modalData: [], + modalContent: [], /* 面板展示内容 */ + modalContentData1: [], + modalContentData2: [], + modalContentData3: [], + modalContentData4: [], + modalContentData5: [], + modalContentData6: [], + modalContentData7: [], + modalContentData8: [], + modalContentData9: [], + modalContentData10: [], + roleShow: '', /* 角色 */ + roleSelectData: '', /* 选择的角色 */ + }; + } + + onInit() { + const sActiveId = this.props.app.currentPane.formId; + const { formSrcRoute } = this.props; + const url = `${config.server_host}configform/getConfigformData/${sActiveId}?sModelsId=${sActiveId}&sName=${formSrcRoute}`; + const { token } = this.props.app; + const options = { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + authorization: token, + }, + }; + + const originData = {}; + fetch(url, options).then(response => response.json()).then((json) => { + if (json.code === 1) { + const data = json.dataset.rows[0]; + this.setState({ modalData: data }); + Object.keys(data).forEach((child) => { + const spitArr = commonUtils.isNotEmptyObject(child) ? child.split('_') : []; + /* 数据增加key属性用于table展示 */ + for (const item of data[child]) { + item.key = item.sId; + } + originData[`modalContentData_${spitArr[1]}`] = data[child]; + }); + this.setState({ ...originData }, () => { this.handleClick(); }); + } else { + // console.log(json.msg); + } + }); + if (this.props.app.userinfo.sType === 'sysadmin') { + const chooseRole = commonFunc.showMessage(this.props.app.commonConst, 'chooseRole');/* 选择角色 */ + const chooseOneRole = commonFunc.showMessage(this.props.app.commonConst, 'chooseOneRole');/* 请选择一个角色 */ + const roleUrl = `${config.server_host}configform/getLogininfosupplygroup?sModelsId=${sActiveId}&sName=${formSrcRoute}`; + /* 获取角色下拉 */ + fetch(roleUrl, options).then(response => response.json()).then((json) => { + if (json.code === 1) { + const data = json.dataset.rows; + const oPtinon = []; + for (const child of data) { + oPtinon.push(); + } + const roleShow = ( + + {chooseRole} + + + + )} + type="info" + showIcon + /> + ); + this.setState({ roleShow }); + } else { + // console.log(json.msg); + } + }); + } + } + + onCheckChange = (e) => { + this.setState({ + indeterminate: false, + checkValue: e.target.checked ? true : '', + }); + }; + + onCheckAll = (e, name, count, configId) => { + const data = JSON.parse(JSON.stringify(this.state.modalData[name] || [])); + const temp = JSON.parse(JSON.stringify(this.state[`modalContentData${count}`] || [])); + const config = JSON.parse(JSON.stringify(this.state[`modalContentData_${configId}`] || [])); + data.forEach((item, idx) => { + data[idx].bVisible = e.target.checked; + }); + temp.forEach((item, idx) => { + temp[idx].bVisible = e.target.checked; + }); + config.forEach((item, idx) => { + config[idx].bVisible = e.target.checked; + }); + this.setState({ + modalData: { ...this.state.modalData, [name]: data }, + [`modalContentData${count}`]: temp, + [`modalContentData_${configId}`]: config, + }); + } + + handleClick=() => { + const { sModelsId } = this.props; + const addStateData = {}; + const sessionKeys = Object.keys(sessionStorage); /* 找到配置 */ + for (const key of sessionKeys) { /* 通过缓存中key的name匹配config配置,通过config配置获取配置sId,通过配置sId在state中找到对应的数据集 */ + const keyArr = commonUtils.isNotEmptyObject(key) ? key.split('_') : []; + if (commonUtils.isNotEmptyArr(keyArr) && sModelsId === keyArr[0]) { /* 防止多页签name名重复导致缓存匹配错误 */ + const tableSid = keyArr[1]; /* 取表名称 */ + if (tableSid) { + let { [`modalContentData_${tableSid}`]: tableData } = this.state; + if (addStateData[`modalContentData_${tableSid}`]) { + tableData = addStateData[`modalContentData_${tableSid}`]; + } else { + tableData = JSON.parse(JSON.stringify(tableData)); + } + + /* 取缓存中的数据 */ + if (commonUtils.isJSON(sessionStorage[key]) && JSON.parse(sessionStorage[key]).length > 0) { + const sessionData = JSON.parse(sessionStorage[key]); + if (commonUtils.isNotEmptyArr(sessionData) && commonUtils.isNotEmptyArr(tableData) && key.indexOf('headerColumns') === -1) { + tableData.forEach((item, index) => { + const iIndex = sessionData.findIndex(session => session.dataIndex === item.sName); + if (iIndex > -1) { + const addState = {}; + if (addState.iFitWidth !== sessionData[iIndex].width) { + addState.iFitWidth = sessionData[iIndex].width; + tableData[index] = { ...tableData[index], ...addState }; + } + } + }); + } + if (key === `${sModelsId}_${tableSid}_headerColumns` || key === `${sModelsId}_${tableSid}_info_headerColumns`) { + const sessionData = JSON.parse(sessionStorage[key]); + const iOrderSort = tableData.map(item => item.iOrder).sort((a, b) => a - b); + const obj = {}; + sessionData.forEach((item, idx) => { + obj[item] = iOrderSort[idx]; + }); + tableData.forEach((item, idx) => { + tableData[idx].iOrder = obj[item.sName]; + }); + tableData.sort((a, b) => a.iOrder - b.iOrder) + tableData.forEach((item, idx) => { + tableData[idx].iOrder = idx + 1; + }) + } + addStateData[`modalContentData_${tableSid}`] = tableData; + } + } + } + } + this.setState({ ...addStateData }); + }; + + handlePpopUpPaneCancel=() => { + this.setState({ modalVisible: false }); + }; + + handleChange=(value, count, record, name) => { + const data = JSON.parse(JSON.stringify(this.state[`modalContentData_${count}`])); + const dataMap = data.filter(item => (item.key === record.key))[0]; + if (dataMap !== undefined) { + dataMap[`${name}`] = value; + } + this.setState({ [`modalContentData_${count}`]: data }); + }; + + handleSelectChange=(value) => { + /* 调用接口 */ + const { formSrcRoute } = this.props; + this.setState({ roleSelectData: value }); + const sActiveId = this.props.app.currentPane.formId; + const url = `${config.server_host}configform/getConfigformData/${sActiveId}?roleSelectId=${value}&&sModelsId=${sActiveId}&sName=${formSrcRoute}`; + const { token } = this.props.app; + const options = { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + authorization: token, + }, + }; + fetch(url, options).then(response => response.json()).then((json) => { + if (json.code === 1) { + const data = json.dataset.rows[0]; + this.setState({ modalData: data }); + Object.keys(data).forEach((child) => { + const spitArr = commonUtils.isNotEmptyObject(child) ? child.split('_') : []; /* 取菜单ID */ + /* 数据增加key属性用于table展示 */ + for (const item of data[child]) { + item.key = item.sId; + } + this.setState({ [`modalContentData_${spitArr[1]}`]: data[child] }); + }); + } else { + // console.log(json.msg); + } + }); + }; + + handleOk=() => { + const { formSrcRoute } = this.props; + const sActiveId = this.props.app.currentPane.formId; + const url = `${config.server_host}configform/sHandleConfigform?sModelsId=${sActiveId}&sName=${formSrcRoute}`; + const { token } = this.props.app; + const { roleShow, roleSelectData, modalData } = this.state; + // const pleaseChooseRole = commonFunc.showMessage(this.props.app.commonConst, 'pleaseChooseRole');/* 请选择角色 */ + // if (roleShow !== '' && roleSelectData === '') { + // message.warning(pleaseChooseRole); + // return; + // } + const submitData = {}; + // let count = 1; + let num = 0; + + Object.keys(modalData).forEach((item) => { + const splitArr = commonUtils.isNotEmptyObject(item) && commonUtils.isNotEmptyArr(item.split('_')) ? item.split('_') : []; + const configId = commonUtils.isNotEmptyArr(splitArr) ? splitArr[1] : ''; + const { [`modalContentData_${configId}`]: tableData } = this.state; + if (commonUtils.isNotEmptyArr(tableData) && tableData.length > 0) { + num = 0; + for (const child of tableData) { + if (num === 0) { + submitData[`${child.sParentId}`] = []; + } + // if (child.bVisible) { + // submitData[`${child.sParentId}`].push(child); + // } + submitData[`${child.sParentId}`].push(child); + num += 1; + } + } + }); + + let value = ''; + if (roleShow !== '') { + value = { + handleType: 'group', + sJurisdictionClassifyId: roleSelectData, + handleData: submitData, + bDefault: commonUtils.isEmpty(roleSelectData) ? true : this.state.checkValue, /* bDefault为true代表更新到后台配置库里 */ + }; + } else { + value = { + handleType: 'user', + handleData: submitData, + }; + } + const options = { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + authorization: token, + }, + body: JSON.stringify(value), + }; + const { dispatch } = this.props; + fetch(url, options).then(response => response.json()).then((json) => { + if (json.code === 1) { + message.success(json.msg); + + // 清除缓存 + if(sessionStorage !== undefined) { + const sessionKeys = Object.keys(sessionStorage); /* 找到配置 */ + for (const key of sessionKeys) { + if(key !== 'feedbackBtnRecord') { + sessionStorage.removeItem(key); + } + } + } + + this.handlePpopUpPaneCancel(); + } else if (json.code === -2) { + dispatch({ type: 'app/throwError', payload: json }); + } + }); + }; + + renderColumns=(text, name, count, record) => { + if (name === 'bVisible' || name === 'bReadonly') { + return this.handleChange(e.target.checked, count, record, name)} />; + } else { + let flag = false; + if (name === 'showName' || name === 'sName') { + flag = true; + } + return this.handleChange(e.target.value, count, record, name)} />; + } + }; + + openModal = () => { + this.setState({ + modalVisible: true, + }) + this.onInit(); + } + + render() { + const { modalData, roleShow } = this.state; + const { app, sTabId, sModelsType } = this.props; + // const { userinfo } = app; + const pane = app.panes.filter(paneTmp => paneTmp.key === sTabId)[0]; + const modalContent = []; + let count = 1; + let checkBoxShow = ''; + let checkAll = ''; + const columniOrder = commonFunc.showMessage(app.commonConst, 'columniOrder');/* 排序 */ + const columnShowName = commonFunc.showMessage(app.commonConst, 'columnShowName');/* 显示名 */ + // const columnChinese = commonFunc.showMessage(app.commonConst, 'columnChinese');/* 显示名 */ + // const columnEnglish = commonFunc.showMessage(app.commonConst, 'columnEnglish');/* 显示名 */ + // const columnBig5 = commonFunc.showMessage(app.commonConst, 'columnBig5');/* 显示名 */ + const columniFitWidth = commonFunc.showMessage(app.commonConst, 'columniFitWidth');/* 宽度 */ + const columnbVisible = commonFunc.showMessage(app.commonConst, 'columnbVisible');/* 是否显示 */ + const columnsName = commonFunc.showMessage(app.commonConst, 'columnsName');/* 字段名 */ + const isDefault = commonFunc.showMessage(app.commonConst, 'isDefault');/* 是否设置默认 */ + // eslint-disable-next-line no-unused-vars + Object.keys(modalData).forEach((child, i) => { + const splitArr = commonUtils.isNotEmptyObject(child) && commonUtils.isNotEmptyArr(child.split('_')) ? child.split('_') : []; + const configName = commonUtils.isNotEmptyArr(splitArr) ? splitArr[0] : ''; + const configId = commonUtils.isNotEmptyArr(splitArr) ? splitArr[1] : ''; + let childTable = ''; + let dataSource = []; + if (commonUtils.isNotEmptyObject(configId)) { /* 从缓存中取宽度 */ + dataSource = this.state[`modalContentData_${configId}`]; + } else { + dataSource = this.state[`modalContentData${count}`]; + } + const columns = [{ + title: columniOrder, + dataIndex: 'iOrder', + render: (text, record) => this.renderColumns(text, 'iOrder', configId, record), + width: 40, + }, { + title: columniFitWidth, + dataIndex: 'iFitWidth', + render: (text, record) => this.renderColumns(text, 'iFitWidth', configId, record), + width: 40, + }, { + title: columnShowName, + dataIndex: 'showName', + render: (text, record) => this.renderColumns(text, 'showName', configId, record), + width: 100, + }]; + if (this.props.app.userinfo.sType === 'sysadmin' || true) { /* 管理员显示字段名 */ + columns.push({ + title: columnsName, + dataIndex: 'sName', + render: (text, record) => this.renderColumns(text, 'sName', configId, record), + width: 80, + }); + } + if (this.props.app.userinfo.sType === 'sysadmin' || true) { /* 管理员设置列是否显示 */ + columns.push({ + title: columnbVisible, + dataIndex: 'bVisible', + render: (text, record) => this.renderColumns(text, 'bVisible', configId, record), + width: 80, + }); + } + if (this.props.app.userinfo.sType === 'sysadmin') { /* 配置选择框 */ + // checkBoxShow = {isDefault}  ; + checkBoxShow = ''; + let visible = 0; + const len = dataSource ? dataSource.length : 0; + for (let i = 0; i < len; i += 1) { + if (dataSource[i].bVisible) { + visible += 1; + } + } + checkAll = 全选   this.onCheckAll(e, child, count, configId)} />; + } + if (this.props.app.userinfo.sType === 'sysadmin' || true) { /* 管理员设置列是否可修改 */ + columns.push({ + title: '是否只读', + dataIndex: 'bReadonly', + render: (text, record) => this.renderColumns(text, 'bReadonly', configId, record), + width: 80, + }); + } + if (this.props.app.userinfo.sType === 'sysadmin' || true) { /* 管理员设置列颜色 */ + columns.push({ + title: '字体颜色', + dataIndex: 'sFontColor', + render: (text, record) => this.renderColumns(text, 'sFontColor', configId, record), + width: 80, + }); + } + + /* 动态列解析 将字段表头换成 动态列返的 */ + // if (!(commonUtils.isNotEmptyObject(sModelsType) && !sModelsType.includes('dynamicList'))) { + // const { slaveConfig } = this.props; + // const columnConfig = commonUtils.isNotEmptyObject(slaveConfig) ? slaveConfig.gdsconfigformslave.filter(item => item.bVisible && item.sName !== '' && item.showName !== '' && !(item.sControlName !== '' && item.sControlName.indexOf('Btn') > -1)) : []; + // /* 动态列 需要将中文名称替换掉 */ + // if (commonUtils.isNotEmptyArr(columnConfig) && dataSource && dataSource.length === columnConfig.length) { + // columnConfig.forEach((item, iIndex) => { + // // dataSource[iIndex].sName = item.sName; + // dataSource[iIndex].showName = item.showName; + // dataSource[iIndex].sChinese = item.sChinese; + // }); + // } + // } + + const dataSource_dep = lodash.cloneDeep(dataSource); + if (dataSource_dep && dataSource_dep.length) { + let min = 0; + for (let i = 0; i < dataSource_dep.length - 1; i += 1) { + min = i; + for (let j = i + 1; j < dataSource_dep.length; j += 1) { + if (Number(dataSource_dep[min].iOrder) > Number(dataSource_dep[j].iOrder)) { + const temp = dataSource_dep[min]; + dataSource_dep[min] = dataSource_dep[j]; + dataSource_dep[j] = temp; + } + } + } + } + + childTable = ( + +
+ {checkBoxShow} +     + {checkAll} + + + + ); + modalContent.push(childTable); + count += 1; + }); + return ( +
+ +
+ + {(pane?.notCurrentPane ? false : this.state.modalVisible) ? + 0 ? this.state.modalPanel.title : ''} + visible={pane?.notCurrentPane ? false : this.state.modalVisible} + onCancel={this.handlePpopUpPaneCancel.bind(this)} + onOk={this.handleOk.bind(this)} + width={1000} + > +
+ { + roleShow !== '' ? roleShow : '' + } +
+ + {modalContent} + +
+
+
+ : ''} +
+
+
+ ); + } +} + +export default AffixMenuComponent; diff --git a/src/components/Common/AntdDraggableDiv.js b/src/components/Common/AntdDraggableDiv.js new file mode 100644 index 0000000..03c2f2c --- /dev/null +++ b/src/components/Common/AntdDraggableDiv.js @@ -0,0 +1,56 @@ +import React, { Component } from 'react'; +import styles from '../../index.less'; + +export default class AntdDraggableDiv extends Component { + constructor(props) { + super(props); + this.state = { + translateX: 0, + translateY: 0, + }; + this.moving = false; + this.lastX = null; + this.lastY = null; + window.onmouseup = e => this.onMouseUp(e); + window.onmousemove = e => this.onMouseMove(e); + } + onMouseDown(e) { + e.stopPropagation(); + this.moving = true; + } + + onMouseUp() { + this.moving = false; + this.lastX = null; + this.lastY = null; + } + + onMouseMove(e) { + if (this.moving) { + this.onMove(e); + } + } + + onMove(e) { + if (this.lastX && this.lastY) { + const dx = e.clientX - this.lastX; + const dy = e.clientY - this.lastY; + this.setState({ translateX: this.state.translateX + dx, translateY: this.state.translateY + dy }); + } + this.lastX = e.clientX; + this.lastY = e.clientY; + } + render() { + const { children, draggableDivClassName } = this.props; + return ( +
this.onMouseDown(e)} + style={{ transform: `translateX(${this.state.translateX}px)translateY(${this.state.translateY}px)` }} + > + {children} +
+
+ ); + } +} diff --git a/src/components/Common/AntdDraggableModal.js b/src/components/Common/AntdDraggableModal.js new file mode 100644 index 0000000..0d0cc4b --- /dev/null +++ b/src/components/Common/AntdDraggableModal.js @@ -0,0 +1,186 @@ +import React from 'react'; +import { Modal } from 'antd'; +import './AntdDraggableModal/antDraggle.less'; + + +class AntDraggableModal extends React.Component { + constructor(props) { + super(props); + this.simpleClass = Math.random().toString(36).substring(2); + this.state = { + isDrop: false, + // eslint-disable-next-line react/no-unused-state + offsetLeft: 0, + // eslint-disable-next-line react/no-unused-state + offsetTop: 0, + realizeHeight: 0, + modalHeight: 0, + }; + this.deltaX = 0; + this.deltaY = 0; + this.contain = {}; + this.antModal = {}; + } + + // eslint-disable-next-line react/sort-comp + handleMove = (event) => { + if (this.state.isDrop) { + this.antModal.style.margin = 0; + this.antModal.style.padding = 0; + const left = event.pageX - this.deltaX; + const top = event.pageY - this.deltaY; + // if (left < 0) { + // left = 0; + // } else if (left > (document.offsetWidth - this.antModal.offsetWidth)) { + // left = document.offsetWidth - this.antModal.offsetWidth; + // } + // if (top < 0) { + // top = 0; + // } else if (top > (document.offsetHeight - this.antModal.offsetHeight)) { + // top = document.offsetHeight - this.antModal.offsetHeight; + // } + this.antModal.style.left = `${left}px`; + this.antModal.style.top = `${top}px`; + } + }; + + addResizeListener = () => { + document.addEventListener('mousedown', this.handleResize); + } + + handleResize = (downEl) => { + const ableList = ['resize-s', 'resize-sw', 'resize-se']; + if (ableList.indexOf(downEl.target.className) === -1) { + return; + } + // const modalContent = document.getElementsByClassName('ant-modal-content')[0]; + const modalContent = downEl.target.parentNode.parentNode; + const modalContentHeight = modalContent.offsetHeight; + if (!this.state.modalHeight) { + this.setState({ + modalHeight: modalContentHeight, + }); + } + const modalContentWidth = modalContent.offsetWidth; + const modalContentLeft = modalContent.offsetLeft; + let resizedHeight = 0; + let resizeYPx = 0; + let resizeXPx = 0; + document.onmousemove = (moveEvent) => { + resizeYPx = moveEvent.pageY - downEl.pageY; + resizeXPx = moveEvent.pageX - downEl.pageX; + resizedHeight = this.state.modalHeight + this.state.realizeHeight + resizeYPx; + if (resizedHeight <= this.state.modalHeight) { + return false; + } + switch (downEl.target.className) { + case 'resize-s': + modalContent.style.height = `${resizedHeight}px`; + break; + case 'resize-sw': + modalContent.style.height = `${resizedHeight}px`; + modalContent.style.width = `${modalContentWidth - resizeXPx}px`; + modalContent.style.left = `${modalContentLeft + resizeXPx}px`; + break; + case 'resize-se': + modalContent.style.height = `${resizedHeight}px`; + modalContent.style.width = `${modalContentWidth + resizeXPx}px`; + break; + default: + break; + } + }; + document.onmouseup = () => { + document.onmousemove = null; + document.onmouseup = null; + setTimeout(() => { + // eslint-disable-next-line no-unused-expressions + window.onSetTableKey && window.onSetTableKey(); + }, 1000); + if (this.state.realizeHeight + resizeYPx <= 0 && this.props.onSaveState) { + this.setState({ + realizeHeight: 0, + }); + this.props.onSaveState({ realizeHeight: this.state.realizeHeight }); + return; + } + if (this.props.onSaveState && resizeYPx !== 0) { + this.setState((prev) => { + return { + realizeHeight: prev.realizeHeight + resizeYPx, + }; + }); + this.props.onSaveState({ realizeHeight: this.state.realizeHeight }); + } + }; + } + + initialEvent = (visible) => { + const { title } = this.props; + if (title && visible) { + setTimeout(() => { + window.removeEventListener('mouseup', this.removeUp, false); + // eslint-disable-next-line prefer-destructuring + this.contain = document.getElementsByClassName(this.simpleClass)[0]; + // eslint-disable-next-line prefer-destructuring + this.header = this.contain.getElementsByClassName('ant-modal-header')[0]; + this.header.style.cursor = 'all-scroll'; + // eslint-disable-next-line prefer-destructuring + this.antModal = this.contain.getElementsByClassName('ant-modal')[0]; + this.header.onmousedown = (e) => { + const disx = e.pageX - this.antModal.offsetLeft; + const disy = e.pageY - this.antModal.offsetTop; + this.deltaX = disx; + this.deltaY = disy; + this.setState({ + isDrop: true, + }); + document.body.onselectstart = () => false; + window.addEventListener('mousemove', this.handleMove.bind(this), false); + }; + window.addEventListener('mouseup', this.removeUp, false); + this.addResizeListener(); + }, 0); + } + }; + + removeUp = () => { + this.setState({ isDrop: false }); + document.body.onselectstart = () => true; + }; + + componentDidMount() { + const { visible = false, open = false } = this.props; + this.initialEvent(open || visible); + } + + componentWillUnmount() { + window.removeEventListener('mousedown', this.handleResize, false); + window.removeEventListener('mouseup', this.removeUp, false); + if (this.props.onSaveState) { + this.props.onSaveState({ realizeHeight: 0 }); + } + } + + render() { + const { + children, wrapClassName, pageLoading, forbidResize, ...other + } = this.props; + + const wrapModalClassName = wrapClassName ? `${wrapClassName} ${this.simpleClass}` : `${this.simpleClass}`; + return ( + + {children} + {!forbidResize &&
} + {!forbidResize &&
} + {!forbidResize &&
} + + ); + } +} +export default AntDraggableModal; diff --git a/src/components/Common/AntdDraggableModal/antDraggle.less b/src/components/Common/AntdDraggableModal/antDraggle.less new file mode 100644 index 0000000..54c933c --- /dev/null +++ b/src/components/Common/AntdDraggableModal/antDraggle.less @@ -0,0 +1,29 @@ +:global { + .ant-modal-content{ + .resize-s{ + width: 100%; + height: 5px; + position: absolute; + left: 0; + bottom: 0; + z-index: 10; + cursor: s-resize; + } + .resize-sw, .resize-se{ + width: 10px; + height: 10px; + position: absolute; + bottom: 0; + z-index: 10; + } + .resize-sw{ + left: 0; + cursor: sw-resize; + } + .resize-se{ + right: 0; + cursor: se-resize; + } + } +} + diff --git a/src/components/Common/CommonBase.js b/src/components/Common/CommonBase.js new file mode 100644 index 0000000..e34052f --- /dev/null +++ b/src/components/Common/CommonBase.js @@ -0,0 +1,3436 @@ +/* eslint-disable */ +/* eslint-disable prefer-destructuring */ +/** + * Created by mar105 on 2019-02-15. + */ + +import React, { Component } from 'react'; +import { message } from '@/utils/common/message'; +import moment from 'moment'; +import lodash from 'lodash'; +import commonConfig from '../../utils/config'; +import * as commonUtils from '../../utils/utils'; +import * as commonServices from '../../services/services'; +import * as commonFunc from './commonFunc'; +import * as commonBusiness from './commonBusiness'; /* 通用单据方法 */ +import instructSet from "@/components/Common/CommonInstructSet"; + +export default (ChildComponent) => { + return class extends Component { + constructor(props) { + super(props); + this.state = { + pageLoading: true, + token: props.routing ? props.formRoute === '/indexOee' ? props.app.token : '' : props.app.token, // /indexOee为oee报产页面 + sTabId: this.handleConfigValue('key', props.formRoute), // type无论是indexoee和一般的都使用eles + sSrcModelsId: props.app.currentPane.sSrcModelsId, /* 获取配置数据用的modelId */ + sModelsId: props.routing ? props.sModelsId : (commonUtils.isNotEmptyStr(props.formRoute) && props.formRoute.indexOf('/indexOee') > -1) ? props.sModelsId : this.handleConfigValue('formId'), /* 获取配置数据用的modelId */ + formRoute: props.routing ? props.formRoute : (commonUtils.isNotEmptyStr(props.formRoute) && props.formRoute.indexOf('/indexOee') > -1) ? props.formRoute : this.handleConfigValue('route'), /* 组件名: 路由名称 */ + formSrcRoute: props.routing ? props.routing.pathname.replace('/', '') : commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase() === '/loginoee' ? '/commonAuto' : '', + sModelsType: this.handleConfigValue('sModelsType', props.formRoute), /* 组件名: 路由名称 */ + bFastOrderView: this.handleConfigValue('bFastOrderView'), /* 是否显示快速下单 */ + formData: [], /* 所有配置 */ + gdsformconst: [], /* 获取配置常量 */ + gdsjurisdiction: [], /* 获取配置权限 */ + currentId: (commonUtils.isNotEmptyStr(props.formRoute) && props.formRoute.indexOf('/indexOee') > -1) ? props.checkedId : props.app.currentPane.checkedId, /* 当前数据的Id */ + selectedRowKeys: [], /* 已选择的数据行(数据格式:数组) */ + clearArray: [], /* table清除数组 */ + calculated: false, // 工单是否经过计算 + iPageSize: commonConfig.pageSize, /* 默认config配置的pageSize */ + showTableName: false, // 展示控件名称 + noChangeDiffMap: props.noChangeDiffMap + }; + this.sDateFormat = 'YYYY-MM-DD'; + window.addEventListener('beforeunload', this.beforeunload); + window.addEventListener('unload', this.unload); + window.addEventListener('keydown', this.handleF9KeyPress); + console.log('sSrcModelsId', this.state.sSrcModelsId); + } + + async componentWillMount() { + if (commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase() !== '/loginoee') { + if (this.props.app.webSocket === null || this.props.app.webSocket.readyState !== WebSocket.OPEN) { + this.props.dispatch({ type: 'app/createWebSocket', payload: { reStart: true, dispatch: this.props.dispatch } }); + } + } + /* 获取配置 */ + this.mounted = true; + const { token, sModelsId, formSrcRoute } = this.state; + let { iPageSize } = this.state; + const config = await commonUtils.getStoreDropDownData(sModelsId, '', ''); + if (commonUtils.isEmpty(config)) { + const configUrl = `${commonConfig.server_host}business/getModelBysId/${sModelsId}?sModelsId=${sModelsId}&sName=${formSrcRoute}`; + const configReturn = (await commonServices.getService(token, configUrl)).data; + if (configReturn.code === 1) { + const [configData] = configReturn.dataset.rows; + const { formData } = configData; + if (commonUtils.isNotEmptyArr(formData)) { + if (commonUtils.isNotEmptyNumber(formData[0].iPageSize) && formData[0].iPageSize !== 0) { + iPageSize = formData[0].iPageSize;/* 后台设定页数 */ + } + } + if (this.mounted) { + commonUtils.setStoreDropDownData(sModelsId, '', '', configData); + this.handleSaveState({ ...configData, iPageSize }); + } + } else { + this.getServiceError(configReturn); + } + } else { + this.handleSaveState({ ...config }); + } + } + + componentDidMount() { + if (this.state.sTabId && !this.state.noChangeDiffMap) { + this.props.dispatch({ type: 'app/changeDiffMap', payload: { sTabId: this.state.sTabId, changed: false } }); + } + if (this.state.formRoute && this.state.formRoute.indexOf('/indexOee') > -1 && this.state.sModelsId && this.state.formRoute) { + const sModelData = { + sModelsId: this.state.sModelsId, + formRoute: this.state.formRoute, + }; + localStorage.setItem('oeeModelData', JSON.stringify(sModelData)); + } + + /* 关闭浏览器前进行提示 */ + } + + shouldComponentUpdate(nextProps, nextState) { + // // 修改或新增后的保存功能 + // if (nextState.enabled && !nextProps.app.diffMap.get(nextState.sTabId) && nextProps.app.diffMap.get(nextState.sTabId) !== undefined) { + // this.props.dispatch({ type: 'app/changeDiffMap', payload: { sTabId: nextState.sTabId, changed: true } }); + // } + // if (!nextState.enabled && nextProps.app.diffMap.get(nextState.sTabId) && nextProps.app.diffMap.get(nextState.sTabId) !== undefined) { + // this.props.dispatch({ type: 'app/changeDiffMap', payload: { sTabId: nextState.sTabId, changed: false } }); + // } + const currentKey = nextProps.app.currentPane.key; /* 当前页签key */ + const { formData } = nextState; + if (commonUtils.isNotEmptyObject(nextProps.formRoute) && nextProps.formRoute.indexOf('/indexOee') > -1) { + return (formData.length > 0); + } + /* 处理loginOee下拉框切换 重新渲染 */ + if (commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase() === '/loginoee') { + return true; + } + if (nextProps.app.unReadSid !== this.props.app.unReadSid) { + return false; + } + return (currentKey === nextState.sTabId && formData.length > 0) + || (nextState.fastOrderModalVisible !== undefined && nextProps.app.currentPane.notCurrentPane === !nextState.fastOrderModalVisible) + || (nextState.visibleStatement !== undefined && nextProps.app.currentPane.notCurrentPane === !nextState.visibleStatement) + || (nextState.visibleBatchPriceUpdate !== undefined && nextProps.app.currentPane.notCurrentPane === !nextState.visibleBatchPriceUpdate) + || (nextState.modalVisible !== undefined && nextProps.app.currentPane.notCurrentPane === !nextState.modalVisible) + || (nextState.visibleModal !== undefined && nextProps.app.currentPane.notCurrentPane === !nextState.visibleModal) + || (nextState.materialsChooseVisible !== undefined && nextProps.app.currentPane.notCurrentPane === !nextState.materialsChooseVisible) + || (nextState.processChooseVisible !== undefined && nextProps.app.currentPane.notCurrentPane === !nextState.processChooseVisible) + || (nextState.visibleFilfile !== undefined && nextProps.app.currentPane.notCurrentPane === !nextState.visibleFilfile) + || (nextState.contextMenuModalVisible !== undefined && nextProps.app.currentPane.notCurrentPane === !nextState.contextMenuModalVisible) + || (nextState.bTabModal !== undefined && nextProps.app.currentPane.notCurrentPane === !nextState.bTabModal) + || (nextState.workScheduleVisible !== undefined && nextProps.app.currentPane.notCurrentPane === !nextState.workScheduleVisible); + } + + componentDidUpdate(nextProps, nextState) { + // 修改或新增后的保存功能 + if (nextProps.onRemovePane && nextState.enabled && !nextProps.app.diffMap.get(nextState.sTabId) && nextProps.app.diffMap.get(nextState.sTabId) !== undefined) { + this.props.dispatch({ type: 'app/changeDiffMap', payload: { sTabId: nextState.sTabId, changed: true } }); + } + if (nextProps.onRemovePane && !nextState.enabled && nextProps.app.diffMap.get(nextState.sTabId) && nextProps.app.diffMap.get(nextState.sTabId) !== undefined) { + this.props.dispatch({ type: 'app/changeDiffMap', payload: { sTabId: nextState.sTabId, changed: false } }); + } + + // 页面加载完成后执行一次指令集 + this.initInstruct(); + // 修改tab显示状态 + this.handleChangeTabStatus(); + } + + componentWillUnmount() { + const { + currentId, + } = this.state; + const { userinfo } = this.props.app; + window.removeEventListener('beforeunload', this.beforeunload); + window.removeEventListener('unload', this.unload); + window.removeEventListener('keydown', this.handleF9KeyPress); + } + + // 页面加载完成后执行一次指令集 + initInstruct = () => { + if (!this.bInit) { + clearTimeout(this.initTimer); + this.initTimer = setTimeout(() => { + this.bInit = true; + const { masterConfig = {} } = this.state; + const { sOnShowInstruct } = masterConfig; + if (sOnShowInstruct) { + instructSet({ + ...this.props, + ...this.state, + btnConfig: { sInstruct: sOnShowInstruct, showName: "页面初始化" }, + onSaveState: this.handleSaveState + }) + } + }, 500); + } + } + + // 修改tab显示状态 + handleChangeTabStatus = () => { + clearTimeout(this.tabTimer); + this.tabTimer = setTimeout(() => { + this.handleChangeTabStatusFunc(); + }, 300); + } + + // 修改tab显示状态方法 + handleChangeTabStatusFunc = () => { + if (!this.baseRef) return; + + const { masterConfig = {} } = this.state; + const { sInstruct: sInstructStr } = masterConfig; + if (!sInstructStr) { + this.baseRef.classList.remove('xlyCommonBase'); + return; + }; + + const sInstruct = commonUtils.convertStrToObj(sInstructStr, {}); + const { tabs = [] } = sInstruct; + if (!tabs.length) { + this.baseRef.classList.remove('xlyCommonBase'); + return; + }; + + // 根据配置获取要隐藏的tab + const hideTabNameList = []; + + tabs.forEach(item => { + const { name, show } = item; + if (show === undefined) return; + + let result = false; + if (typeof show === "boolean") { + result = show; + } else { + result = commonFunc.getEvalResult({ + props: {...this.props, ...this.state}, + str: show, + defaultValue: true + }) + } + if (result === false) { + hideTabNameList.push(name); + } + }); + + // 遍历所有tab页签,隐藏掉在hideTabNameList中的tab页签 + const oTabBtns = this.baseRef.querySelectorAll('.ant-tabs-tab-btn'); + oTabBtns.forEach(oDom => { + const tabName = oDom.innerHTML; + const oTab = oDom.parentNode; + const bHide = hideTabNameList.includes(tabName); + if (bHide) { + oTab.style.display = 'none'; + } else { + oTab.style.display = ''; + } + }); + + // 遍历所有tabsList页签,如果下面的tab没有一个处于激活且显示状态的,默认点击第一个tab + const oNavList = this.baseRef.querySelectorAll('.ant-tabs-nav-list'); + oNavList.forEach(oList => { + const { childNodes } = oList; + const bHasActive = Array.from(childNodes).some(oTab => + oTab.classList.contains("ant-tabs-tab-active") && + oTab.style.display !== "none" + ); + if (!bHasActive) { + const oTemp = Array.from(childNodes).find(oTab => + oTab.style.display !== "none" + ); + if (oTemp) { + oTemp.click(); + } + } + }); + + this.baseRef.classList.remove('xlyCommonBase'); + } + + handleSearchNodes= (key, data, showNameNew) => { + let tableRow = {}; + if (commonUtils.isNotEmptyObject(key)) { + for (let i = 0, len = data.length; i < len; i ++) { + const item = data[i]; + if (data[i].key === key) { + tableRow = item; + return tableRow; + } else if (commonUtils.isNotEmptyArr(item.children)) { + const res = this.handleSearchNodes(key, item.children, showNameNew); + if(commonUtils.isNotEmptyObject(res)) { + return res; + } + } + } + } + return tableRow; + + }; + + /* + componentWillUnmount() { + this.mounted = false; + const { sModelsId } = this.state; + const { app, currentId } = this.props; + const { webSocket, userinfo, currentPane } = app; + const { key } = currentPane; + commonUtils.clearFormStoreDropDownData(sModelsId); + const { copyTo } = app.currentPane; + if (commonUtils.isNotEmptyObject(copyTo)) { + const { slaveData } = copyTo; + const sIdArray = []; + slaveData.forEach((item) => { + const redisKey = item.sSlaveId; + sIdArray.push(redisKey); + }); + const sId = sIdArray.toString(); + commonFunc.sendWebSocketMessage(webSocket, key, 'copyfinish', 'noAction', userinfo.sId, null, sId, userinfo.sId, null); + } + if (!commonUtils.isEmpty(currentId)) { + commonFunc.sendWebSocketMessage(webSocket, key, 'release', 'noAction', userinfo.sId, null, currentId, userinfo.sId, null); + } + } */ + + /** sql条件 */ + getSqlCondition = (showConfig, name, record) => { + const conditonValues = {}; + if (commonUtils.isNotEmptyStr(showConfig.sSqlCondition)) { + // 电化铝bom单独处理,不作标版使用。 + if (showConfig.sName === 'sAlumiteBomBillNo' || showConfig.sControlName === 'BtnPopupsAlumiteBomBillNo') { + const { materialsData, processData: processDataOld, processSelectedRowKeys: processSelectedRowKeysOld } = this.state; + const { slave0Data, slave0SelectedRowKeys } = this.state; + const processData = commonUtils.isEmptyArr(processDataOld) && commonUtils.isEmptyArr(processSelectedRowKeysOld) ? slave0Data : processDataOld; + const processSelectedRowKeys = commonUtils.isEmptyArr(processDataOld) && commonUtils.isEmptyArr(processSelectedRowKeysOld) ? slave0SelectedRowKeys : processSelectedRowKeysOld; + if (commonUtils.isNotEmptyArr(materialsData) && commonUtils.isNotEmptyArr(processSelectedRowKeys)) { + const iMaterialsIndex = materialsData.findIndex(item => item.sProcessTbId === processSelectedRowKeys[0]); + if (iMaterialsIndex > -1) { + conditonValues.iNumberOfTime = materialsData[iMaterialsIndex].iNumberOfTime; + conditonValues.sVersionNum = materialsData[iMaterialsIndex].sVersionNum; + } else { + conditonValues.iNumberOfTime = 0; + conditonValues.sVersionNum = ''; + } + } + } + const conditon = showConfig.sSqlCondition.split(','); + conditon.forEach((item) => { + if (item.indexOf('.') > -1) { + const tableName = item.split('.')[0]; + let fieldName = item.split('.')[1]; + let fieldNameFilter = item.split('.').length > 2 ? item.split('.')[2] : fieldName; + // master.sId 作为参数 master.sId.sId 作为filterDropdown过滤参数 + if (showConfig.sDropDownType === 'picArr' || showConfig.sDropDownType === 'picArrModal' ) { + fieldNameFilter = item.split('.').length > 2 ? item.split('.')[2] : fieldName; + if (fieldName.indexOf('&Search') > -1) { + // 参数为&Search时认为是查找数据集中取数据 + const data = this.state[`${tableName}Data`]; + if (typeof data === 'object' && data.constructor === Object) { + Object.keys(data).forEach((dataItem) => { + if (`&Search${data[dataItem]}` === fieldName) { + let sTmpName = dataItem; + sTmpName = sTmpName.replace('First', 'Third'); + if (data[dataItem].substring(0, 1) === 't') { + fieldName = `p${sTmpName.substring(1, dataItem.length)}`; + } else if (data[dataItem].substring(0, 1) === 'm') { + fieldName = data[dataItem].substring(0, 1) + sTmpName.substring(1, sTmpName.length); + } else { + fieldName = data[dataItem].substring(0, 1) + sTmpName.substring(1, sTmpName.length); + } + } + }); + } + } else if (fieldName.indexOf('&') > -1) { + fieldNameFilter = item.split('.').length > 2 ? item.split('.')[2] : fieldName; + conditonValues[fieldNameFilter] = fieldName.replace('&', ''); + return; + } + } + if (fieldName !== '') { + if (name === tableName && !commonUtils.isEmptyObject(record)) { + const data = record; + conditonValues[fieldNameFilter] = data[fieldName]; + } else { + let data = this.state[`${tableName}Data`]; + if(commonUtils.isEmptyArr(data)) { + const dataRelationJson = this.state.relateRelationJson; + if(commonUtils.isNotEmptyObject(dataRelationJson)){ + const relateName = dataRelationJson[tableName]; + if(relateName) { + data = this.state[`${relateName}Data`]; + } + } + } + + let selectedRowKeys = this.state[`${tableName}SelectedRowKeys`]; + if(tableName === 'tree') { + selectedRowKeys = this.state[`${tableName}SelectedKeys`]; + } + if (typeof data === 'object' && data.constructor === Object) { + conditonValues[fieldNameFilter] = data[fieldName]; + } + else if (fieldName.indexOf('_all') > -1) { + let sAllConditionValue = ''; + const fieldNameNew = fieldName.replace('_all', ''); + if (commonUtils.isNotEmptyArr(data)) { + // 电化铝bom单独处理,不作标版使用。 + let dataNew = data; + if (showConfig.sName === 'sAlumiteBomBillNo' || showConfig.sControlName === 'BtnPopupsAlumiteBomBillNo') { + const { controlData, controlSelectedRowKeys: controlSelectedRowKeysOld, slave0Child1SelectedRowKeys } = this.state; + const controlSelectedRowKeys = commonUtils.isEmptyArr(controlData) ? slave0Child1SelectedRowKeys : controlSelectedRowKeysOld; + if (commonUtils.isNotEmptyArr(controlSelectedRowKeys)) { + dataNew = data.filter(item => item.sControlId === controlSelectedRowKeys[0]); + } + } + for(const item of dataNew) { + if (item[fieldNameNew]) { + sAllConditionValue = sAllConditionValue + ',' + item[fieldNameNew]; + } + } + } + conditonValues[fieldNameFilter] = sAllConditionValue; + }else if(tableName ==='tree' && commonUtils.isNotEmptyArr(selectedRowKeys) && commonUtils.isNotEmptyArr(data)) { + const selectedKey = selectedRowKeys?.toString(); + /* 如果是树形 递归查找选中行 */ + const tableRow = this.handleSearchNodes(selectedKey, data); + if(commonUtils.isNotEmptyObject(tableRow)) { + conditonValues[fieldNameFilter] = tableRow[fieldName]; + } + } + else if (commonUtils.isNotEmptyArr(selectedRowKeys) && commonUtils.isNotEmptyArr(data)) { + let iIndex = data.findIndex(itemData => itemData.sId === selectedRowKeys[0]); + iIndex = iIndex > -1 ? iIndex : data.findIndex(itemData => itemData.sSlaveId === selectedRowKeys[0]); + if (iIndex > -1) { + conditonValues[fieldNameFilter] = data[iIndex][fieldName]; + } + } else if (commonUtils.isNotEmptyArr(data)) { + conditonValues[fieldNameFilter] = data[0][fieldName]; + } + } + } + } + }); + } + return conditonValues; + }; + + /** 获取sql下拉数据 */ + getSqlDropDownData = async (formId, name, showConfig, record, sKeyUpFilterName, pageNum) => { + /* 地址 */ + const { formSrcRoute } = this.state; + if (commonUtils.isEmpty(showConfig.sFieldToContent)) { + if (commonUtils.isEmpty(showConfig.showDropDown)) { + return { + dropDownData: [], totalPageCount: 0, currentPageNo: 0, conditonValues: {}, + }; + } + const url = `${commonConfig.server_host}business/getSelectLimit/${showConfig.sId}?sModelsId=${this.state.sModelsId}&sName=${formSrcRoute}`; + /* 参数 */ + const conditonValues = this.getSqlCondition(showConfig, name, record); + + const body = { + sSqlCondition: commonUtils.isEmptyObject(conditonValues) ? '' : conditonValues, /* 查询条件 */ + }; + if (commonUtils.isEmpty(showConfig.sId)) { + body.showDropDown = showConfig.showDropDown; + body.sKeyUpFilter = showConfig.sKeyUpFilter; + } + if (!commonUtils.isEmpty(pageNum)) { + body.sKeyUpFilterName = sKeyUpFilterName; /* 边输入边过滤,暂时没用1 */ + body.pageNum = pageNum; + // 下拉数据改为无限 + body.pageSize = commonConfig.pageSize; + // body.pageSize = 9999; + } + /* 获取数据 */ + const json = await commonServices.postValueService(this.props.app.token, body, url); + /* code为1代表获取数据成功 */ + if (json.data.code === 1) { + /* 获取数据集 */ + const { rows, totalPageCount, currentPageNo, totalCount } = json.data.dataset; + return { + dropDownData: rows, totalPageCount, currentPageNo, conditonValues, totalCount, + }; + } else { + return { + dropDownData: [], totalPageCount: 0, currentPageNo: 0, conditonValues, + }; + } + } else { + const returnData = []; + if (showConfig.sFieldToContent === '1') { + if (name === 'master') { + const { [`${name}Data`]: data } = this.state; + const sName = `sParamDropDown${showConfig.sName.replace('sParamValue', '')}`; + returnData.push(...commonUtils.objectToArr(data[sName])); + } else { + const { [`${name}Data`]: data, [`${name}SelectedRowKeys`]: selectedRowKeys } = this.state; + const sName = `sParamDropDown${showConfig.sName.replace('sParamValue', '')}`; + if (commonUtils.isNotEmptyObject(record)) { + returnData.push(...commonUtils.objectToArr(record[sName])); + } else if (commonUtils.isNotEmptyArr(data) && commonUtils.isNotEmptyArr(selectedRowKeys)) { + const iIndex = data.findIndex(item => item.sId === selectedRowKeys.toString()); + if (iIndex > -1) { + returnData.push(...commonUtils.objectToArr(data[iIndex][sName])); + } + } + } + } else { + const unionCondition = showConfig.sFieldToContent.split('&&'); + unionCondition.forEach((unionItem) => { + const conditon = unionItem.split(','); + const tableNameContent = conditon[0].split('.')[0]; + let data = this.state[`${tableNameContent}Data`]; + if (commonUtils.isNotEmptyArr(data)) { + if (showConfig.sSqlCondition !== '') { + const sSqlCondition = showConfig.sSqlCondition; + const sqlConditon = sSqlCondition.split(','); + sqlConditon.forEach((item) => { + const tableName = item.split('.')[0]; + const fieldName = item.split('.')[1]; + const fieldNameFilter = item.split('.').length > 2 ? item.split('.')[2] : fieldName; + const dataCondition = this.state[`${tableName}Data`]; + const selectedRowKeys = this.state[`${tableName}SelectedRowKeys`]; + if (typeof dataCondition === 'object' && dataCondition.constructor === Object) { + // 对象不用filter + // data = data.filter(item => commonUtils.isNull(item[fieldNameFilter], '') === commonUtils.isNull(dataCondition[fieldName], '')); + } else if (commonUtils.isNotEmptyArr(selectedRowKeys)) { + let iIndex = dataCondition.findIndex(itemData => itemData.sId === selectedRowKeys[0]); + iIndex = iIndex > -1 ? iIndex : dataCondition.findIndex(itemData => itemData.sSlaveId === selectedRowKeys[0]); + if (iIndex > -1) { + data = data.filter(item => commonUtils.isNull(item[fieldNameFilter], '') === commonUtils.isNull(dataCondition[iIndex][fieldName], '')); + } + } else if (commonUtils.isNotEmptyArr(data)) { + data = data.filter(item => commonUtils.isNull(item[fieldNameFilter], '') === commonUtils.isNull(dataCondition[0][fieldName], '')); + } + }); + } + if (typeof data === 'object' && data.constructor === Object) { + const dataRow = {}; + conditon.forEach((item) => { + const fieldName = item.split('.')[1]; + const fieldNameFilter = item.split('.').length > 2 ? item.split('.')[2] : fieldName; + if (fieldName.indexOf('-') >= 0) { + fieldName.split('-').forEach((itemField) => { + const sFieldValue = commonUtils.isEmpty(data[itemField]) ? '' : data[itemField].toString(); + dataRow[fieldNameFilter] = commonUtils.isEmpty(dataRow[fieldNameFilter]) ? sFieldValue : `${dataRow[fieldNameFilter]}-${sFieldValue}`; + }); + } else { + dataRow[fieldNameFilter] = commonUtils.isEmpty(data[fieldName]) ? '' : data[fieldName].toString(); + } + }); + returnData.push(dataRow); + } else { + data.forEach((itemDataRow) => { + const dataRow = {}; + conditon.forEach((item) => { + const fieldName = item.split('.')[1]; + const fieldNameFilter = item.split('.').length > 2 ? item.split('.')[2] : fieldName; + if (fieldName.indexOf('-') >= 0) { + fieldName.split('-').forEach((itemField) => { + const sFieldValue = commonUtils.isEmpty(itemDataRow[itemField]) ? '' : itemDataRow[itemField].toString(); + dataRow[fieldNameFilter] = commonUtils.isEmpty(dataRow[fieldNameFilter]) ? sFieldValue : `${dataRow[fieldNameFilter]}-${sFieldValue}`; + }); + } else { + dataRow[fieldNameFilter] = commonUtils.isEmpty(itemDataRow[fieldName]) ? '' : itemDataRow[fieldName].toString(); + } + }); + returnData.push(dataRow); + }); + } + } + }); + } + return { dropDownData: returnData, totalPageCount: 0, currentPageNo: 0 }; + } + }; + /* 获取数字格式化规范 */ + getFloatNum = (sName) => { + if (sName.toLowerCase().endsWith('price')) { /* 价格 */ + return this.props.app.decimals.dNetPrice; + } else if (sName.toLowerCase().endsWith('money')) { /* 金额 */ + return this.props.app.decimals.dNetMoney; + } else { /* 其它 */ + return 6; + } + }; + + /** 获取sql下拉数据 */ + getServiceError = async (returnData) => { + if (location.pathname.indexOf('/indexOee/') > -1) { + this.props.dispatch({ type: 'app/throwErrorOee', payload: returnData }); + } else { + this.props.dispatch({ type: 'app/throwError', payload: returnData }); + } + }; + + /* 获取数字格式化规范 */ + getDateFormat = () => { + return this.props.app.dateFormat; + }; + + beforeunload = (e) => { + const confirmationMessage = '您确定要离开么?'; + if (e) { + e.returnValue = confirmationMessage; + } + return confirmationMessage; + } + + unload = () => { + // sessionStorage.clear(); + // const { + // currentId, sModelsId, + // } = this.state; + // const url = `${commonConfig.server_host}logout`; + // this.handleSendSocketMessage('release', 'noAction', currentId, this.props.app.userinfo.sId, null, null); + // this.handleSendSocketMessage('release', 'noAction', sModelsId, this.props.app.userinfo.sId, null, null); + // this.props.dispatch({ type: 'app/loginOut', payload: { url, sId: this.props.app.userinfo.sId, loginOutType: 'loginOut' } }); + } + + handleF9KeyPress = (event) => { + // 判断是否按下的是F9键 + if (event.key === 'F9') { + event.preventDefault(); + this.setState({ + showTableName: !this.state.showTableName, + }); + } + } + + handleSendSocketMessage = (flag, showType, sId, sendTo, msgInfo, param) => { + const { token } = this.props.app; + const sendws = this.handleSendWebSocketMsg; + const { dispatch } = this.props; + if (commonUtils.isNotEmptyObject(token)) { + if (this.props.app.webSocket !== null && this.props.app.webSocket.readyState === WebSocket.OPEN) { + sendws(flag, showType, msgInfo, sId, sendTo, param); + } else { + this.props.dispatch({ type: 'app/createWebSocket', payload: { reStart: true, dispatch } }); + setTimeout(() => { + sendws(flag, showType, msgInfo, sId, sendTo, param); + }, 30000); + } + } + }; + handleSendWebSocketMsg = (flag, showType, msgInfo, sId, sendTo, param) => { + const { app } = this.props; + const { webSocket, userinfo, currentPane } = app; + const { key } = currentPane; + commonFunc.sendWebSocketMessage(webSocket, key, flag, showType, userinfo.sId, msgInfo, sId, sendTo, param); + } + /** sql下拉新增处理 */ + handleSqlDropDownNewRecord = async (showConfig, name) => { + const { + [`${name}SelectedRowKeys`]: tableSelectedRowKeys, [`${name}Data`]: tableNewData, masterData, formSrcRoute, [`${name}Config`]: tableConfig, slaveData, + } = this.state; + /* 待用数据声明 */ + const sTabId = this.props.app.currentPane.key; /* 当前标签页TabId */ + /* 接口地址 */ + const sNameUrl = `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${showConfig.sActiveId}?sModelsId=${showConfig.sActiveId}&sName=${formSrcRoute}`; + const CallBackRecord = this.handleCallBackRecord;/* 字段名,主从表,字段名 */ + /* newRecord时,如果是新增产品,则要带客户过去 */ + let addStata = {}; + for (const each of this.props.app.panes) { + each.notCurrentPane = true; + } + const iIndex = name !== 'master' ? tableNewData.findIndex(item => item.sId === tableSelectedRowKeys.toString()) : -1; + if (commonUtils.isNotEmptyObject(showConfig) && showConfig.sName === 'sProductName') { + if (name !== 'master' && commonUtils.isNotEmptyObject(tableSelectedRowKeys)) { + const newData = tableNewData[iIndex]; + addStata.sCustomerId = newData.sCustomerId; + addStata.sCustomerNo = newData.sCustomerNo; + addStata.sCustomerName = newData.sCustomerName; + if (commonUtils.isEmptyObject(addStata.sCustomerId)) { /* 新增产品时,看客户在从表还是主表。如果不在从表,那看是否在主表 */ + addStata.sCustomerId = masterData.sCustomerId; + addStata.sCustomerNo = masterData.sCustomerNo; + addStata.sCustomerName = masterData.sCustomerName; + } + } + } + /* newRecord 根据配置赋值 带数据 */ + const sCopyToConfigField = commonUtils.isNotEmptyObject(showConfig) && showConfig.sControlName && showConfig.sControlName.includes('BtnNewRecord') ? showConfig.sControlName : {}; + let sCopyToConfigMaster = {}; + if(commonUtils.isNotEmptyArr(sCopyToConfigField) && commonUtils.isNotEmptyArr(tableConfig)) { + sCopyToConfigMaster = tableConfig.gdsconfigformslave.filter(item => item.sControlName === sCopyToConfigField); + console.log(sCopyToConfigMaster, sCopyToConfigMaster); + if(commonUtils.isNotEmptyArr(sCopyToConfigMaster)) { + const sCopyToConfigMasterAssignField= sCopyToConfigMaster[0].sAssignField; + const newCopyTo = {}; + if(iIndex > -1) { + const newData = tableNewData[iIndex]; + newCopyTo.master = masterData; + newCopyTo.slave = commonUtils.isEmptyArr(slaveData) ? {} : slaveData[0]; + newCopyTo.process = newData; + addStata = { ...addStata, ...commonFunc.getAssignFieldValue(sCopyToConfigMasterAssignField, newData, newCopyTo)}; + } + } + } + /* 接口参数 */ + const payload = { + url: sNameUrl, + sParentId: sTabId, + classifyOption: 'add', + newRecordFlag: `NewRecord_${sTabId}`, /* newRecord当前字段 */ + newRecordRelation: addStata, /* newRecord 关联字段,如新增产品,带客户信息 */ + newRecordMethod: CallBackRecord.bind(this, showConfig.sName, name), /* newRecord当前字段 */ + sSrcModelsId: this.state.sModelsId + }; + /* 调用接口 */ + this.props.dispatch({ type: 'content/onRouter', payload }); + }; + + /* 获取配置数据用的sTabId,formId,formRoute */ + handleConfigValue = (value, type) => { + if (commonUtils.isNotEmptyObject(type) && type.indexOf('/indexOee') > -1) { + return this.props[value]; + } else { + const { secondppopupPane, ppopupPane, currentPane } = this.props.app; + return commonUtils.isNotEmptyObject(secondppopupPane) + ? secondppopupPane[value] + : commonUtils.isNotEmptyObject(ppopupPane) + ? ppopupPane[value] : currentPane[value]; + } + }; + + /* 获取后台数据(单条) */ + handleGetDataOne = async (params) => { + const { token, sModelsId } = this.state; + const { + name, configData, condition, isWait, formSrcRoute, bEditClick, slaveConfig + } = params; + + const lockUrl = `${commonConfig.server_host}business/addSysLocking?sModelsId=${sModelsId}&sName=${formSrcRoute}`; + + const configDataId = configData.sId; + const dataUrl = `${commonConfig.server_host}business/getBusinessDataByFormcustomId/${configDataId}?sModelsId=${sModelsId}&sName=${formSrcRoute}`; + const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data; + if (dataReturn.code === 1) { + const [returnData] = dataReturn.dataset.rows[0].dataSet; + if (commonUtils.isNotEmptyArr(returnData)) { + let addState = {}; + const value = { + tableName: configData.sTbName, + sId: [returnData.sId], + }; + if(bEditClick === 'update') { /* 只有点击修改时 调用addSysLocking */ + const { data } = await commonServices.postValueService(token, value, lockUrl); + if (data.code === 1) { /* 失败 */ + addState.sUseInfo = ''; + } else { /* 失败 */ + addState.sUseInfo = data.msg; + if (commonUtils.isNotEmptyObject(data.erroMsg)) { + message.error(data.erroMsg); + } + } + } + addState[`${name}Data`] = returnData; + if(commonUtils.isNotEmptyObject(returnData.customConfig) && commonUtils.isJSON(returnData.customConfig) && commonUtils.isNotEmptyObject(slaveConfig)) { + const columnConfig = JSON.parse(returnData.customConfig); + const newConfig =JSON.parse(JSON.stringify(slaveConfig)); + let buttonConfig = []; + if(commonUtils.isNotEmptyArr(slaveConfig?.gdsconfigformslave)) { + buttonConfig = slaveConfig?.gdsconfigformslave.filter(item => commonUtils.isEmptyObject(item.sName) && commonUtils.isNotEmptyObject(item.sControlName) ); + } + newConfig.gdsconfigformslave = columnConfig.concat(buttonConfig); + addState.slaveConfig = newConfig; + } + addState.currentId = returnData.sId; + if(bEditClick === 'update') { + addState[`${name}Data`].enabled = true; + } + + /* 获取主表数据时表字段数据根据条件控制 本表或其他表格字段的显示与隐藏功能 */ + if (name === 'master' && commonUtils.isNotEmptyObject(configData)) { + const addStateChange = this.handelControlFieldVisible(name, configData, returnData); + if (commonUtils.isNotEmptyObject(addStateChange)) { + addState = { ...addState, ...addStateChange }; + } + } + + if (isWait) { + return addState; + } else if (this.mounted) { + this.handleSaveState({ ...addState }); + } + } + } else { + this.getServiceError(dataReturn); + } + }; + + /* 获取后台数据(数据集) */ + handleGetDataSet = async (params) => { + const { + name, condition, flag, isWait, configData, clearSelectData, + } = params; + const { + token, sModelsId, formRoute, [`${name}SelectedData`]: tableSelectedData, formSrcRoute, formData, [`${name}DelData`]: tableDelData, sModelsType, [`${name}PageSize`]: pageSize, [`${name}Config`]: tableConfig, + } = this.state; + let { + menuChildData, + [`${name}SelectedRowKeys`]: tableSelectedRowKeys, iPageSize, + } = this.state; + const masterConditionData = commonUtils.isNotEmptyObject(condition) ? condition.sSqlCondition : {}; + /* 根据后台主表配置bPagination判断 是否分页 */ + if (commonUtils.isNotEmptyObject(configData) && commonUtils.isNotEmptyObject(condition)) { + const { bPagination } = configData; + if (!bPagination || bPagination === undefined) { + condition.pageSize = 10000; /* 不分页 */ + iPageSize = 10000; + } else { /* 分页 */ + // eslint-disable-next-line no-lonely-if + if (commonUtils.isNotEmptyArr(formData)) { + if (commonUtils.isNotEmptyNumber(formData[0].iPageSize) && formData[0].iPageSize !== 0) { + iPageSize = formData[0].iPageSize;/* 后台设定页数 */ + } + } + } + } + + const configDataId = configData.sId; + const dataUrl = `${commonConfig.server_host}business/getBusinessDataByFormcustomId/${configDataId}?sModelsId=${sModelsId}&sName=${formSrcRoute}`; + const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data; + if (dataReturn.code === 1) { + if( commonUtils.isNotEmptyObject(dataReturn.dataset) && commonUtils.isNotEmptyArr(dataReturn.dataset.rows) ) { + let returnData = dataReturn.dataset.rows[0].dataSet; + if (this.props && this.props.app && this.props.app.currentPane && this.props.app.currentPane.route && dataReturn.dataset.rows[0].columnConfig) { + const columnConfig = dataReturn.dataset.rows[0].columnConfig; + const newConfig = commonUtils.isNotEmptyObject(tableConfig) ? JSON.parse( JSON.stringify(tableConfig)) : JSON.parse(JSON.stringify(configData)) ; + let buttonConfig = []; + if(commonUtils.isNotEmptyArr(tableConfig?.gdsconfigformslave)) { + buttonConfig = tableConfig?.gdsconfigformslave.filter(item => commonUtils.isEmptyObject(item.sName) && commonUtils.isNotEmptyObject(item.sControlName) ); + } + newConfig.gdsconfigformslave = columnConfig.concat(buttonConfig); + let addConfig = {}; + if(name === 'slave' && commonUtils.isNotEmptyObject(newConfig)) { + addConfig = { + [`${name}Config`]:newConfig + }; + } + this.handleSaveState({ + customConfig: columnConfig, + ...addConfig, + }) + } + // const returnData = dataReturn.dataset.rows[0].dataSet; + if (commonUtils.isNotEmptyObject(returnData)) { + if (formRoute === '/indexPage/materialRequirementsPlanning') { + returnData.forEach((tableDataRow) => { + tableDataRow.sSlaveId = tableDataRow.sMaterialsId + tableDataRow.sMaterialsStyle; + tableDataRow.dAuxiliaryQtyAll = tableDataRow.dAuxiliaryQty; + tableDataRow.dMaterialsQtyAll = tableDataRow.dMaterialsQty; + }); + } + if ((sModelsType && sModelsType.includes('linkTree'))) { + returnData.forEach((tableDataRow) => { + tableDataRow.dAuxiliaryQtyAll = tableDataRow.dAuxiliaryQty; + tableDataRow.dMaterialsQtyAll = tableDataRow.dMaterialsQty; + }); + } + /* 若有sDivRow则数据行上面插入一行 */ + const returnFilterData = returnData.filter(item => commonUtils.isNotEmptyObject(item.sDivRow) && item.sDivRow !== ''); + if (commonUtils.isNotEmptyArr(returnFilterData)) { + returnFilterData.forEach((tableDataRow, index) => { + /* 找到白班与晚班区间的汇总条数与工时 */ + let startIndex = 0; /* 找到开始下标 */ + let endindex = 0; /* 找到结束下标 */ + let sliceData = []; + startIndex = returnData.findIndex(item => item.sId === returnFilterData[index].sId); + if (index + 1 < returnFilterData.length) { + endindex = returnData.findIndex(item => item.sId === returnFilterData[index + 1].sId); + } + if (index === returnFilterData.length - 1) { + endindex = returnData.length; + } + if (startIndex < endindex) { + sliceData = returnData.slice(startIndex, endindex); + } + let num = 0; + let dTime = 0; + let dPlateQty = 0; /* 付版 */ + let dProcessQty = 0; + let endTime; + const scheduleShow = ['16508090850002295893127095467000'].includes(sModelsId); + let timeSName = 'dHour1'; + if (scheduleShow) timeSName = 'dSumHour'; + const newRow = {}; + newRow.sId = 'sDivRow' + index; + newRow.sSlaveId = 'sDivRow' + commonUtils.createSid(); + if (commonUtils.isNotEmptyArr(sliceData)) { + num = sliceData.length; + sliceData.forEach((item) => { + if (commonUtils.isNotEmptyNumber(item[timeSName])) { + dTime += item[timeSName]; + dPlateQty += commonUtils.isNotEmptyNumber(item.dPlateQty) ? item.dPlateQty : 0; + dProcessQty += commonUtils.isNotEmptyNumber(item.dProcessQty) ? item.dProcessQty : 0; + if (item?.tEndDate) { + let value = item.tEndDate; + if (endTime) { + value = moment.max(moment(endTime), moment(item.tEndDate)); + } + endTime = value; + } + const iSrcIndex = returnData.findIndex(itemReturn => itemReturn.sSlaveId === item.sSlaveId); /* 汇总的每行上都加newRow的sSlaveId作为父级Id */ + if (iSrcIndex > -1) { + returnData[iSrcIndex] = {...returnData[iSrcIndex], sDivRowParentId: newRow.sSlaveId} + } + } + }); + } + newRow.sDivRowNew = tableDataRow.sDivRow; + newRow.bInsert = true; /* 新插入 */ + newRow.sState = null; + newRow.sProcessId = tableDataRow.sProcessId; + /* 取第一个配置 */ + const configArr = configData.gdsconfigformslave.filter(item => item.bVisible && item.sName !== ''); + if (commonUtils.isNotEmptyArr(configArr)) { + let firstName = ''; + if (configArr[0].sName === 'iOrder') { + firstName = configArr[1].sName; + } else { + firstName = configArr[1].sName; + } + if (commonUtils.isNotEmptyObject(firstName)) { + const firstDataIndex = firstName.substring(0, 1); + if (firstDataIndex !== 't' && firstDataIndex !== 'p') { + newRow[firstName] = tableDataRow.sDivRow; + if (num > 0) { + newRow[firstName] += 'F' + num + '单'; + } + if (dProcessQty > 0) { + newRow[firstName] += ' - ' + dProcessQty; + } + if (tableDataRow.sType === "1" && !scheduleShow ) { + newRow[firstName] += ' - ' + dPlateQty + '付版'; + } + if (dTime > 0) { + if (scheduleShow) { + newRow[firstName] += ' - ' + Math.floor(dTime / 24) + "d" + (dTime % 24).toFixed(2) + 'h'; + } else { + newRow[firstName] += ' - ' + (dTime / 60).toFixed(2) + 'h'; + } + } + if (endTime) { + newRow[firstName] += ' - ' + moment(endTime).format('MM月DD日'); + } + } + } + } + const iInsertIndex = returnData.findIndex(item => item.sSlaveId === tableDataRow.sSlaveId); + if (iInsertIndex > -1) { + returnData[iInsertIndex].sDivRow = ''; + returnData.splice(iInsertIndex, 0, newRow); /* 在目标位置前面增加一行 */ + } + }); + } + if (commonUtils.isEmptyArr(tableSelectedData)) { + if (formRoute !== '/indexPage/materialRequirementsPlanning' && formRoute !== '/indexPage/commonClassify' && + sModelsId !=='12710101117238854446770') { + if (commonUtils.isNotEmptyStr(returnData[0].sSlaveId)) { + const keys = []; + keys.push(returnData[0].sSlaveId); + tableSelectedRowKeys = keys; + } else { + const keys = []; + keys.push(returnData[0].sId); + tableSelectedRowKeys = keys; + } + } + if (flag) { + tableSelectedRowKeys = []; + menuChildData = []; // 打印下拉置空 + } + } + } + if (clearSelectData) { + tableSelectedRowKeys = []; + menuChildData = []; // 打印下拉置空 + } + /** + * 修改日期:2021-03-30 + * 修改人:吕杰 + * 区域:以下 4 行 + * BUG:2185 + * 说明:右下角 增加单据个数显示 + * 原代码: + */ + let billNum = ''; + if (dataReturn.dataset.billNum) { + billNum = `共${dataReturn.dataset.billNum}个单据 `; + } + const iOeeBillPageSize = iPageSize < 100 ? 100 : iPageSize; + const pageSize = formRoute === '/indexPage/commonBill' || (formRoute === '/indexPage/productionMainPlan') + || formRoute === '/indexPage/commonSubBill' || formRoute === '/indexPage/commonGroupBill' || formRoute === '/eleintefaceDialog' ? + iPageSize : location.pathname.includes('commonOeeBill') ? iOeeBillPageSize : dataReturn.dataset.pageSize; + const returnPagination = { + total: dataReturn.dataset.totalCount, + current: dataReturn.dataset.currentPageNo, + pageSize: pageSize, + showTotal: (total) => { + return ( + {`当前显示 ${billNum}共${total}条记录`} + ); + }, + }; + // 如果是commonNewBill,不取接口返回的分页数 + if (formRoute === '/indexPage/commonNewBill' && pageSize) { + const { bPagination } = configData; + let iNewPageSize = pageSize; + if (!bPagination || bPagination === undefined) { + iNewPageSize = 10000; + } else { /* 分页 */ + if (commonUtils.isNotEmptyNumber(configData.iPageSize) && configData.iPageSize !== 0) { + iNewPageSize = configData.iPageSize;/* 后台设定页数 */ + } + } + returnPagination.pageSize = iNewPageSize; + } + // const sumSet1Default = [{ + // "dProfit": '辊底重量:0.00', + // "dTotalProfitMoney": '转入重量:0.00', + // "dNetMargin": '分切重量:0.00', + // "dTotalNetProfit": '边料重量:0.00', + // "dMainBusinessMoney": '转出重量:0.00', + // "dOperaMoney": '总重量:0.00', + // "dFreight": '转入数量:0.00', + // "dOtherbusinessCostMoney": '转出数量:0.00', + // "dSellingExpenses": '总件数:0', + // }]; + const { sumSet, sumSet1 } = dataReturn.dataset.rows[0]; + const totalData = sumSet !== undefined ? sumSet : []; + const totalData1 = sumSet1 !== undefined ? sumSet1 : []; + const filterCondition = commonUtils.isNotEmptyObject(condition) ? condition.bFilter : ''; + const orderBy = commonUtils.isNotEmptyObject(condition) ? condition.sFilterOrderBy : ''; + /* 去除树搜索filterCondition */ + const filterConditionNew = commonUtils.isNotEmptyObject(filterCondition) ? filterCondition.filter(item => item.bFilterType !== 'tree') : ''; + let addState = { + [`${name}Data`]: returnData, + [`${name}Pagination`]: returnPagination, + [`${name}FilterCondition`]: filterConditionNew, + [`${name}OrderBy`]: orderBy, + [`${name}SelectedRowKeys`]: tableSelectedRowKeys, + menuChildData, + /* + 修改日期:2021-03-17 + 修改人:吕杰 + 区域:以下一行 + 需求变更:fix 2135 搜索时添加loading动画 + */ + pageLoading: false, + iPageSize, + masterConditionData + }; + if (commonUtils.isNotEmptyArr(totalData1)) { + addState = { ...addState, [`${name}Total1`]: totalData1, [`${name}AllTotal`]: totalData1 }; + } + if (dataReturn.dataset.currentPageNo === 1) { + addState = { ...addState, [`${name}Total`]: totalData, [`${name}AllTotal`]: totalData }; + } + if(commonUtils.isNotEmptyNumber(dataReturn?.dataset.totalCount)) { + const iCount = dataReturn.dataset.totalCount; + addState = { ...addState, [`${name}TotalCount`]: iCount }; + } + const slaveSelectedData = []; + if ((formRoute === '/indexPage/commonList' || formRoute === '/indexPage/materialRequirementsPlanning') && name === 'slave' && commonUtils.isNotEmptyArr(tableSelectedRowKeys) && !clearSelectData) { + tableSelectedRowKeys.forEach((item) => { + const iPageIndex = returnData.findIndex(pageItem => pageItem.sSlaveId === item); + if (iPageIndex > -1) { + slaveSelectedData.push(returnData[iPageIndex]); + } else if (commonUtils.isNotEmptyArr(tableSelectedData)) { + const iIndex = tableSelectedData.findIndex(pageItem => pageItem.sSlaveId === item); + if (iIndex > -1) { + slaveSelectedData.push(tableSelectedData[iIndex]); + } + } + }); + } else if (formRoute === '/indexPage/materialRequirementsPlanning' && clearSelectData) { /* 处理物料需求计划生成采购申请单,刷新时,数据重复问题 */ + addState.slaveInfoSelectedRowKeys = []; + addState.slaveInfoSelectedData = []; + } + addState[`${name}SelectedData`] = slaveSelectedData; + /* 如果获取数据集时候 删除数据集有数据 则清空 */ + if (commonUtils.isNotEmptyArr(tableDelData)) { + addState[`${name}DelData`] = []; + } + if (isWait) { + return addState; + } else if (this.mounted) { + this.handleSaveState(addState); + } + } else { + console.error(name +'表数据获取错误!'); + } + } else { + /* + 修改日期:2021-03-17 + 修改人:吕杰 + 区域:以下三行 + 需求变更:fix 2135 搜索时添加loading动画 + */ + if (!isWait && this.mounted) { + this.handleSaveState({ pageLoading: false }); + } + this.getServiceError(dataReturn); + } + }; + + /* 获取过滤树数据(数据集) */ + handleGetTreeDataSet = async (params, name) => { + const { + configData, condition, isWait, + } = params; + const { token, sModelsId, formSrcRoute } = this.state; + let treeData = []; + const expandedKeys = []; + const configDataId = configData.sParentId; + const dataUrl = `${commonConfig.server_host}filterTree/getFilterTree/${configDataId}?sModelsId=${sModelsId}&sName=${formSrcRoute}`; + const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data; + if (dataReturn.code === 1) { + const returnData = dataReturn.dataset.rows; + if (commonUtils.isNotEmptyArr(returnData)) { + /* 拼装树结构 */ + treeData = returnData; + /* 默认展开第一个父节点 */ + if (treeData.length > 0) { + if (commonUtils.isNotEmptyObject(treeData[0]) && commonUtils.isNotEmptyObject(treeData[0].key)) { + expandedKeys.push(treeData[0].key); + } else { + treeData =[]; + } + } + } + let addState = { + expandedKeys, + }; + if (name) { + addState[`${name}TreeData`] = treeData; + } else { + addState.treeData = treeData; + } + addState = { ...addState }; + if (isWait) { + return addState; + } else if (this.mounted) { + this.handleSaveState(addState); + } + } else { + this.getServiceError(dataReturn); + } + }; + + /* 重新获取界面配置 */ + handleGetTableConfig = async (name, sModelsId, oldConfig) => { + const { token, formSrcRoute, formRoute } = this.state; + let tableConfig = {}; + const configUrl = `${commonConfig.server_host}business/getModelBysId/${sModelsId}?sModelsId=${sModelsId}&sName=${formSrcRoute}`; + const configReturn = (await commonServices.getService(token, configUrl)).data; + if (configReturn.code === 1) { + const [configData] = configReturn.dataset.rows; + const { formData } = configData; + if (commonUtils.isNotEmptyArr(formData)) { + if (oldConfig) { + tableConfig = formData.find(item => item.sId === oldConfig.sId); + } else if(formRoute === '/indexPage/commonList') { + tableConfig = formData[0]; + } else if(formRoute === '/indexPage/commonNewBill') { + if (name === 'master') { + tableConfig = formData[0]; + } else if (name === 'slave') { + tableConfig = formData.length > 1 ? formData[1] : {}; + } else if (name === 'slave0') { + tableConfig = formData.length > 2 ? formData[2] : {}; + } else if (name === 'slave1') { + tableConfig = formData.length > 3 ? formData[3] : {}; + } else if (name === 'slave2') { + tableConfig = formData.length > 4 ? formData[4] : {}; + } + } else { + if (name === 'master') { + tableConfig = formData[0]; + } else if (name === 'slave') { + tableConfig = formData.length > 1 ? formData[1] : {}; + } else if (name === 'control') { + tableConfig = formData.length > 2 ? formData[2] : {}; + } else if (name === 'materials') { + tableConfig = formData.length > 3 ? formData[3] : {}; + } else if (name === 'process') { + tableConfig = formData.length > 4 ? formData[4] : {}; + } else if (name === 'slave0') { + tableConfig = formData.length > 2 ? formData[2] : {}; + } else if (name === 'slave1') { + tableConfig = formData.length > 3 ? formData[3] : {}; + } else if (name === 'slave2') { + tableConfig = formData.length > 4 ? formData[4] : {}; + } else if (name === 'slave3') { + tableConfig = formData.length > 5 ? formData[5] : {}; + } else if (name === 'slave4') { + tableConfig = formData.length > 6 ? formData[6] : {}; + } + } + } + } else { + this.getServiceError(configReturn); + } + return tableConfig; + } + /* + 修改日期:2021-03-18 + 修改人:吕杰 + 区域:以下handleSaveState函数 + 需求变更:添加回调 + 原代码: + handleSaveState = (values) => { + if (this.mounted) { + this.handleSaveState(values); + } + }; + */ + /* 数据保存到state */ + handleSaveState = (values = {}, callback) => { + if (this.mounted) { + // 如果将要保存的masterConfig是合并过的,则删除掉 + if (commonUtils.isNotEmptyObject(values.masterConfig) && values.masterConfig.bMerged) { + delete values.masterConfig; + } + Object.keys(values).forEach(key => { + // 如果将要保存的slaveConfig是合并过的,则删除掉 + if (key.startsWith('slave') && key.endsWith('Config') && commonUtils.isNotEmptyObject(values[key]) && values[key].bMerged) { + delete values[key]; + } + }); + // 如果改变了主表数据,遍历下所有配置sButtonEnabled的字段,生成配置 + const addState = {}; + const sRulesJsonTotal = this.handleGetRulesJsonTotal(values); + if (sRulesJsonTotal) { + addState.sRulesJsonTotal = sRulesJsonTotal; + } + // if (commonUtils.isNotEmptyObject(addState.sRulesJsonTotal)) { + // console.log('=====sRulesJsonTotal', addState.sRulesJsonTotal); + // } + this.setState({ ...values, ...addState }, typeof callback === 'function' ? callback : undefined); + } + }; + + // 遍历下所有配置sButtonEnabled的字段,生成配置 + handleGetRulesJsonTotal = (values) => { + const { masterConfig: masterConfig1, masterData: masterData1 } = values; + const { masterConfig: masterConfig2, masterData: masterData2, sRulesJsonTotal } = this.state; + + const masterConfig = masterConfig1 || masterConfig2; + const masterData = masterData1 || masterData2; + + const condition0 = commonUtils.isEmptyObject(masterConfig1) && commonUtils.isEmptyObject(masterData1); + const condition1 = commonUtils.isNotEmptyObject(masterConfig) && commonUtils.isNotEmptyObject(masterData1); + const condition2 = commonUtils.isNotEmptyObject(masterConfig) && sRulesJsonTotal === undefined && commonUtils.isNotEmptyObject(masterData); + const condition3 = commonUtils.convertObjToStr(masterData1) === commonUtils.convertObjToStr(masterData2) && sRulesJsonTotal !== undefined; + + const { sRulesTableList = [] } = this.state; + let condition4 = false; + if (sRulesTableList.length) { + sRulesTableList.forEach(tableName => { + const { [`${tableName}Data`]: tableData1 } = values; + const { [`${tableName}Data`]: tableData2 = [] } = this.state; + if (tableData1 !== undefined && commonUtils.convertObjToStr(tableData1) !== commonUtils.convertObjToStr(tableData2)) { + condition4 = true; + } + }) + } + + if (condition0 || !(condition1 || condition2) || condition3) { + if (!condition4) { + return ''; + } + } + + const { gdsconfigformslave = [] } = masterConfig; + return gdsconfigformslave.reduce((result, config) => { + const { sButtonEnabled } = config; + const sRulesJson = commonUtils.convertStrToObj(sButtonEnabled, []); + if (commonUtils.isNotEmptyArr(sRulesJson)) { + for (let i = 0; i < sRulesJson.length; i += 1) { + const rule = sRulesJson[i] || {}; + const { condition = [] } = rule; + let flag = false; // 是否满足条件 + for (let j = 0; j < condition.length; j += 1) { + const item = condition[j]; + const { bFilterName, bFilterCondition, bFilterValue, jsCondition } = item; + if (jsCondition) { + flag = commonFunc.getEvalResult({ + props: {...this.props, ...this.state, ...values}, + str: jsCondition, + defaultValue: false, + reocrdRules: true, + onSaveState: this.handleSaveState, + }) + console.log('=====jsCondition', jsCondition, flag); + } else if (bFilterName !== undefined && bFilterCondition !== undefined && bFilterValue !== undefined) { + const currentValue = masterData[bFilterName]; + flag = this.handleCompareValues(currentValue, bFilterValue, bFilterCondition); + } + if (!flag) { + break; + } + } + if (flag) { + // console.log('=====匹配的规则', config, rule); + const columnList = Object.keys(rule).filter(columnName => columnName && columnName.indexOf('Column') !== -1); + columnList.forEach((columnName) => { + if (commonUtils.isEmptyArr(result[columnName])) { + result[columnName] = []; + } + result[columnName] = Array.from(new Set([...result[columnName], ...rule[columnName]])); + }); + // return result; + } + } + } + return result; + }, {}); + } + + // 根据两个值是否满足比较条件 + handleCompareValues = (value1, value2, compare) => { + if (value1 === undefined || value2 === undefined) { + return false; + } + switch (compare) { + case '=': + return value1 == value2; // eslint-disable-line + case '==': + return value1 === value2; + case '!=': + return value1 !== value2; + case '>': + return value1 > value2; + case '>=': + return value1 >= value2; + case '<': + return value1 < value2; + case '<=': + return value1 <= value2; + case 'like': + return value1.includes(value2); + default: + return false; + } + } + + // 合并主表配置和所有sButtonEnabled配置 + handleMergeMasterConfig = (config) => { + const { masterConfig: masterConfigOld, sRulesJsonTotal } = this.state; + const masterConfig = commonUtils.isNotEmptyObject(config) ? config : masterConfigOld; + if (commonUtils.isEmptyObject(masterConfig)) { + return {}; + } + if (commonUtils.isEmptyObject(sRulesJsonTotal)) { + return masterConfig; + } + const masterConfigNew = lodash.cloneDeep(masterConfig); + const { gdsconfigformslave } = masterConfigNew; + if (commonUtils.isNotEmptyArr(sRulesJsonTotal.showColumn)) { + sRulesJsonTotal.showColumn.filter(item => item).forEach((item) => { + const iIndex = gdsconfigformslave.findIndex(child => item === child.sName); + if (iIndex !== -1) { + gdsconfigformslave[iIndex].bVisible = true; + } + }); + } + + if (commonUtils.isNotEmptyArr(sRulesJsonTotal.hideColumn)) { + sRulesJsonTotal.hideColumn.filter(item => item).forEach((item) => { + const iIndex = gdsconfigformslave.findIndex(child => item === child.sName); + if (iIndex !== -1) { + gdsconfigformslave[iIndex].bVisible = false; + } + }); + } + + if (commonUtils.isNotEmptyArr(sRulesJsonTotal.mustColumn)) { + sRulesJsonTotal.mustColumn.filter(item => item).forEach((item) => { + const iIndex = gdsconfigformslave.findIndex(child => item === child.sName); + if (iIndex !== -1) { + gdsconfigformslave[iIndex].bNotEmpty = true; + } + }); + } + + if (commonUtils.isNotEmptyArr(sRulesJsonTotal.readOnlyColumn)) { + sRulesJsonTotal.readOnlyColumn.filter(item => item).forEach((item) => { + const iIndex = gdsconfigformslave.findIndex(child => item === child.sName); + if (iIndex !== -1) { + gdsconfigformslave[iIndex].bReadonly = true; + } + }); + } + return { ...masterConfigNew, bMerged: true }; + } + + // 合并从表配置和所有sButtonEnabled配置 + handleMergeSlaveConfig = (tableConfig) => { + const { sRulesJsonTotal } = this.state; + if (commonUtils.isEmptyObject(tableConfig)) { + return {}; + } + if (commonUtils.isEmptyObject(sRulesJsonTotal)) { + return tableConfig; + } + const { sTbName } = tableConfig; + const tableConfigNew = lodash.cloneDeep(tableConfig); + const { gdsconfigformslave } = tableConfigNew; + if (commonUtils.isNotEmptyArr(sRulesJsonTotal.showColumn)) { + sRulesJsonTotal.showColumn.filter(item => item).forEach((item) => { + const iIndex = gdsconfigformslave.findIndex(child => item === `${sTbName}.${child.sName}`); + if (iIndex !== -1) { + gdsconfigformslave[iIndex].bVisible = true; + } + const iIndex1 = gdsconfigformslave.findIndex(child => `${sTbName}.${child.sControlName}`.includes(item)); + if (iIndex1 !== -1) { + if (gdsconfigformslave[iIndex1].sControlName.includes('DividerArea')) { + gdsconfigformslave[iIndex1].sControlName = gdsconfigformslave[iIndex1].sControlName.split('.hide')[0]; + } else { + gdsconfigformslave[iIndex1].bControl = true; + } + } + }); + } + + if (commonUtils.isNotEmptyArr(sRulesJsonTotal.hideColumn)) { + sRulesJsonTotal.hideColumn.filter(item => item).forEach((item) => { + const iIndex = gdsconfigformslave.findIndex(child => item === `${sTbName}.${child.sName}`); + if (iIndex !== -1) { + gdsconfigformslave[iIndex].bVisible = false; + } + const iIndex1 = gdsconfigformslave.findIndex(child => `${sTbName}.${child.sControlName}`.includes(item)); + if (iIndex1 !== -1) { + if (gdsconfigformslave[iIndex1].sControlName.includes('DividerArea')) { + gdsconfigformslave[iIndex1].sControlName = `${gdsconfigformslave[iIndex1].sControlName}.hide`; + } else { + gdsconfigformslave[iIndex1].bControl = false; + } + } + }); + } + + if (commonUtils.isNotEmptyArr(sRulesJsonTotal.mustColumn)) { + sRulesJsonTotal.mustColumn.filter(item => item).forEach((item) => { + const iIndex = gdsconfigformslave.findIndex(child => item === `${sTbName}.${child.sName}`); + if (iIndex !== -1) { + gdsconfigformslave[iIndex].bNotEmpty = true; + } + }); + } + + if (commonUtils.isNotEmptyArr(sRulesJsonTotal.readOnlyColumn)) { + sRulesJsonTotal.readOnlyColumn.filter(item => item).forEach((item) => { + const iIndex = gdsconfigformslave.findIndex(child => item === `${sTbName}.${child.sName}`); + if (iIndex !== -1) { + gdsconfigformslave[iIndex].bReadonly = true; + } + }); + } + return { ...tableConfigNew, bMerged: true }; + } + + /** 修改主表数据 */ + handleMasterChange = (name, sFieldName, changeValue, sId, dropDownData, isWait, masterDataNew) => { + const { masterData: masterDataOld } = this.state; + const { + sModelsId, masterConfig, slaveConfig, slave0Config, slave1Config, slave2Config, slave3Config, slave4Config, slave5Config, + } = this.state; + const addState = {}; + let masterData = masterDataNew === undefined ? masterDataOld === undefined ? {} : masterDataOld : masterDataNew; + let { handleType } = masterData; + handleType = commonUtils.isEmpty(handleType) ? 'update' : handleType; + if (sFieldName.substring(0, 1).toLowerCase() === 'c') { + const sAllField = sFieldName.substring(1, sFieldName.length); + const allField = sAllField.split('_'); + const value = changeValue[sFieldName]; + allField.forEach((item, iArr) => { + if (value.length > iArr) { + changeValue[item] = value[iArr]; + } + }); + } + const bClearSelectedRowKeys = location.pathname.includes('commonList') ? false : true; /* 是否清除从表选择行 */ + if (!commonUtils.isEmpty(masterConfig.gdsconfigformslave) && commonUtils.isNotEmptyArr(masterConfig.gdsconfigformslave) && !commonUtils.isEmpty(sFieldName)) { + masterConfig.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && !commonUtils.isEmpty(item.sChineseDropDown) && + (item.sChineseDropDown.includes(`#${sFieldName}`) || item.sChineseDropDown.includes(`*${sFieldName}`)) && + (item.sSqlCondition.includes(sFieldName) || item.sSqlCondition.includes(sFieldName.replace('Name', 'Id')))).forEach((item) => { + commonUtils.setStoreDropDownData(sModelsId, name, item.sName, []); + }); + if (commonUtils.isNotEmptyObject(slaveConfig)) { + slaveConfig.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && !commonUtils.isEmpty(item.sChineseDropDown) && + (item.sChineseDropDown.includes(`#${sFieldName}`) || item.sChineseDropDown.includes(`*${sFieldName}`)) && + (item.sSqlCondition.includes(`master.${sFieldName}`) || item.sSqlCondition.includes(sFieldName.replace('Name', 'Id')))).forEach((item) => { + commonUtils.setStoreDropDownData(sModelsId, 'slave', item.sName, []); + if (bClearSelectedRowKeys) { + addState.slaveSelectedRowKeys = []; + } + }); + } + if (commonUtils.isNotEmptyObject(slave0Config)) { + slave0Config.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && !commonUtils.isEmpty(item.sChineseDropDown) && + (item.sChineseDropDown.includes(`#${sFieldName}`) || item.sChineseDropDown.includes(`*${sFieldName}`)) && + (item.sSqlCondition.includes(`master.${sFieldName}`) || item.sSqlCondition.includes(sFieldName.replace('Name', 'Id')))).forEach((item) => { + commonUtils.setStoreDropDownData(sModelsId, 'slave0', item.sName, []); + if (bClearSelectedRowKeys) { + addState.slave0SelectedRowKeys = []; + } + }); + } + if (commonUtils.isNotEmptyObject(slave1Config)) { + slave1Config.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && !commonUtils.isEmpty(item.sChineseDropDown) && + (item.sChineseDropDown.includes(`#${sFieldName}`) || item.sChineseDropDown.includes(`*${sFieldName}`)) && + (item.sSqlCondition.includes(`master.${sFieldName}`) || item.sSqlCondition.includes(sFieldName.replace('Name', 'Id')))).forEach((item) => { + commonUtils.setStoreDropDownData(sModelsId, 'slave1', item.sName, []); + if (bClearSelectedRowKeys) { + addState.slave1SelectedRowKeys = []; + } + }); + } + if (commonUtils.isNotEmptyObject(slave2Config)) { + slave2Config.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && !commonUtils.isEmpty(item.sChineseDropDown) && + (item.sChineseDropDown.includes(`#${sFieldName}`) || item.sChineseDropDown.includes(`*${sFieldName}`)) && + (item.sSqlCondition.includes(`master.${sFieldName}`) || item.sSqlCondition.includes(sFieldName.replace('Name', 'Id')))).forEach((item) => { + commonUtils.setStoreDropDownData(sModelsId, 'slave2', item.sName, []); + if (bClearSelectedRowKeys) { + addState.slave2SelectedRowKeys = []; + } + }); + } + if (commonUtils.isNotEmptyObject(slave3Config)) { + slave3Config.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && !commonUtils.isEmpty(item.sChineseDropDown) && + (item.sChineseDropDown.includes(`#${sFieldName}`) || item.sChineseDropDown.includes(`*${sFieldName}`)) && + (item.sSqlCondition.includes(`master.${sFieldName}`) || item.sSqlCondition.includes(sFieldName.replace('Name', 'Id')))).forEach((item) => { + commonUtils.setStoreDropDownData(sModelsId, 'slave3', item.sName, []); + if (bClearSelectedRowKeys) { + addState.slave3SelectedRowKeys = []; + } + }); + } + if (commonUtils.isNotEmptyObject(slave4Config)) { + slave4Config.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && !commonUtils.isEmpty(item.sChineseDropDown) && + (item.sChineseDropDown.includes(`#${sFieldName}`) || item.sChineseDropDown.includes(`*${sFieldName}`)) && + (item.sSqlCondition.includes(`master.${sFieldName}`) || item.sSqlCondition.includes(sFieldName.replace('Name', 'Id')))).forEach((item) => { + commonUtils.setStoreDropDownData(sModelsId, 'slave4', item.sName, []); + if (bClearSelectedRowKeys) { + addState.slave4SelectedRowKeys = []; + } + }); + } + if (commonUtils.isNotEmptyObject(slave5Config)) { + slave5Config.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && !commonUtils.isEmpty(item.sChineseDropDown) && + (item.sChineseDropDown.includes(`#${sFieldName}`) || item.sChineseDropDown.includes(`*${sFieldName}`)) && + (item.sSqlCondition.includes(`master.${sFieldName}`) || item.sSqlCondition.includes(sFieldName.replace('Name', 'Id')))).forEach((item) => { + commonUtils.setStoreDropDownData(sModelsId, 'slave5', item.sName, []); + if (bClearSelectedRowKeys) { + addState.slave5SelectedRowKeys = []; + } + }); + } + /* 字段输入时 根据规则 控制其他字段的显示与隐藏 */ + // const iConfigIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === sFieldName); + // if (iConfigIndex > -1) { + // if (commonUtils.isEmptyObject(masterConfig.bak)) { + // masterConfig.bak = JSON.parse(JSON.stringify(masterConfig)); + // } + // const sFiledConfig = masterConfig.gdsconfigformslave[iConfigIndex]; + // if (commonUtils.isNotEmptyObject(sFiledConfig)) { + // const tableDataRow = { ...masterData, ...changeValue, handleType }; + // const sRulesJson = sFiledConfig.sButtonEnabled; + // if (commonUtils.isNotEmptyObject(sRulesJson) && commonUtils.isJSON(sRulesJson)) { + // const sRulesObjArr = JSON.parse(sRulesJson); + // if (commonUtils.isNotEmptyArr(sRulesObjArr)) { + // console.log('sRulesObjArr:', sRulesObjArr); + // sRulesObjArr.forEach((sRulesObj) => { + // const { + // showColumn, hideColumn, condition, tbName, sConfigName, + // } = sRulesObj; + // console.log('tbName:', tbName); + // /* 主表单表字段根据条件控制 其他字段的显示与隐藏 */ + // if (commonUtils.isEmptyObject(tbName)) { + // if (commonUtils.isNotEmptyArr(condition)) { + // let flag = false; + // for (const item of condition) { + // const { + // bFilterName, bFilterCondition, bFilterValue, + // } = item; + // if (bFilterCondition === '>') { + // if (tableDataRow[bFilterName] > bFilterValue) { + // flag = true; + // } + // } else if (bFilterCondition === '=') { + // if (tableDataRow[bFilterName] === bFilterValue) { + // flag = true; + // } + // } else if (bFilterCondition === '<') { + // if (tableDataRow[bFilterName] < bFilterValue) { + // flag = true; + // } + // } + // } + // if (flag) { + // if (commonUtils.isNotEmptyArr(showColumn)) { + // for (const column of showColumn) { + // const iShowIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === column); + // if (iShowIndex > -1) { + // const sFiledObj = masterConfig.gdsconfigformslave[iShowIndex]; + // if (commonUtils.isNotEmptyObject(sFiledObj)) { + // if (commonUtils.isNotEmptyObject(sConfigName) && sConfigName === 'bControl') { + // masterConfig.gdsconfigformslave[iShowIndex].bControl = true; /* 控制字段bControl的显示与隐藏 */ + // } else { + // masterConfig.gdsconfigformslave[iShowIndex].bVisible = true; + // } + // } + // } + // } + // } + // if (commonUtils.isNotEmptyArr(hideColumn)) { + // for (const column of hideColumn) { + // const iHideIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === column); + // if (iHideIndex > -1) { + // if (commonUtils.isNotEmptyObject(sConfigName) && sConfigName === 'bControl') { + // masterConfig.gdsconfigformslave[iHideIndex].bControl = true; /* 控制字段bControl的显示与隐藏 */ + // } else { + // masterConfig.gdsconfigformslave[iHideIndex].bVisible = false; + // } + // } + // } + // } + // addState.masterConfig = masterConfig; + // } + // } + // } else { /* 主表字段根据条件控制 其他表格字段的显示与隐藏 */ + // const { [`${tbName}Config`]: tableConfig } = this.state; + // // const { controlConfig: tableConfig } = this.state; + // if (commonUtils.isNotEmptyObject(tableConfig)) { + // if (commonUtils.isNotEmptyArr(condition)) { + // let flag = false; + // for (const item of condition) { + // const { + // bFilterName, bFilterCondition, bFilterValue, + // } = item; + // if (bFilterCondition === '>') { + // if (tableDataRow[bFilterName] > bFilterValue) { + // flag = true; + // } + // } else if (bFilterCondition === '=') { + // if (tableDataRow[bFilterName] === bFilterValue) { + // flag = true; + // } + // } else if (bFilterCondition === '<') { + // if (tableDataRow[bFilterName] < bFilterValue) { + // flag = true; + // } + // } + // } + // if (flag) { + // if (commonUtils.isNotEmptyArr(showColumn)) { + // for (const column of showColumn) { + // const iShowIndex = tableConfig.gdsconfigformslave.findIndex(item => item.sName === column); + // if (iShowIndex > -1) { + // const sFiledObj = tableConfig.gdsconfigformslave[iShowIndex]; + // if (commonUtils.isNotEmptyObject(sFiledObj)) { + // tableConfig.gdsconfigformslave[iShowIndex].bVisible = true; + // } + // } + // } + // } + // if (commonUtils.isNotEmptyArr(hideColumn)) { + // for (const column of hideColumn) { + // const iHideIndex = tableConfig.gdsconfigformslave.findIndex(item => item.sName === column); + // if (iHideIndex > -1) { + // const sFiledObj = tableConfig.gdsconfigformslave[iHideIndex]; + // if (commonUtils.isNotEmptyObject(sFiledObj)) { + // tableConfig.gdsconfigformslave[iHideIndex].bVisible = false; + // } + // } + // } + // } + // if (commonUtils.isNotEmptyObject(tableConfig)) { + // const tableColumn = commonFunc.getHeaderConfig(tableConfig); + // // addState.masterConfig = masterConfig; + // // addState.controlConfig = tableConfig; /* 表格配置塞到addState中 */ + // // addState.controlColumn = tbColumn; + // addState[`${tbName}Config`] = tableConfig; + // addState[`${tbName}Column`] = tableColumn; + // } + // } + // } + // } + // } + // }); + // } + // } + // } + + // // if (commonUtils.isEmptyObject(addState.masterConfig) && commonUtils.isNotEmptyObject(masterConfig.bak)) { + // // addState.masterConfig = masterConfig.bak; + // // } + // } + } + + masterData = { ...masterData, ...changeValue, handleType }; + + const { dGramWeight, dWlcd, dWlkd, iNumerator } = masterData; + if ( + ( + ['dGramWeight', 'dWlcd', 'dWlkd', 'iNumerator'].includes(sFieldName) || + commonUtils.isEmptyObject(changeValue) + ) && + !commonUtils.isEmpty(dGramWeight) && + !commonUtils.isEmpty(dWlcd) && + !commonUtils.isEmpty(dWlkd) && + !commonUtils.isEmpty(iNumerator) + ) { + masterData = commonBusiness.getMaterialsQty(this.props.app, { ...masterData, sMaterialsStyle: `${dWlcd}*${dWlkd}` }, 'iNumerator', 'iDenominatr'); + if (masterData.iDenominatr) { + masterData.iDenominatr = Number(masterData.iDenominatr).toFixed(0); + } + } + + if (isWait) { + return { masterData, ...addState }; // , sUseInfo: '' + } else if (this.mounted) { + this.handleSaveState({ masterData, ...addState }); // , sUseInfo: '' + return { masterData, ...addState }; + } + }; + + /** 表格数据更改 */ + // name 不写完整的state名称作用为了要用到total // (name, changeValue, sId, dropDownData) + handleTableChange = (name, sFieldName, changeValue, sId, dropDownData, isWait) => { + const { + [`${name}Config`]: tableConfig, sModelsId, masterData, slaveData, controlData, materialsData, processData, slaveInfoData, slaveChildData, + slaveSelectedRowKeys, slaveInfoSelectedRowKeys, controlSelectedRowKeys, materialsSelectedRowKeys, processSelectedRowKeys, slaveChildSelectedRowKeys, + } = this.state; + const { app } = this.props; + let { [`${name}Data`]: tableData } = this.state; + if (name === 'slave' && window.tmpSlaveData) { + tableData = window.tmpSlaveData; + } + const iIndex = tableData.findIndex(item => item.sId === sId); + let { handleType } = tableData[iIndex]; + handleType = commonUtils.isEmpty(handleType) ? 'update' : handleType; + if (sFieldName.substring(0, 1).toLowerCase() === 'c') { + const sAllField = sFieldName.substring(1, sFieldName.length); + const allField = sAllField.split('_'); + const value = changeValue[sFieldName]; + allField.forEach((item, iArr) => { + if (value.length > iArr) { + changeValue[item] = value[iArr]; + } + }); + } + + if (!commonUtils.isEmpty(tableConfig.gdsconfigformslave) && commonUtils.isNotEmptyArr(tableConfig.gdsconfigformslave) && !commonUtils.isEmpty(sFieldName)) { + tableConfig.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && !commonUtils.isEmpty(item.sChineseDropDown) && + (item.sChineseDropDown.includes(`#${sFieldName}`) || item.sChineseDropDown.includes(`*${sFieldName}`)) && + (item.sSqlCondition.includes(`master.${sFieldName}`) || item.sSqlCondition.includes(sFieldName.replace('Name', 'Id')))).forEach((item) => { + commonUtils.setStoreDropDownData(sModelsId, 'slave', item.sName, []); + }); + // tableConfig.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && item.sSqlCondition.includes(sFieldName)).forEach((item) => { + // commonUtils.setStoreDropDownData(sModelsId, name, item.sName, []); + // }); + + /* 字段输入时 根据规则 控制其他字段的显示与隐藏 */ + const iConfigIndex = tableConfig.gdsconfigformslave.findIndex(item => item.sName === sFieldName); + if (iConfigIndex > -1) { + const sFiledConfig = tableConfig.gdsconfigformslave[iConfigIndex]; + if (commonUtils.isNotEmptyObject(sFiledConfig)) { + const tableDataRow = { ...tableData[iIndex], ...changeValue, handleType }; + const sRulesJson = sFiledConfig.sButtonEnabled; + if (commonUtils.isNotEmptyObject(sRulesJson) && commonUtils.isJSON(sRulesJson)) { + const sRulesObj = JSON.parse(sRulesJson); + if (commonUtils.isNotEmptyObject(sRulesObj)) { + const { showColumn, hideColumn, condition } = sRulesObj; + if (commonUtils.isNotEmptyArr(condition)) { + let flag = false; + for (const item of condition) { + const { + bFilterName, bFilterCondition, bFilterValue, + } = item; + if (bFilterCondition === '>') { + if (tableDataRow[bFilterName] > bFilterValue) { + flag = true; + } + } else if (bFilterCondition === '=') { + if (tableDataRow[bFilterName] === bFilterValue) { + flag = true; + } + } else if (bFilterCondition === '<') { + if (tableDataRow[bFilterName] < bFilterValue) { + flag = true; + } + } + } + if (flag) { + if (commonUtils.isNotEmptyArr(showColumn)) { + for (const column of showColumn) { + const iShowIndex = tableConfig.gdsconfigformslave.findIndex(item => item.sName === column); + if (iShowIndex > -1) { + const sFiledObj = tableConfig.gdsconfigformslave[iShowIndex]; + if (commonUtils.isNotEmptyObject(sFiledObj)) { + tableConfig.gdsconfigformslave[iShowIndex].bVisible = true; + } + } + } + } + if (commonUtils.isNotEmptyArr(hideColumn)) { + for (const column of hideColumn) { + const iHideIndex = tableConfig.gdsconfigformslave.findIndex(item => item.sName === column); + if (iHideIndex > -1) { + tableConfig.gdsconfigformslave[iHideIndex].bVisible = false; + } + } + } + + const tableColumn = commonFunc.getHeaderConfig(tableConfig); + this.handleSaveState({ [`${name}Config`]: tableConfig, [`${name}Column`]: tableColumn }); + } + } + } + } + } + } + /* 将选中行塞到tableSelectedData数据集合中 */ + let slaveRow = {}; + let controlRow = {}; + let materialsRow ={}; + let processRow = {}; + let slaveInfoRow = {}; + let slaveChildRow = {}; + if(commonUtils.isNotEmptyArr(slaveData) && commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) { + const iSIndex = slaveData.findIndex(item =>slaveSelectedRowKeys.includes(item.sId)); + if(iSIndex > -1) { + slaveRow = slaveData[iSIndex]; + } + } + if(commonUtils.isNotEmptyArr(slaveInfoData) && commonUtils.isNotEmptyArr(slaveInfoSelectedRowKeys)) { + const iSIndex = slaveInfoData.findIndex(item =>slaveInfoSelectedRowKeys.includes(item.sId)); + if(iSIndex > -1) { + slaveInfoRow = slaveInfoData[iSIndex]; + } + } + if(commonUtils.isNotEmptyArr(slaveChildData) && commonUtils.isNotEmptyArr(slaveChildSelectedRowKeys)) { + const iSIndex = slaveChildData.findIndex(item => slaveChildSelectedRowKeys.includes(item.sId)); + if(iSIndex > -1) { + slaveChildRow = slaveChildData[iSIndex]; + } + } + if(commonUtils.isNotEmptyArr(controlData) && commonUtils.isNotEmptyArr(controlSelectedRowKeys)) { + const iCIndex = controlData.findIndex(item => controlSelectedRowKeys.includes(item.sId)); + if(iCIndex > -1) { + controlRow = controlData[iCIndex]; + } + } + if(commonUtils.isNotEmptyArr(materialsData) && commonUtils.isNotEmptyArr(materialsSelectedRowKeys)) { + const iMIndex = materialsData.findIndex(item => materialsSelectedRowKeys.includes(item.sId)); + if(iMIndex > -1) { + materialsRow = materialsData[iMIndex]; + } + } + if(commonUtils.isNotEmptyArr(processData) && commonUtils.isNotEmptyArr(processSelectedRowKeys)) { + const iPIndex = processData.findIndex(item => processSelectedRowKeys.includes(item.sId)); + if(iIndex > -1) { + processRow = processData[iPIndex]; + } + } + + const tableAllData = { + master: masterData, + slave: slaveData, + control: controlData, + materials: materialsData, + process: processData, + slaveInfo: slaveInfoData, + slaveChild: slaveChildData, + + }; + const tableSelectedData = { + master: masterData, + slaveRow: slaveRow, + controlRow: controlRow, + materialsRow: materialsRow, + processRow: processRow, + slaveInfoRow: slaveInfoRow, + slaveChildRow: slaveChildRow, + } + + const tableDataRowNew = { ...tableData[iIndex], ...changeValue, handleType }; + const tableDataAfter = commonBusiness.getKeyUpEvent(name, sFieldName, tableConfig, masterData, tableDataRowNew, true, tableAllData, tableSelectedData, app); + if (commonUtils.isNotEmptyObject(tableDataAfter)) { + changeValue = { ...tableDataAfter }; + } + } + if (isWait) { + return { ...tableData[iIndex], ...changeValue, handleType }; + } else { + tableData[iIndex] = { ...tableData[iIndex], ...changeValue, handleType }; + if (this.mounted) { + this.handleSaveState({ [`${name}Data`]: tableData, sUseInfo: '' }); + } + } + }; + /** 添加表格空行 */ + handleTableAdd = (name, isWait) => { + /* 外置处理业务 */ + const { + [`${name}Config`]: tableConfig, masterData, slaveData, slaveSelectedRowKeys, controlData, controlSelectedRowKeys, processData, processSelectedRowKeys, materialsData, materialsSelectedRowKeys + } = this.state; + let { [`${name}Data`]: tableData } = this.state; + tableData = commonUtils.isEmptyObject(tableData) ? [] : tableData; + const allTableData = {}; + allTableData.master = masterData; + if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) { + const iSlaveIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys.toString()); + allTableData.slave = slaveData[iSlaveIndex]; + } + if (commonUtils.isNotEmptyArr(controlSelectedRowKeys) && commonUtils.isNotEmptyArr(controlData)) { + const iSlaveIndex = controlData.findIndex(item => item.sId === controlSelectedRowKeys.toString()); + allTableData.control = controlData[iSlaveIndex]; + } + if (commonUtils.isNotEmptyArr(processSelectedRowKeys)) { + const iSlaveIndex = processData.findIndex(item => item.sId === processSelectedRowKeys.toString()); + allTableData.process = processData[iSlaveIndex]; + } + if (commonUtils.isNotEmptyArr(materialsSelectedRowKeys)) { + const iSlaveIndex = materialsData.findIndex(item => item.sId === materialsSelectedRowKeys.toString()); + allTableData.materials = materialsData[iSlaveIndex]; + } + + const iOrderArr = []; + tableData.forEach((item) => { + const iOrder = commonUtils.isNotEmptyNumber(item.iOrder) ? item.iOrder : 0; /* 获取tableData中iOrder最大值 */ + iOrderArr.push(iOrder); + }); + const iOrderMax = Math.max(...iOrderArr); + let tableDataRow = {}; + tableDataRow.handleType = 'add'; + tableDataRow.sId = commonUtils.createSid(); + tableDataRow.sParentId = masterData && masterData.sId ? masterData.sId : null; + tableDataRow.key = tableDataRow.sId; + tableDataRow.bDefault = false; + tableDataRow.iOrder = commonUtils.isNotEmptyArr(tableData) ? iOrderMax + 1 : 1; + tableDataRow.defaultAdded = tableData.length === 0; + allTableData.self = tableDataRow; + if(tableConfig.sTableType === 'single' || name === 'control') { + tableDataRow.sNodeId = commonUtils.createSid(); /* 用于建立关联关系 */ + } + tableDataRow = { ...tableDataRow, ...commonFunc.getDefaultData(tableConfig, allTableData)}; + if (isWait) { + return tableDataRow; + } else { + // tableData.splice(index, 1, tableDataRow); /* 该处会导致新增时删除首行 */ + tableData.push(tableDataRow); + if (this.mounted) { + this.handleSaveState({ [`${name}Data`]: tableData, [`${name}SelectedRowKeys`]: [tableDataRow.sId] }); + } + } + }; + + // name 不写完整的state名称作用为了要用到total + /** 删除表格数据 */ + handleTableDel = (name, isWait, tableSelectedRowKeys, callback) => { + const { app } = this.props; + const { [`${name}Data`]: tableDataOld = [] } = this.state; + let { [`${name}DelData`]: tableDelDataOld = [], [`${name}Pagination`]: pagination = {} } = this.state; + const tableData = [...tableDataOld]; + const tableDelData = [...tableDelDataOld]; + if (commonUtils.isNotEmptyArr(tableSelectedRowKeys)) { + for (const sId of tableSelectedRowKeys) { + /* 看看删除集合和从表中是否都存在该条数据 */ + let tableDataIndex = tableData.findIndex(item => item.sId === sId); + while (tableDataIndex > -1) { + /* 删除从表中的数据并存入删除集合中 */ + const slaveDataFilter = tableData[tableDataIndex]; + tableData.splice(tableDataIndex, 1); + slaveDataFilter.handleType = 'del'; + tableDelData.push(slaveDataFilter); + tableDataIndex = tableData.findIndex(item => item.sId === sId); + } + } + + const addState = {}; + if (commonUtils.isNotEmptyObject(pagination)) { + addState[`${name}Pagination`] = { + ...pagination, + total: tableData.length, + } + } + let newSelectedRowKeys = []; + if(name === 'slave') { /* 删除后定位最后一条 */ + if(commonUtils.isNotEmptyArr(tableData)) { + const len = tableData.length -1; + newSelectedRowKeys = [tableData[len].sId]; + } + } + + if (isWait) { + return { [`${name}Data`]: tableData, [`${name}DelData`]: tableDelData, [`${name}SelectedRowKeys`]: newSelectedRowKeys, ...addState }; + } else { + if (this.mounted) { + this.handleSaveState({ + [`${name}Data`]: tableData, + [`${name}DelData`]: tableDelData, + [`${name}SelectedRowKeys`]: [], + ...addState, + }, () => { + callback && callback(); + }); + } + return true; + } + } else { + if (!isWait) { + message.warn(commonFunc.showMessage(app.commonConst, 'pleaseChooseDelData')); // 请选择删除数据 + } + return false; + } + }; + + /** 处理选择行发生改变 */ + handleTableSelectRowChange = (name, selectedRowKeys, isWait) => { + /* 外置处理业务 */ + const { + formRoute, slaveData, sModelsId, [`${name}Config`]: tableConfig, + } = this.state; + let { slaveSelectedData } = this.state; + const addState = {}; + addState[`${name}SelectedRowKeys`] = selectedRowKeys; + addState.searchUpDownData = {}; + const formRouteArr = [ + '/indexPage/commonList', + '/indexPage/commonListEdit', + '/indexPage/commonListTree', + '/indexPage/commonListLeft' + ]; + if (name === 'slave' && (formRouteArr.includes(formRoute) || formRoute.indexOf('/indexOee') > -1)) { + const slavePageData = slaveData.filter(item => selectedRowKeys.includes(item.sSlaveId)); + slaveSelectedData = commonUtils.isEmpty(slaveSelectedData) ? [] : slaveSelectedData.filter(item => selectedRowKeys.toString().includes(item.sSlaveId)); + selectedRowKeys.forEach((item) => { + const iIndex = slaveSelectedData.findIndex(selectItem => selectItem.sSlaveId === item); + if (iIndex === -1) { + const iPageIndex = slavePageData.findIndex(pageItem => pageItem.sSlaveId === item); + if (iPageIndex > -1) { + slaveSelectedData.push(slavePageData[iPageIndex]); + } + } + }); + addState.slaveSelectedData = slaveSelectedData; + } + if (commonUtils.isNotEmptyObject(tableConfig)) { + tableConfig.gdsconfigformslave.forEach((configItem) => { + const sFieldName = configItem.sName; + if (!commonUtils.isEmpty(tableConfig.gdsconfigformslave) && commonUtils.isNotEmptyArr(tableConfig.gdsconfigformslave) && !commonUtils.isEmpty(sFieldName) && + (commonUtils.isEmptyArr(this.state[`${name}SelectedRowKeys`]) || selectedRowKeys.toString() !== this.state[`${name}SelectedRowKeys`].toString())) { + tableConfig.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && !commonUtils.isEmpty(item.sChineseDropDown) && + (item.sChineseDropDown.includes(`#${sFieldName}`) || item.sChineseDropDown.includes(`*${sFieldName}`)) && + (item.sSqlCondition.includes(`master.${sFieldName}`) || item.sSqlCondition.includes(sFieldName.replace('Name', 'Id')))).forEach((item) => { + commonUtils.setStoreDropDownData(sModelsId, 'slave', item.sName, []); + }); + // tableConfig.gdsconfigformslave.filter(item => !commonUtils.isEmpty(item.sSqlCondition) && item.sSqlCondition.includes(sFieldName)).forEach((item) => { + // commonUtils.setStoreDropDownData(sModelsId, name, item.sName, []); + // }); + } + }); + } + if (this.mounted) { + if (isWait) { + return addState; + } else { + this.handleSaveState(addState); + } + } + }; + + handleViewClick = (name, sName, record, index) => { + const { + [`${name}Config`]: slaveConfig, customConfig, [`${name}Data`]: slaveData, [`${name}Pagination`]: slavePagination, formSrcRoute, masterConfig, + } = this.state; + let { + [`${name}FilterCondition`]: slaveFilterCondition, + } = this.state; + let picArr = slaveConfig?.gdsconfigformslave.filter(item => (item.sName === sName)); + if (commonUtils.isNotEmptyArr(customConfig)) { + picArr = customConfig.filter(item => item.sName === sName); + } + if (commonUtils.isNotEmptyObject(sName) && sName.includes('BtnEject')) { + picArr = masterConfig.gdsconfigformslave.filter(item => item.bVisible && item.sControlName === sName); + } + if (picArr.length > 0) { + const tableDataRow = record; + const iIndex = index; + // let tableDataRow = {}; + // let iIndex = 0; + /* 判断slaveData是数组还是对象 */ + // if (commonUtils.isNotEmptyObject(slaveData) && slaveData.length > 0) { + // iIndex = slaveData.findIndex(item => item.sId === sId); + // tableDataRow = iIndex > -1 ? slaveData[iIndex] : {}; + // } else if (commonUtils.isNotEmptyObject(slaveData)) { + // tableDataRow = slaveData; + // } + const [{ sActiveId }] = picArr; + let [{ sActiveKey }] = picArr; + const sFormId = sActiveId === '1' ? commonUtils.isEmpty(tableDataRow.sFormId) ? tableDataRow.sSrcFormId : tableDataRow.sFormId : sActiveId; + if (commonUtils.isNotEmptyObject(sActiveKey) && sActiveKey.includes('.')) { /* 接口按钮跳转 如果有slave.对应字段 则需要取出对应字段 */ + const index = sActiveKey.lastIndexOf('.'); + sActiveKey = sActiveKey.substring(index + 1, sActiveKey.length); + } + const sNameUrl = `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sFormId}?sModelsId=${sFormId}&sName=${formSrcRoute}`; + const filterCondition = []; + const conditionValues = this.getSqlCondition(picArr[0], name, tableDataRow); + if (!commonUtils.isEmpty(conditionValues)) { + Object.keys(conditionValues).forEach((item) => { + if ((item === 'tStartDate_pro' || item.substring(0, 1) === 'p')) { + if (!commonUtils.isEmpty(conditionValues[item]) && conditionValues[item].length >= 2) { + const tStartDate = moment(conditionValues[item][0]).format(this.sDateFormat); + const tEndDate = moment(conditionValues[item][1]).add(1, 'days').format(this.sDateFormat); + filterCondition.push({ + bFilterName: item, + bFilterCondition: '=', + bFilterValue: `${tStartDate},${tEndDate}`, + }); + } + } else if ((item === 'mStartDate_pro' || item.substring(0, 1) === 'm')) { + if (!commonUtils.isEmpty(conditionValues[item])) { + const tStartDate = moment(conditionValues[item]).startOf('month').format(this.sDateFormat); + const tEndDate = moment(conditionValues[item]).endOf('month').add(1, 'days').format(this.sDateFormat); + filterCondition.push({ + bFilterName: `t${item.substring(1, item.length)}`, + bFilterCondition: '=', + bFilterValue: `${tStartDate},${tEndDate}`, + }); + } + } else if (item.substring(0, 1) === 't') { + filterCondition.push({ + bFilterName: item, + bFilterCondition: '=', + bFilterValue: moment(conditionValues[item]).format(this.sDateFormat), + }); + } else { + filterCondition.push({ + bFilterName: item, + bFilterCondition: '=', + bFilterValue: conditionValues[item], + }); + } + }); + } + let copyTo ={}; + let bLinkPlanTree = commonUtils.isNotEmptyObject(tableDataRow) && tableDataRow.bLinkPlanTree; + if(bLinkPlanTree) { + copyTo = { + treeKey : tableDataRow.sMachineId + tableDataRow.sWorkCenterId, + sWorkCenterName: tableDataRow.sWorkCenterName, + } + } + + let payload = { + url: sNameUrl, + sTabId: commonUtils.createSid(), + sParentId: this.state.sTabId, + urlDataType: 'newPane', + checkedId: tableDataRow[sActiveKey], + bFilter: slaveFilterCondition, + pageSize: this.state.iPageSize, + pages: slavePagination, + currentData: [tableDataRow], + conditonValues: bLinkPlanTree ? undefined : conditionValues, + sListFormmasterId: slaveConfig?.sId, + newKey: tableDataRow[sActiveKey], + currentIndex: iIndex, + filterCondition: bLinkPlanTree ? undefined : filterCondition, + copyTo: copyTo, + sSrcModelsId: this.state.sModelsId, + } + this.props.dispatch({ + type: 'content/onRouter', + payload + }); + } + }; + /* 快捷键跳转 */ + handleQuickViewClick = (name, sName, record, index, myConfigArr) => { + const { + [`${name}Config`]: slaveConfig, customConfig, [`${name}FilterCondition`]: slaveFilterCondition, [`${name}Pagination`]: slavePagination, formSrcRoute, masterConfig, + } = this.state; + + let picArr = slaveConfig.gdsconfigformslave.filter(item => (item.sName === sName)); + + if (commonUtils.isNotEmptyArr(customConfig)) { + picArr = customConfig.filter(item => item.sName === sName); + } + if (commonUtils.isNotEmptyObject(sName) && sName.includes('BtnEject')) { + picArr = masterConfig.gdsconfigformslave.filter(item => item.bVisible && item.sControlName === sName); + } + if (commonUtils.isNotEmptyArr(myConfigArr)) { + picArr = myConfigArr; + } + if (picArr.length > 0) { + const tableDataRow = record; + const iIndex = index; + // let tableDataRow = {}; + // let iIndex = 0; + /* 判断slaveData是数组还是对象 */ + // if (commonUtils.isNotEmptyObject(slaveData) && slaveData.length > 0) { + // iIndex = slaveData.findIndex(item => item.sId === sId); + // tableDataRow = iIndex > -1 ? slaveData[iIndex] : {}; + // } else if (commonUtils.isNotEmptyObject(slaveData)) { + // tableDataRow = slaveData; + // } + const [{ sActiveId }] = picArr; + let [{ sActiveKey }] = picArr; + const sFormId = sActiveId === '1' ? commonUtils.isEmpty(tableDataRow.sFormId) ? tableDataRow.sSrcFormId : tableDataRow.sFormId : sActiveId; + if (commonUtils.isNotEmptyObject(sActiveKey) && sActiveKey.includes('.')) { /* 接口按钮跳转 如果有slave.对应字段 则需要取出对应字段 */ + const index = sActiveKey.lastIndexOf('.'); + sActiveKey = sActiveKey.substring(index + 1, sActiveKey.length); + } + const sNameUrl = `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sFormId}?sModelsId=${sFormId}&sName=${formSrcRoute}`; + const filterCondition = []; + const conditionValues = this.getSqlCondition(picArr[0], name, tableDataRow); + if (!commonUtils.isEmpty(conditionValues)) { + Object.keys(conditionValues).forEach((item) => { + if ((item === 'tStartDate_pro' || item.substring(0, 1) === 'p')) { + if (!commonUtils.isEmpty(conditionValues[item]) && conditionValues[item].length >= 2) { + const tStartDate = moment(conditionValues[item][0]).format(this.sDateFormat); + const tEndDate = moment(conditionValues[item][1]).add(1, 'days').format(this.sDateFormat); + filterCondition.push({ + bFilterName: item, + bFilterCondition: '=', + bFilterValue: `${tStartDate},${tEndDate}`, + }); + } + } else if ((item === 'mStartDate_pro' || item.substring(0, 1) === 'm')) { + if (!commonUtils.isEmpty(conditionValues[item])) { + const tStartDate = moment(conditionValues[item]).startOf('month').format(this.sDateFormat); + const tEndDate = moment(conditionValues[item]).endOf('month').add(1, 'days').format(this.sDateFormat); + filterCondition.push({ + bFilterName: `t${item.substring(1, item.length)}`, + bFilterCondition: '=', + bFilterValue: `${tStartDate},${tEndDate}`, + }); + } + } else if (item.substring(0, 1) === 't') { + filterCondition.push({ + bFilterName: item, + bFilterCondition: '=', + bFilterValue: moment(conditionValues[item]).format(this.sDateFormat), + }); + } else { + filterCondition.push({ + bFilterName: item, + bFilterCondition: '=', + bFilterValue: conditionValues[item], + }); + } + }); + } + let copyTo = {}; + if (commonUtils.isNotEmptyObject(tableDataRow) && tableDataRow.bLinkPlanTree) { + copyTo = { + treeKey: tableDataRow.sMachineId + tableDataRow.sWorkCenterId, + sWorkCenterName: tableDataRow.sWorkCenterName, + }; + } + this.props.dispatch({ + type: 'content/onRouter', + payload: { + url: sNameUrl, + sTabId: commonUtils.createSid(), + sParentId: this.state.sTabId, + urlDataType: 'newPane', + checkedId: (commonUtils.isNotEmptyObject(tableDataRow[sActiveKey])) ? tableDataRow[sActiveKey] : myConfigArr[0].sId, + sName: myConfigArr[0].sName, + bFilter: slaveFilterCondition, + pageSize: this.state.iPageSize, + pages: slavePagination, + currentData: [tableDataRow], + conditonValues: conditionValues, + sListFormmasterId: slaveConfig.sId, + newKey: tableDataRow[sActiveKey], + currentIndex: iIndex, + filterCondition, + copyTo, + sSrcModelsId: this.state.sModelsId, + }, + }); + } + }; + + handleTabModalClick = (name, sName, record, index, showConfig) => { + this.setState({ + bTabModal: true, + tabModalConfig: showConfig, + tabModalRecord: record, + }); + } + handleRowMove = (addState) => { + this.handleSaveState(addState); + }; + handleFilterDropDownData = (dropDownData, showConfig, name, record) => { + if (!commonUtils.isEmptyArr(dropDownData)) { + const conditon = showConfig.sSqlCondition.split(','); + let orTableName; + let orFieldName; + let orFieldNameFilter; + let orValue; + conditon.forEach((item) => { + if (item.indexOf('.') > -1) { + const tableName = item.split('.')[0]; + const fieldName = item.split('.')[1]; + const fieldNameFilter = item.split('.')[2]; + if (tableName.indexOf('|') > -1) { + orTableName = tableName.replace('|', ''); + orFieldName = fieldName; + orFieldNameFilter = fieldNameFilter; + if (orFieldName.indexOf('&') > -1) { + orValue = orFieldName.replace('&', ''); + } else if (!commonUtils.isEmpty(orFieldNameFilter)) { + if (name === orTableName && !commonUtils.isEmpty(record)) { + const data = record; + orValue = data[orFieldName]; + } else { + const data = this.state[`${orTableName}Data`]; + const selectedRowKeys = this.state[`${orTableName}SelectedRowKeys`]; + if (typeof data === 'object' && data.constructor === Object) { + orValue = data[orFieldName]; + } else if (commonUtils.isNotEmptyArr(selectedRowKeys)) { + const iIndex = data.findIndex(itemData => itemData.sId === selectedRowKeys[0]); + if (iIndex > -1) { + orValue = data[iIndex][orFieldName]; + } + } else if (commonUtils.isNotEmptyArr(data)) { + orValue = data[0][orFieldName]; + } + } + } + orValue = orValue.toString(); + } else if (!commonUtils.isEmpty(orFieldName)) { + // master.sId 作为参数 control.sId.sControlId 作为filterDropdown过滤参数 + if (!commonUtils.isEmpty(fieldNameFilter)) { + if (name === tableName && !commonUtils.isEmpty(record)) { + const data = record; + dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[fieldName] || itemDrop[orFieldNameFilter] === orValue); + } else { + const data = this.state[`${tableName}Data`]; + const selectedRowKeys = this.state[`${tableName}SelectedRowKeys`]; + if (typeof data === 'object' && data.constructor === Object) { + dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[fieldName] || itemDrop[orFieldNameFilter] === orValue); + } else if (commonUtils.isNotEmptyArr(selectedRowKeys)) { + const iIndex = data.findIndex(itemData => itemData.sId === selectedRowKeys[0]); + if (iIndex > -1) { + dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[iIndex][fieldName] || itemDrop[orFieldNameFilter] === orValue); + } + } else if (commonUtils.isNotEmptyArr(data)) { + dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[0][fieldName] || itemDrop[orFieldNameFilter] === orValue); + } + } + } + } else if (!commonUtils.isEmpty(fieldNameFilter)) { + if (name === tableName && !commonUtils.isEmpty(record)) { + const data = record; + dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[fieldName]); + } else { + const data = this.state[`${tableName}Data`]; + const selectedRowKeys = this.state[`${tableName}SelectedRowKeys`]; + if (typeof data === 'object' && data.constructor === Object) { + dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[fieldName]); + } else if (commonUtils.isNotEmptyArr(selectedRowKeys)) { + const iIndex = data.findIndex(itemData => (commonUtils.isEmpty(itemData.sSlaveId) ? itemData.sId : itemData.sSlaveId) === selectedRowKeys[0]); + if (iIndex > -1) { + dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[iIndex][fieldName]); + } + } else if (commonUtils.isNotEmptyArr(data)) { + dropDownData = dropDownData.filter(itemDrop => itemDrop[fieldNameFilter] === data[0][fieldName]); + } + } + } + } + }); + } + + // let dropDownData = dropDownDataOld; + // const data = this.state[`${tableName}Data`]; + // const selectedRowKeys = this.state[`${tableName}SelectedRowKeys`]; + // if (commonUtils.isNotEmptyArr(selectedRowKeys)) { + // const SelectedData = data.filter(item => item.sId === selectedRowKeys[0]); + // if (SelectedData.length > 0 && commonUtils.isNotEmptyStr(SelectedData[0][fieldName])) { + // if (commonUtils.isNotEmptyArr(dropDownData)) { + // dropDownData = dropDownData.filter(item => item[fieldName] === SelectedData[0][fieldName]); + // } + // } + // } + return dropDownData; + }; + /* newRecord新纪录保存后,将数据回到到下拉框中 字段名,主从表名,赋值字段 */ + handleCallBackRecord = async (sName, name, sId) => { + const { + [`${name}SelectedRowKeys`]: tableSelectedRowKeys, sModelsId, [`${name}Data`]: tableNewData, slaveData, masterData, sModelsType, token, formRoute, + } = this.state; + const { app } = this.props; + /* 获取下拉的字段showConfig */ + const { [`${[name]}Config`]: nameConfig } = this.state; + const filedShowConfig = nameConfig.gdsconfigformslave.filter(item => (item.sName === sName)); + const AssignField = commonUtils.isNotEmptyArr(filedShowConfig) ? filedShowConfig[0].sAssignField : ''; + const sqlDropDownData = await this.getSqlDropDownData(sModelsId, name, filedShowConfig[0]); + /* 根据sName得到过滤数据 */ + const dropdownData = sqlDropDownData.dropDownData; + const filterDataIndex = dropdownData.findIndex(item => (item.sId === sId) || (commonUtils.isNotEmptyObject(item.sNId) && item.sNId === sId)); + if (filterDataIndex > -1) { + if (name !== 'master' && commonUtils.isNotEmptyObject(tableSelectedRowKeys)) { + const newCopyTo = {}; + const iIndex = tableNewData.findIndex(item => item.sId === tableSelectedRowKeys.toString()); + newCopyTo.master = masterData; + newCopyTo.slave = tableNewData[iIndex]; + let slaveRow = {}; + slaveRow = { ...tableNewData[iIndex], ...commonFunc.getAssignFieldValue(AssignField, dropdownData[filterDataIndex], newCopyTo) }; // 取赋值字段 + slaveRow.handleType = commonUtils.isEmpty(slaveRow.handleType) ? 'update' : slaveRow.handleType; + if (sName === 'sProductId' || sName === 'sProductName') { + slaveRow.sProductInfo = ''; + } + tableNewData[iIndex] = slaveRow; + + /* 套装工单、报价单、工艺卡的从表, 点击newRecord后 回带控制表合版数据 */ + const addState = {}; + if(formRoute && formRoute.includes('PackTableTree') && name === 'slave') { + const { controlData } = this.state;; + let { packData } = this.state; + if(commonUtils.isEmptyArr(packData)){ + packData =[]; + } + if(controlData.length ===1) { + const controlRow = controlData[0]; + const iIndex = packData.findIndex(item=> item.sControlId === controlRow.sId); + if(iIndex > -1){ + const packFilterData = packData.filter(item => item.sControlId === controlRow.sId); + if (commonUtils.isNotEmptyArr(packFilterData)) { + packFilterData.forEach((itemPack, index) => { + let packDataRow = itemPack; + const sControlId = controlRow.sControlId; + packDataRow.sControlId = controlRow.sId; + packDataRow.sSlaveId = slaveRow.sId; + packDataRow.sProductId = slaveRow.sProductId; /* 产品id */ + packDataRow.sCustomerId = slaveRow.sCustomerId; /* 客户id */ + packDataRow.sCustomerName = slaveRow.sCustomerName; /* 客户名称 */ + packDataRow.sProductName = slaveRow.sProductName; /* 产品名称 */ + packDataRow.sProductNo = slaveRow.sProductNo; /* 产品编号 */ + packDataRow.dCombineQty = 1; + packData[index] = { ...packData[index], ...packDataRow }; + if (commonUtils.isNotEmptyObject(packData[index])) { + const { sId, sProductNo, dProductQty, dCombineQty, dFactProductQty, sCombinePartsName } = packData[0]; + const tableCombineSelectedData = []; + const jsonObj = {}; + jsonObj.sId = sId; + jsonObj.sProductNo = sProductNo; /* 产品编号 */ + jsonObj.dCombineQty = commonUtils.isNotEmptyNumber(dCombineQty) ? dCombineQty : 0; /* 排版数 */ + jsonObj.dProductQty = commonUtils.isNotEmptyNumber(dProductQty) ? dProductQty : 0; /* 生产数 */ + jsonObj.dFactProductQty = commonUtils.isNotEmptyNumber(dFactProductQty) ? dFactProductQty : 0; /* 实际生产数 */ + jsonObj.sCombinePartsName = sCombinePartsName; /* 合版部件名称 */ + tableCombineSelectedData.push(jsonObj); + const sCombinedMemo = commonUtils.isNotEmptyArr(tableCombineSelectedData) ? JSON.stringify(tableCombineSelectedData) : ''; /* JSON对象转换为字符串存放到合版信息中 */ + controlRow.sCombinedMemo =commonUtils.isNotEmptyObject(sCombinedMemo)? sCombinedMemo: '合版信息'; + controlRow.handleType = commonUtils.isEmpty(controlRow.handleType) ? 'update' : controlRow.handleType; + controlData[0]={...controlData,...controlRow}; + } + }); + addState.packData = packData; + addState.controlData = controlData; + } + } + } + } + + this.handleSaveState({ [`${name}Data`]: tableNewData, ...addState }); + } else { /* 主表赋值 */ + const changeValue = commonFunc.getAssignFieldValue(AssignField, dropdownData[filterDataIndex]); + const masterNewData = { ...masterData, ...changeValue }; // 取赋值字段 + const sFieldName = sName; + const addState = {}; + if (sFieldName === 'sCustomerId' || sFieldName === 'sCustomerNo' || sFieldName === 'sCustomerName' || sFieldName === 'sSupplyId' || sFieldName === 'sSupplyNo' || sFieldName === 'sSupplyName' || sFieldName === 'sWareHouseId' || sFieldName === 'sWareHouseNo' || sFieldName === 'sWareHouseName' || sFieldName === 'tDeliverDate') { + const slaveDataNew = []; + for (const item of slaveData) { + let tableDataRow = ((sFieldName === 'sWareHouseId' || sFieldName === 'sWareHouseNo' || sFieldName === 'sWareHouseName') && (sModelsType.includes('materialsStock/productionmaterialsadjust'))) ? + { ...item } : { ...item, [sFieldName]: changeValue[sFieldName] }; + if (sFieldName === 'sCustomerId' || sFieldName === 'sCustomerNo' || sFieldName === 'sCustomerName' || sFieldName === 'sSupplyId' || sFieldName === 'sSupplyNo' || sFieldName === 'sSupplyName') { + tableDataRow.sTaxId = changeValue.sTaxId; + tableDataRow.sTaxNo = changeValue.sTaxNo; + tableDataRow.sTaxName = changeValue.sTaxName; + tableDataRow.dTaxRate = changeValue.dTaxRate; + tableDataRow.handleType = commonUtils.isEmpty(tableDataRow.handleType) ? 'update' : tableDataRow.handleType; + const models = sModelsType.includes('sales/') || sModelsType.includes('manufacture/') || sModelsType.includes('productStock/') ? 'Product' : 'Materials'; + + tableDataRow = commonBusiness.getCalculateAllMoney(app, models, 'sTaxId', masterData, tableDataRow); + let dMaterialsMoney = ''; + if (sModelsType.includes('outside/')) { /* 工序发外 */ + let sComputeId = ''; + const sSupplyId = changeValue.sSupplyId; + const sProcessId = tableDataRow.sProcessId; + /* 根据客户id,工序id获取公式ID */ + if (commonUtils.isNotEmptyObject(sSupplyId) && commonUtils.isNotEmptyObject(sProcessId)) { + sComputeId = await commonBusiness.getOutSideProcessFormula({ + token, sModelsId, sSupplyId, sProcessId, + }); + if (commonUtils.isNotEmptyObject(sComputeId)) { + dMaterialsMoney = await commonBusiness.getFormulaValue({ + token, sModelsId, masterData, tableDataRow, sComputeId, + }); + tableDataRow.dMaterialsMoney = dMaterialsMoney; + tableDataRow = commonBusiness.getCalculateMoney(app, masterData, tableDataRow, 'Materials'); + } + } + } + } + if ((sFieldName === 'sWareHouseId' || sFieldName === 'sWareHouseNo' || sFieldName === 'sWareHouseName') && (!sModelsType.includes('materialsStock/productionmaterialsadjust'))) { + tableDataRow.sWareHouseId = changeValue.sWareHouseId; + tableDataRow.sWareHouseNo = changeValue.sWareHouseNo; + tableDataRow.sWareHouseName = changeValue.sWareHouseName; + tableDataRow.sLocationId = changeValue.sLocationId; + tableDataRow.sLocationNo = changeValue.sLocationNo; + tableDataRow.sLocationName = changeValue.sLocationName; + tableDataRow.sWareHouseLocationId = changeValue.sWareHouseLocationId; + tableDataRow.sWareHouseLocationNo = changeValue.sWareHouseLocationNo; + tableDataRow.sWareHouseLocationName = changeValue.sWareHouseLocationName; + tableDataRow.handleType = commonUtils.isEmpty(tableDataRow.handleType) ? 'update' : tableDataRow.handleType; + } + slaveDataNew.push(tableDataRow); + } + addState.slaveData = slaveDataNew; + // this.props.onSaveState({ slaveData: slaveDataNew }); + } + this.handleSaveState({ [`${name}Data`]: masterNewData, ...addState }); + } + } + } + + /** 树选择 */ + handleTreeSelect = (name, selectedKeys, e) => { + const { treeNode } = e.node.props; + this.handleSaveState({ [`${name}SelectedKeys`]: selectedKeys, [`${name}TreeNode`]: treeNode }); + }; + /* 通用弹窗 选择数据带回窗体 */ + handleSelectCommonPopup = (currentPaneName, selectConfig, selectData, tbName, isWait) => { + // 如果配置了sAfterClickInstruct,先走指令集再走原逻辑,否值直接走原逻辑 + const { sAfterClickInstruct, showName } = selectConfig; + if (sAfterClickInstruct) { + instructSet({ + ...this.props, + ...this.state, + slavepupData: selectData, + btnConfig: { sInstruct: sAfterClickInstruct, showName }, + onSaveState: this.handleSaveState, + callback: () => { + this.handleSelectCommonPopupNew(currentPaneName, selectConfig, selectData, tbName, isWait); + } + }) + } else { + if(typeof isWait === 'boolean' && isWait) { + return this.handleSelectCommonPopupNew(currentPaneName, selectConfig, selectData, tbName, isWait); + } else { + this.handleSelectCommonPopupNew(currentPaneName, selectConfig, selectData, tbName); + } + } + }; + + handleSelectCommonPopupNew = (currentPaneName, selectConfig, selectData, tbName, isWait) => { + const { + [`${tbName}SelectedRowKeys`]: tableSelectedRowKeys, masterData, + controlData, controlSelectedRowKeys, sModelsId, + } = this.state; + const { sOnChangeInstruct, showName } = selectConfig; + const type = 'change'; + const onChangeNew = commonUtils.convertStrToObj(sOnChangeInstruct, {}); + const instructType = onChangeNew[type]; + // 回弹字段直接设置单价 + async function setProductPrice(tableDataRowAdd, item, props) { + if (selectConfig.sName === 'sProductId' || selectConfig.sName === 'sProductName' || selectConfig.sName === 'sProductNo') { + const url = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`; + const { sCustomerId } = masterData; /* 增加客户id参数 */ + const value = { + sProName: 'Sp_Cashier_GetProductPrice', + paramsMap: { + sProductGuid: item.sId, + sCustomerId, + }, + }; + const returnData = (await commonServices.postValueService(props.app.token, value, url)).data; + if (returnData.code === 1) { + tableDataRowAdd.dNProductPrice = returnData.dataset.rows[0].dataSet.outData[0].dPrice; /* 产品单价 */ + const dProofingMoney = commonUtils.convertToNum(tableDataRowAdd.dProofingMoney); /* 打样金额 */ + const dPlateMoney = commonUtils.convertToNum(tableDataRowAdd.dPlateMoney); /* 制版金额 */ + const dKnifeMouldMoney = commonUtils.convertToNum(tableDataRowAdd.dKnifeMouldMoney); /* 刀模金额 */ + const dProductQty = commonUtils.convertToNum(tableDataRowAdd.dProductQty); /* 数量 */ + const dCurrencyRate = commonUtils.convertIsNotNumToNumber1(masterData.dCurrencyRate); /* 汇率 */ + const { dNetPrice } = props.app.decimals; + if (dProductQty === 0 || (dProofingMoney === 0 && dPlateMoney === 0 && dKnifeMouldMoney === 0)) { + const dProductForeignPrice = returnData.dataset.rows[0].dataSet.outData[0].dPrice; + tableDataRowAdd.dProductForeignPrice = dProductForeignPrice; + tableDataRowAdd.dProductPrice = commonUtils.convertFixNum(dProductForeignPrice * dCurrencyRate, dNetPrice); + } + } + return tableDataRowAdd; + } else { + return tableDataRowAdd; + } + } + let { [`${tbName}Data`]: tableData, [`${tbName}Pagination`]: pagination = {} } = this.state; + let addReturn = {}; + if (commonUtils.isNotEmptyArr(tableData) && commonUtils.isNotEmptyArr(selectData)) { + const iIndex = commonUtils.isNotEmptyArr(tableSelectedRowKeys) && commonUtils.isNotEmptyObject(tableSelectedRowKeys[0]) ? tableData.findIndex(item => item.sId === tableSelectedRowKeys[0]) : -1; + const iControlIndex = commonUtils.isNotEmptyArr(controlSelectedRowKeys) ? controlData.findIndex(item => item.sId === controlSelectedRowKeys[0]) : -1; /* 控制表 */ + selectData.forEach(async (item, index) => { + const newCopyTo = {}; + newCopyTo.master = masterData; + const sName = selectConfig.sKeyUpFilter; /* 将后台配置筛选字段作为 列字段 */ + let sValue = ''; + if (iIndex > -1) { + newCopyTo.slave = tableData[iIndex]; + sValue = tableData[iIndex][sName]; + } + if (iControlIndex > -1) { + newCopyTo.control = controlData[iControlIndex]; + } + /* 第一条数据若字段值为空或者只有一条数据时 则添加到该行 否则新增一行 */ + if (selectData.length === 1 || (index === 0 && commonUtils.isEmptyObject(sValue))) { + let tableDataRow = {}; // 取默认值 + if (tbName === 'master') { + tableDataRow = { ...tableData, ...commonFunc.getAssignFieldValue(selectConfig.sAssignField, item, newCopyTo) }; // 取赋值字段 + tableData = tableDataRow; + tableData.handleType = commonUtils.isEmpty(tableData.handleType) ? 'update' : tableData.handleType; + if (instructType) { + this.handleExecInstructSet({ + type, + sInstruct: instructType, + showName: `${showName}-${type === 'blur' ? '离焦' : '变化'}`, + }); + } + + } else { + tableDataRow = { ...tableData[iIndex] }; + if (tbName === 'slave') { + tableDataRow.sSqlConditionId = tableDataRow.sId; + } + tableDataRow = { ...tableDataRow, ...commonFunc.getAssignFieldValue(selectConfig.sAssignField, item, newCopyTo) }; // 取赋值字段 + + tableData[iIndex] = tableDataRow; + tableData[iIndex].handleType = commonUtils.isEmpty(tableData[iIndex].handleType) ? 'update' : tableData[iIndex].handleType; + tableData[iIndex] = await setProductPrice(tableData[iIndex], item, this.props); + if (instructType) { + this.handleExecInstructSet({ + type, + sInstruct: instructType, + showName: `${showName}-${type === 'blur' ? '离焦' : '变化'}`, + }); + } + } + } else { + let tableDataRowAdd = this.handleTableAdd(tbName, true); + if (tbName === 'slave') { + tableDataRowAdd.sSqlConditionId = tableDataRowAdd.sId; + } + tableDataRowAdd = { ...tableDataRowAdd, ...commonFunc.getAssignFieldValue(selectConfig.sAssignField, item, newCopyTo) }; // 取赋值字段 + tableDataRowAdd = await setProductPrice(tableDataRowAdd, item, this.props); + if (instructType) { + this.handleExecInstructSet({ + type, + sInstruct: instructType, + showName: `${showName}-${type === 'blur' ? '离焦' : '变化'}`, + }); + } + tableData.push(tableDataRowAdd); + } + + pagination = { + ...pagination, + total: tableData.length, + } + + if (tbName === 'master') { + const result = this.handleMasterChange(tbName, selectConfig.sName, {}, null, null, true, tableData); + tableData = result.masterData; + } + + const addState = { [`${tbName}Data`]: tableData, [`${tbName}Pagination`]: pagination }; + if(typeof isWait !== 'boolean') { + this.handleSaveState(addState); + } + + }); + if(typeof isWait === 'boolean' && isWait) { + addReturn = { [`${tbName}Data`]: tableData, [`${tbName}Pagination`]: pagination }; + return addReturn; + } + } + }; + + + /* 通用弹窗 将选择数据汇总求和带回窗体 */ + handleSelectCommonPopupSum = (currentPaneName, selectConfig, selectData, tbName) => { + const { + [`${tbName}SelectedRowKeys`]: tableSelectedRowKeys, masterData, + controlData, controlSelectedRowKeys, sModelsId, + } = this.state; + // 回弹字段直接设置单价 + async function setProductPrice(tableDataRowAdd, item, props) { + if (selectConfig.sName === 'sProductId' || selectConfig.sName === 'sProductName' || selectConfig.sName === 'sProductNo') { + const url = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`; + const { sCustomerId } = masterData; /* 增加客户id参数 */ + const value = { + sProName: 'Sp_Cashier_GetProductPrice', + paramsMap: { + sProductGuid: item.sId, + sCustomerId, + }, + }; + const returnData = (await commonServices.postValueService(props.app.token, value, url)).data; + if (returnData.code === 1) { + tableDataRowAdd.dNProductPrice = returnData.dataset.rows[0].dataSet.outData[0].dPrice; /* 产品单价 */ + const dProofingMoney = commonUtils.convertToNum(tableDataRowAdd.dProofingMoney); /* 打样金额 */ + const dPlateMoney = commonUtils.convertToNum(tableDataRowAdd.dPlateMoney); /* 制版金额 */ + const dKnifeMouldMoney = commonUtils.convertToNum(tableDataRowAdd.dKnifeMouldMoney); /* 刀模金额 */ + const dProductQty = commonUtils.convertToNum(tableDataRowAdd.dProductQty); /* 数量 */ + const dCurrencyRate = commonUtils.convertIsNotNumToNumber1(masterData.dCurrencyRate); /* 汇率 */ + const { dNetPrice } = props.app.decimals; + if (dProductQty === 0 || (dProofingMoney === 0 && dPlateMoney === 0 && dKnifeMouldMoney === 0)) { + const dProductForeignPrice = returnData.dataset.rows[0].dataSet.outData[0].dPrice; + tableDataRowAdd.dProductForeignPrice = dProductForeignPrice; + tableDataRowAdd.dProductPrice = commonUtils.convertFixNum(dProductForeignPrice * dCurrencyRate, dNetPrice); + } + } + return tableDataRowAdd; + } else { + return tableDataRowAdd; + } + } + let { [`${tbName}Data`]: tableData, [`${tbName}Pagination`]: pagination = {} } = this.state; + if (commonUtils.isNotEmptyArr(tableData) && commonUtils.isNotEmptyArr(selectData)) { + const iIndex = commonUtils.isNotEmptyArr(tableSelectedRowKeys) && commonUtils.isNotEmptyObject(tableSelectedRowKeys[0]) ? tableData.findIndex(item => item.sId === tableSelectedRowKeys[0]) : -1; + const iControlIndex = commonUtils.isNotEmptyArr(controlSelectedRowKeys) ? controlData.findIndex(item => item.sId === controlSelectedRowKeys[0]) : -1; /* 控制表 */ + let dModifyProductQty = 0; + const jsonData = []; + let jsonStr = ''; + selectData.forEach((item, index) => { + const newCopyTo = {}; + newCopyTo.master = masterData; + const sName = selectConfig.sKeyUpFilter; /* 将后台配置筛选字段作为 列字段 */ + let sValue = ''; + if (iIndex > -1) { + newCopyTo.slave = tableData[iIndex]; + sValue = tableData[iIndex][sName]; + } + if (iControlIndex > -1) { + newCopyTo.control = controlData[iControlIndex]; + } + /* 第一条数据若字段值为空或者只有一条数据时 则添加到该行 否则新增一行 */ + if (false) { + let tableDataRow = {}; // 取默认值 + if (tbName === 'master') { + tableDataRow = { ...tableData, ...commonFunc.getAssignFieldValue(selectConfig.sAssignField, item, newCopyTo) }; // 取赋值字段 + tableData = tableDataRow; + tableData.handleType = commonUtils.isEmpty(tableData.handleType) ? 'update' : tableData.handleType; + } else { + dProductQty += commonUtils.isNull(item.dProductQty, 0); /* 赠送数量叠加 */ + tableDataRow = { ...tableData[iIndex], ...commonFunc.getAssignFieldValue(selectConfig.sAssignField, item, newCopyTo) }; // 取赋值字段 + tableData[iIndex] = tableDataRow; + tableData[iIndex].handleType = commonUtils.isEmpty(tableData[iIndex].handleType) ? 'update' : tableData[iIndex].handleType; + // tableData[iIndex] = await setProductPrice(tableData[iIndex], item, this.props); + } + } else { + let tableDataRowAdd = this.handleTableAdd(tbName, true); + /* 叠加求和 */ + dModifyProductQty += commonUtils.isNull(item.dModifyProductQty, 0); /* 赠送数量叠加 */ + tableDataRowAdd = { ...tableDataRowAdd, ...commonFunc.getAssignFieldValue(selectConfig.sAssignField, item, newCopyTo) }; // 取赋值字段 + // tableDataRowAdd = await setProductPrice(tableDataRowAdd, item, this.props); + // tableData.push(tableDataRowAdd); + } + + if(selectConfig.sControlName && selectConfig.sControlName.includes('dStockUpConsumeQty')) { /* 备货消耗数 特殊处理 */ + const obj ={}; + obj.sSlaveId = commonUtils.isNotEmptyObject(item.sSlaveId) ? item.sSlaveId : item.sId; + obj.dModifyProductQty = commonUtils.isNotEmptyNumber(item.dModifyProductQty) ? item.dModifyProductQty : 0; + jsonData.push(obj); + } + + pagination = { + ...pagination, + total: tableData.length, + } + + if (tbName === 'master') { + const result = this.handleMasterChange(tbName, selectConfig.sName, {}, null, null, true, tableData); + tableData = result.masterData; + } + }); + const addState = {}; + if (selectConfig.sControlName && selectConfig.sControlName.includes('sumeQty')) { + /* 找到汇总字段 */ + const sFileSumName = selectConfig.sAssignField && selectConfig.sAssignField.split(':')[0]; + addState[sFileSumName] = dModifyProductQty; + addState.dRavailableQty = dModifyProductQty + tableData[iIndex].dConsumeQty; + addState.handleType = commonUtils.isEmpty(tableData[iIndex].handleType) ? 'update' : tableData[iIndex].handleType; + if(commonUtils.isNotEmptyArr(jsonData)) { + jsonStr = commonUtils.isNotEmptyArr(jsonData) ? JSON.stringify(jsonData) : ''; /* JSON对象转换为字符串存放到合版信息中 */ + addState.sStockUpConsume = jsonStr; + } + tableData[iIndex] = { ...tableData[iIndex], ...addState }; + } + this.handleSaveState({ [`${tbName}Data`]: tableData, [`${tbName}Pagination`]: pagination }); + } + }; + + /* 接口数据带入数据 */ + handleSelectDialog = (name, selectConfig, selectData, tbName) =>{ + const { + [`${tbName}SelectedRowKeys`]: tableSelectedRowKeys, sModelsId, slaveNameList, allDataList, masterConfig, + } = this.state; + let { masterData } = this.state; + const addState = {}; + let { [`${tbName}Data`]: tableData } = this.state; + if (commonUtils.isNotEmptyArr(tableData) && commonUtils.isNotEmptyArr(selectData)) { + const iIndex = commonUtils.isNotEmptyArr(tableSelectedRowKeys) && commonUtils.isNotEmptyObject(tableSelectedRowKeys[0]) ? tableData.findIndex(item => item.sId === tableSelectedRowKeys[0]) : -1; + let sControlNameMatchList = []; + if (tbName === 'master') { + sControlNameMatchList = ['BtnSendDialog', 'BtnSendDialog.master']; + } else { + sControlNameMatchList = [`BtnSendDialog.${tbName}`]; + } + + const btnConfig = masterConfig.gdsconfigformslave.find(item => + item.sControlName && + sControlNameMatchList.includes(item.sControlName)) || {} + + selectData.forEach(async (item, index) => { + let dataMap = {}; + /* 通过主键 找到对应的数据集 对应铺数据 */ + if(commonUtils.isNotEmptyArr(allDataList)) { + for (const key of Object.keys(allDataList)) { + let targetKey = commonUtils.isNotEmptyObject(item.sSlaveId) ? item.sSlaveId : item.sId; + targetKey = 'master-'+targetKey; + if(key && key === targetKey) { + dataMap = allDataList[key]; + if (commonUtils.isNotEmptyArr(slaveNameList) && commonUtils.isNotEmptyArr(dataMap)) { + slaveNameList.forEach((name) => { + const tableConfig = this.state[name +'Config']; /* 动态配置 */ + let tableData = []; + if(commonUtils.isNotEmptyObject(tableConfig)) { + tableData = dataMap[name +'-'+ tableConfig.sTbName]; /* 动态配置 */ + if(commonUtils.isNotEmptyObject(tableData)) { + const newCopyTo = {}; + newCopyTo.master = masterData; + const tableNewData = JSON.parse(JSON.stringify(tableData)); + if(name === 'master') { + masterData = { ...masterData, ...commonFunc.getAssignFieldValue(btnConfig.sAssignField, tableNewData, newCopyTo) }; // 取赋值字段 + addState.masterData = masterData; + } else { + const btnTableName = btnConfig.sControlName +'.'+ name; + const btnTableConfig = commonUtils.isNotEmptyArr(masterConfig.gdsconfigformslave.filter(item => (item.sControlName === btnTableName))) ? + masterConfig.gdsconfigformslave.filter(item => (item.sControlName === btnTableName))[0] : {};// sButtonEnabled sButtonParam + + const newData = []; + tableNewData.forEach((child) => { + let newRow ={}; + if(commonUtils.isNotEmptyObject(btnTableConfig) && btnTableConfig.sAssignField){ + newRow = { ...child, ...commonFunc.getAssignFieldValue(btnTableConfig.sAssignField, child, newCopyTo) }; // 取赋值字段 + }else { + newRow = child; + } + newRow = { + ...newRow, + handleType: 'add', + sId: commonUtils.createSid(), + sParentId: masterData.sId + }; + newData.push(newRow); + }); + addState[name +'Data'] = newData; + } + + } + } + + }); + } + + } + + } + } + }); + console.log('确定后数据:', addState); + this.handleSaveState({ ...addState }); + } + + } + + /* 自定义复制从窗体 选择数据带回窗体 */ + handleCopyFromSelect = (name, selectConfig, selectData) => { + const { sModelsType } = this.state; + let { masterData, slaveData } = this.state; + const addState = {}; + if (commonUtils.isNotEmptyArr(selectData)) { + const newCopyTo = {}; + newCopyTo.master = masterData; + selectData.forEach((item) => { + if (commonUtils.isNotEmptyObject(sModelsType) && sModelsType.includes('onlyMaster')) { /* 单主表调用复制从数据 */ + masterData = { ...masterData, ...commonFunc.getAssignFieldValue(selectConfig.sAssignField, item, newCopyTo) }; // 取赋值字段 + masterData.handleType = commonUtils.isEmpty(masterData.handleType) ? 'update' : masterData.handleType; + addState.masterData = masterData; + } else { /* 从表调用复制从数据 */ + if (commonUtils.isEmptyArr(slaveData)) { + slaveData = []; + } + let tableDataRowAdd = this.handleTableAdd('slave', true); + tableDataRowAdd = { ...tableDataRowAdd, ...commonFunc.getAssignFieldValue(selectConfig.sAssignField, item, newCopyTo) }; // 取赋值字段 + slaveData.push(tableDataRowAdd); + addState.slaveData = slaveData; + } + }); + } + addState.copyFromChooseVisible = false; + this.handleSaveState({ ...addState }); + }; + + + handelControlFieldVisible = (name, configData, tableData) => { + const addState = {}; + /* 获取主表数据时表字段数据根据条件控制 本表或其他表格字段的显示与隐藏功能 */ + if (name === 'master' && commonUtils.isNotEmptyObject(configData) && commonUtils.isNotEmptyObject(tableData)) { + const masterConfig = configData; + const iConfigIndex = masterConfig.gdsconfigformslave.findIndex(item => commonUtils.isNotEmptyObject(item.sButtonEnabled)); + if (iConfigIndex > -1) { + const sFiledConfig = masterConfig.gdsconfigformslave[iConfigIndex]; + if (commonUtils.isNotEmptyObject(sFiledConfig)) { + const tableDataRow = tableData; + const sRulesJson = sFiledConfig.sButtonEnabled; + if (commonUtils.isNotEmptyObject(sRulesJson) && commonUtils.isJSON(sRulesJson)) { + const sRulesObjArr = JSON.parse(sRulesJson); + if (Array.isArray(sRulesObjArr) && commonUtils.isNotEmptyArr(sRulesObjArr)) { + console.log('sRulesObjArr:', sRulesObjArr); + sRulesObjArr.forEach((sRulesObj) => { + const { + showColumn, hideColumn, condition, tbName, sConfigName, + } = sRulesObj; + /* 主表单表字段根据条件控制 其他字段的显示与隐藏 */ + if (commonUtils.isEmptyObject(tbName)) { + if (commonUtils.isNotEmptyArr(condition)) { + let flag = false; + for (const item of condition) { + const { + bFilterName, bFilterCondition, bFilterValue, + } = item; + if (bFilterCondition === '>') { + if (tableDataRow[bFilterName] > bFilterValue) { + flag = true; + } + } else if (bFilterCondition === '=') { + if (tableDataRow[bFilterName] === bFilterValue) { + flag = true; + } + } else if (bFilterCondition === '<') { + if (tableDataRow[bFilterName] < bFilterValue) { + flag = true; + } + } + } + if (flag) { + if (commonUtils.isNotEmptyArr(showColumn)) { + for (const column of showColumn) { + const iShowIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === column); + if (iShowIndex > -1) { + const sFiledObj = masterConfig.gdsconfigformslave[iShowIndex]; + if (commonUtils.isNotEmptyObject(sFiledObj)) { + if (commonUtils.isNotEmptyObject(sConfigName) && sConfigName === 'bControl') { + masterConfig.gdsconfigformslave[iShowIndex].bControl = true; /* 控制字段bControl的显示与隐藏 */ + } else { + masterConfig.gdsconfigformslave[iShowIndex].bVisible = true; + } + } + } + } + } + if (commonUtils.isNotEmptyArr(hideColumn)) { + for (const column of hideColumn) { + const iHideIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === column); + if (iHideIndex > -1) { + if (commonUtils.isNotEmptyObject(sConfigName) && sConfigName === 'bControl') { + masterConfig.gdsconfigformslave[iHideIndex].bControl = true; /* 控制字段bControl的显示与隐藏 */ + } else { + masterConfig.gdsconfigformslave[iHideIndex].bVisible = false; + } + } + } + } + addState.masterConfig = masterConfig; + } + } + } else { /* 主表字段根据条件控制 其他表格字段的显示与隐藏 */ + const { [`${tbName}Config`]: tableConfig } = this.state; + // const { controlConfig: tableConfig } = this.state; + if (commonUtils.isNotEmptyObject(tableConfig)) { + if (commonUtils.isNotEmptyArr(condition)) { + let flag = false; + for (const item of condition) { + const { + bFilterName, bFilterCondition, bFilterValue, + } = item; + if (bFilterCondition === '>') { + if (tableDataRow[bFilterName] > bFilterValue) { + flag = true; + } + } else if (bFilterCondition === '=') { + if (tableDataRow[bFilterName] === bFilterValue) { + flag = true; + } + } else if (bFilterCondition === '<') { + if (tableDataRow[bFilterName] < bFilterValue) { + flag = true; + } + } + } + if (flag) { + if (commonUtils.isNotEmptyArr(showColumn)) { + for (const column of showColumn) { + const iShowIndex = tableConfig.gdsconfigformslave.findIndex(item => item.sName === column); + if (iShowIndex > -1) { + const sFiledObj = tableConfig.gdsconfigformslave[iShowIndex]; + if (commonUtils.isNotEmptyObject(sFiledObj)) { + tableConfig.gdsconfigformslave[iShowIndex].bVisible = true; + } + } + } + } + if (commonUtils.isNotEmptyArr(hideColumn)) { + for (const column of hideColumn) { + const iHideIndex = tableConfig.gdsconfigformslave.findIndex(item => item.sName === column); + if (iHideIndex > -1) { + const sFiledObj = tableConfig.gdsconfigformslave[iHideIndex]; + if (commonUtils.isNotEmptyObject(sFiledObj)) { + tableConfig.gdsconfigformslave[iHideIndex].bVisible = false; + } + } + } + } + if (commonUtils.isNotEmptyObject(tableConfig)) { + const tableColumn = commonFunc.getHeaderConfig(tableConfig); + // addState.masterConfig = masterConfig; + // addState.controlConfig = tableConfig; /* 表格配置塞到addState中 */ + // addState.controlColumn = tbColumn; + addState[`${tbName}Config`] = tableConfig; + addState[`${tbName}Column`] = tableColumn; + } + } + } + } + } + }); + } + } + } + } + } + return addState; + } + + /* 下拉多选离开事件 */ + handleTableBlur = async (name, sFileName, record, tableConfig, other) => { + const { sModelsId, app } = this.props; + const { controlData, slaveConfig,[`${name}Data`]: tableData , [`${name}Config`]: tempConfig } = this.state; + let { slaveData: slaveDataOld, masterData, slaveDelData, } = this.state; + const addState = {}; + if(commonUtils.isEmptyArr(slaveDelData)) { + slaveDelData = []; + } + if (sFileName === 'sPartsNameNew') { + if(commonUtils.isNotEmptyArr(controlData)) { + /* 离开时 把sPartsNameNewId数据挂载到sControlParentId */ + let iIndex = controlData.findIndex(item => item.sId === record.sId); + if(iIndex === -1) { + if(record.sId && record.sId.split('-').length > 1) { + iIndex = controlData.findIndex(item => item.sId === record.sId.split('-')[0]); + } + } + if (iIndex > -1) { + addState.sControlParentId = controlData[iIndex].sPartsNameNewId; + if(commonUtils.isNotEmptyObject(controlData[iIndex].sPartsNameNewId)) { + controlData[iIndex] = {...controlData[iIndex], ...addState}; + this.props.onSaveState({ controlData: controlData }); + } + } + } + } else if (tableConfig.sDropDownType === 'movesql') { /* 通用字段离开调下拉事件 */ + let slaveRow = record; + const sqlDropDownData = await this.getSqlDropDownData(sModelsId, name, tableConfig, slaveRow); + const dDropDownData = sqlDropDownData.dropDownData; + const iIndex = tableData.findIndex(item => item.sId === record.sId); + if (commonUtils.isNotEmptyArr(dDropDownData) && iIndex > -1) { + slaveRow = { ...slaveRow, ...commonFunc.getAssignFieldValue(tableConfig.sAssignField, dDropDownData[0]) }; // 取赋值字段 + slaveRow.handleType = commonUtils.isEmpty(slaveRow.handleType) ? 'update' : slaveRow.handleType; + const sButtonParam = tableConfig.sButtonParam; /* 设置多级联动 */ + if(commonUtils.isNotEmptyObject(sButtonParam)) { + let sLinkFieldName = 'dMaterialsPrice'; + if (commonUtils.isJSON(sButtonParam)) { /* 按钮条件 */ + const linkObj = JSON.parse(sButtonParam); /* 联动配置 */ + let models = 'Materials'; + if (linkObj.linkMaterials) { + sLinkFieldName = linkObj.linkMaterials; + models = 'Materials'; + } else if (linkObj.linkProduct) { + sLinkFieldName = linkObj.linkProduct; + models = 'Product'; + } + slaveRow = commonBusiness.getCalculateAllMoney(app, models, sLinkFieldName, masterData, slaveRow); + } + } + + tableData[iIndex] = { ...tableData[iIndex] , ...slaveRow }; + this.setState({ ...addState }); + } + } else if(commonUtils.isNotEmptyObject(tableConfig) && commonUtils.isNotEmptyObject(tableConfig.sButtonParam)) { + let slaveNewData = []; + const allConfig = { slaveConfig }; + // console.log('sTmpInfoConfigArr', sTmpInfoConfigArr); + const sTmpInfoConfig = tableConfig; + const sButtonParam = tableConfig.sButtonParam; + const btn = commonUtils.isNotEmptyObject(sButtonParam) && commonUtils.isJSON(sButtonParam)? JSON.parse(sButtonParam) : {};; + const sProName = commonUtils.isNotEmptyObject(btn) ? btn.sproName : ''; + const sTmpInfoBySqlBtnName = commonUtils.isNotEmptyObject(btn) ? btn.sControlName : ''; + const sActiveKey = sTmpInfoConfig.sActiveKey; + if (commonUtils.isNotEmptyObject(sTmpInfoConfig)) { + if (commonUtils.isEmptyObject(sTmpInfoBySqlBtnName)) { + const newCopyTo = {}; + newCopyTo.master = masterData; + // newCopyTo.slave = commonUtils.isEmpty(slaveData) ? [] : slaveData[0]; + // const sRowData = copyTo.slaveData; + const sRowData = masterData; + const value = { sProName, sProInParam: JSON.stringify({ params: sRowData }) }; + if (other?.iFlag === 1) { + value.iFlag = 1; + } + const url = `${commonConfig.server_host}procedureCall/doGenericProcedureCall?sModelsId=${sModelsId}`; + const dataReturn = (await commonServices.postValueService(app.token, value, url)).data; + console.log('dataReturn', dataReturn); + if (dataReturn.code === 1) { + if (commonUtils.isNotEmptyArr(slaveDataOld)) { + slaveDataOld.forEach((item) => { + item.handleType = 'del'; + slaveDelData.push(item); + }); + addState.slaveDelData = slaveDelData; + } + const returnData = dataReturn.dataset.rows[0]; + const slaveReturn = returnData.dataSet.proData; + if (commonUtils.isNotEmptyArr(slaveReturn)) { + slaveReturn.forEach((slaveItem) => { + newCopyTo.slave = slaveItem; + let slaveRow = commonFunc.getDefaultData(allConfig.slaveConfig, newCopyTo); // 取默认值 + // if (salveDetailAssignField) { + // slaveRow = {...slaveRow, ...commonFunc.getAssignFieldValue(salveDetailAssignField, copyTo.masterData, newCopyTo)}; + // } else if (salveAssignField) { + // slaveRow = {...slaveRow, ...commonFunc.getAssignFieldValue(salveAssignField, slaveItem, newCopyTo)}; // 取赋值字段 + // } + slaveRow = { ...slaveRow, ...slaveItem }; + slaveRow.handleType = 'add'; + slaveRow.sId = commonUtils.createSid(); + slaveRow.sParentId = masterData.sId; + slaveNewData.push(slaveRow); + }); + } + addState.slaveData = slaveNewData; + this.setState({ ...addState }); + } else { + this.getServiceError({ ...dataReturn, fn: () => this.handleTableBlur(name, sFileName, record, tableConfig, { iFlag: 1 }) }); + } + } else if(sTmpInfoBySqlBtnName.includes('sTmpInfoBySql')) { /* 走TmpInfo逻辑 */ + const newCopyTo = {}; + newCopyTo.master = masterData; + /* 找到自定义TempInfo配置 */ + + const btnConfig = tempConfig.gdsconfigformslave.filter(item => item.sControlName.includes(sTmpInfoBySqlBtnName)); + const dataUrl = `${commonConfig.server_host}salesorder/getTmpInfoBySql/?sModelsId=${sModelsId}`; + const sConfigformId = commonUtils.isEmpty(btnConfig) ? '' : btnConfig[0].sParentId; + const sControlName = commonUtils.isNotEmptyObject(sTmpInfoBySqlBtnName) ? sTmpInfoBySqlBtnName : 'TmpInfoBySql'; + const sAssignField = btnConfig[0].sAssignField; + const sActiveKeyNew = btnConfig[0].sActiveKey; + let sRowData = [record]; + if (name === 'master' && sTmpInfoBySqlBtnName.includes('_update')) { + const { slaveData } = this.state; + if (commonUtils.isNotEmptyArr(slaveData)) { + sRowData = [...sRowData, ...slaveData]; + } + } + const values = { sConfigformId, sControlName, sRowData }; + if (true){ + const dataReturn = (await commonServices.postValueService(app.token, values, dataUrl)).data; + const allReturnMap = {}; + if (dataReturn.code === 1) { + const returnData = dataReturn.dataset.rows[0]; + if (commonUtils.isNotEmptyObject(returnData)) { + for (const key of Object.keys(returnData)) { + const sName = `${key}Data`; + const sDelName = `${key}DelData`; + // allReturnMap[sName] = returnData[key]; + let {[`${key}Data`]: oldData, [`${key}Data`]: oldDelData } = this.state; + if(commonUtils.isEmptyArr(oldDelData)) { + oldDelData = []; + } + if(commonUtils.isEmptyArr(oldData)) { + oldData = []; + } + if(sTmpInfoBySqlBtnName.includes('_edit')) { /* 替换 根据对应字段对比 相同的不管 不同的插入 */ + /* 对应字段 */ + const sActiveKey = sTmpInfoConfig.sActiveKey; + const keyData = returnData[key]; + let newData = []; + if(commonUtils.isNotEmptyArr(keyData)) { + keyData.forEach((child) => { + const filterData = oldData.filter(item => item[sActiveKeyNew] !== child[sActiveKeyNew]); + if(commonUtils.isNotEmptyArr(filterData) && filterData.length === oldData.length) { + const tableRow = { ...child, ...commonFunc.getAssignFieldValue(sAssignField, child) }; // 取赋值字段111 + tableRow.sId = commonUtils.createSid(); + tableRow.sParentId = masterData.sId; + tableRow.handleType = 'add'; + newData.push(tableRow); + } else { /* 相同的根据赋值字段覆盖 */ + const iIndex = oldData.findIndex(item => item[sActiveKeyNew] === child[sActiveKeyNew]); + if(iIndex > -1) { + if(sAssignField) { + oldData[iIndex] ={...oldData[iIndex], ...commonFunc.getAssignFieldValue(sAssignField, child) }; + } else { + oldData[iIndex] ={...oldData[iIndex], ...child }; + } + oldData[iIndex].handleType = commonUtils.isEmpty(oldData[iIndex].handleType) ? 'update' : oldData[iIndex].handleType; + } + } + }); + newData = oldData.concat(newData) + } + + }else if(sTmpInfoBySqlBtnName.includes('_del')) { /* 替换 根据对应字段对比 相同的不管 不同的插入 */ + /* 对应字段 */ + oldData.forEach((child) => { + child.handleType ='del'; + oldDelData.push(child); + }); + allReturnMap[sDelName] = oldDelData; + oldData = []; + const keyData = returnData[key]; + if(commonUtils.isNotEmptyArr(keyData)) { + keyData.forEach((child) => { + const tableRow = { ...child, ...commonFunc.getAssignFieldValue(sAssignField, child) }; // 取赋值字段111 + tableRow.sId = commonUtils.createSid(); + if (sName === 'slaveData' && !tableRow.sSqlConditionId) { + tableRow.sSqlConditionId = tableRow.sId; + } + tableRow.sParentId = masterData.sId; + tableRow.handleType = 'add'; + oldData.push(tableRow); + }); + } + allReturnMap[sName] = oldData; + } else if(sTmpInfoBySqlBtnName.includes('_update')) { /* 更新字段 */ + const keyData = returnData[key]; + if(commonUtils.isNotEmptyArr(keyData) && sActiveKeyNew) { + const [linkField, onchangeField] = sActiveKeyNew.split(','); + const tableName = key.split('_update')[0]; + const { [`${tableName}Data`]: tableData = [] } = this.state; + + for (let i = 0; i < keyData.length; i++) { + const child = keyData[i]; + const tableDataFilter = tableData.filter(item => item[linkField] === child[linkField]); + for (let j = 0; j < tableDataFilter.length; j++) { + const item = tableDataFilter[j]; + const iIndex = tableData.findIndex(row => row.sId === item.sId); + tableData[iIndex] = { ...item, ...child }; + if (onchangeField && this.state.onEventDataChange) { + const { sId, [onchangeField]: fieldsValue } = tableData[iIndex]; + window.tmpSlaveData = tableData; + tableData[iIndex] = await this.state.onEventDataChange('slave', onchangeField, { [onchangeField]: fieldsValue }, sId, [], true); + window.tmpSlaveData = null; + } + } + } + allReturnMap[`${tableName}Data`] = tableData; + } + } else { + allReturnMap[sName] = returnData[key]; + } + + } + if (commonUtils.isNotEmptyArr(allReturnMap.masterData) && Array.isArray(allReturnMap.masterData)) { + allReturnMap.masterData = allReturnMap.masterData[0]; + } + console.log('allReturnMap:', allReturnMap); + this.setState({ ...allReturnMap }); + } + } else { + this.getServiceError(dataReturn); + } + } + } + } else { + message.error('请正确配置自定义按钮!'); + } + } + }; + + /** 通用下载 */ + handleDownload = (name, flag, tableSelectedRowKeys) => { + const { sModelsId, app } = this.props; + const { + [`${name}Data`]: tableData } = this.state; + if (tableSelectedRowKeys === undefined || tableSelectedRowKeys.length !== 1) { + message.warn(commonFunc.showMessage(app.commonConst, 'selectedRowKeysNo'));/* 请先选择一条数据 */ + return; + } + const dataSelect = tableData.filter(item => item.sId === tableSelectedRowKeys[0]); + const { token } = this.props.app; + const { sPicturePath } = dataSelect[0]; + const urlPrint = `${commonConfig.file_host}file/download?sModelsId=${sModelsId}&token=${token}&savePathStr=${sPicturePath}`; + window.open(urlPrint); + }; + + // 调用指令集 + handleExecInstructSet = (params) => { + const { type, sInstruct, showName, callback } = params; + instructSet({ + ...this.props, + ...this.state, + btnConfig: { sInstruct: JSON.stringify(sInstruct), showName }, + onSaveState: this.handleSaveState, + callback + }) + } + + /** + * 色序反显 + * @returns + */ + showCacheData = (isSColorSerialMemo, data, processSelectedRowId) => { + if (isSColorSerialMemo && Array.isArray(data)) { + const value = data.find( + item => item && item.sId === processSelectedRowId + ); + try { + return { + sMemoData: JSON.parse(value?.sColorSerialMemo || '[]'), + isSColorSerialMemo, + } + } catch (error) { + return {} + } + } + } + + /** + * 取消当前页面websocket 状态 + * @returns + */ + handleSendSocketMessageProxy = (flag, showType, sId, sendTo, msgInfo, param) => { + if (!['noAction'].includes(showType) || !['release'].includes(flag)) { + return this.handleSendSocketMessage(flag, showType, sId, sendTo, msgInfo, param); + } + const { currentPane, userinfo } = this.props.app; + const { copyTo } = currentPane; + const { isNotEmptyObject, isNotEmptyArr } = commonUtils; + if (isNotEmptyObject(copyTo)) { + const { + slaveData, srcFormRoute, copyOtherData, masterData, copyToDataSid, + } = copyTo; + const sIdArray = [...copyToDataSid || []]; + + if (!currentPane?.checkedId) { + if (isNotEmptyObject(srcFormRoute) && srcFormRoute.includes('materialRequirementsPlanning')) { /* 物料需求计划用sWorkOrderMaterialId作为唯一键 */ + if (isNotEmptyArr(copyOtherData) && copyOtherData[0]?.name === 'detail' && isNotEmptyArr(copyOtherData[0]?.data)) { + const slaveDetailData = copyOtherData[0].data; + slaveDetailData.forEach((item) => { + const redisKey = item.sWorkOrderMaterialId; + sIdArray.push(redisKey); + }); + } else { /* 变更单、采购申请单 */ + slaveData.forEach((item) => { + const redisKey = item.sWorkOrderMaterialId; + sIdArray.push(redisKey); + }); + } + } + } + + if (isNotEmptyObject(masterData) && + isNotEmptyObject(masterData.sSrcSlaveId)) { + sIdArray.push(masterData.sSrcSlaveId); + } + + if (Array.isArray(slaveData)) { + slaveData.forEach((item) => { + const redisKey = item.sSlaveId; + sIdArray.push(redisKey); + }); + } + + const sId = [...new Set(sIdArray)].filter(Boolean).toString(); + this.handleSendSocketMessage('copyfinish', 'noAction', sId, userinfo.sId, null, null); + } + this.handleSendSocketMessage('release', 'noAction', currentPane?.checkedId || '', userinfo.sId, null, null); + this.handleSendSocketMessage('release', 'noAction', currentPane?.formId || '', userinfo.sId, null, null); + }; + + render() { + return ( +
{ this.baseRef = ref; }} + > + +
+ ); + } + }; +}; diff --git a/src/components/Common/CommonClassifyEvent.js b/src/components/Common/CommonClassifyEvent.js new file mode 100644 index 0000000..ecda1de --- /dev/null +++ b/src/components/Common/CommonClassifyEvent.js @@ -0,0 +1,1426 @@ +/* eslint-disable array-callback-return,no-undef,prefer-destructuring */ +import React, { Component } from 'react'; +import moment from 'moment'; +import { Modal, message } from 'antd'; +import * as commonFunc from './commonFunc'; +import * as commonBusiness from './commonBusiness'; /* 单据业务功能 */ +import * as commonUtils from '../../utils/utils'; /* 通用方法 */ +import commonConfig from '../../utils/config'; +import * as commonServices from '../../services/services'; + +const { confirm } = Modal; + +export default (ChildComponent) => { + return class extends Component { + constructor(props) { + super(props); + this.state = { + }; + } + componentWillReceiveProps(nextProps) { + const { + formData, sModelsId, searchSolution, masterData, + } = nextProps; + const { slaveConfig: slaveConfigOld } = nextProps; + let { iPageSize } = nextProps; + if (commonUtils.isEmptyObject(slaveConfigOld) && formData.length > 0) { + const sId = sModelsId !== undefined ? sModelsId : ''; + /* 数据Id */ + const slaveConfig = formData[0]; + const slaveColumn = commonFunc.getHeaderConfig(slaveConfig); + let filterCondition = []; + if (commonUtils.isNotEmptyObject(masterData) && !commonUtils.isEmpty(masterData.sSearchSolutionId) && commonUtils.isNotEmptyArr(searchSolution)) { + const iIndex = searchSolution.findIndex(item => item.sId === masterData.sSearchSolutionId); + if (iIndex > -1 && !commonUtils.isEmpty(searchSolution[iIndex].sCondition)) { + filterCondition = JSON.parse(searchSolution[iIndex].sCondition); + } + } + /* 首先以下拉页数为准 否则以后台页数为准 如果以上都没有设置 则依照config配置的页码设置 */ + if (commonUtils.isNotEmptyNumber(formData[0].iPageSize) && formData[0].iPageSize !== 0) { + iPageSize = formData[0].iPageSize; + } + this.handleGetData(slaveConfig, filterCondition, 1, iPageSize); + slaveConfig.gdsconfigformslave.push({ + sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnFirst', sControlName: 'BtnFirst', + }); + slaveConfig.gdsconfigformslave.push({ + sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnPrior', sControlName: 'BtnPrior', + }); + slaveConfig.gdsconfigformslave.push({ + sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnNext', sControlName: 'BtnNext', + }); + slaveConfig.gdsconfigformslave.push({ + sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnLast', sControlName: 'BtnLast', + }); + /* 如果后台配置了审核按钮 则无需配置 */ + const filterExamineIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === '' && item.showName !== '' && item.sControlName === 'BtnExamine'); + if (filterExamineIndex === -1) { + slaveConfig.gdsconfigformslave.push({ + sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnExamine', sControlName: 'BtnExamine', + }); + } + + const filterCancelExamineIndex = slaveConfig.gdsconfigformslave.filter(item => item.sName === '' && item.showName !== '' && item.sControlName === 'BtnCancelExamine'); + if (filterCancelExamineIndex === -1) { + slaveConfig.gdsconfigformslave.push({ + sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnCancelExamine', sControlName: 'BtnCancelExamine', + }); + } + + slaveConfig.gdsconfigformslave.push({ + sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnUpCheck', sControlName: 'BtnUpCheck', + }); + slaveConfig.gdsconfigformslave.push({ + sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnDownCheck', sControlName: 'BtnDownCheck', + }); + slaveConfig.gdsconfigformslave.push({ + sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnCopyTo', sControlName: 'BtnCopyTo', + }); + slaveConfig.gdsconfigformslave.push({ + sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnCopyFrom', sControlName: 'BtnCopyFrom', + }); + this.props.onSaveState({ + masterConfig: slaveConfig, slaveConfig, slaveColumn, sId, pageLoading: false, + }); + } + if (commonUtils.isEmptyStr(this.props.sClomunType) && commonUtils.isNotEmptyObject(this.props.masterConfig)) { + const { sTbName } = this.props.masterConfig; + if (sTbName === 'cahsupplyinit' || sTbName === 'cahcustomerinit' || sTbName === 'cahcashierinit') { + this.handleGetPeriod(); + } + } + } + + shouldComponentUpdate(nextProps) { + const { slaveColumn } = nextProps; + return commonUtils.isNotEmptyArr(slaveColumn); + } + componentDidUpdate() { + const { app, slaveData } = this.props; + const { currentPane } = app; + if (currentPane.classifyOption === 'add' && slaveData !== undefined) { + currentPane.classifyOption = ''; + this.handleAdd(); + this.props.onSaveState({ currentPane }); + } + } + + componentWillUnmount() { + const { sModelsId } = this.props; + const { userinfo } = this.props.app; + this.props.handleSendSocketMessage('release', 'noAction', sModelsId, userinfo.sId, null, null); + } + + /** 键盘事件监听 */ + onKeyDown = (e, record, sName, name) => { + const { [`${name}Data`]: tableData, [`${name}Column`]: tableColumn, [`${name}Config`]: tableConfig } = this.props; + + let keyCode = e.keyCode; + let firstName; + let bEnter = false; + if (keyCode === 13) { + // 判断当前单元格是否是最后,不是则跳到下一格,是则跳到下一行第一格 + bEnter = true; + const uniqueTableId = `table_${this.props.sModelsId}_${tableConfig.sId}`; + const currentTable = document.getElementById(uniqueTableId); + const currentTr = currentTable.querySelector(`tr[data-row-key="${record.sId}"]`); + const allInput = currentTr.querySelectorAll(`input[id*="${record.sId}"]`); + const iIndex = Array.from(allInput).findIndex(item => item.getAttribute('id') === `${sName}${record.sId}`); + if (iIndex < allInput.length - 1) { + keyCode = 39; + } else { + const oFirstInput = allInput[0]; + firstName = oFirstInput.getAttribute('id').replace(record.sId, ''); + keyCode = 40; + } + } + + // 以下if条件为 为解决bug2031问题入口 需求:收款单里输入的收款金额,上下键操作把加减金额改为选择上下行(通过上下方向键切换行数) + if ([38, 40].includes(keyCode)) { // 上键、下键 + e.preventDefault(); + if (tableData.length > 1) { // 当从表行数大于一行时才有上下移动的意义 + const index = tableData.findIndex(item => item.sId === record.sId); // 获取当前编辑行的下标 + if (index > -1) { + if (keyCode === 38 && index > 0) { // 方向键上键 且 当前编辑行下标大于0时,为0时无法向上 + const lastSid = tableData[index - 1].sId; // 获取上一个id + this.props.onSaveState({ [`${name}SelectedRowKeys`]: [lastSid] }, () => commonUtils.focus(`${sName}${lastSid}`)); + } + if (keyCode === 40 && index < tableData.length - 1) { // 方向键下键 且 当前编辑行下标小于最大值时,为最大值时无法向下 + const nextSid = tableData[index + 1].sId; // 获取下一个id + this.props.onSaveState({ [`${name}SelectedRowKeys`]: [nextSid] }, () => commonUtils.focus(`${firstName || sName}${nextSid}`)); + } + } + } + } + const move = (keyCode, cursortPosition, columnIndex, currentElement) => { + const inputType = currentElement.getAttribute('type'); + const value = currentElement.value; + if (keyCode === 37 && columnIndex > 0 && cursortPosition < 1) { // 左移 则 列下标必须大于0, 且光标在最左侧 + const lastId = `${tableColumn[columnIndex - 1].dataIndex}${record.sId}`; + if (!commonUtils.focus(lastId, e)) move(keyCode, cursortPosition, columnIndex - 1, currentElement); // 递归 + } + if (keyCode === 39 && columnIndex < tableColumn.length - 1) { // 右移 则 列下标必须小于列数量-1 + if (!record[sName] || cursortPosition >= value.length || inputType === 'search' || bEnter) { // 当前列为空 或 光标位置不小于当前值的长度 + const nextId = `${tableColumn[columnIndex + 1].dataIndex}${record.sId}`; + if (!commonUtils.focus(nextId, e)) move(keyCode, cursortPosition, columnIndex + 1, currentElement); // 递归 + } + } + }; + if ([37, 39].includes(keyCode)) { // 左键、右键 + const currentElement = document.getElementById(`${sName}${record.sId}`); // 当前编辑框对象 + if (currentElement) { + const cursortPosition = commonUtils.getCursortPosition(currentElement); // 光标位置 + const columnIndex = tableColumn.findIndex(item => item.dataIndex === sName); // 当前列下标 + move(keyCode, cursortPosition, columnIndex, currentElement); + } + } + } + + /** 获取表数据 */ + handleGetData = async (slaveConfig, slaveFilterCondition, page, pageSize, slaveOrderBy) => { + const { + app, sModelsType, slavePagination, iPageSize, + } = this.props; + const { currentPane } = app; + const conditonValues = currentPane.conditonValues; + if (commonUtils.isNotEmptyObject(conditonValues)) { + Object.keys(conditonValues).forEach((item) => { + if (!conditonValues[item] && currentPane[item]) { + conditonValues[item] = currentPane[item]; + } + }); + } + + const pageNum = commonUtils.isEmpty(page) ? 1 : page; + pageSize = commonUtils.isEmpty(pageSize) ? commonUtils.isEmpty(slavePagination) || commonUtils.isEmpty(slavePagination.pageSize) ? iPageSize : slavePagination.pageSize : pageSize; + const getData = await this.props.handleGetDataSet({ + name: 'slave', + configData: slaveConfig, + condition: { + pageNum, pageSize, bFilter: slaveFilterCondition, sFilterOrderBy: slaveOrderBy, sSqlCondition: conditonValues, + }, + isWait: true, + }); + const addState = {}; /* 用于界面树形展示的slaveData */ + if (sModelsType && (sModelsType === 'commonClassify/materialsClassify' || sModelsType.includes('children')) && commonUtils.isNotEmptyObject(getData)) { + const slaveData = getData.slaveData; + if (commonUtils.isNotEmptyArr(slaveData)) { + // addState = this.handleGetSlaveTreeData(slaveData); + const expandRowKeys = []; + const firstLevelData = slaveData.filter(item => commonUtils.isEmptyObject(item.sParentId)); + if (commonUtils.isNotEmptyArr(firstLevelData)) { + firstLevelData.forEach((item) => { + expandRowKeys.push(item.sId); + }); + addState.expKeys = expandRowKeys; + } + } + } + this.props.onSaveState({ + ...getData, ...addState, + }); + }; + + /* 获取树形slaveTreeData数据 */ + handleGetSlaveTreeData = (slaveData) => { + const slaveTreeData = []; /* 用于界面树形展示的slaveData */ + const expKeys = []; + const addState = {}; + if (commonUtils.isNotEmptyArr(slaveData)) { + const { slaveConfig } = this.props; + /* 若关联性sSqlCondition配置 则取配置 */ + let keyField = 'sId'; + let keyParentField = 'sParentId'; + let sSqlCondition = ''; + if (commonUtils.isNotEmptyObject(slaveConfig)) { + sSqlCondition = slaveConfig.sSqlCondition; + if (commonUtils.isNotEmptyObject(sSqlCondition) && commonUtils.isNotEmptyArr(sSqlCondition.split('.')) && sSqlCondition.split('.').length > 2) { + keyField = sSqlCondition.split('.')[1]; + keyParentField = sSqlCondition.split('.')[2]; + } + } + + slaveData.forEach((tableDataRow) => { + const tableDataRowNew = JSON.parse(JSON.stringify(tableDataRow)); + if (commonUtils.isEmpty(tableDataRow[keyParentField])) { /* 一级分类 */ + const childrenData = this.handleGetChildData(slaveData, tableDataRowNew[keyField], keyField, keyParentField); /* 获取子数据 */ + if (commonUtils.isNotEmptyArr(childrenData)) { + expKeys.push(tableDataRow.sSlaveId); + tableDataRowNew.children = childrenData; + } + slaveTreeData.push(tableDataRowNew); + } + }); + } + addState.slaveTreeData = slaveTreeData; + addState.expKeys = expKeys; + return addState; + } + /* 获取子节点数据 */ + handleGetChildData = (data, sId, keyField, keyParentField) => { + if (commonUtils.isNotEmptyArr(data)) { + const filterData = data.filter(item => item[keyParentField] === sId); + if (commonUtils.isNotEmptyArr(filterData)) { + filterData.forEach((child, index) => { + const filterChildData = this.handleGetChildData(data, child[keyField], keyField, keyParentField); + if (commonUtils.isNotEmptyArr(filterChildData)) { + filterData[index].children = filterChildData; + } + }); + } + return filterData; + } + } + handlePaginationChange = (page) => { + const { slaveConfig, slaveFilterCondition, slavePagination } = this.props; + this.props.handleGetDataSet({ + name: 'slave', configData: slaveConfig, condition: { pageNum: page, pageSize: slavePagination.pageSize, bFilter: slaveFilterCondition }, + }); + }; + /* 取消操作 */ + handleCancel = () => { + /* 待用数据声明 */ + const { + sModelsId, slaveConfig, slaveFilterCondition, slavePagination, slaveOrderBy, app, iPageSize, + } = this.props; + const { userinfo } = app; + const onSendSocketMessage = this.props.handleSendSocketMessage; + const onGetDataOk = this.handleGetData; + const onSaveStateOk = this.props.onSaveState; + confirm({ + title: '确定要取消', + onOk() { + onGetDataOk(slaveConfig, slaveFilterCondition, slavePagination.current, iPageSize, slaveOrderBy); + onSaveStateOk({ enabled: false }); + onSendSocketMessage('release', 'noAction', sModelsId, userinfo.sId, null, null); + }, + onCancel() { + }, + }); + }; + /** 点击修改按钮操作 */ + handleEdit = async () => { + const { + sModelsId, slaveConfig, slaveFilterCondition, slavePagination, slaveOrderBy, app, formSrcRoute, slaveSelectedRowKeys, dispatch, iPageSize, + } = this.props; + const { userinfo } = app; + const addState = {}; + if (commonUtils.isEmptyArr(slaveSelectedRowKeys)) { + message.error('请选择修改行!'); + this.props.onSaveState({ + loading: false, + }); + return; + } + const lockUrl = `${commonConfig.server_host}business/addSysLocking?sModelsId=${sModelsId}&sName=${formSrcRoute}`; + const value = { + tableName: slaveConfig.sTbName, + sId: [slaveSelectedRowKeys[0]], + }; + const { data } = await commonServices.postValueService(app.token, value, lockUrl); + // eslint-disable-next-line no-underscore-dangle + const _this = this; + if (data.code === 1) { /* 失败 */ + _this.props.onSaveState({ enabled: true, loading: false }); + } else if (data.code === -7) { + // eslint-disable-next-line no-underscore-dangle + confirm({ + title: '单据校验', /* 防呆校验 */ + content: data.msg, + onOk() { + _this.props.onSaveState({ enabled: true }); + }, + onCancel() { + }, + okText: '是', + cancelText: '否', + }); + this.props.onSaveState({ + loading: false, + }); + return true; + } else if (data.code === 2 || data.code === -8) { + Modal.info({ + title: '温馨提示:', + content: ( +
+ {commonFunc.getReturnMsg(data.msg)} +
+ ), + okText: '确认', + onOk() { + _this.props.onSaveState({ enabled: false, loading: false }); + addState.sUseInfo = data.msg; + }, + }); + } else { /* 失败 */ + this.props.onSaveState({ enabled: false, loading: false }); + addState.sUseInfo = data.msg; + if (commonUtils.isNotEmptyObject(data.erroMsg)) { + message.error(data.erroMsg); + } + return; + } + this.handleGetData(slaveConfig, slaveFilterCondition, slavePagination.current, iPageSize, slaveOrderBy); + let timValue = 0; + if (this.props.app.webSocket === null || this.props.app.webSocket.readyState !== WebSocket.OPEN) { + this.props.dispatch({ type: 'app/createWebSocket', payload: { reStart: true, dispatch } }); + timValue = 3000; + } + const reset = (ws, config1) => { + clearTimeout(config1.timerServer); + clearTimeout(config1.serverTimer); + start(ws, config1); + }; + const start = (ws, config1) => { + config1.timerServer = setTimeout(() => { + const message = { sendFrom: this.props.app.userinfo.sId, connectTest: 'test' }; // param 存放其它参数 keyName 需要放入Redis的数据key,keyValue 需要放入Redis的数据key 的值 + ws.send(JSON.stringify(message)); + }, config1.timeoutServer); + }; + setTimeout(() => { + this.props.app.webSocket.onmessage = (msg) => { + reset(this.props.app.webSocket, commonConfig); + const rtmsg = JSON.parse(msg.data); + if (rtmsg.action === 'showMsg') { + message.warning(rtmsg.msg); + this.props.onSaveState({ loading: false }); + } else if (rtmsg.action === 'loginOut') { + if (location.pathname.indexOf('/indexOee') > -1) { + dispatch({ type: 'app/throwErrorOee', payload: { code: -2, msg: rtmsg.msg } }); + } else if (location.pathname.indexOf('/indexMobile') > -1) { + dispatch({ type: 'app/throwErrorMobile', payload: { code: -2, msg: rtmsg.msg } }); + } else { + dispatch({ type: 'app/throwError', payload: { code: -2, msg: rtmsg.msg } }); + } + } else if (rtmsg.action === 'update') { + this.props.onSaveState({ enabled: true, loading: false }); + } else if (this.props.app.webSocket.homeAction) { + this.props.app.webSocket.homeAction(msg); + } + }; + this.props.handleSendSocketMessage('update', 'showMsg', sModelsId, userinfo.sId, null, null); // 分类型不能以Id来,涉及到多条修改 + }, timValue); + }; + /** 点击新增按钮操作 */ + handleAdd = () => { + const { sModelsType, sModelsId } = this.props; + let { slaveSelectedRowKeys, masterData } = this.props; + let { slaveData } = this.props; + if (slaveData === undefined) { + slaveData = []; + } + const newData = this.props.onDataRowAdd('slave', true);/* 调用父级新增 */ + if (commonUtils.isNotEmptyObject(newData)) { + newData.iOrder = slaveData.length; + } + if (sModelsType === 'commonClassfiy/sisPosition') { + newData.maxBillNo = 'sNo'; + } + if (commonUtils.isEmptyArr(slaveSelectedRowKeys)) { /* 通用分类新增,默认新增行为选中行 */ + slaveSelectedRowKeys = []; + slaveSelectedRowKeys.push(newData.sId); + } + /* 多级增加 新增同级 */ + if ((sModelsType === 'commonClassify/materialsClassify' || (commonUtils.isNotEmptyObject(sModelsType) && sModelsType.includes('children')))) { + const iIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys[0]); + /* 找到同级子元素的sControlParentId */ + if (iIndex > -1) { + newData.sParentId = slaveData[iIndex].sParentId; + /* 找到同级父级sAllId */ + const pId = slaveData[iIndex].sParentId; + const iParentIndex = slaveData.findIndex(item => item.sId === pId); + if (iParentIndex > -1) { + const sAllId = slaveData[iParentIndex].sAllId; + if (commonUtils.isEmptyObject(sAllId)) { + message.warn('数据生成错误![sAllId为空]'); + return; + } + newData.sAllId = `${sAllId},${newData.sId}`; + } else { + newData.sAllId = newData.sId; + } + slaveSelectedRowKeys = [newData.sId]; + } else { + newData.sAllId = newData.sId; + } + newData.sStatus = '0'; + } + newData.sFormId = sModelsId; + if (commonUtils.isNotEmptyObject(masterData)) { + masterData = { ...masterData, ...newData }; + } + newData.sFormId = sModelsId; + this.props.onSaveState({ + slaveData: [newData, ...slaveData], + slaveSelectedRowKeys, + masterData, + enabled: true, + }); + }; + + /** 点击新增子级按钮操作 */ + handleAddChild = () => { + const { sModelsType, sModelsId } = this.props; + let { slaveSelectedRowKeys, expKeys } = this.props; + let { slaveData } = this.props; + if (slaveData === undefined) { + slaveData = []; + } + const newData = this.props.onDataRowAdd('slave', true);/* 调用父级新增 */ + if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) { + newData.sParentId = slaveSelectedRowKeys[0]; + const iIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys[0]); + if (iIndex > -1) { + const sAllId = slaveData[iIndex].sAllId; + if (commonUtils.isEmptyObject(sAllId)) { + message.warn('子级数据生成错误![sAllId为空]'); // 获取父节点的sAllId + return; + } + newData.sAllId = `${sAllId},${newData.sId}`; + } + } else { + message.error('请选择父级分类!'); + } + + if (sModelsType === 'commonClassfiy/sisPosition') { + newData.maxBillNo = 'sNo'; + } + newData.sFormId = sModelsId; + if (commonUtils.isEmptyArr(slaveSelectedRowKeys)) { /* 通用分类新增,默认新增行为选中行 */ + slaveSelectedRowKeys = []; + slaveSelectedRowKeys.push(newData.sId); + } + if (commonUtils.isEmptyArr(expKeys)) { /* 通用分类新增,默认新增行为选中行 */ + expKeys = []; + expKeys.push(slaveSelectedRowKeys[0]); + } else { + expKeys.push(slaveSelectedRowKeys[0]); + } + slaveData.push(newData); + this.props.onSaveState({ + slaveData, + slaveSelectedRowKeys, + enabled: true, + expKeys, + }); + }; + /* 删除 */ + handleDel = () => { + const onOkDel = this.handleOkDel; + confirm({ + title: '确定要删除', + onOk() { + onOkDel(); + }, + onCancel() { + }, + }); + }; + handleOkDel = async () => { + const returnData = await this.handleTableDel('slave'); + if (returnData) { + this.handleValidateSave(); + } + }; + handleTableDel = (name, isWait) => { + const { app } = this.props; + const { [`${name}Data`]: tableData, [`${name}SelectedRowKeys`]: tableSelectedRowKeys, sModelsType } = this.props; + let { [`${name}DelData`]: tableDelData } = this.props; + tableDelData = commonUtils.isEmptyArr(tableDelData) ? [] : tableDelData; + if (commonUtils.isNotEmptyArr(tableSelectedRowKeys)) { + if (commonUtils.isNotEmptyObject(sModelsType) && sModelsType.includes('children') && commonUtils.isNotEmptyArr(tableData)) { + /* 删除该节点及所有子节点 */ + const controlChildData = tableData.filter(item => commonUtils.isNotEmptyObject(item.sAllId) && item.sAllId.indexOf(tableSelectedRowKeys[0]) > -1 && item.sId !== tableSelectedRowKeys[0]); + if (commonUtils.isNotEmptyArr(tableData)) { + controlChildData.forEach((itemNew) => { + tableSelectedRowKeys.push(itemNew.sId); + }); + } + } + + for (const sId of tableSelectedRowKeys) { + /* 看看删除集合和从表中是否都存在该条数据 */ + const tableDataIndex = tableData.findIndex(item => item.sId === sId); + if (tableDataIndex > -1) { + /* 删除从表中的数据并存入删除集合中 */ + const slaveDataFilter = tableData[tableDataIndex]; + slaveDataFilter.handleType = 'del'; + tableDelData.push(slaveDataFilter); + } + } + if (isWait) { + return { [`${name}Data`]: tableData, [`${name}DelData`]: tableDelData, [`${name}SelectedRowKeys`]: [] }; + } else { + this.props.onSaveState({ + [`${name}Data`]: tableData, + [`${name}DelData`]: tableDelData, + [`${name}SelectedRowKeys`]: [], + }); + return true; + } + } else { + message.warn(commonFunc.showMessage(app.commonConst, 'pleaseChooseDelData')); // 请选择删除数据 + return false; + } + }; + handleViewClick = (name, sName, record, index, myConfig) => { + if (sName === 'myTableConfig') { + this.handleQuickViewClick(name, sName, record, index, myConfig); + } else if (sName === 'sLookFlowHistory') { + const flowHistroyId = commonUtils.isNotEmptyObject(record) ? record.sId : ''; + this.props.onSaveState({ flowHistroyVisible: true, flowHistroyId }); + } else { + this.props.onViewClick(name, sName, record, index, myConfig); + } + } + handleGetTableConfig = async (name, sModelsId) => { + if (commonUtils.isNotEmptyObject(sModelsId)) { + const newConfig = await this.props.onGetTableConfig(name, sModelsId); + if (commonUtils.isNotEmptyObject(newConfig)) { + this.props.onSaveState({ [`${[name]}Config`]: newConfig }); + } + } + } + handleQuickViewClick = async (name, sName, record, index, myConfigArr) => { + const { + slaveConfig, + slaveData, + slaveFilterCondition, + slavePagination, + formRoute, + sModelsId, + // slaveSelectedData, + // masterData, + // employeeConfig, + } = this.props; + + let picArr = slaveConfig.gdsconfigformslave.filter(item => (item.sName === sName)); + if (commonUtils.isNotEmptyArr(myConfigArr)) { + picArr = myConfigArr; + } + + if (picArr.length > 0) { + const getConfig = this.handleGetTableConfig; + const tableDataRow = record; + const iIndex = index; + const [{ sActiveId }] = picArr; + let [{ sActiveKey }] = picArr; + const sFormId = sActiveId === '1' ? commonUtils.isEmpty(tableDataRow.sFormId) ? tableDataRow.sSrcFormId : tableDataRow.sFormId : sActiveId; + if (commonUtils.isNotEmptyObject(sActiveKey) && sActiveKey.includes('.')) { /* 接口按钮跳转 如果有slave.对应字段 则需要取出对应字段 */ + const index = sActiveKey.lastIndexOf('.'); + sActiveKey = sActiveKey.substring(index + 1, sActiveKey.length); + } + const sNameUrl = `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sFormId}?sModelsId=${sFormId}&sName=${formRoute}`; + const filterCondition = []; + const conditionValues = this.props.getSqlCondition(picArr[0], name, tableDataRow); + if (!commonUtils.isEmpty(conditionValues)) { + Object.keys(conditionValues).forEach((item) => { + if ((item === 'tStartDate_pro' || item.substring(0, 1) === 'p')) { + if (!commonUtils.isEmpty(conditionValues[item]) && conditionValues[item].length >= 2) { + const tStartDate = moment(conditionValues[item][0]).format(this.sDateFormat); + const tEndDate = moment(conditionValues[item][1]).add(1, 'days').format(this.sDateFormat); + filterCondition.push({ + bFilterName: item, + bFilterCondition: '=', + bFilterValue: `${tStartDate},${tEndDate}`, + }); + } + } else if ((item === 'mStartDate_pro' || item.substring(0, 1) === 'm')) { + if (!commonUtils.isEmpty(conditionValues[item])) { + const tStartDate = moment(conditionValues[item]).startOf('month').format(this.sDateFormat); + const tEndDate = moment(conditionValues[item]).endOf('month').add(1, 'days').format(this.sDateFormat); + filterCondition.push({ + bFilterName: `t${item.substring(1, item.length)}`, + bFilterCondition: '=', + bFilterValue: `${tStartDate},${tEndDate}`, + }); + } + } else if (item.substring(0, 1) === 't') { + filterCondition.push({ + bFilterName: item, + bFilterCondition: '=', + bFilterValue: moment(conditionValues[item]).format(this.sDateFormat), + }); + } else { + filterCondition.push({ + bFilterName: item, + bFilterCondition: '=', + bFilterValue: conditionValues[item], + }); + } + }); + } + + this.props.dispatch({ + type: 'content/onRouter', + payload: { + url: sNameUrl, + refresh: getConfig.bind(this, name, sModelsId), /* 刷新方法 */ + sTabId: commonUtils.createSid(), + sParentId: this.state.sTabId, + urlDataType: 'newPane', + checkedId: myConfigArr[0].sId, + sName: myConfigArr[0].sName, + bFilter: slaveFilterCondition, + pageSize: commonConfig.pageSize, + pages: slavePagination, + currentData: slaveData, + conditonValues: conditionValues, + newKey: tableDataRow[sActiveKey], + currentIndex: iIndex, + filterCondition, + }, + }); + } + }; + handleViewChoose= (name, sName, record) => { + if (sName === 'sParams') { // 产量上报 工艺参数 + const { enabled } = this.props; + const slaveSelectOneData = record; + const sProcessParamsSelects = []; + const sParamData = []; + let paramType = ''; + if (commonUtils.isNotEmptyObject(slaveSelectOneData)) { + paramType = slaveSelectOneData.sReportParam; /* 上报参数 */ + } + if (commonUtils.isEmpty(paramType)) { + message.warn('无工艺参数!'); + return; + } + /* 工序参数以表格形式展示 列 */ + const sParamConfig = { + bisMutiSelect: false, + bMutiSelect: false, + }; + const gdsconfigformslave = [{ + sId: commonUtils.createSid(), + sName: 'sId', + showName: '主键', + bVisible: false, + iFitWidth: 200, + }, { + sId: commonUtils.createSid(), + sName: 'bSelfCbx', + showName: '选择', + bVisible: true, + iFitWidth: 37, + }, { + sId: commonUtils.createSid(), + sName: 'sParamKey', + showName: '参数主键', + bVisible: false, + iFitWidth: 200, + }, { + sId: commonUtils.createSid(), + sName: 'sParamName', + showName: '参数名', + bVisible: true, + iFitWidth: 230, + }, { + sId: commonUtils.createSid(), + sName: 'sParamValue', + showName: '参数值', + bVisible: true, + iFitWidth: 230, + }]; + sParamConfig.gdsconfigformslave = gdsconfigformslave; + const sParamColumn = commonFunc.getHeaderConfig(sParamConfig); + if (commonUtils.isNotEmptyObject(paramType)) { + /* 要把数据以表格的形式显示出来 */ + const sParamJsonObj = JSON.parse(paramType); + for (const key of Object.keys(sParamJsonObj)) { + if (key.includes('sParam') && !key.includes('DropDown') && !key.includes('Default')) { + const obj = {}; + obj.sId = commonUtils.createSid(); + obj.sParamKey = key; + obj.sParamName = sParamJsonObj[key]; + /* 找到数字 找到下拉数据源 */ + const num = key.replace(/[^\d]/g, '').trim(); + if (Number(num)) { + const number = Number(num); + const sParamDropDownKey = `sParamDropDown${number}`; + obj.sDropDownData = sParamJsonObj[sParamDropDownKey]; /* 下拉 */ + const sParamDefaultKey = `sParamDefault${number}`; + obj.sParamValue = sParamJsonObj[sParamDefaultKey]; /* 默认值 */ + /* 如果sParamValue有值 则替换默认值 */ + const oldKey = `sParamValue${number}`; + const oldParamValue = slaveSelectOneData[oldKey]; /* 界面打开时,数据集中原始的sParamValue1,sParamValue2数据填充到数据上 */ + if (commonUtils.isNotEmptyObject(oldParamValue)) { + obj.sParamValue = oldParamValue; /* 默认值 */ + } + } + sParamData.push(obj); + } + } + /* 将sParam1中的数据 还原到sParamData数据中 */ + if (commonUtils.isNotEmptyObject(record.sParams)) { + const selectedData = JSON.parse(record.sParams); + if (commonUtils.isNotEmptyArr(selectedData)) { + selectedData.forEach((itemS) => { + const iIndex = sParamData.findIndex(item => item.sParamName === itemS.sParamName); + if (iIndex > -1) { + const addState = {}; + addState.sParamValue = itemS.sParamValue; + addState.bSelfCbx = itemS.bSelfCbx; + sParamData[iIndex] = { ...sParamData[iIndex], ...addState }; + } + }); + } + + /* 如果数据集有一个是非选中的则非选中状态 否则全选 */ + if (commonUtils.isNotEmptyArr(sParamColumn)) { + const iIndex = sParamColumn.findIndex(item => item.dataIndex === 'bSelfCbx'); + if (iIndex > -1) { + const filterData = sParamData.filter(item => !item.bSelfCbx); + if (commonUtils.isNotEmptyArr(filterData)) { + sParamColumn[iIndex] = { ...sParamColumn[iIndex], bCheckAll: false }; + } else { + sParamColumn[iIndex] = { ...sParamColumn[iIndex], bCheckAll: true }; + } + } + } + } + } + this.props.onSaveState({ + slaveRecord: record, + sProcessParamsSelects, + sParamsModalVisible: true, + sParamConfig, + sParamColumn, + sParamData, + sParamModalType: 'sReport', + enabled, + }); + } + } + + /* 动态参数标题选择框 全选/取消全选 */ + handleCheckParamChange = () => { + const { + sParamData, + sParamColumn, + } = this.props; + /* 全选 取消全选功能 */ + if (commonUtils.isNotEmptyArr(sParamData)) { + /* 标题bSelfCbx加标识 */ + const iIndex = sParamColumn.findIndex(item => item.dataIndex === 'bSelfCbx'); + if (iIndex > -1) { + let bSelfCbx = false; + if (sParamColumn[iIndex].bCheckAll) { + bSelfCbx = false; + } else { + bSelfCbx = true; + } + sParamColumn[iIndex] = { ...sParamColumn[iIndex], bCheckAll: bSelfCbx }; + sParamData.forEach((item, index) => { + sParamData[index] = { ...sParamData[index], bSelfCbx }; + }); + } + this.props.onSaveState({ + sParamData, + sParamColumn, + }); + } + } + + /* 选择上报参数点击确定 */ + handleReportParamsOk = () => { // 工艺参数弹窗确定按钮 + const { + slaveData, + slaveRecord, + sParamData, + // enabled, + sParamModalType, + } = this.props; + if (true) { + if (commonUtils.isNotEmptyArr(slaveData) && commonUtils.isNotEmptyObject(slaveRecord)) { + const processSelectDataIndex = slaveData.findIndex(item => item.sId === slaveRecord.sId); + if (processSelectDataIndex > -1) { + if (commonUtils.isNotEmptyArr(sParamData)) { + let sParamJsonData = ''; + const sParamSeletedData = sParamData.filter(item => item.bSelfCbx); + if (commonUtils.isNotEmptyObject(sParamSeletedData)) { + sParamJsonData = JSON.stringify(sParamSeletedData); + } + let { handleType } = slaveData[processSelectDataIndex]; + handleType = commonUtils.isEmpty(handleType) ? 'update' : handleType; + if (sParamModalType === 'sReport') { /* 报价参数点击确定 */ + slaveData[processSelectDataIndex].sParams = sParamJsonData; + } + slaveData[processSelectDataIndex].handleType = handleType; + } + } + } + this.props.onSaveState({ + slaveData, + sParamsModalVisible: false, + }); + } else { + this.props.onSaveState({ + sParamsModalVisible: false, + }); + } + } + + /** toolbar审核(消审) */ + handleAudit = async (flag) => { + /* 待用数据声明 */ + const { masterData, gdsformconst } = this.props; + if (!commonUtils.isEmpty(masterData)) { + /* 作废订单不能审核 */ + if (masterData.bInvalid) { + message.warning(gdsformconst.filter(item => (item.sName === 'sToVoid'))[0].showName); + return ''; + } + /** 数据审核 */ + await this.dataAudit(flag); + } else { + this.props.onSaveState({ + loading: false, + }); + } + }; + + /** 数据审核 */ + dataAudit = async (flag, tmpCheck, isWait) => { + message.destroy(); + /* 待用数据声明 */ + const { + sModelsId, masterData, app, slaveConfig, token, sModelsType, slaveData, slaveSelectedRowKeys, slaveFilterCondition, + } = this.props; + const sSlaveIdArray = []; + if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) { + slaveSelectedRowKeys.forEach((item) => { + sSlaveIdArray.push(item); + }); + } + const slaveId = sSlaveIdArray.toString(); + /* 数据参数 */ + const value = { + sClientType: '1', + paramsMap: { + iFlag: flag, + iTmpCheck: commonUtils.isEmptyNumber(tmpCheck) ? 0 : tmpCheck, + sFormGuid: sModelsId, + sGuid: masterData.sId, + sSlaveId: slaveId, + sBillNo: commonUtils.isNotEmptyObject(masterData.sBillNo) ? masterData.sBillNo : '', + }, + }; + let clearFlag = false; + if (sModelsType.includes('sales/salesOrder') || sModelsType.includes('manufacture/workOrder')) { + if (commonUtils.isNotEmptyArr(slaveData)) { + for (const item of slaveData) { + if (commonUtils.isNotEmptyStr(item.sProductInfo)) { + clearFlag = true; + break; + } + } + } else { + this.props.onSaveState({ + loading: false, + }); + return; + } + } + /* 数据审核 */ + const url = `${commonConfig.server_host}business/doExamine?sModelsId=${sModelsId}`; + const returnData = (await commonServices.postValueService(app.token, value, url)).data; + if (isWait) { + return returnData; + } else { + /* 接收返回值 */ + const check = commonFunc.showMessage(app.commonConst, 'BtnExamine');/* 审核 */ + const BtnCancelExamine = commonFunc.showMessage(app.commonConst, 'BtnCancelExamine');/* 销审 */ + if (returnData.code === 1) { /* 成功 */ + this.props.onSaveState({ + loading: false, + }); + if (flag === 1) { + /* 审核 */ + if (clearFlag && (sModelsType.includes('sales/salesOrder') || sModelsType.includes('manufacture/workOrder'))) { + commonUtils.setStoreDropDownData(sModelsId, 'master', 'sProductId', []); + commonUtils.setStoreDropDownData(sModelsId, 'master', 'sProductNo', []); + commonUtils.setStoreDropDownData(sModelsId, 'master', 'sProductName', []); + } + let outData; + if (commonUtils.isNotEmptyObject(returnData.dataset)) { + outData = returnData.dataset.rows[0].dataSet.outData; + } + if (commonUtils.isNotEmptyStr(outData[0].sReturn)) { + const sReturnArray = outData[0].sReturn.split('|'); + if (outData[0].sReturn.split('-').length < 2) { + // 正常业务提示,非审核模板 + // if (this.props.app.currentPane.refresh !== undefined) { + // this.props.app.currentPane.refresh(); + // } + message.error(check + outData[0].sReturn); + return; + } + const checkConditions = []; + let checkPersonData = {}; + sReturnArray.forEach((item) => { + const checkCondition = item.split('-')[2]; + const iIndex = checkConditions.findIndex(itemCondition => itemCondition.condition === checkCondition); + if (iIndex <= -1) { + checkConditions.push({ + key: commonUtils.createSid(), + condition: checkCondition, + }); + } + }); + const sCheckModelId = sReturnArray[0].split('-')[1]; + if (commonUtils.isNotEmptyStr(sCheckModelId)) { + const urlCheck = `${commonConfig.server_host}checkModel/getUserListByModelId/${sCheckModelId}?sModelsId=${sModelsId}`; + const dataReturn = (await commonServices.getService(token, urlCheck)).data; + if (dataReturn.code === 1) { + checkPersonData = dataReturn.dataset.rows; + checkPersonData.forEach((item) => { + item.key = commonUtils.createSid(); + }); + this.props.onSaveState({ + checkConditions, checkPersonData, sCheckModelId, visible: true, + }); + return true; + } else { /* 失败 */ + this.props.getServiceError({ msg: check + dataReturn }); + } + } + } else { + message.success(check + returnData.msg); + } + } else { + /* 消审 */ + const { outData } = returnData.dataset.rows[0].dataSet; + if (commonUtils.isNotEmptyStr(outData[0].sReturn)) { + message.error(outData[0].sReturn); + } else { + // if (this.props.app.currentPane.refresh !== undefined) { + // this.props.app.currentPane.refresh(); + // } + message.success(BtnCancelExamine + returnData.msg); + } + } + await this.handleGetData(slaveConfig, slaveFilterCondition, 1); + if (this.props.app.currentPane.refresh !== undefined) { + this.props.app.currentPane.refresh(); + } + } else { /* 失败 */ + this.props.getServiceError(returnData); + this.props.onSaveState({ + loading: false, + }); + } + return true; + } + }; + + /** toolbar校验保存 */ + handleValidateSave = async () => { + let isTrue = true; + this.form.validateFields((err) => { + /* 验证通过与不通过走不同的流程 */ + if (err) { /* 验证失败 */ + /* 直接渲染显示错误提示 */ + for (const key of Object.keys(err)) { + message.warning(err[key].errors[0].message); + } + isTrue = false; + this.props.onSaveState({ + loading: false, + }); + } else { /* 验证成功 */ + const { + slaveData, slaveConfig, slaveDelData, + } = this.props; + const data = []; + if (!commonBusiness.validateTable(slaveConfig, slaveData, this.props)) { + this.props.onSaveState({ + loading: false, + }); + isTrue = false; + return; + } + data.push(commonBusiness.mergeData('slave', slaveConfig.sTbName, slaveData, slaveDelData)); + if (slaveConfig.sTbName.toLowerCase().includes('master')) { + const { sUserName = '' } = commonUtils.convertStrToObj(localStorage.getItem('xlybusinessuserinfo')); + data[0].column.forEach((item) => { + const { handleType } = item; + if (handleType !== 'add') { + item.sUpdatePerson = sUserName; + item.tUpdate = moment().format('YYYY-MM-DD HH:mm:ss'); + } + }); + } + this.handleSaveData({ data, sClientType: '1' }); + } + }); + if (!isTrue) throw new Error('异常'); + }; + /** toolbar保存 */ + handleSaveData = async (params) => { + const { + token, sModelsId, slaveFilterCondition, slaveConfig, slavePagination, slaveOrderBy, app, slaveData, iPageSize, + } = this.props; + const { userinfo } = app; + const onSendSocketMessage = this.props.handleSendSocketMessage; + const returnData = await commonBusiness.saveData({ token, value: params, sModelsId }); + if (commonUtils.isNotEmptyObject(returnData)) { + /* 防呆校验 */ + if (returnData.code === -7) { + // eslint-disable-next-line no-underscore-dangle + const _this = this; + confirm({ + title: '单据校验', /* 防呆校验 */ + content: returnData.msg, + onOk() { + params.iFlag = 1; + _this.handleSaveData(params); + }, + onCancel() { + }, + okText: '保存', + cancelText: '不保存', + }); + this.props.onSaveState({ + loading: false, + }); + return true; + } else if (returnData.code === 2 || returnData.code === -8) { + Modal.info({ + title: '温馨提示:', + content: ( +
+ {commonFunc.getReturnMsg(returnData.msg)} +
+ ), + okText: '确认', + onOk() {}, + }); + } + commonUtils.clearStoreDropDownData(); + /* 新记录时,关闭后能自动带值 */ + const callBackRecord = this.props.app.currentPane.newRecordMethod; + if (callBackRecord !== undefined && commonUtils.isNotEmptyArr(slaveData) && slaveData.length > 0) { + const filterData = slaveData.filter(item => (item.handleType === 'add')); + const sId = commonUtils.isNotEmptyArr(filterData) && filterData.length > 0 ? filterData[0].sId : null; + /* 回调 传[新增的数据sId] */ + if (this.props.app.currentPane.newRecordMethod !== undefined) { + this.props.app.currentPane.newRecordMethod(sId); + } + } + if (this.props.app.currentPane.refresh !== undefined) { + this.props.app.currentPane.refresh(); + } + /* END */ + onSendSocketMessage('release', 'noAction', sModelsId, userinfo.sId, null, null); + this.props.onSaveState({ + enabled: false, slaveDelData: [], loading: false, + }); + this.handleGetData(slaveConfig, slaveFilterCondition, slavePagination.current, iPageSize, slaveOrderBy); + return true; + } else { + this.props.onSaveState({ + slaveDelData: [], + loading: false, + }); + return false; + } + }; + /** 表单回带 */ + handleForm = (form) => { + this.form = form; + }; + /* 作废、取消作废的公用函数 */ + handleInvalid = (obj) => { + const props = { ...this.props, ...this.state, ...obj }; + const onOkInvaild = this.handleOkChangeInvaild; + confirm({ + title: obj.title, + onOk() { + onOkInvaild(props); + }, + onCancel() { + }, + }); + }; + /* 切换作废状态 */ + handleOkChangeInvaild = async (props) => { + props = this.handleOkInvalid(props); + this.setState({ ...props }); + }; + /** 作废,取消作废 */ + handleOkInvalid = async (props) => { + const { + sModelsId, slaveData, slaveConfig, handleType, slaveSelectedRowKeys, app, slavePagination, + } = props; + if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) { + const { token } = props.app; + const { sTbName } = slaveConfig; + const value = { + sClientType: '1', + sId: slaveSelectedRowKeys, + sTableName: sTbName, + handleType, + sBooleanCheck: false, + }; + const url = `${commonConfig.server_host}checkModel/updatebInvalid?sModelsId=${sModelsId}`; + const { data } = await commonServices.postValueService(token, value, url); + if (data.code === 1) { + message.success(data.msg); + for (const key of slaveSelectedRowKeys) { + const selectData = slaveData.filter(item => item.sId === key); + selectData.bInvalid = handleType === 'toVoid'; + } + /* 作废(取消作废)后刷新页面 */ + this.handlePaginationChange(slavePagination.current); + } else { + this.props.getServiceError(data); + } + return props; + } else { + message.warn(commonFunc.showMessage(app.commonConst, 'sChoosebInvalid'));/* 请选择作废数据 */ + } + }; + /** 按钮操作事件 */ + handleButtonClick = (name) => { + if (name === 'BtnOut') { + this.handleOut(); + } else if (name === 'BtnRefresh') { + const { slavePagination } = this.props; + this.handlePaginationChange(slavePagination.current); + } else if (name === 'BtnSetPeriod') { + this.handleBtnSetPeriod(); + } else if (name === 'BtnRelievePeriod') { + this.handleBtnRelievePeriod(); + } + }; + + /* 导出Excel */ + handleOut = async () => { + const { + slaveConfig, formRoute, masterData, + } = this.props; + + /* 导出使用Post提交 */ + const url = `${commonConfig.server_host}excel/export/${slaveConfig.sId}?sModelsId=${slaveConfig.sParentId}&sName=${formRoute}&token=${encodeURIComponent(this.props.app.token)}`; + const conditionValuesStr = JSON.stringify({ sId: masterData?.sId, sBillNo: masterData?.sBillNo }); + this.handleOpenOut(url, '', '', undefined, conditionValuesStr); + }; + + /* Get提交地址栏参数过多,更改Get提交为Post提交 */ + handleOpenOut = (url, bFilter, slaveOrderBy, sGroupByList, conditionValues) => { + const newWin = window.open(); + let formStr = ''; + // 设置样式为隐藏,打开新标签再跳转页面前,如果有可现实的表单选项,用户会看到表单内容数据 + formStr = `
` + + ``; + if (commonUtils.isNotEmptyObject(conditionValues)) { + formStr += ``; + } + formStr += ''; + newWin.document.body.innerHTML = formStr; + newWin.document.forms[0].submit(); + return newWin; + } + + /* 获取期初 */ + handleGetPeriod = async () => { + const { sTbName } = this.props.masterConfig; + let sClomunType = ''; + if (sTbName === 'cahsupplyinit') { + sClomunType = 'bAP'; + } else if (sTbName === 'cahcustomerinit') { + sClomunType = 'bAR'; + } else if (sTbName === 'cahcashierinit') { + sClomunType = 'bCashier'; + } + const { sModelsId } = this.props; + const { token } = this.props.app; + const url = `${commonConfig.server_host}sysAccountPeriod/getSysAccountPeriod?sModelsId=${sModelsId}`; + const value = { sClientType: '1', sClomunType }; + const { data } = await commonServices.postValueService(token, value, url); + if (data.code === 1) { + const [{ isSysAccountPeriod }] = data.dataset.rows; + this.props.onSaveState({ + adDisabled: isSysAccountPeriod, + sClomunType, + }); + } else { + this.props.getServiceError(data); + } + }; + /* 设置期初 */ + handleBtnSetPeriod = async () => { + const { sTbName } = this.props.masterConfig; + let sClomunType = ''; + if (sTbName === 'cahsupplyinit') { + sClomunType = 'bAP'; + } else if (sTbName === 'cahcustomerinit') { + sClomunType = 'bAR'; + } else if (sTbName === 'cahcashierinit') { + sClomunType = 'bCashier'; + } + const { sModelsId } = this.props; + const { token } = this.props.app; + const url = `${commonConfig.server_host}sysAccountPeriod/updateSysAccountPeriod?sModelsId=${sModelsId}`; + const value = { sClientType: '1', handleType: 'add', sClomunType }; + const { data } = await commonServices.postValueService(token, value, url); + if (data.code === 1) { + message.success(data.msg); + this.props.onSaveState({ adDisabled: true, enabled: false }); + } else { + this.props.getServiceError(data); + } + }; + /* 解除锁定 */ + handleBtnRelievePeriod = async () => { + const { sModelsId } = this.props; + const { token } = this.props.app; + const { sTbName } = this.props.masterConfig; + let sClomunType = ''; + if (sTbName === 'cahsupplyinit') { + sClomunType = 'bAP'; + } else if (sTbName === 'cahcustomerinit') { + sClomunType = 'bAR'; + } else if (sTbName === 'cahcashierinit') { + sClomunType = 'bCashier'; + } + const url = `${commonConfig.server_host}sysAccountPeriod/updateSysAccountPeriod?sModelsId=${sModelsId}`; + const value = { sClientType: '1', handleType: 'reset', sClomunType }; + const { data } = await commonServices.postValueService(token, value, url); + if (data.code === 1) { + message.success(data.msg); + this.props.onSaveState({ adDisabled: false }); + } else { + this.props.getServiceError(data); + } + }; + + handleTitleChange = (slavePagination, filters, sorter) => { + const { slaveConfig, slaveFilterCondition } = this.props; + const sort = sorter.order === 'ascend' ? 'asc' : 'desc'; + const slaveOrderBy = Object.keys(sorter).length > 0 ? { [sorter.columnKey]: sort } : ''; // 后端未支持空对象, 先用空表示 + this.handleGetData(slaveConfig, slaveFilterCondition, slavePagination.current, slavePagination.pageSize, slaveOrderBy); + }; + handleTitleChangeEnabled = (slavePagination) => { + this.props.onSaveState({ slavePagination }); + }; + handleTableSelectRowChange = async (name, selectedRowKeys) => { + const { + [`${name}Data`]: tableData, sModelsType, sModelsId, token, masterConfig, enabled, + } = this.props; + if (commonUtils.isNotEmptyArr(selectedRowKeys)) { + if (sModelsType === 'commonClassfiy/salesMan') { + const addState = this.props.onTableSelectRowChange(name, selectedRowKeys, true); + const { [`${name}SelectedRowKeys`]: rowKeys } = addState; + for (const sId of rowKeys) { + const tableDataIndex = tableData.findIndex(item => item.sId === sId); + const sNameIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === 'sName');/* 判断配置中是否有员工编号字段 */ + if (tableDataIndex > -1 && sNameIndex > -1) { + const tableDataRow = JSON.parse(JSON.stringify(tableData[tableDataIndex])); + masterConfig.gdsconfigformslave[sNameIndex].iTag = 0; /* 默认是0 */ + if (enabled && tableDataRow.handleType !== 'add') { /* 判断销售人员是否已被占用 */ + const value = { + tableName: masterConfig.sTbName, + sId: [sId], + }; + const url = `${commonConfig.server_host}business/addSysLocking?sModelsId=${sModelsId}`; + /* 接收返回值 */ + const { data } = await commonServices.postValueService(token, value, url); + if (data.code === 1) { + const sNameIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === 'sName'); + masterConfig.gdsconfigformslave[sNameIndex].iTag = 1; /* ,已占用销售人员,员工不能修改 即下拉不可选 */ + } else { /* 失败 */ + this.props.getServiceError(data); + } + } + } + } + } else if (name === 'sParam' && commonUtils.isNotEmptyArr(selectedRowKeys)) { + /* 点击工艺参数列表 根据点击行动态加载配置 */ + const { sParamData, sParamConfig } = this.props; + /* 找到最后一个选中 */ + const lastSelectedKeys = selectedRowKeys[selectedRowKeys.length - 1]; + const iIndex = sParamData.findIndex(item => lastSelectedKeys === item.sId); + /* 选中数据时 塞入选中行的配置 */ + if (iIndex > -1) { + const sParamObj = sParamData[iIndex]; + const index = sParamConfig.gdsconfigformslave.findIndex(item => item.sName === 'sParamValue'); + if (index > -1) { + if (commonUtils.isNotEmptyObject(sParamObj.sDropDownData)) { + sParamConfig.gdsconfigformslave[index].sDropDownType = 'const'; + sParamConfig.gdsconfigformslave[index].showDropDown = JSON.stringify(sParamObj.sDropDownData); + } else { + sParamConfig.gdsconfigformslave[index].sDropDownType = ''; + sParamConfig.gdsconfigformslave[index].showDropDown = undefined; + } + } + /* 点击时 若没打钩 则选择框打钩 若已经打钩则取消打钩 */ + if (sParamData[iIndex].bSelfCbx) { + // sParamData[iIndex] = { ...sParamData[iIndex], bSelfCbx: false }; + } else { + sParamData[iIndex] = { ...sParamData[iIndex], bSelfCbx: true }; + } + this.props.onSaveState({ + sParamData, + }); + } + } + } + this.props.onTableSelectRowChange(name, selectedRowKeys); + } + /* 点击展开图标时,调用接口获取嵌套字表数据 */ + handleOnExpand = async (expanded, record) => { + const { expKeys } = this.props; + /* 添加移除展开的sId */ + const { formRoute } = this.props; + let newExp = commonUtils.isNotEmptyArr(expKeys) ? expKeys : []; + let rowKeyId = ''; + if (formRoute === '/indexPage/materialRequirementsPlanning') { + rowKeyId = record.sMaterialsGS; + } + if (expanded) { + if (commonUtils.isNotEmptyObject(rowKeyId)) { + newExp.push(rowKeyId); + } + } else { + newExp = newExp.filter(item => item !== rowKeyId); + } + this.props.onSaveState({ expKeys: newExp }); + } + + render() { + return ( + + ); + } + }; +}; diff --git a/src/components/Common/CommonComponent/index.js b/src/components/Common/CommonComponent/index.js new file mode 100644 index 0000000..b894ba3 --- /dev/null +++ b/src/components/Common/CommonComponent/index.js @@ -0,0 +1,3034 @@ +import moment from 'moment'; +import React, { Component, createRef } from 'react'; +import reactComponentDebounce from '@/components/Common/ReactDebounce'; +import '@ant-design/compatible/assets/index.css'; +import { + InputNumber, + Checkbox, + DatePicker, + Input, + Cascader, + Select, + AutoComplete, + Spin, + message, + Form, + Upload, + Image, + Button, + Space, + Table, + Pagination, + Tooltip, +} from 'antd'; +import { + EyeOutlined, + FilePdfOutlined, + FileWordOutlined, + FileExcelOutlined, + FileOutlined, + RightOutlined, +} from '@ant-design/icons'; +import * as commonUtils from '@/utils/utils'; +import styles from '@/index.less'; +import Provinces from '@/assets/provinces.json'; +import Cities from '@/assets/cities.json'; +import Areas from '@/assets/areas.json'; +import commonConfig from '@/utils/config'; +import { VirtualKeyboard } from '@/oee/common/oeeKeyBoard';// 虚拟软键盘 +import 'braft-editor/dist/output.css'; + +const FormItem = Form.Item; +const { Option } = Select; +const { TextArea } = Input; +const { Search } = Input; +const InputNumberA = reactComponentDebounce(300)(InputNumber); +const InputA = reactComponentDebounce(300)(Input); +const AutoCompleteA = reactComponentDebounce(300)(AutoComplete); /* 处理快速选择产品后离开 产品无法赋值问题s */ +const TextAreaA = reactComponentDebounce(500)(TextArea); +// const InputNumberA = InputNumber; +// const InputA = Input; +// const AutoCompleteA = AutoComplete; +// const TextAreaA = TextArea; +const { RangePicker, MonthPicker } = DatePicker; + +export default class CommonComponent extends Component { + /** 构造函数 */ + constructor(props) { + super(props); + this.state = { + dataValue: props.dataValue, /* 本showType数据 */ + enabled: props.enabled, /* 是否是查看状态(数据格式:布尔) */ + dropDownData: [], /* 下拉数据集(如果不是下拉控件该值为空,数据格式:数组对象) */ + conditonValues: {}, + sFieldName: props.showConfig.sName, // 字段名 + bNotEmpty: props.showConfig.bNotEmpty, + mode: props.showConfig.bMultipleChoice ? 'multiple' : 'default', + bNewRecord: props.showConfig.bNewRecord, /* 是否有新纪录 */ + sActiveDisplay: true, + pageNum: 0, + totalPageCount: 1, + searchValue: '', + searchDropDownData: [], + searchTotalPageCount: 1, + searchPageNum: 0, + spinState: false, + currentPage: 1, + selectTableData: [], + buttonLoading: false, + key: 0, + selectTableIndex: 0, + }; + this.firstDataIndex = props.showConfig.sName.substring(0, 1); /* 控件首字母(数据格式:字符串) */ + this.max = props.showConfig.sMaxValue; /* 最大值(数据格式:数字) */ + this.min = props.showConfig.sMinValue; /* 最小值(数据格式:数字) */ + // 重构修改 + this.getFieldDecorator = commonUtils.isUndefined(props.form) ? undefined : props.form.getFieldDecorator; /* 字段验证(数据格式:数字) */ + // this.getFieldDecorator = commonUtils.isUndefined(props.form) ? undefined : undefined; /* 字段验证(数据格式:数字) */ + this.floatNum = this.props.getFloatNum(props.showConfig.sName); /* 数字格式化规范转换(数据格式:数字) */ + this.floatPrice = this.getFloatPrice(this.floatNum); /* 价格格式化规范转换(数据格式:数字) */ + this.formItemLayout = commonUtils.isNotEmptyObject(props.formItemLayout) ? + props.formItemLayout : + location.pathname.toLowerCase().indexOf('oee') > -1 ? { labelCol: { span: 7, style: { color: 'rgba(0, 0, 0, 0.65)', backgroundColor: '#BFEFFF' } }, wrapperCol: { span: 15 } } : + { labelCol: { span: 7, style: { height: '27.82px', color: 'rgba(0, 0, 0, 0.65)', backgroundColor: '#BFEFFF' } }, wrapperCol: { span: 15 } }; /* 表格样式(主要是colspan和rowspan,数据格式:对象) */ + this.isDropdownFilter = false; + this.V = { value: props.dataValue }; + this.myRef = createRef(); + this.dropDownCount = 0; + this.bSpecial = location.pathname?.includes('ResearchTableTree') && props.showConfig.sName === 'sProductName'; + } + + /** 渲染前只执行一次 */ + componentWillMount() { + this.mounted = true; + if (this.props.showConfig.sDropDownType === 'const') { /* 常量下拉 */ + /* 常量下拉其实只取一次数据就可以啦,去过数据的会给state中的dropDownData赋值,所以dropDownData有值的情况就不需要再获取了 */ + const showDropDown = commonUtils.isNotEmptyArr(this.props.showConfig.dropDownData) ? this.props.showConfig.dropDownData : + (typeof this.props.showConfig.showDropDown === 'object') ? this.props.showConfig.showDropDown : commonUtils.objectToArr(commonUtils.convertStrToObj(this.props.showConfig.showDropDown)); + /* 给state赋值 */ + if (this.mounted) { + this.setState({ + dropDownData: showDropDown, + }); + } + } else if (this.props.showConfig.sDropDownType === 'sql' && !commonUtils.isEmptyArr(this.props.showConfig.dropDownData)) { + if (this.mounted) { + this.setState({ + dropDownData: this.props.showConfig.dropDownData, + }); + } + } + } + + componentDidMount() { + const currentNode = this.myRef.current; + const selectInputNode = currentNode.querySelector("input[class*='ant-select-selection-search-input']"); + const antInput = currentNode.querySelector("input[class*='ant-input']"); + const oInput = selectInputNode || antInput; + if (oInput) { + oInput.addEventListener('compositionstart', () => { + this.chineseInputting = true; + }); + oInput.addEventListener('compositionend', () => { + this.chineseInputting = false; + if (this.handleCompleteInputEventCache) { + this.handleCompleteInputEventCache(); + } + }); + } + + if (currentNode) { + if (['t', 'm', 'y'].includes(this.firstDataIndex)) { + const oInput = currentNode.querySelector(`input[id*="${this.props.showConfig.sName}"]`); + if (oInput) { + let { sDateFormat } = this.props.showConfig; + if (commonUtils.isEmptyStr(sDateFormat)) { + if (this.firstDataIndex === 'm') { + sDateFormat = 'YYYY-MM'; + } else if (this.firstDataIndex === 'y') { + sDateFormat = 'YYYY'; + } else { + sDateFormat = this.props.getDateFormat(); + } + } + oInput.oninput = (e) => { + const { value } = e.target; + const isValidDate = moment(value, sDateFormat, true).isValid(); + if (isValidDate) { + this.handleSelectOptionEvent(moment(this.state.dataValue), value); + } + }; + } + } + } + document.addEventListener('mousedown', this.handleSelectClick); + } + + /** props改变的时候触发 */ + componentWillReceiveProps(nextProps) { + /* 如果是下拉控件,则要获取数据(获取下拉数据前要先更新sqlCondition) */ + const { + dataValue, enabled, sFieldName, bNotEmpty, showName, sDropDownType, + } = this.state; + if (nextProps.showConfig === undefined || this.props.showConfig === undefined) return; + this.firstDataIndex = nextProps.showConfig.sName.substring(0, 1); /* 控件首字母(数据格式:字符串) */ + + if (nextProps.showConfig.sDropDownType === 'const') { /* 常量下拉 */ + /* 常量下拉其实只取一次数据就可以啦,去过数据的会给state中的dropDownData赋值,所以dropDownData有值的情况就不需要再获取了 */ + const showDropDown = commonUtils.isNotEmptyArr(nextProps.showConfig.dropDownData) ? nextProps.showConfig.dropDownData : + (typeof nextProps.showConfig.showDropDown === 'object') ? nextProps.showConfig.showDropDown : commonUtils.objectToArr(commonUtils.convertStrToObj(nextProps.showConfig.showDropDown)); + // 对应工序单独处理 + // if (this.props.showConfig.showName === '对应工序') { + // showDropDown = nextProps.customDropData; + // } + /* 给state赋值 */ + if (this.mounted) { + this.setState({ + dropDownData: showDropDown, + }); + } + } else if (nextProps.showConfig.sDropDownType === 'sql' && !commonUtils.isEmptyArr(nextProps.showConfig.dropDownData)) { + if (this.mounted) { + this.setState({ + dropDownData: nextProps.showConfig.dropDownData, + }); + } + } + /* 把需要更新的数据setState */ + if (dataValue !== nextProps.dataValue || enabled !== nextProps.enabled || bNotEmpty !== nextProps.showConfig.bNotEmpty || sFieldName !== nextProps.showConfig.sName || (showName !== nextProps.showConfig.showName || !showName) || sDropDownType !== nextProps.showConfig.sDropDownType || (this.bSpecial && this.props.record.sProductNo !== nextProps.record.sProductNo)) { + if (this.mounted) { + if (commonUtils.isEmpty(nextProps.dataValue)) { + this.lastValue = nextProps.dataValue; + } + const addState = { + dataValue: nextProps.dataValue, + enabled: nextProps.enabled, + sFieldName: nextProps.showConfig.sName, + sDropDownType: nextProps.showConfig.sDropDownType, + bNotEmpty: nextProps.showConfig.bNotEmpty, + showName: nextProps.showConfig.showName, + }; + if (this.bSpecial && this.completeSelectFlag) { + addState.key = this.state.key + 1; + } + this.completeSelectFlag = false; + this.setState(addState); + } + } + } + + shouldComponentUpdate(nextProps, nextState) { + const { + dataValue, enabled, dropDownData, searchValue, searchDropDownData, sFieldName, bNotEmpty, sActiveDisplay, sDropDownType, spinState, showConfig, + } = this.state; + + return nextProps.showConfig !== undefined && (dataValue !== nextState.dataValue || enabled !== nextState.enabled || + sFieldName !== nextState.sFieldName || sDropDownType !== nextState.sDropDownType || bNotEmpty !== nextState.bNotEmpty || JSON.stringify(dropDownData) !== JSON.stringify(nextState.dropDownData) || + searchValue !== nextState.searchValue || JSON.stringify(searchDropDownData) !== JSON.stringify(nextState.searchDropDownData) || + JSON.stringify(sActiveDisplay) !== JSON.stringify(nextState.sActiveDisplay) || nextProps.showTime !== this.props.showTime || + spinState !== nextState.spinState || JSON.stringify(nextState.selectTableData) !== JSON.stringify(this.state.selectTableData) || + JSON.stringify(nextProps.showConfig) !== JSON.stringify(showConfig)); + } + + componentDidUpdate() { + const { dataValue, searchValue } = this.state; + if (dataValue === '' && searchValue) { + // eslint-disable-next-line + this.setState({ + searchValue: '', + }); + } + } + + componentWillUnmount() { + this.mounted = false; + document.removeEventListener('mousedown', this.handleSelectClick); + } + + onFocus = () => { + this.isDropdownFilter = false; + this.setState({ sActiveDisplay: false }); + }; + + onBlur = (event) => { + if (this.onExecInstructSet('blur')) return; + + this.isDropdownFilter = false; + if (this.state.searchValue !== '' && this.props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(this.props.showConfig.dropDownData)) { + if (!this.props.showConfig.bCanInput) { + this.handleSelectOptionEvent(''); + } + this.setState({ + searchPageNum: 1, + searchTotalPageCount: 1, + // searchDropDownData: [], + // searchValue: '', + spinState: false, + sActiveDisplay: true, + }); + } else { + this.setState({ + sActiveDisplay: true, + }); + } + /* 若下拉配置了movesql 则离开时 调用下拉sql数据 */ + if (this.props.showConfig && (this.props.showConfig.sDropDownType === 'movesql' || commonUtils.isNotEmptyObject(this.props.showConfig.sButtonParam))) { + this.props.onDropDownBlur(this.props.name, this.props.showConfig.sName, this.props.record, this.props.showConfig); + } + + this.onCheckFields(500); + this.onBlurText(event, 500); + }; + + onBlurText = (event, timeout = 0) => { + if (this.onExecInstructSet('blur')) return; + const currentValue = event?.target?.value; + if (currentValue === this.lastValue) return; + setTimeout(() => { + const { + name, + record, + sBtnSendDialogConfigList, + onToolBarBtnClick, + } = this.props; + if (name !== 'master') return; + if (commonUtils.isEmptyArr(sBtnSendDialogConfigList)) return; + const { sName } = this.props.showConfig; + if (!record[sName]) return; + + const { sActiveKey, sControlName } = + sBtnSendDialogConfigList.find((item) => { + const { sActiveKey = '' } = item; + return sActiveKey.split(',').includes(`${name}.${sName}`); + }) + || {}; + if (sControlName !== 'BtnSendDialog') { + if (!sActiveKey) return; + this.lastValue = currentValue; + onToolBarBtnClick({ key: sControlName }); + } + }, timeout); + } + + onExecInstructSet = (type) => { + const { sInstruct: sInstructStr, showName, sOnChangeInstruct } = this.props.showConfig; + const sInstruct = commonUtils.convertStrToObj(sInstructStr, {}); + let { [type]: instructType } = sInstruct; + if (type === 'change') { + const onChangeNew = commonUtils.convertStrToObj(sOnChangeInstruct, {}); + instructType = onChangeNew[type]; + } + if (instructType) { + if (this.props.onExecInstructSet) { + this.props.onExecInstructSet({ + type, + sInstruct: instructType, + showName: `${showName}-${type === 'blur' ? '离焦' : '变化'}`, + }); + } else { + message.error('未定义调用指令集事件!'); + } + return true; + } + return false; + } + + onCheckFields = () => { + // 手机号、邮箱校验等校验 + // setTimeout(() => { + const sDateFormatTypeList = ['phone', 'mobile', 'mail', 'postcode']; + const { sName, showName, sDateFormat } = this.props.showConfig; + const { record } = this.props; + const value = record[sName]; + if ( + value !== undefined && value !== '' && sDateFormatTypeList.includes(sDateFormat) + ) { + let flag = false; + if (sDateFormat === 'phone') { + const reg = /^0\d{2,3}-\d{7,8}$/; + const reg1 = /^1[0-9]{10}$/; + const reg2 = /^0\d{2,3}-\d{7,8}-\d{1,8}$/; + if (!reg.test(value) && !reg1.test(value) && !reg2.test(value)) { + flag = true; + } + } else if (sDateFormat === 'mobile') { + const reg = /^0\d{2,3}-\d{7,8}$/; + const reg1 = /^1[0-9]{10}$/; + const reg2 = /^0\d{2,3}-\d{7,8}-\d{1,8}$/; + if (!reg.test(value) && !reg1.test(value) && !reg2.test(value)) { + flag = true; + } + } else if (sDateFormat === 'mail') { + const reg = /^[a-zA-Z0-9]{1,20}@[a-zA-Z0-9]{1,5}\.[a-zA-Z0-9]{1,5}$/; + if (!reg.test(value)) { + flag = true; + } + } else if (sDateFormat === 'postcode') { + const reg = /^[1-9][0-9]{5}$/; + if (!reg.test(value)) { + flag = true; + } + } + + if (flag) { + this.props.onChange(this.props.name, 'verificationFailed', { verificationFailed: true, verificationFailedMsg: `【${showName}】【${sName}】格式不正确!` }, this.props.sId, []); + message.warning(`【${showName}】【${sName}】格式不正确!`); + } else if (record.verificationFailed) { + record.verificationFailed = undefined; + } + } + // }, timeout); + } + + /** 下拉时看是否要重新获取数据 */ + onDropdownVisibleChange = (open) => { + const { + dropDownData, bNewRecord, pageNum: pageNumOld, totalPageCount: totalPageCountOld, searchValue, conditonValues, + } = this.state; + + if (this.mounted && open) { + const conditonValuesNew = this.props.getSqlCondition(this.props.showConfig, this.props.name, this.props.record); + const pageNum = JSON.stringify(conditonValuesNew) !== JSON.stringify(conditonValues) ? 1 : pageNumOld === 0 ? 1 : pageNumOld; + const totalPageCount = conditonValuesNew !== conditonValues ? 1 : totalPageCountOld; + if (pageNum === 1 && this.props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(this.props.showConfig.dropDownData)) { + this.setState({ spinState: true }); + this.getDropDownData(pageNum, totalPageCount, searchValue, this.dropDownCount); + } + } else { + // if (searchValue !== '' && this.props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(this.props.showConfig.dropDownData)) { + // this.setState({ + // searchPageNum: 1, searchTotalPageCount: 1, searchDropDownData: [], searchValue: '', spinState: false, + // }); + // } + this.isDropdownFilter = false; + } + if (this.props.onDropdownVisibleChange !== undefined) { + if (dropDownData.length === 0 && !bNewRecord) { + /* 如果没有值并且没有新纪录,则不展开 */ + open = false; + } + this.props.onDropdownVisibleChange(open); + } + } + + onDoubleClick = () => { + const sMemo = this.props.showConfig.sName; + const title = this.props.showConfig.showName; + const bSParamValue = sMemo === 'sParamValue'; + if ((commonUtils.isNotEmptyObject(sMemo) && sMemo.indexOf('Memo') > -1) || (bSParamValue && !this.props.record.sDropDownData) || + (this.props.showConfig.sControlName && this.props.showConfig.sControlName.toLowerCase().indexOf('memo') > -1)) { + const sCurrMemoProps = { + title, + name: this.props.name, + sValue: this.props.dataValue, + sMemoField: sMemo, + bVisibleMemo: true, + sRecord: this.props.record, + sMemoConfig: this.props.showConfig, + bOnlyShow: !this.props.enabled, + }; + if (this.props.bInSlaveMemo) { + this.props.onSaveState({ sCurrMemoProps1: sCurrMemoProps }); + } else if (this.props.onSaveState) { + this.props.onSaveState({ sCurrMemoProps }); + } + } else if (commonUtils.isNotEmptyObject(sMemo) && sMemo.indexOf('sValue') > -1) { /* 计算方案 变量设置双击弹出 */ + this.props.onFieldDoubleClick(this.props.record, this.state.dataValue, this.props.showConfig, this.props.name); + } else if (commonUtils.isNotEmptyObject(sMemo) && sMemo.indexOf('sAssignField') > -1) { /* 赋值字段 变量设置双击弹出 */ + this.props.onFieldDoubleClick(this.state.dataValue, this.props.showConfig, this.props.name); + } + } + + onEditorClick = () => { + // if (this.props.enabled) { + // + // } + const curEditorProps = { + title: this.props.showConfig.showName, + name: this.props.name, + value: this.props.dataValue, + sName: this.props.showConfig.sName, + visible: true, + record: this.props.record, + config: this.props.showConfig, + }; + this.props.onSaveState({ curEditorProps }); + } + + onKeyUp = (e) => { + if (this.props.onKeyUp) { + this.props.onKeyUp(e); + } + } + + onKeyDown = (e) => { + // 如果输入的是字母数字或者中文 + if (!this.state.bDropDownOpen && /^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(e.keyCode)) { + this.setState({ bDropDownOpen: true }); + } + if (e.ctrlKey && e.keyCode === 82) { /* CTRL+ALT+R 代替右击事件 */ + this.onContextMenu(e); + } else if (e.key === 'F10') { + message.info(this.props.showConfig.sName); + } else if (e.ctrlKey && (e.altKey || e.metaKey) && e.keyCode === 71) { /* CTRL+ALT+G F7 设置界面 */ + const { sType } = this.props?.app?.userinfo || {}; + if (!['sysadmin'].includes(sType)) { + return; + } + if (commonUtils.isNotEmptyObject(this.props)) { + const { + name, tableConfig, record, configName, + } = this.props; + if (commonUtils.isNotEmptyObject(tableConfig)) { + const myTableConfig = JSON.parse(JSON.stringify(tableConfig)); + myTableConfig.sActiveId = '16411004790004762980820285096000'; + myTableConfig.sName = this.props.showConfig.sName; + const myTableConfigArr = []; + myTableConfigArr.push(myTableConfig); + if (this.props.name === 'master') { /* 主表 */ + this.props.onViewClick(name, 'myTableConfig', record, 0, myTableConfigArr, configName); + } else { /* 从表 */ + this.props.onViewClick(name, 'myTableConfig', record, 0, myTableConfigArr, configName); + } + } + } + } else if (this.props.onKeyDown) { + const { showConfig, record, name } = this.props; + this.props.onKeyDown(e, record, showConfig.sName, name); + } + } + + /* CommonList列表onkeydown-F10处理 */ + onKeyDownDiv = (e) => { + if (this.props.onKeyDown) { + this.props.onKeyDown(e); + } + if (e.key === 'F10') { + message.info(this.props.showConfig.sName); + } else if (e.ctrlKey && e.keyCode === 67) { + console.log('复制成功!'); + } else if (e.ctrlKey && e.keyCode === 65) { + console.log('全选成功!'); + } else { + e.preventDefault(); + return false; + } + } + + /* 单击右键全部更新,弹出窗选择后,更新此列所有数据 (只更新非只读字段) */ + onContextMenu = (e) => { + if (this.state.enabled && commonUtils.isNotEmptyObject(this.props) && this.props.name !== 'master' && commonUtils.isNotEmptyObject(this.props.showConfig)) { + const { showConfig, name } = this.props; + const { bReadonly } = showConfig; + if (bReadonly) { + return; + } + e.preventDefault(); /* 阻止浏览器本身的右击事件 */ + if (this.props.onContextMenu) { + const { showConfig, record } = this.props; + this.props.onContextMenu(e, record, showConfig, name); + } + } + } + + /* 字段选择弹窗 */ + onFieldPopupModal = (showConfig, name, open) => { + if (open !== undefined) { + this.props.onFieldPopupModal(showConfig, name); + } + } + /** 获取selectprops对象 */ + getSelectProps = () => { + /* 返回值声明 */ + const obj = { + id: `${this.props.showConfig.sName}${this.props.record ? this.props.record.sId : commonUtils.createSid()}`, + showSearch: true, /* 是否有查找功能 */ + // disabled: !this.state.enabled /* 修改的时候传过来的数据 */ + onSelect: () => { + if (this.state.mode !== 'multiple') { + this.setState({ bDropDownOpen: false, bNotFirstEnter: true }); + } + }, + onChange: this.handleSelectOptionEvent, /* 选择触发事件 */ + filterOption: this.filterOption, /* 搜索时过滤对应的 option 属性 */ + onDropdownVisibleChange: this.onDropdownVisibleChange, + onPopupScroll: this.handlePopupScroll, + onSearch: this.handleSearch, + notFoundContent: this.state.spinState ? : '暂无数据', + // getPopupContainer: this.props.name === 'slave' || this.props.name === 'searchColumnShow' ? this.getPopupContainer : null,/*解决下拉框不随浏览器滚动问题 */ + onFocus: this.onFocus, + // onBlur: this.onBlur, + onBlur: (e) => { + this.setState({ bDropDownOpen: false, bNotFirstEnter: false }); + this.onBlur(e); + }, + mode: this.state.mode, + onPaste: (event) => { + if (this.props.showConfig.bMultipleChoice) { + const clipboardText = event.clipboardData.getData('text/plain').trim(); + if (clipboardText) { + const { dataValue = '' } = this.state; + let dataValueNew = dataValue; + if (dataValueNew === '') { + dataValueNew += clipboardText; + } else { + dataValueNew += `,${clipboardText}`; + } + this.handleSelectOptionEvent(dataValueNew, []); + document.activeElement.blur(); + } + } + }, + }; + if (this.props.showConfig.sDropDownType === 'sql') { + obj.optionLabelProp = 'title'; + } + if (this.props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !this.state.enabled; + } + obj.placeholder = this.props.showConfig.placeholder; + /* 区分Oee设置字体与其他系统设置字体 */ + obj.dropdownStyle = commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase().indexOf('oee') > -1 ? { fontSize: '1.3rem' } : { fontSize: '12px' }; + obj.dropdownClassName = commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase().indexOf('oee') > -1 ? (location.pathname.toLowerCase().indexOf('loginoee') > -1 ? 'loginOeeDropDown' : 'oeeDropDown') : ''; + /* 主表时才赋值value */ + if (this.props.bTable) { + if (this.props.showConfig.bMultipleChoice) { + obj.value = !commonUtils.isEmpty(this.state.dataValue) ? this.state.dataValue.split(',') : []; /* 数据值 */ + } else { + obj.value = this.state.dataValue; /* 数据值 */ + } + obj.className = this.props.costomClassName === undefined ? styles.editSelect : this.props.costomClassName; + } + if (this.props.showConfig.iDropWidth > 0) { + obj.dropdownMatchSelectWidth = false; /* true时 下拉菜单和选择器同宽。默认将设置 min-width,当值小于选择框宽度时会被忽略。 */ + obj.dropdownStyle.width = this.props.showConfig.iDropWidth; + } + obj.onInputKeyDown = (e) => { + const { bDropDownOpen, bNotFirstEnter } = this.state; + if (bDropDownOpen && [38, 40, 13].includes(e.keyCode)) { + // eslint-disable-next-line no-console + } else if (bDropDownOpen && [27].includes(e.keyCode)) { + this.setState({ bDropDownOpen: false }); + } else if (e.keyCode === 13 && !bNotFirstEnter) { + this.setState({ bDropDownOpen: true, bNotFirstEnter: true }); + } else { + this.onKeyDown(e); + } + }; + obj.onKeyUp = this.onKeyUp; + obj.open = this.state.bDropDownOpen !== undefined ? this.state.bDropDownOpen : false; + // obj.onBlur = () => { + // this.setState({ bDropDownOpen: false }); + // }; + obj.onMouseMove = () => { + this.bInputIn = true; + }; + obj.onMouseLeave = () => { + this.bInputIn = false; + }; + /* 返回值 */ + return obj; + }; + + getSelectTableProps = () => { + const { currentPage, tempCurrentPage, searchValue } = this.state; + const pageNum = searchValue === '' ? currentPage : tempCurrentPage; + + /* 返回值声明 */ + const obj = { + id: `${this.props.showConfig.sName}${this.props.record ? this.props.record.sId : commonUtils.createSid()}`, + dropdownMatchSelectWidth: false, + filterOption: this.filterOption, /* 搜索时过滤对应的 option 属性 */ + onDropdownVisibleChange: (open) => { + this.onDropdownVisibleChange(open); + if (open === false) { + clearTimeout(this.blurtimer); + this.blurtimer = setTimeout(() => { + this.onBlur(); + }, 500); + } else { + clearTimeout(this.blurtimer); + this.onFocus(); + } + }, + onSearch: this.selectTableSearch, + showSearch: true, + // onFocus: this.onFocus, + // onBlur: this.onBlur, + }; + if (this.props.showConfig.sDropDownType === 'sql') { + obj.optionLabelProp = 'title'; + } + if (this.props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !this.state.enabled; + } + obj.placeholder = this.props.showConfig.placeholder; + /* 区分Oee设置字体与其他系统设置字体 */ + obj.dropdownStyle = commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase().indexOf('oee') > -1 ? { fontSize: '1.3rem' } : { fontSize: '12px' }; + obj.dropdownClassName = commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase().indexOf('oee') > -1 ? (location.pathname.toLowerCase().indexOf('loginoee') > -1 ? 'loginOeeDropDown' : 'oeeDropDown') : ''; + /* 主表时才赋值value */ + if (this.props.bTable) { + obj.value = this.props.showConfig.bMultipleChoice && !commonUtils.isEmpty(this.state.dataValue) ? this.state.dataValue.split(',') : this.state.dataValue; /* 数据值 */ + obj.className = this.props.costomClassName === undefined ? styles.editSelect : this.props.costomClassName; + } + if (this.props.showConfig.iDropWidth > 0) { + obj.dropdownMatchSelectWidth = false; /* true时 下拉菜单和选择器同宽。默认将设置 min-width,当值小于选择框宽度时会被忽略。 */ + } + obj.onInputKeyDown = (e) => { + const { + selectTableData = [], + selectTableIndex = 0, + bDropDownOpen, + bNotFirstEnter, + } = this.state; + const { keyCode } = e; + + try { + if (bDropDownOpen) { + const oTBody = this.selectTableRef1.querySelector('.ant-table-body'); + const { scrollTop } = oTBody; + + const oTr = this.selectTableRef1.querySelector('.selected-record-row'); + const trRect = oTr.getBoundingClientRect(); + const tbodyRect = oTBody.getBoundingClientRect(); + + const tbodyTop = tbodyRect.top + window.scrollY; + const tbodyBottom = tbodyRect.bottom + window.scrollY; + + const trTop = trRect.top + window.scrollY; + const trBottom = trRect.bottom + window.scrollY; + if (keyCode === 40) { + const selectTableIndexNew = Math.min(selectTableIndex + 1, selectTableData.length - 1); + if (selectTableIndex !== selectTableIndexNew) { + const bInView = trTop + 29 >= tbodyTop && trBottom + 29 <= tbodyBottom; + if (!bInView) { + oTBody.scrollTop = scrollTop + 29; + } + this.setState({ + selectTableIndex: selectTableIndexNew, + }); + } + } else if (keyCode === 38) { + const selectTableIndexNew = Math.max(selectTableIndex - 1, 0); + if (selectTableIndex !== selectTableIndexNew) { + const bInView = trTop - 29 >= tbodyTop && trBottom - 29 <= tbodyBottom; + if (!bInView) { + oTBody.scrollTop = scrollTop - 29; + } + this.setState({ + selectTableIndex: selectTableIndexNew, + }); + } + } else if (keyCode === 13) { + e.stopPropagation(); + this.setState({ bNotFirstEnter: true }); + setTimeout(() => { + oTr.click(); + }, 10); + } else { + this.onKeyDown(e); + } + } else if (![37, 38, 39, 40, 13].includes(keyCode)) { + this.setState({ bDropDownOpen: true }); + } else if (keyCode === 13 && !bNotFirstEnter) { + this.setState({ bDropDownOpen: true, bNotFirstEnter: true }); + } else { + this.onKeyDown(e); + } + } catch (error) { + console.log(error); + } + }; + obj.open = this.state.bDropDownOpen !== undefined ? this.state.bDropDownOpen : false; + obj.onBlur = () => { + if (!this.bInPagination) { + this.setState({ bDropDownOpen: false, bNotFirstEnter: false }); + } + }; + obj.onMouseMove = () => { + this.bInputIn = true; + }; + obj.onMouseLeave = () => { + this.bInputIn = false; + }; + obj.onKeyUp = this.onKeyUp; + /* eslint-disable */ + obj.dropdownRender = (menu) => ( + <> + {/*
+ this.selectTableSearch(e)}/> +
*/} + {menu} +
{ this.bInPagination = true; }} + onMouseLeave={() => { + this.bInPagination = false; + if (this.selectTableRef) { + this.selectTableRef.focus(); + } + }} + > + this.selectTableChange(e)} showSizeChanger={false} current={pageNum} pageSize={20} size="small" total={this.state.totalCount} /> + + {this.props.showConfig.bFirstEmpty && ( + ) + } + {this.props.showConfig.bNewRecord && ( + ) + } + +
+ + ) + /* eslint-enable */ + /* 返回值 */ + return obj; + }; + + getSelectTableOption = () => { + const { selectTableData, selectTableIndex = 0 } = this.state; + const { showConfig } = this.props; + const { sTableTitleSql } = showConfig; + const tempColumnArr = sTableTitleSql.split(','); + let scrollX = 0; + const columns = tempColumnArr.map((item, index) => { + const tempArr = item.split(':'); + const [value, title, columnWidth] = tempArr; + let width; + if (!Number.isNaN(Number(columnWidth))) { // 如果配置了列宽 + width = Number(columnWidth); + } else { // 没有配置列宽,就根据字符数算宽度 + // 获取中文字数、非中文字数, 中文12px,其它8px + const titleStr = title; + const totalStringLen = titleStr.length; + const otherStrLen = titleStr.replace(/[^\x00-\xff]/g, '').length; // eslint-disable-line + const chineseStrLen = totalStringLen - otherStrLen; + const defaultWidth = (chineseStrLen * 12) + (otherStrLen * 8); + const maxStrLen = selectTableData.reduce((res, pre) => { + let tempValue = pre[value] !== undefined ? pre[value] : ''; + if (tempValue === '') { + return res; + } + tempValue = typeof tempValue === 'string' ? tempValue : JSON.stringify(tempValue); + const totalStringLen = tempValue.length; + const otherStrLen = tempValue.replace(/[^\x00-\xff]/g, '').length; // eslint-disable-line + const chineseStrLen = totalStringLen - otherStrLen; + const tempWidth = (chineseStrLen * 12) + (otherStrLen * 8); + return Math.max(tempWidth, res); + }, defaultWidth); + width = Math.min(maxStrLen + 8, 300); + } + + scrollX += width; + + return { + title, + dataIndex: value, + key: value, + width: index !== tempColumnArr.length - 1 ? width : undefined, + render: (text) => { + return ({text}); + }, + }; + }); + + return ( +
{ + return selectTableIndex === index ? 'selected-record-row' : ''; + }} + rowKey="sId" + onRow={(record, index) => { + return { + index, + onMouseEnter: () => { + this.setState({ + selectTableIndex: index, + }); + }, + onClick: () => { + this.setState({ tempCurrentPage: null, bDropDownOpen: false, bNotFirstEnter: true }); + this.handleSelectOptionEvent(record.sSlaveId || record.sId); + }, + }; + }} + pagination={false} + scroll={{ + y: 256 - 10 - 29 - 32, + x: scrollX, + }} + dataSource={selectTableData} + columns={columns} + /> + + ); + } + + /** 获取complete对象 */ + getCompleteProps = () => { + /* 返回值声明 */ + const obj = { + id: `${this.props.showConfig.sName}${this.props.record ? this.props.record.sId : commonUtils.createSid()}`, + // disabled: !this.state.enabled /* 修改的时候传过来的数据 */ + onChange: this.handleCompleteInputEvent, /* 选择触发事件 */ + onSelect: (value) => { + this.setState({ bDropDownOpen: false, bNotFirstEnter: true }); + this.completeSelectFlag = true; + if (value === '') { + if (this.props.showConfig.sDropDownType === 'sql') { + this.props.handleSqlDropDownNewRecord(this.props.showConfig, this.props.name); + } + } else if (this.state.dataValue === value) { + this.completeFlag = true; + this.handleCompleteInputEvent(value); + if (this.myRef && this.myRef.current) { + const oInput = this.myRef.current.querySelector(`#${this.props.showConfig.sName}`); + if (oInput) { + setTimeout(() => { + oInput.blur(); + }, 1000); + } + } + } else if (this.myRef && this.myRef.current) { + const oInput = this.myRef.current.querySelector(`#${this.props.showConfig.sName}`); + if (oInput) { + oInput.blur(); + } + } + }, + filterOption: this.filterOption, /* 搜索时过滤对应的 option 属性 */ + onDropdownVisibleChange: this.onDropdownVisibleChange, + onPopupScroll: this.handlePopupScroll, + /* 区分Oee设置字体与其他系统设置字体 */ + dropdownClassName: commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase().indexOf('oee') > -1 ? (location.pathname.toLowerCase().indexOf('loginoee') > -1 ? 'loginOeeDropDown' : 'oeeDropDown') : '', + onSearch: this.handleSearch, + notFoundContent: this.state.spinState ? : '暂无数据', + onFocus: this.onFocus, + onBlur: (e) => { + this.setState({ bDropDownOpen: false, bNotFirstEnter: false }); + this.onBlur(e); + }, + }; + if (this.props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !this.state.enabled; + } + obj.placeholder = this.props.showConfig.placeholder; + /* 区分Oee设置字体与其他系统设置字体 */ + obj.dropdownStyle = commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase().indexOf('oee') > -1 ? { fontSize: '1.3rem' } : { fontSize: '12px' }; + /* 主表时才赋值value */ + if (this.props.bTable) { + obj.value = this.props.showConfig.bMultipleChoice && !commonUtils.isEmpty(this.state.dataValue) ? this.state.dataValue.split(',') : this.state.dataValue; /* 数据值 */ + obj.className = this.props.costomClassName === undefined ? styles.editSelect : this.props.costomClassName; + } + if (this.props.showConfig.iDropWidth > 0) { + obj.dropdownMatchSelectWidth = false; /* true时 下拉菜单和选择器同宽。默认将设置 min-width,当值小于选择框宽度时会被忽略。 */ + obj.dropdownStyle.width = this.props.showConfig.iDropWidth; + } + if (typeof commonUtils.convertStrToNumber(this.max) === 'number' && commonUtils.convertStrToNumber(this.max) !== 0 && this.max.indexOf('.d') === -1 && this.max.indexOf('.i') === -1) { + obj.maxLength = this.max; /* 最大长度 */ + } + obj.onInputKeyDown = (e) => { + const { bDropDownOpen, bNotFirstEnter } = this.state; + if (bDropDownOpen && [38, 40, 13].includes(e.keyCode)) { + // eslint-disable-next-line no-console + } else if (e.keyCode === 13 && !bNotFirstEnter) { + this.setState({ bDropDownOpen: true, bNotFirstEnter: true }); + } else { + this.onKeyDown(e); + } + }; + obj.onKeyUp = this.onKeyUp; + obj.open = this.state.bDropDownOpen !== undefined ? this.state.bDropDownOpen : false; + obj.onMouseMove = () => { + this.bInputIn = true; + }; + obj.onMouseLeave = () => { + this.bInputIn = false; + }; + /* 返回值 */ + return obj; + }; + + getSearchProps = () => { + const obj = { + onKeyDown: this.onKeyDown, + onChange: e => this.handleSelectOptionEvent(e.target.value), /* 数据改变回带到父组件 */ + value: commonUtils.isUndefined(this.state.dataValue) ? '选择' : commonUtils.strUndefinedToEmpty(this.state.dataValue), /* 数据值 */ + }; + return obj; + } + /** 获取optionValue对象 */ + getOptionValues = (data) => { + /* 返回值声明 */ + let res = ''; + /* 计数器 */ + let count = 1; + /* 遍历每一条数据 */ + const iVisCount = commonUtils.isEmpty(this.props.showConfig.iVisCount) || this.props.showConfig.iVisCount === 0 ? 1 : this.props.showConfig.iVisCount; + if (commonUtils.isNotEmptyStr(this.props.showConfig.sVisColumnName)) { + res = data[this.props.showConfig.sVisColumnName]; + } else { + for (const key of Object.keys(data)) { + /* 这里主要是为了实现配置中控制下拉的展现列数 */ + if (count <= iVisCount && key !== 'sId') { + if (res === '') { + res = data[key]; + } else { + res = res.concat('-').concat(data[key]); + } + count += 1; + } + } + } + // 如果res值为''时,下拉会显示value值,为了解决这种情况,返回' ' + if (res === '') { + res = ' '; + } + /* 返回值 */ + return res; + }; + + // 获取上传组件props + getUploadProps = () => { + const { formId, app, enabled } = this.props; + const { token } = app; + return { + listType: 'picture-card', + className: 'avatar-uploader', + action: `${commonConfig.file_host}file/upload?sModelsId=${formId}&token=${token}&sUploadType=model`, + disabled: !enabled || false, + onChange: (info) => { + const { file } = info; + if (file.response && file.response.code === 1) { + const sPicturePath = file.response.dataset.rows[0].savePathStr; + this.props.onChange(this.props.name, this.props.showConfig.sName, { [this.props.showConfig.sName]: sPicturePath }, this.props.sId, []); + } else if (file.response && file.response.code === -1) { + message.error(file.response.msg); + } + }, + accept: 'image/*', + showUploadList: false, + }; + }; + + // 获取上传组件内容 + getUploadContents = () => { + const fileName = commonUtils.isUndefined(this.state.dataValue) ? '' : commonUtils.strUndefinedToEmpty(this.state.dataValue); + const imageUrl = `${commonConfig.file_host}file/download?savePathStr=${fileName}&sModelsId=100&token=${this.props.token}`; + return fileName ? + () : ( +
+
+ 上传 +
+
); + }; + + // 获取上传图片右上角清空按钮属性 + getUploadButtonProps = () => { + const fileName = commonUtils.isUndefined(this.state.dataValue) ? '' : commonUtils.strUndefinedToEmpty(this.state.dataValue); + return { + type: 'link', + style: { + position: 'absolute', + top: 0, + left: 75, + display: this.props.enabled && fileName ? '' : 'none', + }, + onClick: () => { + this.props.onChange(this.props.name, this.props.showConfig.sName, { [this.props.showConfig.sName]: '' }, this.props.sId, []); + }, + }; + }; + + /** 获取innerinput控件1 */ + getInnerInput = (innerInputProps) => { + const { + sTableTitleSql, iVisCount, sName, sDateFormat, + } = this.props.showConfig; + if (commonUtils.isNotEmptyStr(sTableTitleSql) && iVisCount > 1) { + return ; + } + if (sName === 'sIcon') { + return (<>{this.getUploadContents()}); + } + if (this.props.showConfig.sName && this.props.showConfig.sName.toLowerCase().includes('fullmemo')) { + const row = commonUtils.isNotEmptyNumber(this.props.showConfig.iRowValue) ? this.props.showConfig.iRowValue : 1; + const minHeight = (row * 20) + 6 + 4 + 2; + return
; + } + if ((this.props.showConfig.sDropDownType === 'sql' || this.props.showConfig.sDropDownType === 'const') + && (this.firstDataIndex === 'i' || this.firstDataIndex === 'd' || this.firstDataIndex === 's')) { /* 下拉选择框(数字和文本选择框才会下拉) */ + if (this.props.showConfig.bCanInput) { /* 文本输入下拉框 */ + const propsObj = { ...this.getCompleteProps() }; + return {this.getSelectOption('autoComplete')}; + } else { /* 普通下拉框 */ + return ; + } + } else if (this.state.enabled && commonUtils.isNotEmptyObject(this.props.showConfig.sName) && this.props.showConfig.sDropDownType === 'popup') { /* 通用弹窗 */ + return (); + } else if (this.firstDataIndex === 'i' || this.firstDataIndex === 'd') { /* 数字输入框(整形i和浮点型d) */ + return innerInputProps.readOnly ? : + location.pathname.includes('quotationPackTableTree') && this.props.name === 'control' && this.props.showConfig.sName === 'dSinglePQty' ? : ; + } else if (this.firstDataIndex === 'b') { /* 选择框(布尔类型b) */ + return {this.showName}; + // return {this.showName}; + } else if (this.firstDataIndex === 'm' || sDateFormat === 'YYYY-MM' || sDateFormat === 'YYYYMM') { /* 月份选择框(月份类型m) */ + return this.props.bTable ? : ; + } else if (this.firstDataIndex === 't') { /* 时间选择框(时间类型t) */ + if (['tYear'].includes(this.props.showConfig.sName)) { + innerInputProps.picker = 'year'; + innerInputProps.format = 'YYYY'; + innerInputProps.allowClear = false; + } + return this.props.bTable ? : ; + } else if (this.firstDataIndex === 'y') { /* 年份选择框(年份类型y) */ + return this.props.bTable ? : ; + } else if (this.firstDataIndex === 'p') { /* 时间选择框(时间类型t) */ + return ; + } else if (this.firstDataIndex === 's') { /* 文本输入框(文本s) */ + if (this.props.textArea) { /* 大文本输入框 */ + return ; + } else { /* 普通文本输入框 */ + return ; + } + } else if (this.firstDataIndex === 'c') { /* 地址联动框(联动下拉类型c) */ + return ; + } else { /* 文本输入框(默认类型) */ + return ; + } + }; + + // 获取innerinput控件后面的按钮 + getInnerButton = () => { + const props = { + onClick: () => { + const { slaveConfig = { gdsconfigformslave: [] } } = this.props; + const { gdsconfigformslave } = slaveConfig; + const { sName } = this.props.showConfig; + const config = gdsconfigformslave.find(item => item.sControlName === `BtnPopup.${sName}`); + if (config && this.props.onFieldPopupModal) { + this.props.onFieldPopupModal(config, this.props.name, 'CommonListSelect'); + } + }, + }; + return ; + } + + // 获取innerinput控件后面的按钮(自定义) + getInnerButtonCostom = (showConfig) => { + const { name, sysEnabled } = this.props; + const { showName } = showConfig; + let disabled = this.props.showConfig?.buttonbReadonly; + if (!disabled) { + disabled = !sysEnabled; + } + const props = { + type: 'primary', + disabled, + loading: this.state.buttonLoading, + onClick: () => { + if (this.props.onCostomChange) { + this.props.onCostomChange(name, showConfig); + } + }, + }; + return ; + } + + /** 获取selectOption对象 */ + getSelectOption = (type) => { + /* 返回值声明 */ + const options = []; + /* 执行条件 */ + const { searchValue, dropDownData, searchDropDownData } = this.state; + const dropDownDataNew = commonUtils.isEmpty(searchValue) ? dropDownData : searchDropDownData; + if (commonUtils.isNotEmptyArr(dropDownDataNew)) { + /* 遍历下拉数据 */ + for (const each of dropDownDataNew) { + if (commonUtils.isNotEmptyObject(each)) { + /* 拼接optoin对象 */ + let keyValue = !commonUtils.isEmpty(each.sSlaveId) ? each.sSlaveId : each.sId; + if (this.firstDataIndex === 'i') { + keyValue = parseInt(keyValue, 0); + } else if (this.firstDataIndex === 'd') { + keyValue = parseFloat(keyValue); + } + let res = ''; + if (commonUtils.isNotEmptyStr(this.props.showConfig.sVisColumnName)) { + res = each[this.props.showConfig.sVisColumnName]; + } else { + res = Object.keys(each).length > 0 ? each[Object.keys(each)[0]] : ''; + } + keyValue = commonUtils.isEmpty(keyValue) ? '' : keyValue; + if (type === 'autoComplete') { + // 为autoComplete作特殊处理 + const option = this.props.showConfig.bCanInput ? + () : + (); + /* 返回值赋值s */ + options.push(option); + } else { + const option = this.props.showConfig.bCanInput ? + () : + (); + /* 返回值赋值 */ + options.push(option); + } + } + } + } + if (this.state.searchValue === '') { + /* 下拉空处理 */ + if (this.props.showConfig.bFirstEmpty) { + // 重构修改 options.unshift(); + if (type === 'autoComplete') { + options.unshift(); + } else { + options.unshift(); + } + } + } + /* 返回值 */ + return options; + }; + + /* 获取sqlCondition对象 */ + getFloatPrice = (floatNum) => { + /* 返回值声明 */ + let floatPrice = ''; + /* 返回值赋值 */ + if (!commonUtils.isUndefined(floatNum)) { + for (let i = 0; i < floatNum; i += 1) { + floatPrice += '\\d'; + } + } + /* 返回值 */ + return floatPrice; + }; + + /** 获取下拉值 */ + getDropDownData = async (pageNum, totalPageCount, searchValue, dropDownCount) => { + if (this.chineseInputting) { + return; + } + /** 下拉类型区分 + 1、判断是否直接传下拉,如果传了就直接用,并存储到store中去 + 2、没有传看 getStoreDropDownData有没有存储,存储后直接取用 + 3、 没有存储时直接调用后台SQL语句去下拉 */ + if (this.props.showConfig.sDropDownType === 'sql') { /* 数据下拉 */ + const { dropDownData: dropDownDataOld, searchDropDownData: searchDropDownDataOld } = this.state; + if (pageNum <= totalPageCount) { + const sqlDropDownData = await this.props.getSqlDropDownData(this.props.formId, this.props.name, this.props.showConfig, this.props.record, searchValue, pageNum); + if (dropDownCount !== undefined && dropDownCount < this.dropDownCount) { + return; + } + if (this.mounted) { + if (searchValue !== '') { + const dropDownData = []; + if (commonUtils.isNotEmptyArr(sqlDropDownData.dropDownData)) { + if (pageNum !== 1) { + dropDownData.push(...searchDropDownDataOld); + } + dropDownData.push(...sqlDropDownData.dropDownData); + } + this.setState({ + searchDropDownData: dropDownData, + conditonValues: sqlDropDownData.conditonValues, + searchTotalPageCount: sqlDropDownData.totalPageCount, + searchPageNum: sqlDropDownData.currentPageNo, + spinState: false, + searchValue, + totalCount: sqlDropDownData.totalCount, + selectTableData: sqlDropDownData.dropDownData, + }); + } else { + const dropDownData = []; + if (commonUtils.isNotEmptyArr(sqlDropDownData.dropDownData)) { + if (pageNum !== 1) { + dropDownData.push(...dropDownDataOld); + } + dropDownData.push(...sqlDropDownData.dropDownData); + } + this.setState({ + dropDownData, + conditonValues: sqlDropDownData.conditonValues, + totalPageCount: sqlDropDownData.totalPageCount, + pageNum: sqlDropDownData.currentPageNo, + spinState: false, + searchValue: '', + totalCount: sqlDropDownData.totalCount, + selectTableData: sqlDropDownData.dropDownData, + }); + } + } + } + } + }; + + /** 获取innerinput控件参数 */ + getInnerInputProps = () => { + /* 主表和从表的innerinputprops对象有区别 */ + if (!this.props.bTable) { /* 主表 */ + return this.getInnerInputPropsMaster(); + } else { /* 主从表 */ + return this.getInnerInputPropsSlave(); + } + }; + + /** 获取innerinput控件参数(从) */ + getInnerInputPropsSlave = () => { + /* 返回值声明 */ + let obj = {}; + if (this.firstDataIndex === 'i' || this.firstDataIndex === 'd') { /* 数字输入框(整形i和浮点型d) */ + obj = this.getNumberInnerInputPropsSlave(); + } else if (this.firstDataIndex === 'b') { /* 选择框(布尔类型b) */ + obj = this.getBooleanInnerInputPropsSlave(); + } else if (this.firstDataIndex === 't' || this.firstDataIndex === 'p' || this.firstDataIndex === 'm' || this.firstDataIndex === 'y') { /* 时间选择框(时间类型t) */ + obj = this.getDateInnerInputPropsSlave(); + } else if (this.firstDataIndex === 's') { /* 文本输入框(文本s) */ + obj = this.getTextInnerInputPropsSlave(); + obj.onDoubleClick = this.onDoubleClick; + } else if (this.firstDataIndex === 'c') { /* 地址联动框(联动下拉类型c) */ + obj = this.getAddressInnerInputPropsSlave(); + } + obj.onKeyDown = this.onKeyDown; + obj.onFocus = this.onFocus; + obj.onBlur = this.onBlur; + obj.onMouseEnter = this.onFocus; + obj.id = `${this.props.showConfig.sName}${this.props.record ? this.props.record.sId : commonUtils.createSid()}`; /* 所有从表组件添加id */ + obj.placeholder = this.props.showConfig.placeholder || ''; + /* 返回值 */ + return obj; + }; + + /* 获取地址innerinputprops对象(从) */ + getAddressInnerInputPropsSlave = () => { + /* 返回值 */ + const obj = { + // disabled: !this.state.enabled, /* 是否可编辑 */ + placeholder: '请选择省市区', /* 预期值的提示信息 */ + options: this.getProvinceCityAreaData(), /* 数据 */ + changeOnSelect: true, /* 对每个选择值进行更改 */ + onChange: this.handleSelectOptionEvent, /* 数据改变回带到父组件 */ + value: commonUtils.isUndefined(this.state.dataValue) ? [] : typeof this.state.dataValue === 'string' ? + this.state.dataValue.split(',') : commonUtils.convertUndefinedToEmptyArr(this.state.dataValue), /* 数据值 */ + }; + if (this.props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !this.state.enabled; + } + /* 返回值 */ + return obj; + }; + + /* 获取文本innerinputprops对象(从) */ + getTextInnerInputPropsSlave = () => { + /* 返回值声明 */ + const bShowSuffix = this.props.showConfig.sName === 'sSaveProName' || this.props.showConfig.sName === 'sDeleteProName' || this.props.showConfig.sName === 'sSaveProNameBefore' || this.props.showConfig.sName === 'sProcName' || this.props.showConfig.sName === 'sButtonParam'; /* 是否展示后缀图标 */ + const bShowArrow = this.props.showConfig.sName === 'dNeedAuxiliaryQty'; + const obj = { + // disabled: !this.state.enabled, /* 是否可编辑 */ + id: `${this.props.showConfig.sName}${commonUtils.createSid()}`, /* 虚拟数字键盘使用id获取光标 */ + onChange: e => this.handleSelectOptionEvent(e), /* 数据改变回带到父组件 */ + value: commonUtils.isUndefined(this.state.dataValue) ? '' : commonUtils.strUndefinedToEmpty(this.state.dataValue), /* 数据值 */ + // eslint-disable-next-line no-return-assign + ref: ref => this[this.props.showConfig.sName] = ref, /* 虚拟数字键盘获得光标需用 */ + onClick: this.handleInputOnClick.bind(this, this.props.showConfig.sName), /* 虚拟数字键盘 第二个参数必须id */ + suffix: bShowSuffix ? : + (bShowArrow ? : ''), + rows: commonUtils.isNotEmptyNumber(this.props.showConfig.iRowValue) ? this.props.showConfig.iRowValue : 1, + }; + if (this.props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !this.state.enabled; + } + /* 最大值最小值 */ + if (typeof commonUtils.convertStrToNumber(this.max) === 'number' && commonUtils.convertStrToNumber(this.max) !== 0 && this.max.indexOf('.d') === -1 && this.max.indexOf('.i') === -1) { + obj.maxLength = this.max; /* 最大长度 */ + obj.title = obj.value; + } + obj.placeholder = this.props.showConfig.placeholder; + obj.autocomplete = 'new-password'; + /* 返回值 */ + return obj; + }; + + /* 获取日期innerinputprops对象(从) */ + getDateInnerInputPropsSlave = () => { + let { sDateFormat } = this.props.showConfig; + if (commonUtils.isEmptyStr(sDateFormat)) { + if (this.firstDataIndex === 'm') { + sDateFormat = 'YYYY-MM'; + } else if (this.firstDataIndex === 'y') { + sDateFormat = 'YYYY'; + } else { + sDateFormat = this.props.getDateFormat(); + } + } + let showtimeFormat = false; + // if (sDateFormat === 'YYYY-MM-DD HH:mm:ss') { + if (sDateFormat.length > 11) { + showtimeFormat = true; + } else { + showtimeFormat = false; + } + /* 返回值声明 */ + const obj = { + placeholder: '', /* 时间的提示信息 */ + disabled: !this.state.enabled, /* 是否可编辑 */ + onChange: this.handleSelectOptionEvent, /* 数据改变回带到父组件 */ + format: sDateFormat, // this.props.getDateFormat(), /* 格式化规则 */ + disabledDate: this.getDataMaxAndMin, /* 不可选日期 */ + showTime: showtimeFormat, + style: { width: '100%' }, /* 样式 */ + onBlur: () => { + this.onExecInstructSet('blur'); + }, + }; + // if (this.props.readOnly) { + // obj.readOnly = 'readOnly'; + // } else { + // obj.disabled = !this.state.enabled; + // } + if (!this.state.enabled) { + obj.suffixIcon = ; + } + /* 值填充 */ + obj.value = commonUtils.isEmpty(this.state.dataValue) ? null : moment(this.state.dataValue); + /* 返回值 */ + return obj; + }; + + /* 获取布尔innerinputprops对象(从) */ + getBooleanInnerInputPropsSlave = () => { + /* 返回值声明 */ + const obj = { + disabled: !this.state.enabled, /* 是否可编辑 */ + onChange: this.handleSelectOptionEvent, /* 数据改变回带到父组件 */ + checked: commonUtils.isUndefined(this.state.dataValue) ? false : commonUtils.converNumStrToBoolean(this.state.dataValue), /* 是否选中 */ + }; + // if (this.props.readOnly) { + // obj.readOnly = true; + // } else { + // obj.disabled = !this.state.enabled; + // } + /* 返回值 */ + return obj; + }; + + /* 获取数字innerinputprops对象(从) */ + getNumberInnerInputPropsSlave = () => { + const bShowArrow = this.props.showConfig.sName === 'dNeedAuxiliaryQty' && this.props.showConfig.sControlName !== 'slaveInfo'; + /* 返回值声明 */ + const obj = { + id: `${this.props.showConfig.sName}${this.props.showConfig.sId}`, /* 虚拟数字键盘使用id获取光标 */ + className: styles.inputNum, /* 样式名称 */ + // disabled: !this.state.enabled, /* 是否可编辑 */ + onChange: this.handleSelectOptionEvent, /* 数据改变回带到父组件 */ + parser: (oldValue) => { + const value = this.handleCheckNumberInnerInput(oldValue); + return value; + }, + // eslint-disable-next-line no-return-assign + ref: ref => this[this.props.showConfig.sName] = ref, /* 虚拟数字键盘获得光标需用 */ + onClick: this.handleInputOnClick.bind(this, this.props.showConfig.sName), /* 虚拟数字键盘 第二个参数必须id */ + }; + if (bShowArrow) { + obj.addonAfter = ; + } + if (this.props.readOnly) { + obj.readOnly = true; + } else { + obj.disabled = !this.state.enabled; + } + /* 最大值最小值 */ + if (typeof commonUtils.convertStrToNumber(this.max) === 'number' && commonUtils.convertStrToNumber(this.max) !== 0 && this.max.indexOf('.d') === -1 && this.max.indexOf('.i') === -1) { + obj.max = this.max; /* 最大值 */ + } else if (!commonUtils.isEmpty(this.max) && this.max.indexOf('.') > -1 && commonUtils.isNotEmptyObject(this.props.record)) { + obj.max = this.props.record[this.max.substring(this.max.indexOf('.') + 1)]; + } + if (typeof commonUtils.convertStrToNumber(this.min) === 'number' && commonUtils.convertStrToNumber(this.min) !== 0) { + obj.min = this.min; /* 最小值 */ + } + if (obj.max < 0) { /* 为解决收付款单据未收款为负数时收款金额不能大于未收款问题,当最大值小于0时,变更为设为最小值 */ + obj.min = obj.max; + obj.max = 0; + } + /* 浮点型需要格式化 */ + if (this.firstDataIndex === 'd') { + // obj.formatter = value => this.toFamatter(value); + // obj.parser = value => this.toFamatter(value); + // obj.precision = this.floatNum; + // obj.formatter = value => this.limitDecimals(value); + // obj.parser = value => this.limitDecimals(value); + } + + /* 值填充 */ + const { dNetPrice } = this.props.app.decimals; + const { showConfig } = this.props; + const { sName, showName } = showConfig; + const digit = sName.includes('Price') ? dNetPrice : 6; + const numCheck = new RegExp(`^(-?\\d+)(\\.?)(\\d{1,${digit}})?$`); + const numValue = this.state.dataValue; + if (!isNaN(+numValue)) { + if (!numCheck.test(numValue) && numValue) { + message.warning(`【${showName}】【${sName}】最多${digit}位小数`); + } + } + obj.value = this.state.dataValue; + obj.step = 0; + /* 返回值 */ + return obj; + }; + + /** 获取innerinput控件参数(主) */ + getInnerInputPropsMaster = () => { + /* 返回值声明 */ + let obj = {}; + if (this.firstDataIndex === 'i' || this.firstDataIndex === 'd') { /* 数字输入框(整形i和浮点型d) */ + obj = this.getNumberInnerInputPropsMaster(); + } else if (this.firstDataIndex === 'b') { /* 选择框(布尔类型b) */ + obj = this.getBooleanInnerInputPropsMaster(); + } else if (this.firstDataIndex === 't' || this.firstDataIndex === 'p' || this.firstDataIndex === 'm' || this.firstDataIndex === 'y') { /* 时间选择框(时间类型t) */ + obj = this.getDateInnerInputPropsMaster(); + } else if (this.firstDataIndex === 's') { /* 文本输入框(文本s) */ + if (this.props.textArea) { /* 大文本输入框 */ + obj = this.getTextAreaInnerInputPropsMaster(); + obj.onDoubleClick = this.onDoubleClick; + } else { /* 普通文本输入框 */ + obj = this.getTextInnerInputPropsMaster(); + } + } else if (this.firstDataIndex === 'c') { /* 地址联动框(联动下拉类型c) */ + obj = this.getAddressInnerInputPropsMaster(); + } + obj.onKeyDown = this.onKeyDown; + obj.onKeyUp = this.onKeyUp; + if (this.props.allowClear) { + obj.allowClear = this.props.allowClear; /* 带移除图标 */ + } + obj.placeholder = this.props.showConfig.placeholder || ''; + // obj.onContextMenu = this.onContextMenu; + /* 返回值 */ + return obj; + }; + + /* 获取地址innerinputprops对象(主) */ + getAddressInnerInputPropsMaster = () => { + const obj = { + // disabled: !this.state.enabled, /* 是否可编辑 */ + placeholder: '请选择省市区', /* 预期值的提示信息 */ + options: this.getProvinceCityAreaData(), /* 数据 */ + changeOnSelect: true, /* 对每个选择值进行更改 */ + onChange: this.handleSelectOptionEvent, /* 数据改变回带到父组件 */ + }; + if (this.props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !this.state.enabled; + } + return obj; + }; + + /* 获取文本innerinputprops对象(主) */ + getTextInnerInputPropsMaster = () => { + /* 返回值声明 */ + const bShowSuffix = this.props.showConfig.sName === 'sButtonParam' || this.props.showConfig.sName === 'sSqlStr' || this.props.showConfig.sName === 'sConfigSqlStr' || this.props.showConfig.sName === 'sProcName'; /* 是否展示后缀图标 */ + const obj = { + id: `${this.props.showConfig.sName}${commonUtils.createSid()}`, /* 虚拟数字键盘使用id获取光标 */ + // disabled: !this.state.enabled, /* 是否可编辑 */ + onChange: e => this.handleSelectOptionEvent(e), /* 数据改变回带到父组件 */ + // eslint-disable-next-line no-return-assign + ref: ref => this[this.props.showConfig.sName] = ref, /* 虚拟数字键盘获得光标需用 */ + onClick: this.handleInputOnClick.bind(this, this.props.showConfig.sName), /* 虚拟数字键盘 第二个参数必须id */ + suffix: bShowSuffix ? : '', + }; + if (this.props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !this.state.enabled; + } + if (this.props.bPassWord) { + obj.type = 'password'; /* 文本密码类型 */ + } + /* 最大值最小值 */ + // if (this.props.showConfig.sName === 'sZmmGgxh') { + // console.log('sZmmGgxhsZmmGgxh', this.max, (typeof commonUtils.convertStrToNumber(this.max) === 'number' && commonUtils.convertStrToNumber(this.max) !== 0 && this.max.indexOf('.d') === -1 && this.max.indexOf('.i') === -1)); + // } + if (typeof commonUtils.convertStrToNumber(this.max) === 'number' && commonUtils.convertStrToNumber(this.max) !== 0 && this.max.indexOf('.d') === -1 && this.max.indexOf('.i') === -1) { + obj.maxLength = this.max; /* 最大长度 */ + } + obj.onBlur = this.onBlurText; + obj.autocomplete = 'new-password'; + /* 返回值 */ + return obj; + }; + + /* 获取大文本innerinputprops对象(主) */ + getTextAreaInnerInputPropsMaster = () => { + /* 返回值声明 */ + const obj = { + id: `${this.props.showConfig.sName}${commonUtils.createSid()}`, /* 虚拟数字键盘使用id获取光标 */ + // disabled: !this.state.enabled, /* 是否可编辑 */ + // rows: 3, /* 纵跨度 */ + rows: commonUtils.isNotEmptyNumber(this.props.showConfig.iRowValue) ? this.props.showConfig.iRowValue : 1, /* 产品部要求 备注设置成一行到底 */ + onChange: this.handleSelectOptionEvent, /* 数据改变回带到父组件 */ + // eslint-disable-next-line no-return-assign + ref: ref => this[this.props.showConfig.sName] = ref, /* 虚拟数字键盘获得光标需用 */ + onClick: this.handleInputOnClick.bind(this, this.props.showConfig.sName), /* 虚拟数字键盘 第二个参数必须id */ + }; + if (this.props.readOnly) { + obj.readOnly = 'readOnly'; + } if (commonUtils.isNotEmptyObject(this.props.showConfig.sName) && this.props.showConfig.sName.toLowerCase().endsWith('memo')) { + if (!this.state.enabled) { /* 非编辑模式下 */ + obj.readOnly = true; + obj.style = { backgroundColor: '#f1f2f8' }; + } else { + obj.disabled = !this.state.enabled; + } + } else { + obj.disabled = !this.state.enabled; + } + /* 最大值最小值 */ + if (typeof commonUtils.convertStrToNumber(this.max) === 'number' && commonUtils.convertStrToNumber(this.max) !== 0 && this.max.indexOf('.d') === -1 && this.max.indexOf('.i') === -1) { + obj.maxLength = this.max; /* 最大长度 */ + } + return obj; + }; + + /* 获取日期最大值和最小值 */ + getDataMaxAndMin = (current) => { + return this.getDataMax(current) || this.getDataMin(current); + } + + /* 获取日期最大值 */ + getDataMax = (current) => { + const showtimeFormat = this.props.showConfig.sDateFormat?.length > 11; + if (commonUtils.isNotEmptyStr(this.props.showConfig.sMaxValue) && this.props.showConfig.sMaxValue.split('.').length > 1) { + const conditionValues = this.props.getSqlCondition({ sSqlCondition: this.props.showConfig.sMaxValue }, '', {}); + const sMaxValue = Object.keys(conditionValues).length > 0 ? conditionValues[Object.keys(conditionValues)[0]] : this.props.showConfig.sMaxValue; + const tDate = this.props.showConfig.sMaxValue === 'now' ? moment() : moment(sMaxValue); + return showtimeFormat ? commonUtils.isNotEmptyStr(this.props.showConfig.sMaxValue) && current > tDate : + commonUtils.isNotEmptyStr(this.props.showConfig.sMaxValue) && current.endOf('day') > tDate.endOf('day'); + } else { + const tDate = this.props.showConfig.sMaxValue === 'now' ? moment() : moment(this.props.showConfig.sMaxValue); + return showtimeFormat ? commonUtils.isNotEmptyStr(this.props.showConfig.sMaxValue) && current > tDate : + commonUtils.isNotEmptyStr(this.props.showConfig.sMaxValue) && current.endOf('day') > tDate.endOf('day'); + } + } + + /* 获取日期最小值 */ + getDataMin = (current) => { + const showtimeFormat = this.props.showConfig.sDateFormat?.length > 11; + if (commonUtils.isNotEmptyStr(this.props.showConfig.sMinValue) && this.props.showConfig.sMinValue.split('.').length > 1) { + const conditionValues = this.props.getSqlCondition({ sSqlCondition: this.props.showConfig.sMinValue }, '', {}); + const sMinValue = Object.keys(conditionValues).length > 0 ? conditionValues[Object.keys(conditionValues)[0]] : this.props.showConfig.sMinValue; + const tDate = this.props.showConfig.sMinValue === 'now' ? moment() : moment(sMinValue); + return showtimeFormat ? commonUtils.isNotEmptyStr(this.props.showConfig.sMinValue) && current < tDate : + commonUtils.isNotEmptyStr(this.props.showConfig.sMinValue) && current.endOf('day') < tDate.endOf('day'); + } else { + const tDate = this.props.showConfig.sMinValue === 'now' ? moment() : moment(this.props.showConfig.sMinValue); + return showtimeFormat ? commonUtils.isNotEmptyStr(this.props.showConfig.sMinValue) && current < tDate : + commonUtils.isNotEmptyStr(this.props.showConfig.sMinValue) && current.endOf('day') < tDate.endOf('day'); + } + } + + /* 获取时间innerinputprops对象(主) */ + getDateInnerInputPropsMaster = () => { + let { sDateFormat } = this.props.showConfig; + if (commonUtils.isEmptyStr(sDateFormat)) { + if (this.firstDataIndex === 'm') { + sDateFormat = 'YYYY-MM'; + } else if (this.firstDataIndex === 'y') { + sDateFormat = 'YYYY'; + } else { + sDateFormat = this.props.getDateFormat(); + } + } + let showtimeFormat = false; + // if (sDateFormat === 'YYYY-MM-DD HH:mm:ss') { + if (sDateFormat.length > 11) { + showtimeFormat = true; + } else { + showtimeFormat = false; + } + // 2021-6-5日修改,生产排程日期选择精确到小时 + const obj = { + placeholder: '', /* 时间的提示信息 */ + disabled: !this.state.enabled, /* 是否可编辑 */ + style: { width: '100%' }, /* 样式 */ + // showTime: this.props.showTime ? { format: 'HH:mm', defaultValue: [moment('00:00', 'HH:mm'), moment('00:00', 'HH:mm')] } : '', + // showTime: this.props.showTime, + showTime: showtimeFormat, + format: this.props.showTime ? 'YYYY-MM-DD HH:mm:ss' : sDateFormat, // this.props.getDateFormat(), /* 格式化规则 */ + onChange: this.handleSelectOptionEvent, /* 数据改变回带到父组件 */ + disabledDate: this.getDataMaxAndMin, /* 不可选日期 */ + onBlur: () => { + this.onExecInstructSet('blur'); + }, + }; + // if (this.props.readOnly) { + // obj.readOnly = 'readOnly'; + // } else { + // obj.disabled = !this.state.enabled; + // } + return obj; + }; + + /* 获取布尔innerinputprops对象(主) */ + getBooleanInnerInputPropsMaster = () => { + const obj = { + disabled: !this.state.enabled, /* 是否显示 */ + onChange: this.handleSelectOptionEvent, /* 数据改变回带到父组件 */ + checked: commonUtils.isUndefined(this.state.dataValue) ? false : commonUtils.converNumStrToBoolean(this.state.dataValue), /* 是否选中 */ + }; + // if (this.props.readOnly) { + // obj.readOnly = true; + // } else { + // obj.disabled = !this.state.enabled; + // } + return obj; + }; + // eslint-disable-next-line react/sort-comp + handleInputOnClick = (id) => { + // 判断是否是oee系统,否则不显示虚拟键盘 + if (commonUtils.isNotEmptyObject(location.pathname) && location.pathname.indexOf('/indexOee') > -1) { + if (VirtualKeyboard.isKeyBoard()) { // 关闭上次键盘 + VirtualKeyboard.closeKeyboard(); + } + const keyboardValue = {}; + if (commonUtils.isNotEmptyObject(this.props.dataValue)) { + keyboardValue.value = this.props.dataValue; + } else { + keyboardValue.value = ''; + } + VirtualKeyboard.showKeyboardSetState(keyboardValue, this, id); + } + if (this.props.onInputClick) { + // eslint-disable-next-line prefer-destructuring + const sName = this.props.showConfig.sName; + const rowId = this.props.record.sId; + this.props.onInputClick(rowId, sName); + } + } + + /* 获取数字innerinputprops对象(主) */ + getNumberInnerInputPropsMaster = () => { + /* 如果是浮点型并且有格式规定,display类型需要变为block */ + let display = 'inline-block'; + if (this.firstDataIndex === 'd' && this.floatNum !== 0) { + display = 'block'; + } + // const sInputId = `id${commonUtils.createSid()}`; + /* 返回值赋值 */ + const obj = { + id: `${this.props.showConfig.sName}${commonUtils.createSid()}`, /* 虚拟数字键盘使用id获取光标 */ + style: { width: 'auto', display, marginRight: 0 }, /* 样式 */ + // disabled: !this.state.enabled, /* 是否显示 */ + onChange: this.handleSelectOptionEvent, /* 数据改变回带到父组件 */ + parser: (oldValue) => { + const value = this.handleCheckNumberInnerInput(oldValue); + return value; + }, + // eslint-disable-next-line no-return-assign + ref: ref => this[this.props.showConfig.sName] = ref, /* 虚拟数字键盘获得光标需用 这里得ref中得变量必须是input得id */ + onClick: this.handleInputOnClick.bind(this, this.props.showConfig.sName), /* 虚拟数字键盘 第二个参数必须id */ + }; + if (this.props.readOnly) { + obj.readOnly = true; + } else { + obj.disabled = !this.state.enabled; + } + /* 最大值最小值 */ + if (typeof commonUtils.convertStrToNumber(this.max) === 'number' && commonUtils.convertStrToNumber(this.max) !== 0 && this.max.indexOf('.d') === -1 && this.max.indexOf('.i') === -1) { + obj.max = this.max; /* 最大值 */ + } else if (!commonUtils.isEmpty(this.max) && this.max.indexOf('.') > -1 && commonUtils.isNotEmptyObject(this.props.record)) { + obj.max = this.props.record[this.max.substring(this.max.indexOf('.') + 1)]; + } + if (typeof commonUtils.convertStrToNumber(this.min) === 'number' && commonUtils.convertStrToNumber(this.min) !== 0) { + obj.min = this.min; /* 最小值 */ + } + obj.placeholder = this.props.showConfig.placeholder; + /* 格式规格不为0就在props里设置一下 */ + // if (this.firstDataIndex === 'd' && this.floatNum !== 0) { + // obj.precision = this.floatNum; + // } + /* 返回值 */ + return obj; + }; + + /* 获取省市区数据 */ + getProvinceCityAreaData = () => { + /* 返回值声明 */ + const options = []; + /* 获取省数据 */ + this.getProvinceData(options); + /* 获取市数据 */ + this.getCityData(options); + /* 获取区数据 */ + this.getAreaData(options); + /* 返回值 */ + return options; + }; + + /* 获取省数据 */ + getProvinceData = (options) => { + Provinces.forEach((childProvince) => { + options.push({ + value: childProvince.name, /* 文字 */ + label: childProvince.name, /* 标签 */ + code: childProvince.code, /* 编码 */ + children: [], /* 子节点(city) */ + }); + }); + }; + + /* 获取市数据 */ + getCityData = (options) => { + options.forEach((childProvince) => { + const cities = Cities.filter(item => item.provinceCode === childProvince.code); + if (cities.length > 0) { + cities.forEach((childCity) => { + childProvince.children.push({ + value: childCity.name, /* 文字 */ + label: childCity.name, /* 标签 */ + code: childCity.code, /* 编码 */ + children: [], /* 子节点(area) */ + }); + }); + } + }); + }; + + /* 获取区数据 */ + getAreaData = (options) => { + options.forEach((childProvince) => { + const cities = childProvince.children; + cities.forEach((childCity) => { + const areas = Areas.filter((item => item.cityCode === childCity.code)); + if (areas.length > 0) { + areas.forEach((area) => { + childCity.children.push({ + value: area.name, /* 文字 */ + label: area.name, /* 标签 */ + code: area.code, /* 编码 */ + }); + }); + } + }); + }); + }; + + /* 获取formitemprops对象 */ + getOutFormItemProps = () => { + /* 主表和从表的formitemprops对象有区别 */ + if (!this.props.bTable) { /* 主表 */ + return this.getOutFormItemPropsMaster(); + } else if (this.props.bViewTable) { /* 表格单行显示 */ + return this.getOutFormItemPropsViewSlave(); + } else { /* 从表 */ + return this.getOutFormItemPropsSlave(); + } + }; + + /* 获取formitemprops对象(主) */ + getOutFormItemPropsMaster = () => { + /* 返回值声明 */ + let obj = {}; + if (this.firstDataIndex === 'i' + || this.firstDataIndex === 'd' + || this.firstDataIndex === 'p' + || this.firstDataIndex === 't' + || this.firstDataIndex === 'm' + || this.firstDataIndex === 's' + || this.firstDataIndex === 'c') { /* 数字输入框(整形i和浮点型d), + 时间选择框(时间类型t), + 文本输入框(文本s), + 地址联动框(联动下拉类型c) */ + obj = { + label: this.props.showConfig.showName, /* 标签 */ + className: styles.formItemMargin, /* 样式名称 */ + ...this.formItemLayout, /* 主要是rowspan和colspan */ + }; + } else if (this.firstDataIndex === 'b') { /* 选择框(布尔类型b) */ + obj = { + label: this.props.showConfig.showName, /* 标签 */ + className: styles.formItemMag10, /* 样式名称 */ + ...this.formItemLayout, /* 主要是rowspan和colspan */ + }; + } + if (this.props.itemLabel === 'hide') { + delete obj.label; + } + /* 设置标题颜色 */ + if (this.props.showConfig.sFontColor) { + // eslint-disable-next-line prefer-destructuring + const sFontColor = this.props.showConfig.sFontColor; + obj.labelCol.style = { color: sFontColor, fontWeight: 'bold', backgroundColor: '#BFEFFF' }; + } + /* 返回值 */ + return obj; + }; + + /* 获取formitemprops对象(单条从表数据) */ + getOutFormItemPropsViewSlave = () => { + /* 返回值声明 */ + let obj = {}; + if (this.firstDataIndex === 'i' + || this.firstDataIndex === 'd' + || this.firstDataIndex === 'p' + || this.firstDataIndex === 't' + || this.firstDataIndex === 'm' + || this.firstDataIndex === 's' + || this.firstDataIndex === 'c') { /* 数字输入框(整形i和浮点型d), + 时间选择框(时间类型t), + 文本输入框(文本s), + 地址联动框(联动下拉类型c) */ + obj = { + label: this.props.showConfig.showName, /* 标签 */ + className: styles.formItemMargin, /* 样式名称 */ + ...this.formItemLayout, /* 主要是rowspan和colspan */ + }; + } else if (this.firstDataIndex === 'b') { /* 选择框(布尔类型b) */ + obj = { + label: this.props.showConfig.showName, /* 标签 */ + className: styles.formItemMag10, /* 样式名称 */ + ...this.formItemLayout, /* 主要是rowspan和colspan */ + }; + } + if (this.props.itemLabel === 'hide') { + delete obj.label; + } + /* 设置标题颜色 */ + if (this.props.showConfig.sFontColor) { + // eslint-disable-next-line prefer-destructuring + const sFontColor = this.props.showConfig.sFontColor; + obj.labelCol.style = { color: sFontColor, fontWeight: 'bold', backgroundColor: '#BFEFFF' }; + } + /* 返回值 */ + return obj; + }; + + + /* 获取formitemprops对象(从) */ + getOutFormItemPropsSlave = () => { + /* 返回值声明 */ + let obj = {}; + if (this.firstDataIndex === 'i' + || this.firstDataIndex === 'd' + || this.firstDataIndex === 'c' + || this.props.showConfig.sDropDownType === 'sql' + || this.props.showConfig.sDropDownType === 'const') { /* 数字输入框(整形i和浮点型d), + 时间选择框(时间类型t), + 文本输入框(文本s), + 地址联动框(联动下拉类型c), + 所有的下拉(从表只有文字下拉,分常量和sql两种) */ + obj = { + className: styles.formItemMargin0, /* 样式名称 */ + }; + } else if (this.firstDataIndex === 'b') { /* 选择框(布尔类型b) */ + obj = { + className: styles.tableCheckBox, /* 样式名称 */ + }; + } else if (this.firstDataIndex === 't' || this.firstDataIndex === 'p' || this.firstDataIndex === 'm' || this.firstDataIndex === 'y') { /* 时间选择框(时间类型t) */ + obj = { + className: styles.tableDataPicker, /* 样式名称 */ + }; + } else if (this.firstDataIndex === 's') { /* 文本输入框(文本s) */ + obj = { + className: styles.editInput, /* 样式名称 */ + }; + } + /* 返回值 */ + return obj; + }; + + /* 获取fielddecoratorprops对象 */ + getFieldDecoratorProps = () => { + /* 返回值声明 */ + let obj = {}; + if (this.firstDataIndex === 'i' || this.firstDataIndex === 'd' || this.firstDataIndex === 't' || this.firstDataIndex === 'p' || this.firstDataIndex === 's' || this.firstDataIndex === 'b') { /* 数字输入框(整形i和浮点型d),时间选择框(时间类型t),文本输入框(文本s),选择框(布尔类型b) */ + obj = { rules: [{ required: this.props.showConfig.bNotEmpty, message: `${this.props.showConfig.showName}为必填项` }] }; + } else if (this.firstDataIndex === 'c') { /* 地址联动框(联动下拉类型c) */ + obj = { + initialValue: ['北京市', '市辖区', '东城区'], /* 默认值 */ + rules: [{ required: this.props.showConfig.bNotEmpty, message: `${this.props.showConfig.showName}为必填项` }], /* 规则 */ + }; + } + /* 返回值 */ + return obj; + }; + getPopupContainer = (triggerNode) => { + const trigger = triggerNode; + if (commonUtils.isNotEmptyObject(trigger)) { + return triggerNode; + } + } + + handleSelectClick = () => { + if (this.bInputIn) { + this.setState({ bDropDownOpen: true }); + } + } + + // 限制数字位数 + handleCheckNumberInnerInput = (value) => { + const { sDateFormat: sDateFormatOld, sFieldValidation: sFieldValidationOld, sName } = this.props.showConfig; + const { record = {}, app = {} } = this.props; + const { auxiliaryQty = {} } = app; + + let sDateFormat = sDateFormatOld; + let sFieldValidation = sFieldValidationOld; + if (sName === 'dAuxiliaryQty' && commonUtils.isNotEmptyObject(record.sAuxiliaryUnit)) { + const decimal = auxiliaryQty[record.sAuxiliaryUnit]; + if (decimal !== undefined) { + sDateFormat = 'decimalPoint'; + sFieldValidation = `,${decimal}`; + } + } + + if (sDateFormat !== 'decimalPoint' || sFieldValidation === undefined || value === null || (typeof value === 'string' && !value)) { + return value; + } + + const [length1, length2] = sFieldValidation.split(','); + + let newValue = value; + if (length2 !== undefined) { + newValue = commonUtils.convertFixNum(value, Number(length2)); + } + if (isNaN(newValue) || Object.is(newValue, -0)) { + return value; + } + if (length1 !== undefined && length1 !== '') { + const str = newValue.toString(); + const [integerPart, decimalPart] = str.split('.'); + if (integerPart.length > length1) { + const truncatedInteger = integerPart.slice(0, length1); + if (decimalPart !== undefined) { + newValue = Number(`${truncatedInteger}.${decimalPart}`); + } else { + newValue = Number(truncatedInteger); + } + } + } + + return newValue; + } + + selectTableChange = (pageNum) => { + if (this.selectTableRef) { + this.selectTableRef.focus(); + } + if (this.state.searchValue) { + this.setState({ tempCurrentPage: pageNum, selectTableIndex: 0 }); + } else { + this.setState({ currentPage: pageNum, selectTableIndex: 0 }); + } + this.selectTableRef1.querySelector('.ant-table-body').scrollTop = 0; + this.getDropDownData(pageNum, this.state.totalPageCount, this.state.searchValue); + }; + + selectTableSearch = (searchValue) => { + if (this.dropDownTimer) { + clearTimeout(this.dropDownTimer); + } + this.dropDownTimer = setTimeout(() => { + this.setState({ + searchValue, + tempCurrentPage: searchValue ? 1 : undefined, + }); + const pageNum = searchValue ? 1 : this.state.currentPage; + this.dropDownCount += 1; + this.getDropDownData(pageNum, this.state.totalPageCount, searchValue, this.dropDownCount); + }, 500); + }; + + toFamatter = (values) => { + if (values !== 0 && commonUtils.isNotEmptyNumber(values) && values !== null) { + const { sDateFormat } = this.props.showConfig; + const { dNetMoney, dNetPrice } = this.props.app.decimals; + /* 如果配置时间格式中设置了0.0000则以配置为准,没有设置时间格式 则以系统设定为主 */ + if (commonUtils.isNotEmptyObject(sDateFormat)) { + /* 取小数点位数 */ + let point = 0; + const strIndex = sDateFormat.indexOf('.'); + if (strIndex > -1 && sDateFormat.length > 1) { + point = sDateFormat.substring(strIndex + 1, sDateFormat.length).length; + if (commonUtils.isNotEmptyNumber(values) && values !== null) { + const dConfigResult = commonUtils.convertFixNum(Number(values), point).toFixed(point); + if (!isNaN(dConfigResult)) { + values = dConfigResult; + } + } + } + } else if (this.props.showConfig.sName.toLowerCase().endsWith('price')) { /* 单价格式化显示1 */ + if (commonUtils.isNotEmptyNumber(values) && values !== null) { + const dResult = commonUtils.convertFixNum(Number(values), dNetPrice).toFixed(dNetPrice); + if (!isNaN(dResult)) { + values = dResult; + } + } + } else if (this.props.showConfig.sName.toLowerCase().endsWith('money')) { /* 金额格式化显示 */ + if (commonUtils.isNotEmptyNumber(values) && values !== null) { + const dResult = commonUtils.convertFixNum(Number(values), dNetMoney).toFixed(dNetMoney); + if (!isNaN(dResult)) { + values = dResult; + } + } + } + return values; + } else { + return values; + } + } + /** 处理下拉选择事件 */ + handleSelectOptionEvent = (newValue, dateString) => { + if (this.chineseInputting) { + return; + } + // if (location.pathname?.includes('productionScheduleTree') && this.props.showConfig.sName && this.props.showConfig.sName.includes('sThird-')) { + // return; + // } + + // antd autocomplete官方组件用到了react高版本的事件合成,但checkbox没用到; + // 做了兼容处理 + // if (newValue === undefined || newValue == null) { + // return; + // } + if (newValue === undefined) return; + if (newValue !== null && newValue.target && newValue.target.type !== 'checkbox') { + newValue = newValue.target.value; + } + /* 下拉新增单独处理 */ + const dEmptyValue = this.props.showConfig.sName === 'dMachineLength' || this.props.showConfig.sName === 'dMachineWidth' ? newValue : null; /* 设置数值型为空值时 数据置为0 或空值 */ + let value = this.firstDataIndex === 's' && !this.props.textArea && commonUtils.isEmpty(newValue) ? newValue.replace('--', '') : + this.firstDataIndex === 't' ? dateString : (this.firstDataIndex === 'd' || this.firstDataIndex === 'i') && commonUtils.isEmpty(newValue) ? dEmptyValue : newValue; + value = this.props.showConfig.bMultipleChoice ? value.toString() : value; + // if (value === 0) { + // setTimeout(() => { + // if (document.getElementById(`${this.props.showConfig.sName}${this.props.sId}`)) { + // document.getElementById(`${this.props.showConfig.sName}${this.props.sId}`).select(); + // } + // }, 51); + // } + this.isDropdownFilter = true; + if (this.props.showConfig.sDropDownType === 'sql' && value === '@#*000@') { + this.props.handleSqlDropDownNewRecord(this.props.showConfig, this.props.name); + if (this.mounted) { + this.setState({ dataValue: '' }); + } + return; + } + if (this.props.showConfig.sDropDownType === 'sql' && value === '=+@') { /* 如果是选择空值,则将特殊字符过滤为空值 */ + value = ''; + } + if (this.props.showConfig.sDropDownType === 'const' && value === '=+@') { /* 如果是选择空值,则将特殊字符过滤为空值 */ + value = ''; + } + /* 回带值声明 */ + const returnValue = {}; + const { searchValue, searchDropDownData, dropDownData } = this.state; + const dropDownDataNew = commonUtils.isEmptyArr(searchValue) ? dropDownData : searchDropDownData; + + const getTValue = (value) => { + const { sDateFormat = 'YYYY-MM-DD' } = this.props.showConfig; + + if (moment(value, sDateFormat, true).isValid()) return value; // 如果数据满足日期格式,则直接返回 + + if (commonUtils.isEmpty(value)) { + return null; + } else if (sDateFormat) { + return moment(value).format(this.props.showConfig.sDateFormat); + } else { + return value; + } + }; + + /* 回带值赋值(sName:value) */ + returnValue[this.props.showConfig.sName] = + // this.firstDataIndex === 's' && this.props.textArea ? value.target.value : + this.firstDataIndex === 'i' ? commonUtils.isEmpty(value) ? undefined : this.props.showConfig.sName === 'iOrder' ? value : parseInt(value, 0) : + this.firstDataIndex === 'd' ? commonUtils.isEmpty(value) ? undefined : this.floatNumberCheck(value) : + this.firstDataIndex === 't' ? getTValue(value) : + this.firstDataIndex === 'b' ? value.target.checked : value === null ? undefined : value; + if (!this.props.showConfig.bMultipleChoice) { + const { sAssignField } = this.props.showConfig; + const [changeData] = dropDownDataNew.filter(item => (!commonUtils.isEmpty(item.sSlaveId) ? item.sSlaveId : item.sId) === value.toString()); + if (!commonUtils.isEmpty(sAssignField)) { + /* 赋值数组 */ + const sAssignFieldObj = sAssignField.split(','); + if (commonUtils.isNotEmptyObject(changeData)) { + for (const child of sAssignFieldObj) { + if (child.indexOf(':') > -1) { + const sFieldName = child.split(':')[0].trim() === 'self' ? this.props.showConfig.sName : child.split(':')[0].trim(); + const sValueName = child.split(':')[1].trim(); + // returnValue[sFieldName] = changeData[sValueName] || changeData.value; + returnValue[sFieldName] = changeData[sValueName] === 0 ? 0 : changeData[sValueName] || changeData.value; + } + } + } else if (!this.props.showConfig.bCanInput) { + // 下拉选择空时,需要, bCanInput一定要为false不然印件名称输入时也被置空了 + for (const child of sAssignFieldObj) { + if (child.indexOf(':') > -1) { + const sFieldName = child.split(':')[0].trim() === 'self' ? this.props.showConfig.sName : child.split(':')[0].trim(); + returnValue[sFieldName] = ''; + } + } + } + } + } else { + const { sAssignField } = this.props.showConfig; + const changeData = dropDownDataNew.filter(item => (`,${value.toString()},`).includes((!commonUtils.isEmpty(item.sSlaveId) ? `,${item.sSlaveId},` : `,${item.sId},`))); + if (!commonUtils.isEmpty(sAssignField)) { + /* 赋值数组 */ + const sAssignFieldObj = sAssignField.split(','); + if (commonUtils.isNotEmptyArr(changeData)) { + for (const child of sAssignFieldObj) { + if (child.indexOf(':') > -1) { + const sFieldName = child.split(':')[0].trim() === 'self' ? this.props.showConfig.sName : child.split(':')[0].trim(); + const sValueName = child.split(':')[1].trim(); + const valueArr = []; + changeData.forEach((itemData) => { + valueArr.push(itemData[sValueName]); + }); + returnValue[sFieldName] = valueArr.toString(); + } + } + } else if (!this.props.showConfig.bCanInput) { + // 下拉选择空时,需要, bCanInput一定要为false不然印件名称输入时也被置空了 + for (const child of sAssignFieldObj) { + if (child.indexOf(':') > -1) { + const sFieldName = child.split(':')[0].trim() === 'self' ? this.props.showConfig.sName : child.split(':')[0].trim(); + returnValue[sFieldName] = ''; + } + } + } + } + + // 如果returnValue的第一个key对应的value的数据和上文的value个数不一致, 则取value的数据; + // 处理原因:如果已选数据不在下拉数据中时(比如懒加载模式),会过滤掉已选数据 + if (commonUtils.isNotEmptyArr(Object.keys(returnValue))) { + const [returnValueKey0, returnValueValue0] = [Object.keys(returnValue)[0], Object.values(returnValue)[0]]; + if (returnValueValue0.split(',').length !== value.split(',').length || (returnValueValue0 === '' && value !== '')) { + returnValue[returnValueKey0] = value; + } + } + } + + if (this.state.searchPageNum !== 0 || this.state.searchTotalPageCount !== 1 || this.state.searchDropDownData !== [] || this.state.searchValue !== '' || this.state.spinState !== false) { + this.setState({ + searchPageNum: 0, searchTotalPageCount: 1, searchDropDownData: [], searchValue: '', spinState: false, + }); + } + // /* 调用父组件的回带函数 */ + this.props.onChange(this.props.name, this.props.showConfig.sName, returnValue, this.props.sId, dropDownDataNew); + + clearTimeout(this.onChangeTimer); + this.onChangeTimer = setTimeout(() => { + this.onExecInstructSet('change'); + }, 500); + }; + + /** 处理autoComplete下拉选择事件 */ + // handleCompleteInputEvent = (newValue) => { + // // antd autocomplete官方组件用到了react高版本的事件合成,但checkbox没用到; + // // 做了兼容处理 + // if (newValue === undefined || newValue == null) { + // return; + // } + // if (newValue === undefined) return; + // if (newValue.target && newValue.target.type !== 'checkbox') { + // newValue = newValue.target.value; + // } + // const returnValue = {}; + // const { searchValue, searchDropDownData, dropDownData } = this.state; + // const dropDownDataNew = commonUtils.isEmptyArr(searchValue) ? dropDownData : searchDropDownData; + // returnValue[this.props.showConfig.sName] = newValue; + // if (this.state.searchPageNum !== 0 || this.state.searchTotalPageCount !== 1 || this.state.searchDropDownData !== [] || this.state.searchValue !== '' || this.state.spinState !== false) { + // this.setState({ + // searchPageNum: 0, searchTotalPageCount: 1, searchDropDownData: [], searchValue: '', spinState: false, + // }); + // } + // this.props.onChange(this.props.name, this.props.showConfig.sName, returnValue, this.props.sId, dropDownDataNew); + // }; + handleCompleteInputEvent = (newValue, dateString) => { + // 输入完成后的半秒内,如果触发了输入事件,则不执行 + if (this.chineseInputting) { + this.handleCompleteInputEventCache = () => { + this.chineseInputtingTimer = setTimeout(() => { + this.handleCompleteInputEvent(newValue, dateString); + this.handleCompleteInputEventCache = null; + }, 500); + }; + return; + } + clearTimeout(this.chineseInputtingTimer); + // antd autocomplete官方组件用到了react高版本的事件合成,但checkbox没用到; + // eslint-disable-next-line no-unused-vars + // const newKey = newValue.key || 0; + newValue = commonUtils.isNotEmptyObject(newValue.value) ? newValue.value : newValue; /* 处理可输入下拉框 输入数据时 没触发onChange事件 */ + // antd autocomplete官方组件用到了react高版本的事件合成,但checkbox没用到; + // 做了兼容处理 + if (newValue === undefined) { + return; + } + if (newValue.target && newValue.target.type !== 'checkbox') { + newValue = newValue.target.value; + } + /* 下拉新增单独处理 */ + const dMachine = ['dMachineLength', 'dMachineWidth'].includes(this.props.showConfig.sName); + if (dMachine) { + if (!/^\d+(\.\d+)?(\*\d+(\.\d+)?)?$/.test(newValue)) { + newValue = ''; + } + } + const dEmptyValue = this.props.showConfig.sName === 'dMachineLength' || this.props.showConfig.sName === 'dMachineWidth' ? newValue : 0; /* 设置数值型为空值时 数据置为0 或空值 */ + let value = this.firstDataIndex === 's' && !this.props.textArea && commonUtils.isEmpty(newValue) ? newValue.replace('--', '') : + this.firstDataIndex === 't' ? dateString : (this.firstDataIndex === 'd' || this.firstDataIndex === 'i') && commonUtils.isEmpty(newValue) ? dEmptyValue : newValue; + value = this.props.showConfig.bMultipleChoice ? value.toString() : value; + + // if (this.props.showConfig.sName === 'dMachineLength' || this.props.showConfig.sName === 'dMachineWidth') { /* 处理上机长宽 下拉数据 数据分割错误问题 */ + // value = this.floatNumberCheck(value); + // } + + this.isDropdownFilter = true; + if (this.props.showConfig.sDropDownType === 'sql' && value === '@#*000@') { + this.props.handleSqlDropDownNewRecord(this.props.showConfig, this.props.name); + if (this.mounted) { + this.setState({ dataValue: '' }); + } + return; + } + if (this.props.showConfig.sDropDownType === 'sql' && value === '=+@') { /* 如果是选择空值,则将特殊字符过滤为空值 */ + value = ''; + } + if (this.props.showConfig.sDropDownType === 'const' && value === '=+@') { /* 如果是选择空值,则将特殊字符过滤为空值 */ + value = ''; + } + + /* 回带值声明 */ + const returnValue = {}; + const { searchValue, searchDropDownData, dropDownData } = this.state; + const dropDownDataNew = commonUtils.isEmptyArr(searchValue) ? dropDownData : searchDropDownData; + /* 回带值赋值(sName:value) */ + returnValue[this.props.showConfig.sName] = + // this.firstDataIndex === 's' && this.props.textArea ? value.target.value : + this.firstDataIndex === 'i' ? commonUtils.isEmpty(value) ? undefined : this.props.showConfig.sName === 'iOrder' ? value : parseInt(value, 0) : + this.firstDataIndex === 'd' ? commonUtils.isEmpty(value) ? dMachine ? '' : undefined : value : // this.floatNumberCheck(value) : + this.firstDataIndex === 't' ? commonUtils.isEmpty(value) ? null : value : + this.firstDataIndex === 'b' ? value.target.checked : value === null ? undefined : value; + if (!this.props.showConfig.bMultipleChoice) { + const { sAssignField } = this.props.showConfig; + // const [changeData] = dropDownDataNew.filter(item => (!commonUtils.isEmpty(item.sSlaveId) ? item.sSlaveId : item.sId) === newKey.toString()); + let res = ''; + if (dropDownDataNew.length > 0) { + if (commonUtils.isNotEmptyStr(this.props.showConfig.sVisColumnName)) { + res = this.props.showConfig.sVisColumnName; + } else { + res = Object.keys(dropDownDataNew[0]).length > 0 ? Object.keys(dropDownDataNew[0])[0] : ''; + } + } + const [changeData] = dropDownDataNew.filter(item => (!commonUtils.isEmpty(res) ? item[res] : item.sId) === value.toString()); + if (!commonUtils.isEmpty(sAssignField)) { + /* 赋值数组 */ + const sAssignFieldObj = sAssignField.split(','); + if (commonUtils.isNotEmptyObject(changeData)) { + for (const child of sAssignFieldObj) { + if (child.indexOf(':') > -1) { + const sFieldName = child.split(':')[0].trim() === 'self' ? this.props.showConfig.sName : child.split(':')[0].trim(); + const sValueName = child.split(':')[1].trim(); + returnValue[sFieldName] = changeData[sValueName] || changeData.value; + } + } + } else if (!this.props.showConfig.bCanInput) { + // 下拉选择空时,需要, bCanInput一定要为false不然印件名称输入时也被置空了 + for (const child of sAssignFieldObj) { + if (child.indexOf(':') > -1) { + const sFieldName = child.split(':')[0].trim() === 'self' ? this.props.showConfig.sName : child.split(':')[0].trim(); + returnValue[sFieldName] = ''; + } + } + } + } + } else { + const { sAssignField } = this.props.showConfig; + const changeData = dropDownDataNew.filter(item => (`,${value.toString()},`).includes((!commonUtils.isEmpty(item.sSlaveId) ? `,${item.sSlaveId},` : `,${item.sId},`))); + if (!commonUtils.isEmpty(sAssignField)) { + /* 赋值数组 */ + const sAssignFieldObj = sAssignField.split(','); + if (commonUtils.isNotEmptyArr(changeData)) { + for (const child of sAssignFieldObj) { + if (child.indexOf(':') > -1) { + const sFieldName = child.split(':')[0].trim() === 'self' ? this.props.showConfig.sName : child.split(':')[0].trim(); + const sValueName = child.split(':')[1].trim(); + const valueArr = []; + changeData.forEach((itemData) => { + valueArr.push(itemData[sValueName]); + }); + returnValue[sFieldName] = valueArr.toString(); + } + } + } else if (!this.props.showConfig.bCanInput) { + // 下拉选择空时,需要, bCanInput一定要为false不然印件名称输入时也被置空了 + for (const child of sAssignFieldObj) { + if (child.indexOf(':') > -1) { + const sFieldName = child.split(':')[0].trim() === 'self' ? this.props.showConfig.sName : child.split(':')[0].trim(); + returnValue[sFieldName] = ''; + } + } + } + } + } + if (this.state.searchPageNum !== 0 || this.state.searchTotalPageCount !== 1 || this.state.searchDropDownData !== [] || this.state.searchValue !== '' || this.state.spinState !== false) { + this.setState({ + searchPageNum: 0, searchTotalPageCount: 1, searchDropDownData: [], searchValue: '', spinState: false, + }); + } + // /* 调用父组件的回带函数 */ + let bSpecial = true; + if (location.pathname && location.pathname.includes('ResearchTableTree')) { + bSpecial = false; + } + if (bSpecial && this.state.dataValue === returnValue[this.props.showConfig.sName]) { + if (!this.completeFlag) { + const addState = {}; + addState[this.props.showConfig.sName] = undefined; + setTimeout(() => { + this.props.onChange(this.props.name, this.props.showConfig.sName, { ...returnValue, ...addState }, this.props.sId, dropDownDataNew); + }, 0); + } + this.completeFlag = false; + } + // setTimeout(() => { + // this.props.onChange(this.props.name, this.props.showConfig.sName, returnValue, this.props.sId, dropDownDataNew); + // }, 50); + this.props.onChange(this.props.name, this.props.showConfig.sName, returnValue, this.props.sId, dropDownDataNew); + + clearTimeout(this.onChangeTimer); + this.onChangeTimer = setTimeout(() => { + this.onExecInstructSet('change'); + }, 500); + }; + // handleCompleteOptionEvent = (newValue, dateString) => { + // // antd autocomplete官方组件用到了react高版本的事件合成,但checkbox没用到; + // const newKey = newValue.key; + // newValue = newValue.value; + // /* 下拉新增单独处理 */ + // const dEmptyValue = this.props.showConfig.sName === 'dMachineLength' || this.props.showConfig.sName === 'dMachineWidth' ? newValue : 0; /* 设置数值型为空值时 数据置为0 或空值 */ + // let value = this.firstDataIndex === 's' && !this.props.textArea && commonUtils.isEmpty(newValue) ? newValue.replace('--', '') : + // this.firstDataIndex === 't' ? dateString : (this.firstDataIndex === 'd' || this.firstDataIndex === 'i') && commonUtils.isEmpty(newValue) ? dEmptyValue : newValue; + // value = this.props.showConfig.bMultipleChoice ? value.toString() : value; + // // let value = this.firstDataIndex === 's' && !this.props.textArea && commonUtils.isEmpty(newValue) ? newValue.replace('--', '') : + // // this.firstDataIndex === 't' ? dateString : (this.firstDataIndex === 'd' || this.firstDataIndex === 'i') && commonUtils.isEmpty(newValue) ? 0 : newValue; + // // value = this.props.showConfig.bMultipleChoice ? value.toString() : value; + // this.isDropdownFilter = true; + // if (this.props.showConfig.sDropDownType === 'sql' && value === '@#*000@') { + // this.props.handleSqlDropDownNewRecord(this.props.showConfig, this.props.name); + // if (this.mounted) { + // this.setState({ dataValue: '' }); + // } + // return; + // } + // if (this.props.showConfig.sDropDownType === 'sql' && value === '=+@') { /* 如果是选择空值,则将特殊字符过滤为空值 */ + // value = ''; + // } + // if (this.props.showConfig.sDropDownType === 'const' && value === '=+@') { /* 如果是选择空值,则将特殊字符过滤为空值 */ + // value = ''; + // } + // /* 回带值声明 */ + // const returnValue = {}; + // const { searchValue, searchDropDownData, dropDownData } = this.state; + // const dropDownDataNew = commonUtils.isEmptyArr(searchValue) ? dropDownData : searchDropDownData; + // /* 回带值赋值(sName:value) */ + // returnValue[this.props.showConfig.sName] = + // // this.firstDataIndex === 's' && this.props.textArea ? value.target.value : + // this.firstDataIndex === 'i' ? commonUtils.isEmpty(value) ? undefined : this.props.showConfig.sName === 'iOrder' ? value : parseInt(value, 0) : + // this.firstDataIndex === 'd' ? commonUtils.isEmpty(value) ? undefined : this.floatNumberCheck(value) : + // this.firstDataIndex === 't' ? commonUtils.isEmpty(value) ? null : value : + // this.firstDataIndex === 'b' ? value.target.checked : value === null ? undefined : value; + // if (!this.props.showConfig.bMultipleChoice) { + // const { sAssignField } = this.props.showConfig; + // let res = ''; + // if (dropDownDataNew.length > 0) { + // if (commonUtils.isNotEmptyStr(this.props.showConfig.sVisColumnName)) { + // res = this.props.showConfig.sVisColumnName; + // } else { + // res = Object.keys(dropDownDataNew[0]).length > 0 ? dropDownDataNew[0][Object.keys(dropDownDataNew[0])[0]] : ''; + // } + // } + // const [changeData] = dropDownDataNew.filter(item => (!commonUtils.isEmpty(res) ? item[res] : item.sId) === value.toString()); + // + // if (!commonUtils.isEmpty(sAssignField)) { + // /* 赋值数组 */ + // const sAssignFieldObj = sAssignField.split(','); + // if (commonUtils.isNotEmptyObject(changeData)) { + // for (const child of sAssignFieldObj) { + // if (child.indexOf(':') > -1) { + // const sFieldName = child.split(':')[0].trim() === 'self' ? this.props.showConfig.sName : child.split(':')[0].trim(); + // const sValueName = child.split(':')[1].trim(); + // returnValue[sFieldName] = changeData[sValueName] || changeData.value; + // } + // } + // } else if (!this.props.showConfig.bCanInput) { + // // 下拉选择空时,需要, bCanInput一定要为false不然印件名称输入时也被置空了 + // for (const child of sAssignFieldObj) { + // if (child.indexOf(':') > -1) { + // const sFieldName = child.split(':')[0].trim() === 'self' ? this.props.showConfig.sName : child.split(':')[0].trim(); + // returnValue[sFieldName] = ''; + // } + // } + // } + // } + // } else { + // const { sAssignField } = this.props.showConfig; + // const changeData = dropDownDataNew.filter(item => (`,${value.toString()},`).includes((!commonUtils.isEmpty(item.sSlaveId) ? `,${item.sSlaveId},` : `,${item.sId},`))); + // if (!commonUtils.isEmpty(sAssignField)) { + // /* 赋值数组 */ + // const sAssignFieldObj = sAssignField.split(','); + // if (commonUtils.isNotEmptyArr(changeData)) { + // for (const child of sAssignFieldObj) { + // if (child.indexOf(':') > -1) { + // const sFieldName = child.split(':')[0].trim() === 'self' ? this.props.showConfig.sName : child.split(':')[0].trim(); + // const sValueName = child.split(':')[1].trim(); + // const valueArr = []; + // changeData.forEach((itemData) => { + // valueArr.push(itemData[sValueName]); + // }); + // returnValue[sFieldName] = valueArr.toString(); + // } + // } + // } else if (!this.props.showConfig.bCanInput) { + // // 下拉选择空时,需要, bCanInput一定要为false不然印件名称输入时也被置空了 + // for (const child of sAssignFieldObj) { + // if (child.indexOf(':') > -1) { + // const sFieldName = child.split(':')[0].trim() === 'self' ? this.props.showConfig.sName : child.split(':')[0].trim(); + // returnValue[sFieldName] = ''; + // } + // } + // } + // } + // } + // if (this.state.searchPageNum !== 0 || this.state.searchTotalPageCount !== 1 || this.state.searchDropDownData !== [] || this.state.searchValue !== '' || this.state.spinState !== false) { + // this.setState({ + // searchPageNum: 0, searchTotalPageCount: 1, searchDropDownData: [], searchValue: '', spinState: false, + // }); + // } + // // /* 调用父组件的回带函数 */ + // console.log('returnValue', returnValue); + // this.props.onChange(this.props.name, this.props.showConfig.sName, returnValue, this.props.sId, dropDownDataNew); + // }; + /** 搜索时过滤对应的 option 属性 */ + filterOption = (input, option) => { + const { pageNum, totalPageCount } = this.state; + const newInput = input.toString().trim(); /* 下拉框默认为空 不需要替换'--’ */ + if (pageNum <= totalPageCount && this.props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(this.props.showConfig.dropDownData)) { + return true; + } else if (commonUtils.isNotEmptyObject(option.props.children)) { + try { + return (!this.isDropdownFilter && this.props.showConfig.bCanInput) ? true : (option.props.children.toLowerCase().indexOf(newInput.toLowerCase()) >= 0); + } catch (error) { + return false; + } + } + }; + + + /** + * 小数校验 + */ + floatNumberCheck = (num) => { + const dNetPrice = this.props.app?.decimals?.dNetPrice; + const { showConfig } = this.props; + const { sName, showName } = showConfig; + const digit = sName.includes('Price') && dNetPrice ? dNetPrice : 6; + if (typeof num === 'string') { + num = num.replace('*', ''); + } + const checkRule = new RegExp(`^(-?\\d+)(\\.?)(\\d{1,${digit}})?$`); + if (!checkRule.test(num) && num && num !== '-' && num !== '.') { + message.warning(`【${showName}】【${sName}】最多输入${digit}位小数!`); + return undefined; + } else { + return num; + } + } + + /** 小数位控制 noinspection JSAnnotator控制 string | number */ + limitDecimals = (values) => { + let reg = ''; + if (this.floatNum > 0) { + reg = `^(\\d+).(${this.floatPrice})*$`; + } else { + reg = '^(\\d+).(\\d\\d\\d\\d\\d\\d)*$'; + } + if (typeof values === 'string') { + if (values !== undefined && values.indexOf('.') <= -1) { + reg = '^(\\d+)*$'; + return !isNaN(Number(values)) ? values.replace(new RegExp(reg), '$1') : ''; + } else { + return !isNaN(Number(values)) ? values.replace(new RegExp(reg), '$1.$2') : ''; + } + } else if (typeof values === 'number') { + if (values !== undefined && String(values).indexOf('.') <= -1) { + reg = '^(\\d+)*$'; + return !isNaN(values) ? String(values).replace(new RegExp(reg), '$1') : ''; + } else { + return !isNaN(values) ? String(values).replace(new RegExp(reg), '$1.$2') : ''; + } + } else { + return ''; + } + }; + + handleViewClick = () => { + const { record, app, showConfig } = this.props; + const { sControlName, sActiveKey } = showConfig; /* 弹出标志,弹出界面对应数据主字段 */ + if (commonUtils.isNotEmptyObject(sControlName) && commonUtils.isNotEmptyObject(sActiveKey)) { + const printPdf = sControlName; + if (commonUtils.isNotEmptyObject(printPdf) && printPdf === 'printPdf' && commonUtils.isNotEmptyObject(sActiveKey)) { + const { token } = app; + const sActiveId = this.props.showConfig.sActiveId === '1' ? commonUtils.isEmpty(record.sFormId) ? record.sSrcFormId : record.sFormId : this.props.showConfig.sActiveId; + const printsId = record[sActiveKey]; + const urlPrint = `${commonConfig.file_host}printReport/printPdfByFromDataId/${printsId}.pdf?sModelsId=${sActiveId}&sId=${printsId}&token=${encodeURIComponent(token)}`; + // const urlPrint = `${commonConfig.file_host}printReport/printPdfByFromDataId?sModelsId=${sActiveId}&sId=${printsId}&token=${encodeURIComponent(token)}`; + window.open(urlPrint); + } else if (showConfig.sDropDownType && showConfig.sDropDownType.toLowerCase().includes('picarrmodal')) { /* 蓝色链接跳转用Modal呈现 */ + // this.props.onTabModalClick(name, sName, record, index, showConfig, configName); + this.props.onTabModalClick(this.props.name, this.props.showConfig.sName, record, undefined, showConfig, this.props.sName); + } else { + this.props.onViewClick(this.props.name, this.props.showConfig.sName, this.props.record); + } + } else if (showConfig.sDropDownType && showConfig.sDropDownType.toLowerCase().includes('picarrmodal')) { /* 蓝色链接跳转用Modal呈现 */ + // this.props.onTabModalClick(name, sName, record, index, showConfig, configName); + this.props.onTabModalClick(this.props.name, this.props.showConfig.sName, record, undefined, showConfig, this.props.sName); + } else { + this.props.onViewClick(this.props.name, this.props.showConfig.sName, this.props.record); + } + } + + /* 打开新窗口查看SQL编辑器 */ + handleOpenWin = () => { + const { dataValue, showConfig, record } = this.props; + // eslint-disable-next-line prefer-destructuring + const sBtnName = showConfig.sName; + const sBtnContent = commonUtils.isNotEmptyObject(dataValue) ? encodeURIComponent(dataValue) : ''; + const sBtnControlName = commonUtils.isNotEmptyObject(showConfig.sName) ? showConfig.sName : ''; + if (commonUtils.isNotEmptyObject(sBtnContent) && commonUtils.isNotEmptyObject(record)) { + const sFormId = commonUtils.isNotEmptyObject(record.sParentId) ? record.sParentId : ''; + const urlPrint = `${commonConfig.server_host}template/getSql/${sBtnName}/?sBtnContent=${sBtnContent}&sBtnControlName=${sBtnControlName}&sFormId=${sFormId}`; + const w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; + const h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; + // const newWin = window.open('','_blank'); + const features = `width=${w + 350},height=${h + 300}, top=0, left=0, toolbar=no, menubar=no,scrollbars=no,resizable=no, location =no, status=no`; + const newWin = window.open('', 'SQL查看器', features); + newWin.document.write(``); + // window.open(urlPrint); + } else { + message.error('未找到对应过程名'); + } + }; + + /* 右箭头点击 */ + handleRightArrow = () => { + if (this.props.onRightArrow) { + const { name, record, showConfig } = this.props; + this.props.onRightArrow(name, showConfig.sName, record, undefined, showConfig); + } + } + + handlePreviewImage = (e, dataUrl) => { + e.stopPropagation(); + this.props.onPreviewImage(e, dataUrl); + } + handleViewChoose = () => { + const bGycs = this.props.showConfig?.showName?.includes('工艺参数'); + if (this.state.enabled || bGycs) this.props.onViewChoose(this.props.name, this.props.showConfig.sName, this.props.record); + } + handleMemoShow= () => { + this.props.onMemoShow(this.props.name, this.props.showConfig.sName, this.props.record, 0, this.props.showConfig); + } + + handlePreviewOffice = (dataUrl) => { + this.props.onPreviewOffice(dataUrl); + } + + handlePopupScroll = (e) => { + e.persist(); + const { target } = e; + if (Math.ceil(target.scrollTop + target.offsetHeight) >= target.scrollHeight && this.props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(this.props.showConfig.dropDownData)) { + const { + pageNum, searchPageNum, searchTotalPageCount, searchValue, totalPageCount, + } = this.state; + const nextPageNum = pageNum + 1; + const nextSearchPageNum = searchPageNum + 1; + if (searchValue !== '') { + this.getDropDownData(nextSearchPageNum, searchTotalPageCount, searchValue); + } else { + this.getDropDownData(nextPageNum, totalPageCount, searchValue); + } + } + }; + + handleSearch = (value) => { + if (this.dropDownTimer) { + clearTimeout(this.dropDownTimer); + } + this.dropDownTimer = setTimeout(() => { + if (this.props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(this.props.showConfig.dropDownData)) { + this.setState({ spinState: true }); + this.getDropDownData(1, 1, value); + } + }, 500); + }; + /** 渲染 */ + render() { + /* 获取innerinput控件参数 */ + const innerInputProps = this.getInnerInputProps(); + + const { slaveConfig = { gdsconfigformslave: [] }, bSColorSerialMemo } = this.props; + const { gdsconfigformslave } = slaveConfig; + const { sName } = this.props.showConfig; + const btPopIndex = gdsconfigformslave.findIndex(item => item.sControlName === `BtnPopup.${sName}`); + const btCostomIndex = gdsconfigformslave.findIndex(item => item.sControlName === `BtnCustom.${sName}`); + + /* 获取innerinput控件 */ + const innerInput = btPopIndex > -1 && btCostomIndex > -1 ? ( + + {this.getInnerInput(innerInputProps)} + {this.getInnerButton()} + {this.getInnerButtonCostom(gdsconfigformslave[btCostomIndex])} +
+ + ) : btPopIndex !== -1 ? ( + + {this.getInnerInput(innerInputProps)} + {this.getInnerButton()} +
+ + ) : btCostomIndex !== -1 ? ( + + {this.getInnerInput(innerInputProps)} + {this.getInnerButtonCostom(gdsconfigformslave[btCostomIndex])} +
+ + ) : this.getInnerInput(innerInputProps); + + let viewInfo = ''; + if (this.props.showConfig.sDropDownType !== 'popup' && !commonUtils.isEmpty(this.props.showConfig.sActiveId) && !commonUtils.isEmpty(this.props.showConfig.sActiveKey) && (commonUtils.isNotEmptyObject(this.props.dataValue) || commonUtils.isNotEmptyNumber(this.props.dataValue))) { + viewInfo = ( +
+ + {this.props.dataValue} + +
); + } + const sModelsType = commonUtils.isNotEmptyObject(this.props) && commonUtils.isNotEmptyObject(this.props.app) ? this.props.app.currentPane.sModelsType : ''; + let bParamColor = false; + if (this.props && sName === 'sParamValue' && this.props.dataValue) { + if (this.props.dataValue === '选择色序' || this.props.record.sParamKey === 'sParam1001') { + bParamColor = true; + } + } + if (sName === 'sCombinedMemo' || sName === 'sColorSerialMemo' || bSColorSerialMemo || bParamColor || sName === 'sPositiveColor' || sName === 'sOppositeColor' || sName === 'sCombineProductNameNew' || sName === 'sParams' || sName === 'sParamsNew' || sName === 'sQuoParams' || (commonUtils.isNotEmptyObject(sModelsType) && !sModelsType.includes('Set') && sName === 'sCombinePartsNameNew')) { + let sValue = ''; + /* 将合版信息json解析成需要的字符串形式 */ + if (sName === 'sCombinedMemo') { + let JsonData = []; + if (commonUtils.isNotEmptyObject(this.props.dataValue)) { + try { + JsonData = JSON.parse(this.props.dataValue); + } catch (e) { + JsonData = []; + } + } + if (commonUtils.isNotEmptyArr(JsonData)) { + JsonData.forEach((item) => { + sValue += `${item.sProductNo}:排${item.dCombineQty}个,`; + }); + sValue = commonUtils.isNotEmptyObject(sValue) ? sValue.substr(0, sValue.length - 1) : ''; + } + } else if (sName === 'sColorSerialMemo' || bSColorSerialMemo || sName === 'sPositiveColor' || sName === 'sOppositeColor' || bParamColor) { + let JsonData = []; + if (commonUtils.isNotEmptyObject(this.props.dataValue)) { + try { + JsonData = JSON.parse(this.props.dataValue); + } catch (e) { + JsonData = []; + } + } + if (typeof JsonData === 'object' && commonUtils.isNotEmptyArr(JsonData)) { + JsonData.forEach((item) => { + sValue += `${item.sName}+`; + }); + sValue = commonUtils.isNotEmptyObject(sValue) ? sValue.substr(0, sValue.length - 1) : ''; + } + } else if (sName === 'sParams' || sName === 'sQuoParams' || sName === 'sParamsNew') { + if (this.props.onGetParamsValue) { + // 页面自行处理sparams的sValue + sValue = this.props.onGetParamsValue({ sName, sValue: this.props.dataValue, record: this.props.record }); + } else { + let JsonData = []; + if (commonUtils.isNotEmptyObject(this.props.dataValue)) { + try { + JsonData = JSON.parse(this.props.dataValue); + } catch (e) { + JsonData = []; + } + } + if (commonUtils.isNotEmptyArr(JsonData)) { + JsonData.forEach((item) => { + if (item.bSelfCbx) { + const strValue = commonUtils.isNotEmptyObject(item.sParamValue) ? item.sParamValue : ''; + sValue += `${item.sParamName}:${strValue},`; + } + }); + sValue = commonUtils.isNotEmptyObject(sValue) ? sValue.substr(0, sValue.length - 1) : ''; + } + } + } else { + sValue = this.props.dataValue; + } + viewInfo = ( +
+ {commonUtils.isNotEmptyObject(sValue) ? sValue : sName === 'sCombinedMemo' ? '合版信息' : '请选择'} + +
); + } + /* commonClassify 制单日期、制单人员新增时设置保存时自动生成 */ + let speacilNote = ''; + const { record } = this.props; + if (commonUtils.isNotEmptyObject(record) && commonUtils.isEmptyObject(record[sName]) && commonUtils.isNotEmptyObject(sName) && (sName === 'tCreateDate' || sName === 'sMakePerson')) { + speacilNote = (
保存后自动生成
); + } + + const bShowMemo = false && commonUtils.isNotEmptyObject(sName) && sName.indexOf('sMemo') > -1 && !sName.includes('ProcessMemo'); /* 非编辑状态下 备注以蓝色链接呈现 */ + /* 如果是图片类型 ,加载图片 */ + let imgBox = ''; + if (commonUtils.isNotEmptyObject(sName) && sName.indexOf('picture') > -1) { + const picAddr = commonUtils.isNotEmptyObject(record[sName]) ? record[sName].split(',') : ''; + if (commonUtils.isNotEmptyObject(picAddr)) { + const { token } = this.props.app; + const dataUrl = picAddr[0].includes('xlyerpfiles') ? `${commonConfig.file_host}file/download?savePathStr=${picAddr[0]}&scale=0.1&sModelsId=100&token=${token}` : picAddr[0]; /* 缩略图 */ + // const dataPriviewUrl = `${commonConfig.server_host}file/download?savePathStr=${picAddr}&width=800&&height=500&sModelsId=100&token=${token}`; /* 预览 */ + const officeFileTypeList = ['PDF', 'DOCX', 'XLSX']; + const imgTypeList = ['PNG', 'SVG', 'JPG', 'JPEG', 'GIF', 'BMP', 'TIFF', 'ICO']; + const officeFileType = picAddr[0].split('.').pop().toUpperCase(); + let fileIcon = ; + if (officeFileType === 'DOCX') { + fileIcon = ; + } else if (officeFileType === 'XLSX') { + fileIcon = ; + } + let imgBox1 = ''; + if (officeFileTypeList.includes(officeFileType)) { + imgBox1 = ( + { + this.handlePreviewOffice(picAddr[0]); + }} + > + {fileIcon} + + ); + } else if (imgTypeList.includes(officeFileType)) { + imgBox1 = ( + this.handlePreviewImage(e, picAddr)} + > + img 0} + style={{ width: '30px', height: '20px' }} + /> + + ); + } else { + imgBox1 = ( + + + + ); + } + imgBox = ( +
+ {imgBox1} +
); + } + } else if (this.props.name === 'master' && sName !== 'sQualityRequirementsMemo' && !this.props.enabled && commonUtils.isNotEmptyObject(sName) && bShowMemo) { /* 所有备注非编辑状态下点击链接可以弹出备注窗体 */ + imgBox = ( +
+
{this.props.dataValue} 
+
+
); + // 富文本处理 + // if (this.props.showConfig.bEditor) { + // imgBox = (<>); + // } + if (this.props.showConfig.sName && this.props.showConfig.sName.toLowerCase().includes('fullmemo')) { + imgBox = (<>); + } + } + /* 获取outformitem控件参数 */ + const outFormItemProps = this.getOutFormItemProps(); + /* 获取fieldDecorator参数 */ + const fieldDecoratorProps = this.getFieldDecoratorProps(); + /* 通用组件(主表存在getFieldDecorator表单验证,而从表则不需要) */ + const commonAssembly = ( {speacilNote}{imgBox}{!this.props.bTable ? this.getFieldDecorator(this.props.showConfig.sName, fieldDecoratorProps)(innerInput) : innerInput}{viewInfo} ); + const { iColValue, showConfig } = this.props; + const readonlyStyle = showConfig.bReadonly || showConfig.iTag === 1 ? 'readonlyStyle' : ''; + const costomStyle = showConfig.costomStyle || ''; + /* 页面输出 */ + return ( +
+
+ {commonAssembly} +
+
+ ); + } +} diff --git a/src/components/Common/CommonComponent/index_new.js b/src/components/Common/CommonComponent/index_new.js new file mode 100644 index 0000000..deceaac --- /dev/null +++ b/src/components/Common/CommonComponent/index_new.js @@ -0,0 +1,1188 @@ +import moment from 'moment'; +import React, { useState, useEffect } from 'react'; +import { useMount, useUnmount } from 'ahooks'; +// import reactComponentDebounce from 'react-component-debounce'; +import '@ant-design/compatible/assets/index.css'; +import { + InputNumber, + Checkbox, + DatePicker, + Input, + Cascader, + Select, + AutoComplete, + Spin, + message, + Form, +} from 'antd'; +import * as commonUtils from '@/utils/utils'; +import styles from '@/index.less'; +import Provinces from '@/assets/provinces.json'; +import Cities from '@/assets/cities.json'; +import Areas from '@/assets/areas.json'; +import commonConfig from '@/utils/config'; +import { VirtualKeyboard } from '@/oee/common/oeeKeyBoard'; + +const FormItem = Form.Item; +const { Option } = Select; +const { TextArea } = Input; +const { Search } = Input; +// const InputNumberA = reactComponentDebounce(500)(InputNumber); +// const InputA = reactComponentDebounce(500)(Input); +// const AutoCompleteA = reactComponentDebounce(50)(AutoComplete); +// const TextAreaA = reactComponentDebounce(500)(TextArea); +const InputNumberA = InputNumber; +const InputA = Input; +const AutoCompleteA = AutoComplete; +const TextAreaA = TextArea; +const { RangePicker, MonthPicker } = DatePicker; + +function CommonComponent(props) { + const [dataValue, setDataValue] = useState(props.dataValue); + const [enabled, setEnabled] = useState(props.enabled); + const [showName, setShowName] = useState(''); + const [dropDownData, setDropDownData] = useState([]); + const [conditonValues, setConditonValues] = useState({}); + const [sFieldName, setSFieldName] = useState(props.showConfig.sName); + const [bNotEmpty, setBNotEmpty] = useState(props.showConfig.bNotEmpty); + const [sDropDownType, setSDropDownType] = useState(''); + const [sActiveDisplay, setSActiveDisplay] = useState(true); + const [pageNum, setPageNum] = useState(0); + const [totalPageCount, setTotalPageCount] = useState(1); + const [searchValue, setSearchValue] = useState(''); + const [searchDropDownData, setSearchDropDownData] = useState([]); + const [searchTotalPageCount, setSearchTotalPageCount] = useState(1); + const [searchPageNum, setSearchPageNum] = useState(0); + const [spinState, setSpinState] = useState(false); + + let firstDataIndex = props.showConfig.sName.substring(0, 1); + const mode = props.showConfig.bMultipleChoice ? 'multiple' : 'default'; + const { bNewRecord } = props.showConfig; + const max = props.showConfig.sMaxValue; + const min = props.showConfig.sMinValue; + const getFieldDecorator = commonUtils.isUndefined(props.form) ? undefined : props.form.getFieldDecorator; /* 字段验证(数据格式:数字) */ + const floatNum = props.getFloatNum(props.showConfig.sName); + // const floatPrice = getFloatPrice(floatNum); + const formItemLayout = commonUtils.isNotEmptyObject(props.formItemLayout) ? + props.formItemLayout : + { labelCol: { span: 7 }, wrapperCol: { span: 15 } }; + let isDropdownFilter = false; + // const V = { value: props.dataValue }; + let mounted = false; + let dropDownTimer = null; + + useMount(() => { + mounted = true; + let showDropDown = []; + if (props.showConfig.sDropDownType === 'const') { + showDropDown = commonUtils.isNotEmptyArr(props.showConfig.dropDownData) ? props.showConfig.dropDownData : + (typeof props.showConfig.showDropDown === 'object') ? props.showConfig.showDropDown : commonUtils.objectToArr(commonUtils.convertStrToObj(props.showConfig.showDropDown)); + } else if (props.showConfig.sDropDownType === 'sql' && !commonUtils.isEmptyArrNew(props.showConfig.dropDownData)) { + showDropDown = props.showConfig.dropDownData; + } + setDropDownData(showDropDown); + }); + + useUnmount(() => { + mounted = false; + }); + + useEffect(() => { + if (props.showConfig === undefined || props.showConfig === undefined) return; + firstDataIndex = props.showConfig.sName.substring(0, 1); + if (props.showConfig.sDropDownType === 'const') { + const showDropDown = commonUtils.isNotEmptyArr(props.showConfig.dropDownData) ? props.showConfig.dropDownData : + (typeof props.showConfig.showDropDown === 'object') ? props.showConfig.showDropDown : commonUtils.objectToArr(commonUtils.convertStrToObj(props.showConfig.showDropDown)); + if (mounted) { + setDropDownData(showDropDown); + } + } else if (props.showConfig.sDropDownType === 'sql' && !commonUtils.isEmptyArr(props.showConfig.dropDownData)) { + if (mounted) { + setDropDownData(props.showConfig.dropDownData); + } + } + + if (dataValue !== props.dataValue || enabled !== props.enabled || bNotEmpty !== props.showConfig.bNotEmpty || sFieldName !== props.showConfig.sName || showName !== props.showConfig.showName || sDropDownType !== props.showConfig.sDropDownType) { + if (mounted) { + setDataValue(props.dataValue); + setEnabled(props.enabled); + setSFieldName(props.showConfig.sName); + setSDropDownType(props.showConfig.sDropDownType); + setBNotEmpty(props.showConfig.bNotEmpty); + setShowName(props.showConfig.showName); + } + } + }, [props]); + + const onFocus = () => { + isDropdownFilter = false; + setSActiveDisplay(false); + }; + + const onBlur = () => { + isDropdownFilter = false; + if (searchValue !== '' && props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(props.showConfig.dropDownData)) { + if (!props.showConfig.bCanInput) { + handleSelectOptionEvent(''); + } + setSearchPageNum(1); + setSearchTotalPageCount(1); + setSearchDropDownData([]); + setSearchValue(''); + setSpinState(false); + setSActiveDisplay(true); + } + }; + + const onDropdownVisibleChange = (open) => { + if (mounted && open) { + const conditonValuesNew = props.getSqlCondition(props.showConfig, props.name, props.record); + const pageNumNew = JSON.stringify(conditonValuesNew) !== JSON.stringify(conditonValues) ? 1 : pageNum === 0 ? 1 : pageNum; + const totalPageCountNew = conditonValuesNew !== conditonValues ? 1 : totalPageCount; + if (pageNum === 1 && props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(props.showConfig.dropDownData)) { + setSpinState(true); + getDropDownData(pageNumNew, totalPageCountNew, searchValue); + } + } else { + isDropdownFilter = false; + } + if (props.onDropdownVisibleChange !== undefined) { + if (dropDownData.length === 0 && !bNewRecord) { + open = false; + } + props.onDropdownVisibleChange(open); + } + }; + + const onDoubleClick = () => { + const sMemo = props.showConfig.sName; + const title = props.showConfig.showName; + if (commonUtils.isNotEmptyObject(sMemo) && sMemo.indexOf('Memo') > -1) { + const sCurrMemoProps = { + title, + name: props.name, + sValue: props.dataValue, + sMemoField: sMemo, + bVisibleMemo: true, + sRecord: props.record, + sMemoConfig: props.showConfig, + }; + props.onSaveState({ sCurrMemoProps }); + } + }; + + const onKeyUp = (e) => { + if (props.onKeyUp) { + props.onKeyUp(e); + } + }; + + // const { onKeyDown } = useDebounceFn( + // (e) => { + // console.log(1111); + // if (props.onKeyDown) { + // const { showConfig, record } = props; + // props.onKeyDown(e, record, showConfig.sName); + // } + // if (e.key === 'F10') { + // message.info(props.showConfig.sName); + // } + // }, + // { + // wait: 500, + // }, + // ); + + const onKeyDown = (e) => { + if (props.onKeyDown) { + const { showConfig, record } = props; + props.onKeyDown(e, record, showConfig.sName); + } + if (e.key === 'F10') { + message.info(props.showConfig.sName); + } + }; + + // const onKeyDownDiv = (e) => { + // if (props.onKeyDown) { + // props.onKeyDown(e); + // } + // if (e.key === 'F10') { + // message.info(props.showConfig.sName); + // } else { + // e.preventDefault(); + // return false; + // } + // }; + + const onContextMenu = (e) => { + if (enabled && commonUtils.isNotEmptyObject(props) && props.name !== 'master' && commonUtils.isNotEmptyObject(props.showConfig)) { + const { showConfig, name } = props; + const { bReadonly } = showConfig; + if (bReadonly) { + return; + } + e.preventDefault(); /* 阻止浏览器本身的右击事件 */ + if (props.onContextMenu) { + const { showConfig, record } = props; + props.onContextMenu(e, record, showConfig, name); + } + } + }; + + const onFieldPopupModal = (showConfig, name, open) => { + if (open) { + props.onFieldPopupModal(showConfig, name); + } + }; + + const getSelectProps = () => { + /* 返回值声明 */ + const obj = { + showSearch: true, + onChange: handleSelectOptionEvent, + filterOption, + onDropdownVisibleChange, + onPopupScroll: handlePopupScroll, + onSearch: handleSearch, + notFoundContent: spinState ? : '暂无数据', + onFocus, + onBlur, + mode, + }; + if (props.showConfig.sDropDownType === 'sql') { + obj.optionLabelProp = 'title'; + } + if (props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !enabled; + } + obj.placeholder = props.showConfig.placeholder; + obj.dropdownStyle = commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase().indexOf('oee') > -1 ? { fontSize: '1.3rem' } : { fontSize: '12px' }; + if (props.bTable) { + obj.value = props.showConfig.bMultipleChoice && !commonUtils.isEmpty(dataValue) ? dataValue.split(',') : dataValue; + obj.className = styles.editSelect; + } + if (props.showConfig.iDropWidth > 0) { + obj.dropdownMatchSelectWidth = false; + obj.dropdownStyle.width = props.showConfig.iDropWidth; + } + obj.onInputKeyDown = onKeyDown; + obj.onKeyUp = onKeyUp; + /* 返回值 */ + return obj; + }; + + const getSearchProps = () => { + const obj = { + onChange: e => handleSelectOptionEvent(e.target.value), /* 数据改变回带到父组件 */ + value: commonUtils.isUndefined(dataValue) ? '选择' : commonUtils.strUndefinedToEmpty(dataValue), /* 数据值 */ + }; + return obj; + }; + + const getOptionValues = (data) => { + let res = ''; + let count = 1; + const iVisCount = commonUtils.isEmpty(props.showConfig.iVisCount) || props.showConfig.iVisCount === 0 ? 1 : props.showConfig.iVisCount; + if (commonUtils.isNotEmptyStr(props.showConfig.sVisColumnName)) { + res = data[props.showConfig.sVisColumnName]; + } else { + for (const key of Object.keys(data)) { + if (count <= iVisCount && key !== 'sId') { + if (res === '') { + res = data[key]; + } else { + res = res.concat('-').concat(data[key]); + } + count += 1; + } + } + } + return res; + }; + + const getInnerInput = (innerInputProps) => { + // console.log(innerInputProps, 'innerInputProps'); + if ((props.showConfig.sDropDownType === 'sql' || props.showConfig.sDropDownType === 'const') + && (firstDataIndex === 'i' || firstDataIndex === 'd' || firstDataIndex === 's')) { + if (props.showConfig.bCanInput) { + return {getSelectOption()}; + } else { + return ; + } + } else if (enabled && commonUtils.isNotEmptyObject(props.showConfig.sName) && props.showConfig.sDropDownType === 'popup') { /* 通用弹窗 */ + return (); + } else if (firstDataIndex === 'i' || firstDataIndex === 'd') { /* 数字输入框(整形i和浮点型d) */ + return innerInputProps.readOnly ? : ; + } else if (firstDataIndex === 'b') { /* 选择框(布尔类型b) */ + return {showName}; + } else if (firstDataIndex === 't') { /* 时间选择框(时间类型t) */ + return props.bTable ? : ; + } else if (firstDataIndex === 'm') { /* 月份选择框(月份类型m) */ + return props.bTable ? : ; + } else if (firstDataIndex === 'p') { /* 时间选择框(时间类型t) */ + return ; + } else if (firstDataIndex === 's') { /* 文本输入框(文本s) */ + if (props.textArea) { + return ; + } else { + return ; + } + } else if (firstDataIndex === 'c') { /* 地址联动框(联动下拉类型c) */ + return ; + } else { + return ; + } + }; + + const getSelectOption = () => { + const options = []; + const dropDownDataNew = commonUtils.isEmpty(searchValue) ? dropDownData : searchDropDownData; + if (commonUtils.isNotEmptyArr(dropDownDataNew)) { + for (const each of dropDownDataNew) { + if (commonUtils.isNotEmptyObject(each)) { + let keyValue = !commonUtils.isEmpty(each.sSlaveId) ? each.sSlaveId : each.sId; + if (firstDataIndex === 'i') { + keyValue = parseInt(keyValue, 0); + } else if (firstDataIndex === 'd') { + keyValue = parseFloat(keyValue); + } + let res = ''; + if (commonUtils.isNotEmptyStr(props.showConfig.sVisColumnName)) { + res = each[props.showConfig.sVisColumnName]; + } else { + res = Object.keys(each).length > 0 ? each[Object.keys(each)[0]] : ''; + } + keyValue = commonUtils.isEmpty(keyValue) ? '' : keyValue; + const option = props.showConfig.bCanInput ? + () : + (); + options.push(option); + } + } + } + if (searchValue === '') { + if (props.showConfig.bFirstEmpty) { + options.unshift(); + } + } + return options; + }; + + // const getFloatPrice = (floatNum) => { + // let floatPrice = ''; + // if (!commonUtils.isUndefined(floatNum)) { + // for (let i = 0; i < floatNum; i += 1) { + // floatPrice += '\\d'; + // } + // } + // return floatPrice; + // }; + + const getDropDownData = async (pageNum, totalPageCount, searchValue) => { + /** 下拉类型区分 + 1、判断是否直接传下拉,如果传了就直接用,并存储到store中去 + 2、没有传看 getStoreDropDownData有没有存储,存储后直接取用 + 3、 没有存储时直接调用后台SQL语句去下拉 */ + if (props.showConfig.sDropDownType === 'sql') { + if (pageNum <= totalPageCount) { + const sqlDropDownData = await props.getSqlDropDownData(props.formId, props.name, props.showConfig, props.record, searchValue, pageNum); + if (mounted) { + const dropDownDataNew = []; + if (commonUtils.isNotEmptyArr(sqlDropDownData.dropDownData)) { + if (pageNum !== 1) { + if (searchValue !== '') { + dropDownDataNew.push(...searchDropDownData); + } else { + dropDownDataNew.push(...dropDownData); + } + } + dropDownDataNew.push(...sqlDropDownData.dropDownData); + } + if (searchValue !== '') { + setSearchDropDownData(dropDownDataNew); + setSearchTotalPageCount(sqlDropDownData.totalPageCount); + setSearchPageNum(sqlDropDownData.currentPageNo); + setSearchValue(searchValue); + } else { + setDropDownData(dropDownDataNew); + setTotalPageCount(sqlDropDownData.totalPageCount); + setPageNum(sqlDropDownData.currentPageNo); + setSearchValue(''); + } + setConditonValues(sqlDropDownData.conditonValues); + setSpinState(false); + } + } + } + }; + + const getInnerInputProps = () => { + if (!props.bTable) { + /* 主表 */ + return getInnerInputPropsMaster(); + } else { + /* 主从表 */ + return getInnerInputPropsSlave(); + } + }; + + const getInnerInputPropsSlave = () => { + let obj = {}; + if (firstDataIndex === 'i' || firstDataIndex === 'd') { /* 数字输入框(整形i和浮点型d) */ + obj = getNumberInnerInputPropsSlave(); + } else if (firstDataIndex === 'b') { /* 选择框(布尔类型b) */ + obj = getBooleanInnerInputPropsSlave(); + } else if (firstDataIndex === 't' || firstDataIndex === 'p' || firstDataIndex === 'm') { /* 时间选择框(时间类型t) */ + obj = getDateInnerInputPropsSlave(); + } else if (firstDataIndex === 's') { /* 文本输入框(文本s) */ + obj = getTextInnerInputPropsSlave(); + obj.onDoubleClick = onDoubleClick; + } else if (firstDataIndex === 'c') { /* 地址联动框(联动下拉类型c) */ + obj = getAddressInnerInputPropsSlave(); + } + obj.onKeyDown = onKeyDown; + obj.onFocus = onFocus; + obj.onBlur = onBlur; + obj.onMouseEnter = onFocus; + obj.id = `${props.showConfig.sName}${props.record ? props.record.sId : commonUtils.createSid()}`; + return obj; + }; + + const getAddressInnerInputPropsSlave = () => { + const obj = { + placeholder: '请选择省市区', + options: getProvinceCityAreaData(), + changeOnSelect: true, + onChange: handleSelectOptionEvent, + value: commonUtils.isUndefined(dataValue) ? [] : typeof dataValue === 'string' ? + dataValue.split(',') : commonUtils.convertUndefinedToEmptyArr(dataValue), + }; + if (props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !enabled; + } + return obj; + }; + + const getTextInnerInputPropsSlave = () => { + const obj = { + id: `${props.showConfig.sName}${commonUtils.createSid()}`, + onChange: e => handleSelectOptionEvent(e), + value: commonUtils.isUndefined(dataValue) ? '' : commonUtils.strUndefinedToEmpty(dataValue), + // ref: (ref) => { + // // [props.showConfig.sName] = ref; + // console.log(ref); + // }, + onClick: handleInputOnClick(props.showConfig.sName), + }; + if (props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !enabled; + } + if (typeof commonUtils.convertStrToNumber(max) === 'number' && commonUtils.convertStrToNumber(max) !== 0 && max.indexOf('.d') === -1 && max.indexOf('.i') === -1) { + obj.maxLength = max; + } + obj.placeholder = props.showConfig.placeholder; + return obj; + }; + + const getDateInnerInputPropsSlave = () => { + let { sDateFormat } = props.showConfig; + if (commonUtils.isEmptyStr(sDateFormat)) { + if (firstDataIndex === 'm') { + sDateFormat = 'YYYY-MM'; + } else { + sDateFormat = props.getDateFormat(); + } + } + const obj = { + placeholder: '', + disabled: !enabled, + onChange: handleSelectOptionEvent, + format: sDateFormat, + disabledDate: getDataMaxAndMin, + }; + if (!enabled) { + obj.suffixIcon = ; + } + obj.value = commonUtils.isEmpty(dataValue) ? null : moment(dataValue); + return obj; + }; + + const getBooleanInnerInputPropsSlave = () => { + const obj = { + disabled: !enabled, + onChange: handleSelectOptionEvent, + checked: commonUtils.isUndefined(dataValue) ? false : commonUtils.converNumStrToBoolean(dataValue), + }; + return obj; + }; + + const getNumberInnerInputPropsSlave = () => { + const obj = { + id: `${props.showConfig.sName}${props.showConfig.sId}`, + className: styles.inputNum, + onChange: value => handleSelectOptionEvent(value), + // ref: (ref) => { + // console.log(ref); + // // [props.showConfig.sName] = ref; + // }, + onClick: handleInputOnClick(props.showConfig.sName), + }; + if (props.readOnly) { + obj.readOnly = true; + } else { + obj.disabled = !enabled; + } + if (typeof commonUtils.convertStrToNumber(max) === 'number' && commonUtils.convertStrToNumber(max) !== 0 && max.indexOf('.d') === -1 && max.indexOf('.i') === -1) { + obj.max = max; + } else if (!commonUtils.isEmpty(max) && max.indexOf('.') > -1 && commonUtils.isNotEmptyObject(props.record)) { + obj.max = props.record[max.substring(max.indexOf('.') + 1)]; + } + if (typeof commonUtils.convertStrToNumber(min) === 'number' && commonUtils.convertStrToNumber(min) !== 0) { + obj.min = min; + } + if (obj.max < 0) { /* 为解决收付款单据未收款为负数时收款金额不能大于未收款问题,当最大值小于0时,变更为设为最小值 */ + obj.min = obj.max; + obj.max = 0; + } + const numCheck = /^(-?\d+)(\.?)(\d{1,6})?$/; + if (!numCheck.test(dataValue) && dataValue) { + message.warning('最多6位小数'); + } + obj.value = dataValue; + obj.step = 0; + return obj; + }; + + const getInnerInputPropsMaster = () => { + let obj = {}; + if (firstDataIndex === 'i' || firstDataIndex === 'd') { /* 数字输入框(整形i和浮点型d) */ + obj = getNumberInnerInputPropsMaster(); + } else if (firstDataIndex === 'b') { /* 选择框(布尔类型b) */ + obj = getBooleanInnerInputPropsMaster(); + } else if (firstDataIndex === 't' || firstDataIndex === 'p' || firstDataIndex === 'm') { /* 时间选择框(时间类型t) */ + obj = getDateInnerInputPropsMaster(); + } else if (firstDataIndex === 's') { /* 文本输入框(文本s) */ + if (props.textArea) { /* 大文本输入框 */ + obj = getTextAreaInnerInputPropsMaster(); + obj.onDoubleClick = onDoubleClick; + } else { /* 普通文本输入框 */ + obj = getTextInnerInputPropsMaster(); + } + } else if (firstDataIndex === 'c') { /* 地址联动框(联动下拉类型c) */ + obj = getAddressInnerInputPropsMaster(); + } + obj.onKeyDown = onKeyDown; + obj.onKeyUp = onKeyUp; + obj.onContextMenu = onContextMenu; + return obj; + }; + + const getAddressInnerInputPropsMaster = () => { + const obj = { + placeholder: '请选择省市区', + options: getProvinceCityAreaData(), + changeOnSelect: true, + onChange: handleSelectOptionEvent, + }; + if (props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !enabled; + } + return obj; + }; + + const getTextInnerInputPropsMaster = () => { + /* 返回值声明 */ + const obj = { + id: `${props.showConfig.sName}${commonUtils.createSid()}`, + onChange: e => handleSelectOptionEvent(e), + // ref: (ref) => { + // // this[props.showConfig.sName] = ref + // console.log(ref); + // }, + onClick: handleInputOnClick(props.showConfig.sName), /* 虚拟数字键盘 第二个参数必须id */ + }; + if (props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !enabled; + } + if (props.bPassWord) { + obj.type = 'password'; /* 文本密码类型 */ + obj.autocomplete = 'off'; /* 禁止浏览器自动填充到表单 */ + } + if (typeof commonUtils.convertStrToNumber(max) === 'number' && commonUtils.convertStrToNumber(max) !== 0 && max.indexOf('.d') === -1 && max.indexOf('.i') === -1) { + obj.maxLength = max; + } + return obj; + }; + + const getTextAreaInnerInputPropsMaster = () => { + const obj = { + id: `${props.showConfig.sName}${commonUtils.createSid()}`, + rows: 1, + onChange: handleSelectOptionEvent, + // ref: (ref) => { + // // this[props.showConfig.sName] = ref; + // console.log(ref); + // }, + onClick: handleInputOnClick.bind(this, props.showConfig.sName), + }; + if (props.readOnly) { + obj.readOnly = 'readOnly'; + } else { + obj.disabled = !enabled; + } + if (typeof commonUtils.convertStrToNumber(max) === 'number' && commonUtils.convertStrToNumber(max) !== 0 && max.indexOf('.d') === -1 && max.indexOf('.i') === -1) { + obj.maxLength = max; + } + return obj; + }; + + const getDataMaxAndMin = (current) => { + return getDataMax(current) || getDataMin(current); + }; + + + const getDataMax = (current) => { + const tDate = props.showConfig.sMaxValue === 'now' ? moment() : moment(props.showConfig.sMaxValue); + return commonUtils.isNotEmptyStr(props.showConfig.sMinValue) && current.endOf('day') > tDate.endOf('day'); + }; + + const getDataMin = (current) => { + const tDate = props.showConfig.sMinValue === 'now' ? moment() : moment(props.showConfig.sMinValue); + return commonUtils.isNotEmptyStr(props.showConfig.sMinValue) && current.endOf('day') < tDate.endOf('day'); + }; + + const getDateInnerInputPropsMaster = () => { + let { sDateFormat } = props.showConfig; + if (commonUtils.isEmptyStr(sDateFormat)) { + if (firstDataIndex === 'm') { + sDateFormat = 'YYYY-MM'; + } else { + sDateFormat = props.getDateFormat(); + } + } + const obj = { + placeholder: '', + disabled: !enabled, + style: { width: '100%' }, + showTime: props.showTime, + format: props.showTime ? 'YYYY-MM-DD HH:mm:ss' : sDateFormat, + onChange: handleSelectOptionEvent, + disabledDate: getDataMaxAndMin, + }; + return obj; + }; + + const getBooleanInnerInputPropsMaster = () => { + const obj = { + disabled: !enabled, /* 是否显示 */ + onChange: handleSelectOptionEvent, /* 数据改变回带到父组件 */ + checked: commonUtils.isUndefined(dataValue) ? false : commonUtils.converNumStrToBoolean(dataValue), + }; + return obj; + }; + + const handleInputOnClick = (id) => { + // 判断是否是oee系统,否则不显示虚拟键盘 + if (commonUtils.isNotEmptyObject(props.formRoute) && props.formRoute.indexOf('/indexOee') > -1) { + if (VirtualKeyboard.isKeyBoard()) { // 关闭上次键盘 + VirtualKeyboard.closeKeyboard(); + } + const keyboardValue = {}; + if (commonUtils.isNotEmptyObject(props.dataValue)) { + keyboardValue.value = props.dataValue; + } else { + keyboardValue.value = ''; + } + // 重构,待完成 + VirtualKeyboard.showKeyboardSetState(keyboardValue, this, id); + } + }; + + const getNumberInnerInputPropsMaster = () => { + /* 如果是浮点型并且有格式规定,display类型需要变为block */ + let display = 'inline-block'; + if (firstDataIndex === 'd' && floatNum !== 0) { + display = 'block'; + } + const obj = { + id: `${props.showConfig.sName}${commonUtils.createSid()}`, + style: { width: 'auto', display, marginRight: 0 }, + onChange: handleSelectOptionEvent, + // ref: (ref) => { + // // this[props.showConfig.sName] = ref; + // console.log(ref); + // }, + onClick: handleInputOnClick(props.showConfig.sName), /* 虚拟数字键盘 第二个参数必须id */ + }; + if (props.readOnly) { + obj.readOnly = true; + } else { + obj.disabled = !enabled; + } + /* 最大值最小值 */ + if (typeof commonUtils.convertStrToNumber(max) === 'number' && commonUtils.convertStrToNumber(max) !== 0 && max.indexOf('.d') === -1 && max.indexOf('.i') === -1) { + obj.max = max; /* 最大值 */ + } else if (!commonUtils.isEmpty(max) && max.indexOf('.') > -1 && commonUtils.isNotEmptyObject(props.record)) { + obj.max = props.record[max.substring(max.indexOf('.') + 1)]; + } + if (typeof commonUtils.convertStrToNumber(min) === 'number' && commonUtils.convertStrToNumber(min) !== 0) { + obj.min = min; /* 最小值 */ + } + obj.placeholder = props.showConfig.placeholder; + return obj; + }; + + const getProvinceCityAreaData = () => { + const options = []; + getProvinceData(options); + getCityData(options); + getAreaData(options); + return options; + }; + + const getProvinceData = (options) => { + Provinces.forEach((childProvince) => { + options.push({ + value: childProvince.name, + label: childProvince.name, + code: childProvince.code, + children: [], + }); + }); + }; + + const getCityData = (options) => { + options.forEach((childProvince) => { + const cities = Cities.filter(item => item.provinceCode === childProvince.code); + if (cities.length > 0) { + cities.forEach((childCity) => { + childProvince.children.push({ + value: childCity.name, + label: childCity.name, + code: childCity.code, + children: [], + }); + }); + } + }); + }; + + const getAreaData = (options) => { + options.forEach((childProvince) => { + const cities = childProvince.children; + cities.forEach((childCity) => { + const areas = Areas.filter((item => item.cityCode === childCity.code)); + if (areas.length > 0) { + areas.forEach((area) => { + childCity.children.push({ + value: area.name, + label: area.name, + code: area.code, + }); + }); + } + }); + }); + }; + + const getOutFormItemProps = () => { + if (!props.bTable) { + /* 主表 */ + return getOutFormItemPropsMaster(); + } else { + /* 从表 */ + return getOutFormItemPropsSlave(); + } + }; + + const getOutFormItemPropsMaster = () => { + let obj = {}; + if (firstDataIndex === 'i' + || firstDataIndex === 'd' + || firstDataIndex === 'p' + || firstDataIndex === 't' + || firstDataIndex === 'm' + || firstDataIndex === 's' + || firstDataIndex === 'c') { + obj = { + label: props.showConfig.showName, + className: styles.formItemMargin, + ...formItemLayout, + }; + } else if (firstDataIndex === 'b') { + obj = { + label: props.showConfig.showName, + className: styles.formItemMag10, + ...formItemLayout, + }; + } + if (props.itemLabel === 'hide') { + delete obj.label; + } + return obj; + }; + + const getOutFormItemPropsSlave = () => { + let obj = {}; + if (firstDataIndex === 'i' + || firstDataIndex === 'd' + || firstDataIndex === 'c' + || props.showConfig.sDropDownType === 'sql' + || props.showConfig.sDropDownType === 'const') { + obj = { + className: styles.formItemMargin0, + }; + } else if (firstDataIndex === 'b') { + obj = { + className: styles.tableCheckBox, + }; + } else if (firstDataIndex === 't' || firstDataIndex === 'p' || firstDataIndex === 'm') { + obj = { + className: styles.tableDataPicker, + }; + } else if (firstDataIndex === 's') { + obj = { + className: styles.editInput, + }; + } + return obj; + }; + + const getFieldDecoratorProps = () => { + let obj = {}; + if (firstDataIndex === 'i' || firstDataIndex === 'd' || firstDataIndex === 't' || firstDataIndex === 'p' || firstDataIndex === 's' || firstDataIndex === 'b') { + obj = { rules: [{ required: props.showConfig.bNotEmpty, message: `${props.showConfig.showName}为必填项` }] }; + } else if (firstDataIndex === 'c') { + obj = { + initialValue: ['北京市', '市辖区', '东城区'], + rules: [{ required: props.showConfig.bNotEmpty, message: `${props.showConfig.showName}为必填项` }], + }; + } + return obj; + }; + + // const getPopupContainer = (triggerNode) => { + // const trigger = triggerNode; + // if (commonUtils.isNotEmptyObject(trigger)) { + // return triggerNode; + // } + // }; + + const handleSelectOptionEvent = (newValue, dateString) => { + if (newValue === undefined) return; + let value = firstDataIndex === 's' && !props.textArea && commonUtils.isEmpty(newValue) ? newValue.replace('--', '') : + firstDataIndex === 't' ? dateString : (firstDataIndex === 'd' || firstDataIndex === 'i') && commonUtils.isEmpty(newValue) ? 0 : newValue; + value = props.showConfig.bMultipleChoice ? value.toString() : value; + isDropdownFilter = true; + if (props.showConfig.sDropDownType === 'sql' && value === '@#*000@') { + props.handleSqlDropDownNewRecord(props.showConfig, props.name); + if (mounted) { + setDataValue(''); + } + return; + } + if (props.showConfig.sDropDownType === 'sql' && value === '=+@') { + value = ''; + } + if (props.showConfig.sDropDownType === 'const' && value === '=+@') { + value = ''; + } + const returnValue = {}; + const dropDownDataNew = commonUtils.isEmptyArr(searchValue) ? dropDownData : searchDropDownData; + /* 回带值赋值(sName:value) */ + returnValue[props.showConfig.sName] = + firstDataIndex === 'i' ? commonUtils.isEmpty(value) ? undefined : props.showConfig.sName === 'iOrder' ? value : parseInt(value, 0) : + firstDataIndex === 'd' ? commonUtils.isEmpty(value) ? undefined : floatNumberCheck(value) : + firstDataIndex === 't' ? commonUtils.isEmpty(value) ? null : value : + firstDataIndex === 'b' ? value.target.checked : value === null ? undefined : value; + if (!props.showConfig.bMultipleChoice) { + const { sAssignField } = props.showConfig; + const [changeData] = dropDownDataNew.filter(item => (!commonUtils.isEmpty(item.sSlaveId) ? item.sSlaveId : item.sId) === value.toString()); + if (!commonUtils.isEmpty(sAssignField)) { + const sAssignFieldObj = sAssignField.split(','); + if (commonUtils.isNotEmptyObject(changeData)) { + for (const child of sAssignFieldObj) { + if (child.indexOf(':') > -1) { + const sFieldName = child.split(':')[0].trim() === 'self' ? props.showConfig.sName : child.split(':')[0].trim(); + const sValueName = child.split(':')[1].trim(); + returnValue[sFieldName] = changeData[sValueName] || changeData.value; + } + } + } else if (!props.showConfig.bCanInput) { + for (const child of sAssignFieldObj) { + if (child.indexOf(':') > -1) { + const sFieldName = child.split(':')[0].trim() === 'self' ? props.showConfig.sName : child.split(':')[0].trim(); + returnValue[sFieldName] = ''; + } + } + } + } + } else { + const { sAssignField } = props.showConfig; + const changeData = dropDownDataNew.filter(item => (`,${value.toString()},`).includes((!commonUtils.isEmpty(item.sSlaveId) ? `,${item.sSlaveId},` : `,${item.sId},`))); + if (!commonUtils.isEmpty(sAssignField)) { + const sAssignFieldObj = sAssignField.split(','); + if (commonUtils.isNotEmptyArr(changeData)) { + for (const child of sAssignFieldObj) { + if (child.indexOf(':') > -1) { + const sFieldName = child.split(':')[0].trim() === 'self' ? props.showConfig.sName : child.split(':')[0].trim(); + const sValueName = child.split(':')[1].trim(); + const valueArr = []; + changeData.forEach((itemData) => { + valueArr.push(itemData[sValueName]); + }); + returnValue[sFieldName] = valueArr.toString(); + } + } + } else if (!props.showConfig.bCanInput) { + for (const child of sAssignFieldObj) { + if (child.indexOf(':') > -1) { + const sFieldName = child.split(':')[0].trim() === 'self' ? props.showConfig.sName : child.split(':')[0].trim(); + returnValue[sFieldName] = ''; + } + } + } + } + } + setSearchPageNum(0); + setSearchTotalPageCount(1); + setSearchDropDownData([]); + setSearchValue(''); + setSpinState(false); + props.onChange(props.name, props.showConfig.sName, returnValue, props.sId, dropDownDataNew); + }; + + const filterOption = (input, option) => { + const newInput = input.toString().trim(); + if (pageNum <= totalPageCount && props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(props.showConfig.dropDownData)) { + return true; + } else if (commonUtils.isNotEmptyObject(option.props.children)) { + return !isDropdownFilter && props.showConfig.bCanInput ? true : option.props.children.toLowerCase().indexOf(newInput.toLowerCase()) >= 0; + } + }; + + const floatNumberCheck = (num) => { + const checkRule = /^(-?\d+)(\.?)(\d{1,6})?$/; + if (!checkRule.test(num) && num && num !== '-' && num !== '.') { + message.warning('最多输入6位小数!'); + return undefined; + } else { + return num; + } + }; + + // const limitDecimals = (values) => { + // let reg = ''; + // if (floatNum > 0) { + // reg = `^(\\d+).(${floatPrice})*$`; + // } else { + // reg = '^(\\d+).(\\d\\d\\d\\d\\d\\d)*$'; + // } + // if (typeof values === 'string') { + // if (values !== undefined && values.indexOf('.') <= -1) { + // reg = '^(\\d+)*$'; + // return !isNaN(Number(values)) ? values.replace(new RegExp(reg), '$1') : ''; + // } else { + // return !isNaN(Number(values)) ? values.replace(new RegExp(reg), '$1.$2') : ''; + // } + // } else if (typeof values === 'number') { + // if (values !== undefined && String(values).indexOf('.') <= -1) { + // reg = '^(\\d+)*$'; + // return !isNaN(values) ? String(values).replace(new RegExp(reg), '$1') : ''; + // } else { + // return !isNaN(values) ? String(values).replace(new RegExp(reg), '$1.$2') : ''; + // } + // } else { + // return ''; + // } + // }; + + const handleViewClick = () => { + const { record, app, showConfig } = props; + const { sControlName, sActiveKey } = showConfig; + if (commonUtils.isNotEmptyObject(sControlName) && commonUtils.isNotEmptyObject(sActiveKey)) { + const printPdf = sControlName; + if (commonUtils.isNotEmptyObject(printPdf) && printPdf === 'printPdf' && commonUtils.isNotEmptyObject(sActiveKey)) { + const { token } = app; + const sActiveId = props.showConfig.sActiveId === '1' ? commonUtils.isEmpty(record.sFormId) ? record.sSrcFormId : record.sFormId : props.showConfig.sActiveId; + const printsId = record[sActiveKey]; + const urlPrint = `${commonConfig.file_host}printReport/printPdfByFromDataId?sModelsId=${sActiveId}&sId=${printsId}&token=${encodeURIComponent(token)}`; + window.open(urlPrint); + } else { + props.onViewClick(props.name, props.showConfig.sName, props.record); + } + } else { + props.onViewClick(props.name, props.showConfig.sName, props.record); + } + }; + + const handlePreviewImage = (e, dataUrl) => { + props.onPreviewImage(e, dataUrl); + }; + + const handleViewChoose = () => { + props.onViewChoose(props.name, props.showConfig.sName, props.record); + }; + + const handlePopupScroll = (e) => { + e.persist(); + const { target } = e; + if (Math.ceil(target.scrollTop + target.offsetHeight) >= target.scrollHeight && props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(props.showConfig.dropDownData)) { + const nextPageNum = pageNum + 1; + const nextSearchPageNum = searchPageNum + 1; + if (searchValue !== '') { + getDropDownData(nextSearchPageNum, searchTotalPageCount, searchValue); + } else { + getDropDownData(nextPageNum, totalPageCount, searchValue); + } + } + }; + + const handleSearch = (value) => { + if (dropDownTimer) { + clearTimeout(dropDownTimer); + } + dropDownTimer = setTimeout(() => { + if (props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(props.showConfig.dropDownData)) { + setSpinState(true); + getDropDownData(1, 1, value); + } + }, 500); + }; + + // 处理渲染函数 + const innerInputProps = getInnerInputProps(); + const innerInput = getInnerInput(innerInputProps); + const { sName } = props.showConfig; + let viewInfo = ''; + if (props.showConfig.sDropDownType !== 'popup' && !commonUtils.isEmpty(props.showConfig.sActiveId) && !commonUtils.isEmpty(props.showConfig.sActiveKey) && (commonUtils.isNotEmptyObject(props.dataValue) || commonUtils.isNotEmptyNumber(props.dataValue))) { + viewInfo = ( +
+ {props.dataValue} + +
); + } + const sModelsType = commonUtils.isNotEmptyObject(props) && commonUtils.isNotEmptyObject(props.app) ? props.app.currentPane.sModelsType : ''; + if (sName === 'sCombinedMemo' || sName === 'sColorSerialMemo' || (commonUtils.isNotEmptyObject(sModelsType) && !sModelsType.includes('Set') && sName === 'sCombinePartsNameNew')) { + let sValue = ''; + /* 将合版信息json解析成需要的字符串形式 */ + if (sName === 'sCombinedMemo') { + let JsonData = []; + if (commonUtils.isNotEmptyObject(props.dataValue)) { + try { + JsonData = JSON.parse(props.dataValue); + } catch (e) { + JsonData = []; + } + } + if (commonUtils.isNotEmptyArr(JsonData)) { + JsonData.forEach((item) => { + sValue += `${item.sProductNo}:排${item.dCombineQty}个,`; + }); + sValue = commonUtils.isNotEmptyObject(sValue) ? sValue.substr(0, sValue.length - 1) : ''; + } + } else if (sName === 'sColorSerialMemo') { + let JsonData = []; + if (commonUtils.isNotEmptyObject(props.dataValue)) { + try { + JsonData = JSON.parse(props.dataValue); + } catch (e) { + JsonData = []; + } + } + if (commonUtils.isNotEmptyArr(JsonData)) { + JsonData.forEach((item) => { + sValue += `${item.sName}+`; + }); + sValue = commonUtils.isNotEmptyObject(sValue) ? sValue.substr(0, sValue.length - 1) : ''; + } + } else { + sValue = props.dataValue; + } + viewInfo = ( +
+ {commonUtils.isNotEmptyObject(sValue) ? sValue : sName === 'sCombinedMemo' ? '合版信息' : '请选择'} + +
); + } + let speacilNote = ''; + const { record } = props; + if (commonUtils.isNotEmptyObject(record) && commonUtils.isEmptyObject(record[sName]) && commonUtils.isNotEmptyObject(sName) && (sName === 'tCreateDate' || sName === 'sMakePerson')) { + speacilNote = (
保存后自动生成
); + } + let imgBox = ''; + if (commonUtils.isNotEmptyObject(sName) && sName.indexOf('picture') > -1) { + const picAddr = commonUtils.isNotEmptyObject(record[sName]) ? record[sName].split(',') : ''; + if (commonUtils.isNotEmptyObject(picAddr)) { + const { token } = props.app; + const dataUrl = `${commonConfig.server_host}file/download?savePathStr=${picAddr}&scale=0.1&sModelsId=100&token=${token}`; /* 缩略图 */ + imgBox = ( +
+ + img 0} onMouseOver={e => handlePreviewImage(e, picAddr)} style={{ width: '30px', height: '20px' }} /> + +
); + } + } + const outFormItemProps = getOutFormItemProps(); + const fieldDecoratorProps = getFieldDecoratorProps(); + const commonAssembly = ( {viewInfo}{speacilNote}{imgBox}{!props.bTable ? getFieldDecorator(props.showConfig.sName, fieldDecoratorProps)(innerInput) : innerInput} ); + const { iColValue } = props; + return ( +
+
+ {commonAssembly} +
+
+ ); +} +export default CommonComponent; diff --git a/src/components/Common/CommonInstructSet.js b/src/components/Common/CommonInstructSet.js new file mode 100644 index 0000000..f587470 --- /dev/null +++ b/src/components/Common/CommonInstructSet.js @@ -0,0 +1,2581 @@ +/* eslint-disable */ + +import lodash from "lodash"; +import moment from "moment"; +import { Modal, notification } from "antd"; +import { message } from "@/utils/common/message"; +import * as commonUtils from "@/utils/utils"; +import * as commonFunc from "@/components/Common/commonFunc"; +import commonConfig from "@/utils/config"; +import * as commonServices from "@/services/services"; +import * as commonBusiness from "@/components/Common/commonBusiness"; +import FaceDetect from "@/components/FaceDetect"; + +let step = 1; // 步骤计数 +let exesqlTodo = []; // 最后需要一起执行的sql +let saveDataTodo = []; // 最后需要一起保存的数据 +let sendMsgDataTodo = {}; // 最后需要一起发送的消息 +let refreshTableList = []; // 最后需要刷新的表格 +let refreshParentTableList = []; // 最后需要刷新的父页面表格 +let possibleErrorList = []; // 可能的错误 +let changeTabName = ""; + +// 获取指令对应的方法 +const getOprFun = instruct => { + const { opr } = instruct; + outputInfo(instruct); + const myMap = { + fordo: handleForDo, + ifdo: handleIfDo, + + filter: handleFilter, + copy: handleCopy, + add: instruct.dataset || !instruct.srcDataset ? handleAddNew : handleAdd, + del: handleDel, + emptyAll: handleEmptyAll, + opensql: handleOpenSql, + exesql: handleExeSql, + edit: handleEdit, + console: handleConsole, + msg: handleMsg, + sendmsg: handleSendMsg, + + print: handlePrint, + faceauth: handleFaceAuth, + popup: handlePopup, + save: commonUtils.isNotEmptyArr(instruct.data) ? handleMesSave : handleSave, + refresh: handleRefresh, + closepop: handleClosePop, + procedure: handleProcedure, + changetab: handleChangeTab, + poprepair: handlePoprepair, + newempty: handleNewEmpty, + "": () => ({}) + }; + + const result = myMap[opr] || myMap[""]; + return result; +}; + +// 提示信息 +const showMsg = value => { + let params = { type: "info", content: "" }; + if (typeof value === "object") { + params = { + ...params, + ...value + }; + } else { + params.content = value; + } + + const { type, content } = params; + const title = type === "error" ? "指令集错误信息" : "指令集提示信息"; + + Modal[type]({ + width: 1000, + title: title, + content:
{content}
, + okText: "知道了" + }); +}; + +// 基础校验 +const instructCheck = props => { + let { btnConfig } = props; + + if (!btnConfig) { + const { btnName, masterConfig } = props; + btnConfig = masterConfig?.gdsconfigformslave?.find( + item => item.sControlName === btnName + ); + } + + if (!btnConfig) { + showMsg("没有找到按钮配置!"); + return false; + } + + const { sInstruct: sInstructStr } = btnConfig; + if (!sInstructStr) { + showMsg("指令集未配置!"); + return false; + } + + const sInstruct = commonUtils.convertStrToObj(sInstructStr, []); + + if (!sInstruct.length) { + showMsg({ + type: "error", + content: ( +
+
指令集格式错误!
+
错误指令集内容:
+
{sInstructStr}
+
+ ) + }); + return false; + } + + return sInstruct; +}; + +// 添加额外数据 +const addExtraData = props => { + // 转换页面定义的表名和sGrd + const { tableNameCompareJson = {} } = props; + if (commonUtils.isNotEmptyObject(tableNameCompareJson)) { + Object.keys(tableNameCompareJson).forEach(key => { + const value = tableNameCompareJson[key]; + if (props[`${value}Data`]) { + props[`${key}Data`] = props[`${value}Data`]; + props[`${key}Config`] = props[`${value}Config`]; + props[`${key}DelData`] = props[`${value}DelData`]; + props[`${key}SelectedRowKeys`] = props[`${value}SelectedRowKeys`]; + } + }); + } + + // 获取当前选中机台任务数据 + props.currentSelectedMachineTask = + props.app.globalData?.currentSelectedMachineTaskDataRow; + + // 获取当前开工机台任务数据 + props.currentStartWorkMachineTask = + props.app.globalData?.currentStartWorkMachineTaskDataRow; + + // 获取当前工单信息数据 + props.currentWorkOrderInfo = props.app.globalData?.currentWorkOrderInfo; +}; + +// 根据datasetList过滤出要保存到页面的数据 +const filterDataByDatasetList = (props, addState) => { + const { tableNameCompareJson = {} } = props; + const keyList = Object.keys(tableNameCompareJson); + + const { datasetList = [] } = addState; + const addStateNew = {}; + datasetList.forEach(tableNameOld => { + const tableName = keyList.includes(tableNameOld) + ? tableNameCompareJson[tableNameOld] + : tableNameOld; + + // 获取新增修改数据 + const tableData = addState[`${tableNameOld}Data`]; + if (tableData) { + addStateNew[`${tableName}Data`] = tableName.includes("master") + ? tableData[0] + : tableData; + } + + // 获取删除的数据 + const tableDelData = addState[`${tableNameOld}DelData`]; + if (tableDelData) { + addStateNew[`${tableName}DelData`] = tableDelData; + } + }); + return addStateNew; +}; + +/********************************************************** 入口函数 **********************************************************/ +const instructSet = async props => { + if (window.instructSetLock) return; // 防止连点 + try { + window.instructSetLock = true; + await instructSetInit(props); + } catch (error) { + console.log("=====", error); + props.onSaveState({ pageLoading: false }); + } + setTimeout(() => { + window.instructSetLock = false; + }, 500); +}; + +// 入口函数 -> 初始化 +const instructSetInit = async props => { + step = 1; + exesqlTodo = []; + saveDataTodo = []; + sendMsgDataTodo = {}; + refreshTableList = []; + refreshParentTableList = []; + possibleErrorList = []; + changeTabName = ""; + + // 基础校验 + const sInstruct = instructCheck(props); + if (!sInstruct) return; + + // 添加额外数据 + addExtraData(props); + + props.onSaveState({ pageLoading: true }); + + console.log("=====sInstruct", sInstruct); + + let addState = {}; + + for (let i = 0; i < sInstruct.length; i++) { + const instruct = sInstruct[i]; + const operationFun = getOprFun(instruct); + const resultData = await operationFun({ ...props, ...addState }, instruct); + + addState = { + ...addState, + ...resultData + }; + } + + // 是否要关闭弹窗 + const bClosePop = addState.closePop; + + // 根据datasetList过滤出要保存到页面的数据 + const addStateNew = filterDataByDatasetList(props, addState); + + console.log("=====保存到页面的数据", addStateNew); + console.log("=====最后需要一起执行的sql", exesqlTodo); + if (possibleErrorList.length) { + console.log("=====可能存在的问题====="); + possibleErrorList.forEach(({ instruct, content }, index) => { + console.log(`=====${index + 1}、指令集`, instruct, content); + }); + } + + handleExeSqlAll(props, () => { + handleMesSaveAll(props, () => { + handleSendMsgAll(props); + + // const { showName } = props.btnConfig; + // notification.success({ + // message: `【${showName}】指令集执行完成!`, + // placement: "topRight", + // duration: 3 + // }); + console.log("=====页面需要刷新的表格:", refreshTableList); + props.onSaveState({ + ...addStateNew, + refreshTableList, + pageLoading: false + }); + + console.log("=====父页面需要刷新的表格:", refreshParentTableList); + if (refreshParentTableList.length) { + const { parentProps } = props; + parentProps.onSaveState({ + refreshTableList: refreshParentTableList + }); + } + + if (bClosePop) { + const { app } = props; + setTimeout(() => { + app.globalFun.onCloseCommonModal({ type: "commonModal" }); + }, 300); + } + + if (changeTabName) { + utils.changeTabName(); + } + + props.callback && props.callback(); + }); + }); +}; + +/********************************************************** 指令集 **********************************************************/ + +// 循环操作 +const handleForDo = async (props, instructTotal) => { + const { dataset, fordoset = `${dataset}One`, foropr } = instructTotal; + const { [`${dataset}Data`]: tableData } = props; + + // 最后的返回值 + let forOneResult = {}; + for (let i = 0; i < tableData.length; i++) { + const fordosetName = fordoset; + const fordosetData = tableData[i]; + + for (let j = 0; j < foropr.length; j++) { + const instruct = foropr[j]; + const operationFun = getOprFun(instruct); + forOneResult = { + ...forOneResult, + ...(await operationFun( + { ...props, fordosetName, fordosetData, ...forOneResult }, + instruct + )) + }; + } + } + + console.log("=====【fordo】返回结果: ", forOneResult); + return forOneResult; +}; + +// 条件操作 +const handleIfDo = async (props, instruct) => { + const { fordosetName, fordosetData } = props; + const { conditions, dataset = "" } = instruct; + + const datasetListExtra = {}; + dataset + .split(",") + .filter(item => item) + .forEach(item => { + const [tableName, filterType] = item.split("@"); + const filterData = utils.getFilterData(props, tableName, filterType); + datasetListExtra[tableName] = filterData[0]; + }); + + let result = {}; + for (let i = 0; i < conditions.length; i++) { + const item = conditions[i]; + const { condition, commands } = item; + // 判断是否满足条件 + const bMatch = utils.bMatchCondition(props, item, datasetListExtra); + if (!bMatch) continue; + + console.log("=====commands", commands); + let ifDoResult = {}; + for (let j = 0; j < commands.length; j++) { + // if (j > 10) continue; + const command = commands[j]; + const operationFun = getOprFun(command); + const resultData = await operationFun( + { ...props, ...ifDoResult }, + command + ); + if (resultData.stop) { + continue; + } + ifDoResult = { + ...ifDoResult, + ...resultData + }; + } + result = { ...result, ...ifDoResult }; + console.log("=====ifDoResult", ifDoResult); + } + + return result; +}; + +// 过滤操作 +const handleFilter = (props, instruct) => { + const { + srcDataset, + newDataset, + fordoset = `${srcDataset}One`, + dataset, + condition + } = instruct; + + // 源数据 + const [tableName, filterType] = srcDataset.split("@"); + const srcData = utils.getFilterData(props, tableName, filterType); + + // 过滤后数据 + const newData = srcData.filter(item => + utils.bMatchCondition(props, instruct, { + [fordoset]: item + }) + ); + + const result = { + [`${newDataset}Data`]: newData + }; + + outputResult(result); + return result; +}; + +/************************* 复制指令 copy ************************/ +const handleCopy = (props, instruct) => { + const { srcDataset, newDataset } = instruct; + + const { dataList = [] } = utils.getDatasetDataList( + props, + instruct, + "srcDataset" + ); + let srcData = dataList[0] || []; + + // 如果数据源是循环的那条数据 + const { fordosetName, fordosetData } = props; + if (fordosetName && srcDataset === fordosetName && fordosetData) { + srcData = [fordosetData]; + } + + if (!srcData.length) { + showMsg({ + content: "error", + content: ( +
+
{`【${srcDataset}】数据源为空`}
+
请检查该复制指令集:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error(`【${srcDataset}】数据源为空`); + } + + // 获取赋值后的数据 + let srcDataNew = utils.getDataAfterAssign(props, instruct, srcData); + + srcDataNew = srcDataNew.map(item => ({ + sParentId: props.masterData?.sId || props.currentId || "", + ...item, + sId: commonUtils.createSid(), + handleType: "add" + })); + + const resultData = [...srcDataNew]; + + const result = { [`${newDataset}Data`]: resultData }; + + outputResult(result); + return result; +}; + +/************************* 新增指令(旧)(没有dataset) add ************************/ +const handleAdd = (props, instruct) => { + const { desDataset, srcDataset } = instruct; + const { + [`${srcDataset}Data`]: srcData = [], + [`${desDataset}Data`]: desData = [], + datasetList = [] + } = props; + + const datasetListNew = datasetList.includes(desDataset) + ? datasetList + : [...datasetList, desDataset]; + + const srcDataNew = srcData.map(item => ({ + sParentId: props.masterData?.sId || props.currentId || "", + ...item, + sId: commonUtils.createSid(), + handleType: "add" + })); + + const result = { + [`${desDataset}Data`]: [...desData, ...srcDataNew], + datasetList: datasetListNew + }; + outputResult(result); + return result; +}; +/************************* 新增指令(新)(有dataset) add ************************/ +const handleAddNew = (props, instruct) => { + const { desDataset, dataset, sValue = "" } = instruct; + + if (!desDataset) { + showMsg({ + type: "error", + content: ( +
+
被新增的数据集desDataset不能为空!
+
请检查该新增指令集:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error("被新增的数据集desDataset不能为空!"); + } else if (desDataset.includes("@") || desDataset.includes(",")) { + showMsg({ + type: "error", + content: ( +
+
被新增的数据集desDataset不支持@或,写法!
+
请检查该新增指令集:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error("被新增的数据集desDataset不支持@或,写法!"); + } + + const { + dataobj = {}, + dataNameList = [], + dataList = [] + } = utils.getDatasetDataList(props, instruct); + + let dataLengthList = [1]; + // 校验是否有空数据集 + const dataLengthListNew = dataList.map((item = [], index) => { + if (item.length === 0) { + showMsg({ + type: "error", + content: ( +
+
{`【${dataNameList[index]}】数据源为空`}
+
请检查该新增指令集:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error(`【${dataNameList[index]}】数据源为空`); + } + return item.length; + }); + dataLengthList = dataLengthListNew.length + ? dataLengthListNew + : dataLengthList; + + // 校验所有数据集的长度是否一致 + const dataLengthSet = new Set(dataLengthList); + if (dataLengthSet.size !== 1) { + showMsg({ + type: "error", + content: ( +
+
{`【${dataset}】数据源长度不一致`}
+
请检查该新增指令集:
+
{JSON.stringify(instruct)}
+
过滤后的数据为:
+
{JSON.stringify(dataobj)}
+
+ ) + }); + throw new Error(`【${dataset}】数据源长度不一致`); + } + + const addData = []; + for (let i = 0; i < dataLengthList[0]; i++) { + let rowData = {}; + + // 优先级低的默认参数 + const rowDataAdd0 = { + sParentId: props.masterData?.sId || props.currentId || "" + }; + const rowDataAdd = { + handleType: "add", + sId: commonUtils.createSid() + }; + + const dataOneObj = dataList.reduce((prev, item, index) => { + return { + ...prev, + [dataNameList[index]]: item[i] + }; + }, {}); + + if (!sValue || sValue === "*") { + // 全部字段 + rowData = { + ...rowDataAdd0, + ...Object.values(dataOneObj).reduce((prev, item) => { + return { + ...prev, + ...item + }; + }, {}), + ...rowDataAdd + }; + } else { + // 指定字段 + rowData = utils.getRowDataByValue( + props, + instruct, + dataOneObj, + dataNameList + ); + + rowData = { + ...rowDataAdd0, + ...rowData, + ...rowDataAdd + }; + } + + addData.push(rowData); + } + + const { [`${desDataset}Data`]: oldData = [], datasetList = [] } = props; + const datasetListNew = datasetList.includes(desDataset) + ? datasetList + : [...datasetList, desDataset]; + const result = { + datasetList: datasetListNew, + [`${desDataset}Data`]: [...oldData, ...addData] + }; + outputResult(result); + + return result; +}; + +// 删除指令 +const handleDel = (props, instruct) => { + const { desDataset } = instruct; + + const [tableName] = desDataset.split("@"); + const fordoset = `${tableName}One`; + + const { + [`${tableName}Data`]: data = [], + [`${tableName}DelData`]: delData = [], + datasetList = [] + } = props; + + const { dataList = [] } = utils.getDatasetDataList( + props, + instruct, + "desDataset" + ); + + const filterData = dataList[0]; + if (commonUtils.isEmptyArr(filterData)) { + possibleErrorList.push({ + instruct, + content: `【${tableName}】过滤后的数据为空` + }); + } + + const delDataNew = filterData + .filter(item => + utils.bMatchCondition(props, instruct, { + [fordoset]: item + }) + ) + .map(item => ({ + ...item, + handleType: "del" + })); + + let result = {}; + if (commonUtils.isNotEmptyArr(delDataNew)) { + const dataNew = data.filter( + item => !delDataNew.some(del => del.sId === item.sId) + ); + + const datasetListNew = datasetList.includes(tableName) + ? datasetList + : [...datasetList, tableName]; + + result = { + datasetList: datasetListNew, + [`${tableName}Data`]: dataNew, + [`${tableName}DelData`]: [...delData, ...delDataNew] + }; + } + outputResult(result); + return result; +}; + +// 清空数据集 +const handleEmptyAll = (props, instruct) => { + const { desDataset } = instruct; + const list = desDataset.split(","); + + const { datasetList = [] } = props; + + const datasetListNew = [...datasetList]; + + const result = {}; + list.forEach(tableName => { + result[`${tableName}Data`] = []; + if (!datasetListNew.includes(tableName)) { + datasetListNew.push(tableName); + } + }); + + result.datasetList = datasetListNew; + + outputResult(result); + return result; +}; + +/************************* 编辑指令 edit todo ************************/ +const handleEdit = (props, instruct) => { + const editData = utils.getDataAfterConditionAndAssign( + props, + instruct, + "desDataset" + ); + + const editDataNew = editData.map(item => ({ + ...item, + handleType: item.handleType || "update" + })); + + const { datasetList = [] } = props; + const { desDataset } = instruct; + + const [tableName] = desDataset.split("@"); + let tableData = props[`${tableName}Data`]; + + tableData = Array.isArray(tableData) ? tableData : [tableData]; + + const tableDataNew = tableData.map(rowData => { + const iIndex = editDataNew.findIndex(item => item.sId === rowData.sId); + if (iIndex !== -1) { + return editDataNew[iIndex]; + } else { + return rowData; + } + }); + + const datasetListNew = datasetList.includes(tableName) + ? datasetList + : [...datasetList, tableName]; + const result = { + datasetList: datasetListNew, + [`${tableName}Data`]: tableDataNew + }; + + outputResult(result); + return result; +}; + +// 弹窗指令 +const handlePopup = (props, instruct) => { + const { sActiveId, sActiveName } = props.btnConfig; + const { title = sActiveName, dataset } = instruct; + + // 获取sqlCondition值 + let sParentConditions = {}; + if (dataset) { + dataset + .split(",") + .filter(item => item) + .forEach(item => { + const [tableName, filterType] = item.split("@"); + const filterData = utils.getFilterData(props, tableName, filterType); + const record = filterData[0]; + sParentConditions = { + ...sParentConditions, + ...props.getSqlCondition(props.btnConfig, tableName, record) + }; + }); + } + + props.onOpenCommonModal({ + type: "commonModal", + sActiveId, + title, + sParentConditions, + parentProps: props, + onOk: data => { + console.log("=====onOk", data); + }, + onCancel: () => { + console.log("=====onCancel"); + } + }); + + return {}; +}; + +// 保存指令(表单模式保存)(指令里没有data属性) +const handleSave = (props, instruct) => { + props.onSaveState({ pageLoading: true }); + // 获取主表数据 + const { masterData, masterConfig } = props; + if (commonUtils.isEmpty(masterConfig)) { + throw new Error("请先配置主表后再保存!"); + } + // 校验主表数据 + if (!commonBusiness.validateMaster(masterConfig, masterData, props)) { + props.onSaveState({ pageLoading: false }); + throw new Error("主表校验失败!"); + } + // 获取从表数据 + const allSlaveData = commonFunc.getAllTableData(props); + // 校验从表数据 + const keyList = Object.keys(allSlaveData).filter(item => item !== "master"); + for (let i = 0; i < keyList.length; i++) { + const key = keyList[i]; + const slaveConfig = props[`${key}Config`]; + const slaveData = allSlaveData[key]; + if (!commonBusiness.validateTable(slaveConfig, slaveData, props)) { + props.onSaveState({ pageLoading: false }); + throw new Error("从表校验失败!"); + } + } + // 保存接口 + const data = []; + Object.keys(allSlaveData).forEach(key => { + const config = props[`${key}Config`]; + const saveTmpData = key === "master" ? [masterData] : props[`${key}Data`]; + const delTmpData = key === "master" ? null : props[`${key}DelData`]; + data.push( + commonBusiness.mergeData(key, config.sTbName, saveTmpData, delTmpData) + ); + }); + + if (masterData.sId) { + utils.saveData(props, { + data, + sClientType: "1", + sSysLogSrcId: masterData.sId + }); + } + + return {}; +}; + +/************************* 保存指令(单表保存)(指令里有data属性) save ************************/ +const handleMesSave = (props, instruct) => { + const { data = [], doNotRefresh } = instruct; + const saveData = []; + + const name2maxBillNoMap = {}; + + for (let i = 0; i < data.length; i++) { + const item = data[i]; + const { tablename, srcDataset, maxBillNo } = item; + name2maxBillNoMap[srcDataset] = maxBillNo; + if (!tablename || !srcDataset) { + showMsg({ + type: "error", + content: ( +
+
+ 保存指令集data中的tablename和srcDataset为必填项,请检查该指令集配置! +
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error( + "保存指令集data中的tablename和srcDataset为必填项,请检查该指令集配置!" + ); + } + const { + [`${srcDataset}Data`]: tableData = [], + [`${srcDataset}DelData`]: delData = [], + [`${srcDataset}Config`]: config = {} + } = props; + + const saveTmpData = + srcDataset.includes("master") && !Array.isArray(tableData) + ? [tableData] + : tableData; + const delTmpData = srcDataset.includes("master") ? null : delData; + + if ( + commonUtils.isNotEmptyObject(config) && + !commonBusiness.validateTable(config, saveTmpData, props) + ) { + throw new Error("数据校验失败!"); + } + + saveData.push( + commonBusiness.mergeData(srcDataset, tablename, saveTmpData, delTmpData) + ); + } + + saveDataTodo = [ + ...saveDataTodo, + ...saveData + .filter(item => commonUtils.isNotEmptyArr(item.column)) + .map(({ sTable, name, column }) => { + if (!doNotRefresh) { + handleRefresh(props, { dataset: name }); + } + return { + tablename: sTable, + srcDataset: column, + maxBillNo: name2maxBillNoMap[name] + }; + }) + ]; + console.log("=====saveDataTodo", saveDataTodo); + return {}; +}; + +// 保存指令(单表保存)-> 批量保存 +const handleMesSaveAll = async (props, onSucess) => { + if (!saveDataTodo.length) { + onSucess && onSucess(); + return; + } + + const { sModelsId, app } = props; + const { token } = app; + const dataUrl = `${ + commonConfig.server_host + }instruct/save?sModelsId=${sModelsId}`; + const values = { + opr: "save", + data: saveDataTodo + }; + const dataReturn = (await commonServices.postValueService( + token, + values, + dataUrl + )).data; + + if (dataReturn.code === 1) { + onSucess && onSucess(); + } else { + props.onSaveState({ pageLoading: false }); + showMsg({ + type: "error", + content: ( +
+
save接口报错!
+
请求地址:
+
{dataUrl}
+
传入参数:
+
{JSON.stringify(values)}
+
报错信息
+
{JSON.stringify(dataReturn)}
+
+ ) + }); + } +}; + +/************************* 刷新指令 refresh ************************/ +const handleRefresh = (props, instruct) => { + const { dataset = "*" } = instruct; + + // 全部刷新 + if (dataset === "*") { + refreshTableList.push("*"); + return {}; + } + + const tableList = dataset.split(","); + + // 指定表格刷新(当前页面) + tableList + .filter(item => item && !item.includes("parent.")) + .forEach(tableName => { + let tableNameNew = tableName; + const { tableNameCompareJson = {} } = props; + if (commonUtils.isNotEmptyObject(tableNameCompareJson)) { + tableNameNew = tableNameCompareJson[tableName] || tableName; + } + + const tableConfig = props[`${tableNameNew}Config`]; + if (!tableConfig) { + possibleErrorList.push({ + instruct, + content: `未找到【${tableName}】对应的表格/表单` + }); + } + + if (refreshTableList.includes(tableNameNew)) return; + refreshTableList.push(tableNameNew); + }); + + // 指定表格刷新(父页面) + tableList + .filter(item => item && item.includes("parent.")) + .forEach(tableName => { + let tableNameNew = tableName.replace("parent.", ""); + const { parentProps = {} } = props; + const { tableNameCompareJson = {} } = parentProps; + if (commonUtils.isNotEmptyObject(tableNameCompareJson)) { + tableNameNew = tableNameCompareJson[tableNameNew] || tableNameNew; + } + + const tableConfig = parentProps[`${tableNameNew}Config`]; + if (!tableConfig) { + possibleErrorList.push({ + instruct, + content: `未找到【${tableName}】对应的表格/表单` + }); + } + + if (refreshParentTableList.includes(tableNameNew)) return; + refreshParentTableList.push(tableNameNew); + }); + + return {}; +}; + +// console指令 +const handleConsole = (props, instruct) => { + const { srcDataset = "" } = instruct; + if (!srcDataset) return {}; + const datasetList = srcDataset.split(","); + datasetList.map(tableName => { + const { [`${tableName}Data`]: data } = props; + console.log(`=====数据源【${tableName}】: `, data); + }); + return {}; +}; + +/************************* 消息指令 msg ************************/ +const handleMsg = async (props, instruct) => { + const { msg: msgOld, code, time = 3 } = instruct; + + let msg = msgOld; + if (msg && msg.includes("${")) { + msg = handleComputeData(props, msg, { + ...utils.getDatasetDataList(props, instruct).dataOneObj + }); + } + + if (code === 1) { + message.success(msg, time); + } else if (code === -1) { + message.error(msg, time); + throw new Error(msg); + } else if (code === 2) { + Modal.info({ + title: "温馨提示:", + content:
{msg}
, + okText: "确认", + onOk() {} + }); + } else if (code === -7) { + const result = await new Promise(resolve => { + Modal.confirm({ + title: "温馨提示:", + content:
{msg}
, + okText: "确认", + cancelText: "取消", + onOk() { + resolve(true); + }, + onCancel() { + resolve(false); + } + }); + }); + if (!result) { + throw new Error(); + } + } else if (code === -8) { + Modal.error({ + title: "错误提示:", + content:
{msg}
, + okText: "确认", + onOk() {} + }); + throw new Error(msg); + } else { + message.warning(msg, time); + } + + return {}; +}; + +/************************* 发送消息指令 sendmsg ************************/ +// 发送消息 -> 暂存消息,数据保存完后一起执行 +const handleSendMsg = (props, instruct) => { + const { dataList } = utils.getDatasetDataList(props, instruct, "srcDataset"); + const result = { + ...instruct, + srcDataset: dataList[0] + }; + sendMsgDataTodo = result; + outputResult(result); + return {}; +}; + +const handleSendMsgAll = async props => { + if (commonUtils.isEmptyObject(sendMsgDataTodo)) return; + + const { sModelsId, app } = props; + const { token } = app; + const dataUrl = `${ + commonConfig.server_host + }instruct/sendmsg?sModelsId=${sModelsId}`; + const values = sendMsgDataTodo; + const dataReturn = (await commonServices.postValueService( + token, + values, + dataUrl + )).data; + + if (dataReturn.code === 1) { + message.success(dataReturn.msg || "消息发送成功!"); + } else { + props.onSaveState({ pageLoading: false }); + showMsg({ + type: "error", + content: ( +
+
sendmsg接口报错!
+
请求地址:
+
{dataUrl}
+
传入参数:
+
{JSON.stringify(values)}
+
报错信息
+
{JSON.stringify(dataReturn)}
+
+ ) + }); + } +}; + +/************************* 打印指令 print ************************/ +const handlePrint = (props, instruct) => { + const { sModelsId, app } = props; + const { token } = app; + + const { reportName, reportType } = instruct; + + const { dataObj = {} } = utils.getDatasetDataList( + props, + instruct, + "srcDataset" + ); + + for (const tableName in dataObj) { + const tableData = dataObj[tableName]; + if (commonUtils.isEmptyArr(tableData)) { + possibleErrorList.push({ + instruct, + content: `未获取到数据源【${tableName}】的数据` + }); + } + } + + if (!reportName) { + showMsg({ + type: "error", + content: ( +
+
报表名称不能为空!
+
请检查打印报表指令集:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error("打印报表名称不能为空!"); + } + + const dataUrl = `${ + commonConfig.server_host + }printReport/printInstruct/${reportName}`; + + const params = { + sModelsId, + token, + slaveOneData: JSON.stringify(dataObj), + reportType + }; + console.log("=====打印时form表单提交的参数", params); + + handleOpenPost(dataUrl, params); + + return {}; +}; + +// 打印指令 -> 打开打印页面 +const handleOpenPost = ( + url, + { sModelsId, token, slaveOneData, reportType } +) => { + const newWin = window.open(); + let formStr = ""; + formStr = + `
` + + `` + + `` + + `` + + `` + + ""; + newWin.document.body.innerHTML = formStr; + newWin.document.forms[0].submit(); + return newWin; +}; + +// 人脸识别 +const handleFaceAuth = async (props, instruct) => { + let result = {}; + result = await new Promise(resolve => { + const modal = Modal.info({ + title: "人脸识别", + content: ( + { + const resultRowData = e.dataset.rows[0]; + const { newDataset } = instruct; + const { datasetList = [] } = props; + const datasetListNew = datasetList.includes(newDataset) + ? datasetList + : [...datasetList, newDataset]; + const resultData = { + datasetList: datasetListNew, + [`${newDataset}Data`]: [resultRowData] + }; + resolve(resultData); + modal.destroy(); + }} + actionType={"identifyFace"} + /> + ), + wrapClassName: "xlyFaceAuthModal", + okText: "取消", + onOk() { + resolve({ + stop: true + }); + } + }); + }); + outputResult(result); + return result; +}; + +/************************* 查询sql opnsql ************************/ +const handleOpenSql = async (props, instruct) => { + const { + app, + currentSelectedMachineTask, + currentStartWorkMachineTask, + currentWorkOrderInfo + } = props; + const { userinfo } = app; + + const { data = [] } = instruct; + + let result = {}; + + for (let i = 0; i < data.length; i++) { + const item = data[i]; + + let srcDatasetRow = {}; + const { dataNameList = [], dataList = [] } = utils.getDatasetDataList( + props, + item, + "srcDataset" + ); + + if (!dataList.length) { + const { sSqlCondition } = item; + if (sSqlCondition.includes("userinfo")) { + srcDatasetRow = { + ...srcDatasetRow, + ...userinfo + }; + } + if (sSqlCondition.includes("currentWorkOrderInfo")) { + srcDatasetRow = { + ...srcDatasetRow, + ...currentWorkOrderInfo + }; + } + if (sSqlCondition.includes("currentSelectedMachineTask")) { + srcDatasetRow = { + ...srcDatasetRow, + ...currentSelectedMachineTask + }; + } + if (sSqlCondition.includes("currentStartWorkMachineTask")) { + srcDatasetRow = { + ...srcDatasetRow, + ...currentStartWorkMachineTask + }; + } + } + + dataList.forEach((data = [], index) => { + if (!data.length) { + showMsg({ + type: "error", + content: ( +
+
{`获取${dataNameList[index]}数据集数据为空!`}
+
错误指令集内容:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error(`获取${dataNameList[index]}数据集数据为空!`); + } + srcDatasetRow = { + ...srcDatasetRow, + ...data[0] + }; + }); + + const resultData = await handleGetSqlValue(props, item, srcDatasetRow); + + resultData.forEach((item = {}) => { + const itemNew = {}; + Object.keys(item).forEach(key => { + if (!key.endsWith("Data")) { + itemNew[`${key}Data`] = item[key]; + } else { + itemNew[key] = item[key]; + } + }); + + result = { ...result, ...itemNew }; + }); + } + + outputResult(result); + return result; +}; + +// 查询sql -> 调用查询接口 +const handleGetSqlValue = async (props, data, srcDatasetRow = {}) => { + const { sModelsId, app } = props; + const { token } = app; + const dataUrl = `${ + commonConfig.server_host + }instruct/opensql?sModelsId=${sModelsId}`; + const values = { + opr: "opensql", + data: [ + { + ...data, + srcDataset: [srcDatasetRow] + } + ] + }; + const dataReturn = (await commonServices.postValueService( + token, + values, + dataUrl + )).data; + + if (dataReturn.code === 1) { + const { rows = [] } = dataReturn.dataset; + + if (!rows.length) { + possibleErrorList.push({ + instruct: values, + content: "返回结果为空" + }); + } + return rows; + } else { + showMsg({ + type: "error", + content: ( +
+
opensql查询接口报错!
+
请求地址:
+
{dataUrl}
+
传入参数:
+
{JSON.stringify(values)}
+
报错信息
+
{JSON.stringify(dataReturn)}
+
+ ) + }); + throw new Error("opensql指令执行失败!"); + } +}; + +/************************* 执行sql exesql ************************/ +// 执行sql -> 暂存sql,全部执行完后一起执行 +const handleExeSql = (props, instruct) => { + const { data = [] } = instruct; + const result = []; + data.forEach(item => { + const { sql, srcDataset } = item; + + const { dataList = [] } = utils.getDatasetDataList( + props, + item, + "srcDataset" + ); + + const resultData = dataList[0] || []; + + if (srcDataset && dataList.length && commonUtils.isEmptyArr(dataList[0])) { + showMsg({ + type: "error", + content: ( +
+
{`获取${srcDataset}数据集数据为空!`}
+
错误指令集内容:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error(`获取${srcDataset}数据集数据为空!`); + } + + result.push({ + sql, + srcDataset: resultData + }); + }); + + outputResult(result); + exesqlTodo = [...exesqlTodo, ...result]; + return {}; +}; + +/************************* 关闭弹窗指令 closepop ************************/ +const handleClosePop = (props, instruct) => { + return { closePop: true }; +}; + +/************************* 执行存储过程 procedure ************************/ +const handleProcedure = async (props, instruct) => { + const { config = {}, bRefresh = false } = instruct; + + if (commonUtils.isEmptyObject(config)) { + showMsg({ + type: "error", + content: ( +
+
存储过程配置为空!
+
请检查该指令集:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error("存储过程配置为空!"); + } + + const result = await new Promise(resolve => { + props.onProcedureCall({ + btnConfig: { sButtonParam: JSON.stringify(config) }, + onSuccess: () => { + resolve(true); + }, + onConfirm: () => { + resolve(true); + }, + onError: () => { + resolve(false); + }, + nextProps: props + }); + }); + + if (!result) { + throw new Error("存储过程执行失败!"); + } else if (bRefresh) { + // 等待刷新后继续执行剩余指令集 + const { btnConfig, tableLineParams, callback } = props; + const { sInstruct: sInstructStr } = btnConfig; + let sInstructNew = commonUtils.convertStrToObj(sInstructStr, []); + const iIndex = sInstructNew.findIndex(item => item.opr === "procedure"); + sInstructNew = sInstructNew.filter((_, index) => index > iIndex); + + const addState = {}; + if (sInstructNew.length) { + addState.onDoInstructAfterProcedure = () => { + props.onExecInstructSet({ + btnConfig: { ...btnConfig, sInstruct: JSON.stringify(sInstructNew) }, + tableLineParams, + callback + }); + }; + } + + props.onSaveState({ refreshTableList: ["*"], ...addState }); + throw new Error("存储过程执行成功!"); + } else { + console.log("=====执行存储过程成功(未刷新页面)"); + return {}; + } +}; + +/************************* 跳转tab页 changetab ************************/ +const handleChangeTab = (props, instruct) => { + const { tabName } = instruct; + if (!tabName) { + showMsg({ + type: "error", + content: ( +
+
跳转tab页指令未配置tabName!
+
请检查该指令集:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error("跳转tab页指令未配置tabName!"); + } + changeTabName = tabName; + return {}; +}; + +/************************* 弹窗修改字段 poprepair ************************/ +const handlePoprepair = async (props, instruct) => { + const { title, fieldNames, srcDataset } = instruct; + + if (!title || !fieldNames) { + showMsg({ + type: "error", + content: ( +
+
跳转弹窗修改字段指令未配置title/fieldNames!
+
请检查该指令集:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error("跳转弹窗修改字段指令未配置title/fieldNames!"); + } + + const { tableLineParams = {} } = props; + let { name: tableName, record, index } = tableLineParams; + + if (!tableName) { + tableName = srcDataset; + record = {}; + index = 0; + } + + const { + [`${tableName}Config`]: config, + [`${tableName}Data`]: tableData + } = props; + + if (tableName) { + index = tableData.findIndex(item => item.sId === record.sId); + } + + const fieldNameList = fieldNames.split(","); + + const filterConfig = config?.gdsconfigformslave?.filter(item => { + return fieldNameList.includes(item.sName); + }); + + if (!filterConfig || filterConfig.length === 0) { + showMsg({ + type: "error", + content: ( +
+
{`未找到字段集合【${fieldNames}】对应的配置,请确认配置是否正确!`}
+
请检查该指令集:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error( + `未找到字段集合【${fieldNames}】对应的配置,请确认配置是否正确!` + ); + } + + const { dataOneObj = {}, dataNameList = [] } = utils.getDatasetDataList( + props, + instruct + ); + const extraData = utils.getRowDataByValue( + props, + instruct, + dataOneObj, + dataNameList + ); + + const { confirmBtnName } = instruct; + const returnData = await new Promise(resolve => { + props.onSaveState({ + commonRepairModalParams: { + visible: true, + title, + tableName, + config, + record: { ...record, ...tableData[index], ...extraData }, + filterConfig, + confirmBtnName, + callback: rowData => { + resolve(rowData); + } + } + }); + }); + + let result = {}; + + // 如果是确认返回 + if (returnData && commonUtils.isNotEmptyObject(returnData)) { + const { datasetList = [], [`${tableName}Data`]: tableData = [] } = props; + const datasetListNew = datasetList.includes(tableName) + ? datasetList + : [...datasetList, tableName]; + + const tableDataNew = JSON.parse(JSON.stringify(tableData)); + tableDataNew[index] = { + ...returnData, + handleType: tableDataNew[index].handleType || "update" + }; + + result = { + datasetList: datasetListNew, + [`${tableName}Data`]: tableDataNew + }; + } else { + throw new Error("======弹窗指令终止"); + } + + outputResult(result); + return result; +}; + +/************************* 新增空数据集 newempry ************************/ +const handleNewEmpty = (props, instruct) => { + const { newDataset, desDataset } = instruct; + + const tableName = desDataset || newDataset; + const bUpdate = !!desDataset; + + let result = {}; + if (bUpdate) { + const { datasetList = [] } = props; + const datasetListNew = datasetList.includes(tableName) + ? datasetList + : [...datasetList, tableName]; + result = { + ...result, + datasetList: datasetListNew, + [`${tableName}Data`]: [ + { + sId: commonUtils.createSid(), + handleType: "add", + sParentId: props.masterData?.sId || props.currentId || "" + } + ] + }; + } else { + result = { + ...result, + [`${tableName}Data`]: [{}] + }; + } + + outputResult(result); + return result; +}; + +// 执行sql -> 执行所有sql +const handleExeSqlAll = async (props, onSucess) => { + if (!exesqlTodo.length) { + onSucess && onSucess(); + return; + } + + const { sModelsId, app } = props; + const { token } = app; + const dataUrl = `${ + commonConfig.server_host + }instruct/exesql?sModelsId=${sModelsId}`; + const values = { + opr: "exesql", + data: exesqlTodo + }; + const dataReturn = (await commonServices.postValueService( + token, + values, + dataUrl + )).data; + + if (dataReturn.code === 1) { + onSucess && onSucess(); + } else { + props.onSaveState({ pageLoading: false }); + showMsg({ + type: "error", + content: ( +
+
exesql接口报错!
+
请求地址:
+
{dataUrl}
+
传入参数:
+
{JSON.stringify(values)}
+
报错信息
+
{JSON.stringify(dataReturn)}
+
+ ) + }); + } +}; + +// 赋值时的js运算 +const handleComputeData = (props, str, datasetList) => { + const { + fordosetName, + fordosetData = {}, + app, + currentSelectedMachineTask, + currentStartWorkMachineTask, + currentWorkOrderInfo + } = props; + const { userinfo } = app; + + // 定义变量(给eval中的变量用) + const tempDataOld = { + [fordosetName]: fordosetData, + ...datasetList, + userinfo, + currentSelectedMachineTask, + currentStartWorkMachineTask, + currentWorkOrderInfo + }; + + const tempData = {}; + Object.keys(tempDataOld).forEach(key => { + if (!key || key.includes("undefined")) return; + tempData[key] = tempDataOld[key]; + if ( + key.includes("@") || + [ + "userinfo", + "currentSelectedMachineTask", + "currentStartWorkMachineTask", + "currentWorkOrderInfo" + ].includes(key) + ) + return; + if (!key.endsWith("One")) { + tempData[`${key}One`] = tempDataOld[key]; + } else { + tempData[key.substring(0, key.length - 3)] = tempDataOld[key]; + } + }); + + // 将变量fordosetName替换 + let strNew = str; + Object.keys(tempData).forEach(key => { + const reg = new RegExp(`${key}\\.`, "g"); + strNew = strNew.replace(reg, `tempData["${key}"].`); + }); + + tempData.moment = moment; + strNew = strNew.replace(/moment\(/g, `tempData.moment(`); + strNew = strNew.replace(/moment\./g, `tempData.moment.`); + + let result = ""; + try { + // 将conditionNew中的变量赋值 + const evalStr = eval("`" + strNew + "`"); + // 执行判断条件 + result = eval(evalStr); + result = result === undefined ? "" : result; + console.log("======赋值js运算结果", { + str, + strNew, + evalStr, + result + }); + } catch (error) { + showMsg({ + type: "error", + content: ( +
+
赋值运算错误!
+
请检查赋值运算语法!
+
赋值运算内容:
+
{str}
+
赋值运算被替代后的结果:
+
{JSON.stringify(strNew)}
+
赋值运算可能用到的数据集:
+
{JSON.stringify(tempData)}
+
+ ) + }); + console.log("=====err", { str, strNew, error }); + throw new Error("js运算错误"); + } + return result; +}; + +const outputInfo = instruct => { + const { opr } = instruct; + console.log(`=====步骤${step},操作类型【${opr}】,指令: `, instruct); + step++; +}; + +const outputResult = result => { + console.log(`=====步骤${step - 1}结果: `, result); +}; + +const utils = { + // 保存数据 + saveData: async (props, params) => { + const { token, sModelsId, currentId, masterData, app } = props; + const { userinfo } = app; + const BtnSave = commonFunc.showMessage( + app.commonConst, + "BtnSave" + ); /* 保存 */ + params.optName = BtnSave; + const returnData = await commonBusiness.saveData({ + token, + value: params, + sModelsId + }); + + if (commonUtils.isEmptyObject(returnData)) { + props.onSaveState({ + loading: false + }); + return false; + } + + /* 防呆校验 */ + if (returnData.code === -7) { + confirm({ + title: "单据校验" /* 防呆校验 */, + content: returnData.msg, + onOk() { + params.iFlag = 1; + utils.saveData(params); + }, + onCancel() {}, + okText: "保存", + cancelText: "不保存" + }); + props.onSaveState({ + loading: false + }); + return true; + } + props.onSendSocketMessage( + "release", + "noAction", + currentId, + userinfo.sId, + null, + null + ); + props.onSaveState({ + enabled: false, + currentId: masterData.sId, + loading: false + }); + return true; + }, + // 获取过滤后的数据 + getDatasetDataList: (props, instruct, datasetName = "dataset") => { + const { [datasetName]: dataset = "" } = instruct; + const dataNameList = []; // 名称列表 + const dataList = []; // 数据列表 + const dataObj = {}; // 对象 格式:名称: 数据列表 + const dataOneObj = {}; // 对象 格式:名称: 数据列表第一条 + dataset + .split(",") + .filter(item => item) + .forEach(itemOld => { + const item = itemOld.replace(/\s/g, ""); + const [tableName, filterType] = item.split("@"); + const filterData = utils.getFilterData(props, tableName, filterType); + dataNameList.push(tableName); + dataList.push(filterData); + dataObj[tableName] = filterData; + dataOneObj[tableName] = filterData[0] || {}; + }); + return { + dataNameList, + dataList, + dataObj, + dataOneObj + }; + }, + // 过滤数据 + getFilterData: (props, tableName, filterTypeOld = "") => { + if (tableName === "userinfo") { + return [props.app.userinfo]; + } + + let _props = props; + + let filterType = filterTypeOld; + if (filterType && filterType.includes("parent")) { + filterType = filterType.replace("parent", ""); + _props = props.parentProps; + } + + const { tableLineParams, fordosetName, fordosetData } = _props; + let { [`${tableName}Data`]: tableDataOld = [] } = _props; + + if (tableName === fordosetName) { + tableDataOld = [fordosetData]; + } + + // 将{}类型的数据转成[{}]类型的数据 + const tableData = Array.isArray(tableDataOld) + ? tableDataOld + : [tableDataOld]; + + let { [`${tableName}SelectedRowKeys`]: selectedRowKeys = [] } = _props; + if ( + commonUtils.isEmptyArr(selectedRowKeys) || + !tableData.some( + item => + item.sId === selectedRowKeys[0] || + item.sSlaveId === selectedRowKeys[0] + ) + ) { + selectedRowKeys = tableData[0] ? [tableData[0].sId] : []; + } + + // if ( + // filterType === "line" || + // (filterType === "sec" && + // tableLineParams && + // tableLineParams.name === tableName && + // tableLineParams.record) + // ) { + // // 表格按钮所在行数据 + // return [tableLineParams.record]; + // } else + if (filterType === "sec") { + // 选中数据 + return tableData.filter( + item => + selectedRowKeys.includes(item.sId) || + selectedRowKeys.includes(item.sSlaveId) + ); + } else if (filterType === "first") { + // 数据集第一条数据 + // todo + return tableData[0]; + } + + return tableData; + }, + // 获取赋值后的数据 + getDataAfterAssign: (props, instruct, tableDataOld) => { + const tableDataOldClone = lodash.cloneDeep(tableDataOld); + const { srcDataset, sValue, fordoset = `${srcDataset}One` } = instruct; + + // 没有sValue时,返回全部 + if (!sValue) return tableDataOldClone; + + const tableDataNew = sValue.includes("*") ? tableDataOldClone : []; + + // 过滤掉列表里的* + const list = sValue.split(",").filter(item => item && item !== "*"); + + list.forEach(item => { + const [sFieldNameNew, ...rest] = item.split(":"); + const sFieldName = rest.join(":") || sFieldNameNew; + + tableDataOld.forEach((rowData, index) => { + if (!tableDataNew[index]) { + tableDataNew[index] = {}; + } + + let result = ""; + if (sFieldName && sFieldName.includes("${")) { + // 如果有js运算 + result = handleComputeData(props, sFieldName, { + [fordoset]: rowData, + ...utils.getDatasetDataList(props, instruct).dataOneObj + // ...handleGetDataSetData(props, instruct) + }); + } else { + // 普通赋值 + result = rowData[sFieldName]; + } + tableDataNew[index][sFieldNameNew] = result; + }); + }); + + return tableDataNew; + }, + // 根据sValue获取行数据 + getRowDataByValue: (props, instruct, dataOneObj, dataNameList) => { + const { sValue = "" } = instruct; + + let rowData = {}; + sValue.split(",").forEach(item => { + const partValue = item.trim(); + + const regexTest = (reg, str) => { + let tempResult = false; + try { + tempResult = reg.test(str); + } catch (error) {} + return tempResult; + }; + + const [ + regex1, + regex2, + regex3, + regex4, + regex5, + regex6, + regex7 + ] = utils.getRegex(); + + if (partValue.includes(".*")) { + // 如果是 数据集名称.* 格式(某个数据集的全部数据) + const [tableName] = partValue.split(".*"); + rowData = { + ...rowData, + ...dataOneObj[tableName] + }; + } else if (regexTest(regex3, partValue)) { + // 合计某个字段的值 + const [assignField, ...rest] = partValue.split(":"); + let jsStr = rest.join(":"); + rowData = { + ...rowData, + [assignField]: utils.getSumData(props, jsStr) + }; + } else if (regexTest(regex4, partValue)) { + // 合并某个字段的值 + const [assignField, ...rest] = partValue.split(":"); + let jsStr = rest.join(":"); + rowData = { + ...rowData, + [assignField]: utils.getMergeData(props, jsStr) + }; + } else if (regexTest(regex5, partValue)) { + // 取最大值 + const [assignField, ...rest] = partValue.split(":"); + let jsStr = rest.join(":"); + rowData = { + ...rowData, + [assignField]: utils.getMaxData(props, jsStr) + }; + } else if (regexTest(regex6, partValue)) { + // 获取数据集条数 + const [assignField, ...rest] = partValue.split(":"); + let jsStr = rest.join(":"); + rowData = { + ...rowData, + [assignField]: utils.getCountData(props, jsStr) + }; + } else if (regexTest(regex7, partValue)) { + // 取数组中某个字段分组后的组数 + const [assignField, ...rest] = partValue.split(":"); + let jsStr = rest.join(":"); + rowData = { + ...rowData, + [assignField]: utils.getGroupCountData(props, jsStr) + }; + } else if (partValue.includes("${")) { + // 如果是 赋值字段名称:js计算 格式 + const [assignField, ...rest] = partValue.split(":"); + const jsStr = rest.join(":"); + rowData = { + ...rowData, + [assignField]: handleComputeData(props, jsStr, { + ...dataOneObj + }) + }; + } else if (regex1.test(partValue)) { + // 如果是 赋值字段名称:数据集名称.数据集字段名称 格式 + const [assignField, tableValues] = partValue.split(":"); + const [tableName, fieldName] = tableValues.split("."); + rowData = { + ...rowData, + [assignField]: dataOneObj[tableName][fieldName] + }; + } else if (regex2.test(partValue)) { + // 如果是 赋值字段名称:数据集字段名称 格式 + const [assignField, fieldName] = partValue.split(":"); + const tableName = dataNameList[0]; + rowData = { + ...rowData, + [assignField]: dataOneObj[tableName][fieldName] + }; + } + }); + return rowData; + }, + // 获取conditon过滤并赋值后的数据 + getDataAfterConditionAndAssign: ( + props, + instruct, + datasetName = "desDataset" + ) => { + const { [datasetName]: targetDatasetOld, condition, sValue } = instruct; + + const [targetDataset] = targetDatasetOld.split("@"); + + if (!sValue) { + showMsg({ + type: "error", + content: ( +
+
数据集的赋值字段sValue不能为空!
+
请检查该指令集:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error("数据集的赋值字段sValue不能为空!"); + } + + const { + dataObj = {}, + dataNameList = [], + dataList = [] + } = utils.getDatasetDataList(props, instruct, datasetName); + let filterData = dataList[0]; + + const { dataOneObj = {} } = utils.getDatasetDataList(props, instruct); + + if (commonUtils.isEmptyArr(filterData)) { + showMsg({ + type: "error", + content: ( +
+
{`${targetDataset}】数据源为空`}
+
过滤出的数据集为:
+
{JSON.stringify(dataObj)}
+
请检查该指令集:
+
{JSON.stringify(instruct)}
+
+ ) + }); + throw new Error(`${targetDataset}】数据源为空`); + } + + // const tableDataOld = props[`${targetDataset}Data`] || []; + + // 没有配置condition, 返回原数据 + // if (!condition) return tableDataOld; + + const fordoset = `${targetDataset}One`; + filterData = filterData.filter(item => + utils.bMatchCondition(props, instruct, { + [fordoset]: item + }) + ); + + const returnData = []; + filterData.forEach(item => { + let rowData = item; + if (sValue === "*") { + // 全部字段 + rowData = { + ...item + }; + } else { + const dataOneObjNew = { + ...dataOneObj, + [targetDataset]: item + }; + rowData = { + ...rowData, + ...utils.getRowDataByValue( + props, + instruct, + dataOneObjNew, + dataNameList + ) + }; + } + returnData.push(rowData); + }); + + return returnData; + }, + // 判断是否满足条件 + bMatchCondition: (props, instruct, datasetListExtra = {}) => { + const { + fordosetName, + fordosetData = {}, + app, + currentSelectedMachineTask, + currentStartWorkMachineTask, + currentWorkOrderInfo + } = props; + const { userinfo } = app; + + const { + conditionNotEmpty, + conditionEmpty, + condition, + dataset = "" + } = instruct; + + // 如果都不为空,继续执行 + if (conditionNotEmpty !== undefined) { + let temp = true; + conditionNotEmpty.split(",").forEach(item => { + const [tableName, filterType] = item.split("@"); + const tableData = utils.getFilterData(props, tableName, filterType); + temp = temp && tableData.length > 0; + }); + return temp; + } + + // 如果都为空,继续执行 + if (conditionEmpty !== undefined) { + let temp = true; + conditionEmpty.split(",").forEach(item => { + const [tableName, filterType] = item.split("@"); + const tableData = utils.getFilterData(props, tableName, filterType); + temp = temp && tableData.length === 0; + }); + return temp; + } + + // 如果没有条件,默认全部为true + if (!condition) return true; + + // 如果包含#,则将 #内容# 部分进行特殊处理 + let conditionNew = condition; + if (condition.includes("#")) { + const regex = /#[^#]+#/g; + conditionNew = conditionNew.replace(regex, match => { + const content = match.substring(1, match.length - 1); + return utils.getRegexResult(props, content); + }); + } + + // 定义变量(给eval中的变量用) + const tempDataOld = { + [fordosetName]: fordosetData, + ...datasetListExtra, + userinfo, + currentSelectedMachineTask, + currentStartWorkMachineTask, + currentWorkOrderInfo + }; + + const tempData = {}; + Object.keys(tempDataOld).forEach(key => { + if (!key || key === "undefined") return; + tempData[key] = tempDataOld[key]; + if ( + key.includes("@") || + [ + "userinfo", + "currentSelectedMachineTask", + "currentStartWorkMachineTask", + "currentWorkOrderInfo" + ].includes(key) + ) + return; + if (!key.endsWith("One")) { + tempData[`${key}One`] = tempDataOld[key]; + } else { + tempData[key.substring(0, key.length - 3)] = tempDataOld[key]; + } + }); + + const datasetList = dataset.split(",").filter(item => !!item); + datasetList.forEach(item => { + const [tableName, filterType] = item.split("@"); + const tableData = utils.getFilterData(props, tableName, filterType); + if (commonUtils.isNotEmptyArr(tableData)) { + tempData[item] = tableData[0]; + tempData[tableName] = tableData[0]; + } + }); + + console.log("=====tempData", tempData); + + // 将变量fordosetName替换 + Object.keys(tempData).forEach(key => { + const reg = new RegExp(`${key}\\.`, "g"); + conditionNew = conditionNew.replace(reg, `tempData["${key}"].`); + }); + + // 替换时间函数moment + tempData.moment = moment; + conditionNew = conditionNew.replace(/moment\(/g, `tempData.moment(`); + conditionNew = conditionNew.replace(/moment\./g, `tempData.moment.`); + + let bMatch = false; + try { + // 将conditionNew中的变量赋值 + const evalStr = eval("`" + conditionNew + "`"); + // 执行判断条件 + bMatch = eval(evalStr); + console.log("======判断条件返回结果", { + condition, + conditionNew, + evalStr, + bMatch + }); + } catch (error) { + showMsg({ + type: "error", + content: ( +
+
conditon条件运算错误!
+
1、请检查condition语法!
+
2、请检查ccondition用到的数据集是否在dataset中正确配置!
+
conditon所在指令集:
+
{JSON.stringify(instruct)}
+
conditon内容:
+
{condition}
+
condition被替代后的结果:
+
{JSON.stringify(conditionNew)}
+
condition可能用到的数据集:
+
{JSON.stringify(tempData)}
+
+ ) + }); + console.log("=====err", { condition, conditionNew, error }); + throw new Error("js运算错误"); + } + + return bMatch; + }, + // 汇总某个表格的某个字段 + getSumData: (props, jsStr) => { + const jsStrNew = jsStr.substring(2, jsStr.length - 1); + const [tableName, temp1] = jsStrNew.split("@"); + const [temp2, sFieldName] = temp1.split("."); + const decimal = temp2.split("sum")[1]; + + const { [`${tableName}Data`]: tableData } = props; + let sum = 0; + tableData.forEach(rowData => { + const value = commonUtils.convertStrToNumber0(rowData[sFieldName]); + sum += value; + }); + + const result = decimal ? sum.toFixed(decimal) : sum.toString(); + + return result; + }, + // 合并某个字段的值 + getMergeData: (props, jsStr) => { + const jsStrNew = jsStr.substring(2, jsStr.length - 1); + const [tableName, temp1] = jsStrNew.split("@"); + const [temp2, sFieldName] = temp1.split("."); + const temp3 = temp2.split("merge")[1]; + const joinerType = temp3.replace("quo", ""); + const bHasQuo = temp3?.includes("quo"); + + const { [`${tableName}Data`]: tableData } = props; + let tempList = []; + tableData.forEach(rowData => { + const value = commonUtils.strUndefinedToEmpty(rowData[sFieldName]); + if (bHasQuo) { + tempList.push(`'${value}'`); + } else { + tempList.push(value); + } + }); + + const joinerJson = { + "": "", + dot: ",", + plus: "+", + minus: "-", + divide: "/", + underline: "_" + }; + const joiner = joinerJson[joinerType] || ""; + + const result = tempList.join(joiner); + + return result; + }, + // 取最大值 + getMaxData: (props, jsStr) => { + const jsStrNew = jsStr.substring(2, jsStr.length - 1); + const [tableName, temp1] = jsStrNew.split("@"); + const [, sFieldName] = temp1.split("."); + + const { [`${tableName}Data`]: tableData } = props; + let maxValue = 0; + tableData.forEach(rowData => { + const value = commonUtils.convertStrToNumber0(rowData[sFieldName]); + maxValue = Math.max(maxValue, value); + }); + + return maxValue; + }, + // 获取数据集条数 + getCountData: (props, jsStr) => { + const jsStrNew = jsStr.substring(2, jsStr.length - 1); + const [tableName] = jsStrNew.split("@"); + const { [`${tableName}Data`]: tableData = [] } = props; + return tableData.length; + }, + // 取数组中某个字段分组后的组数 + getGroupCountData: (props, jsStr) => { + const jsStrNew = jsStr.substring(2, jsStr.length - 1); + const [tableName, temp1] = jsStrNew.split("@"); + const [, sFieldName] = temp1.split("."); + + const { [`${tableName}Data`]: tableData } = props; + const tempMap = new Map(); + tableData.forEach(rowData => { + tempMap.set(rowData[sFieldName], true); + }); + + return tempMap.size; + }, + // 跳转页面 + changeTabName: () => { + console.log("=====跳转页面", changeTabName); + setTimeout(() => { + const oTabs = document.querySelectorAll( + `.ant-tabs-tab-btn[id*="${changeTabName}"]` + ); + let oTab = null; + if (oTabs.length === 0) { + showMsg({ + type: "error", + content:
{`未找到tab页面【${changeTabName}】`}
+ }); + throw new error(`未找到tab页面【${changeTabName}】`); + } else if (oTabs.length === 1) { + oTab = oTabs[0]; + } else if (oTabs.length > 1) { + oTabs.forEach(item => { + const { innerHTML } = item; + if (innerHTML === changeTabName) { + oTab = item; + } + }); + } + + if (!oTab) { + showMsg({ + type: "error", + content:
{`未找到tab页面【${changeTabName}】`}
+ }); + throw new error(`未找到tab页面【${changeTabName}】`); + } + + oTab.click(); + }, 500); + }, + // 获取指令集中所有数据 + getAllData: (props, dataset) => { + const { app, fordosetName, fordosetData } = props; + const { userinfo, globalData = {} } = app; + const { + currentSelectedMachineTaskDataRow: currentSelectedMachineTask = {}, + currentStartWorkMachineTaskDataRow: currentStartWorkMachineTask = {}, + currentWorkOrderInfo = {} + } = globalData; + + // 全局参数 + let allData = { + userinfo, + currentSelectedMachineTask, + currentStartWorkMachineTask, + currentWorkOrderInfo, + moment: moment + }; + + // 循环参数 + if (fordosetName) { + allData[fordosetName] = fordosetData || {}; + } + + // 所有Data结尾数据的第一条 + Object.keys(props) + .filter(key => { + if (!key) return false; + const bEndWithData = key.endsWith("Data"); + if (!bEndWithData) return false; + const data = props[key]; + return typeof data === "object" && commonUtils.isNotEmptyObject(data); + }) + .forEach(key => { + const tableName = key.substring(0, key.length - 4); + const data = props[`${tableName}Data`]; + allData[tableName] = Array.isArray(data) ? data[0] : data; + }); + + // dataset过滤后数据的第一条 + const { dataOneObj } = utils.getDatasetDataList(props, { dataset }); + allData = { ...allData, ...dataOneObj }; + return allData; + }, + // 获取正则规则及其对应方法 + getRegex: () => { + const regex1 = /^([^\s:]+):([^\s.]+)\.([^\s.]+)$/; + const regex2 = /^([^\s:]+):([^\s.]+)$/; + const regex3 = /\$\{[^{}@]+@sum\d+\.[^{}]+\}/g; // ${任意@sum任意数字.任意} + const regex4 = /\$\{[^{}@]+@merge.*\.[^{}]+\}/g; // ${任意@merge类型.任意} + const regex5 = /\$\{[^{}@]+@max\.[^{}]+\}/g; // ${任意@max.任意} + const regex6 = /\$\{[^{}@]+@count\}/g; // ${任意@count} + const regex7 = /\$\{[^{}@]+@groupCount\.[^{}]+\}/g; // ${任意@groupCount.任意} + return [regex1, regex2, regex3, regex4, regex5, regex6, regex7]; + }, + getRegexResult: (props, jsStr) => { + const [ + regex1, + regex2, + regex3, + regex4, + regex5, + regex6, + regex7 + ] = utils.getRegex(); + + const regexTest = (reg, str) => { + let tempResult = false; + try { + tempResult = reg.test(str); + } catch (error) {} + return tempResult; + }; + + let result = ""; + if (regexTest(regex3, jsStr)) { + // 合计某个字段的值 + result = utils.getSumData(props, jsStr); + } else if (regexTest(regex4, jsStr)) { + // 合并某个字段的值 + result = utils.getMergeData(props, jsStr); + } else if (regexTest(regex5, jsStr)) { + // 取最大值 + result = utils.getMaxData(props, jsStr); + } else if (regexTest(regex6, jsStr)) { + // 获取数据集条数 + result = utils.getCountData(props, jsStr); + } else if (regexTest(regex7, jsStr)) { + // 取数组中某个字段分组后的组数 + result = utils.getGroupCountData(props, jsStr); + } + + return result; + }, + // 通用解析 + getEvalResult: (props, { stringValue, dataset, bBooleanMode = false }) => { + // 获取当前页面所有数据 + const tempData = utils.getAllData(props, dataset); + + // 替换变量 + let strNew = stringValue; + Object.keys(tempData).forEach(key => { + const reg = new RegExp(`${key}\\.`, "g"); + strNew = strNew.replace(reg, `tempData["${key}"].`); + }); + + // 替换时间函数moment + tempData.moment = moment; + strNew = strNew.replace(/moment\(/g, `tempData.moment(`); + strNew = strNew.replace(/moment\./g, `tempData.moment.`); + + let result = ""; + try { + // 调试模式 + if (window.debuggerValue && stringValue.includes(window.debuggerValue)) { + debugger; + } + + // 第一遍运算(将变量转换成对应的值) + const evalStr = eval("`" + strNew + "`"); + // 第二遍运算(将字符串进行js运算) + result = eval(evalStr); + result = bBooleanMode ? !!result : result; + console.log("======赋值js运算结果", { + 传入内容: stringValue, + 替换变量后结果: strNew, + 第一遍运算后结果: evalStr, + 第二遍运算后结果: result + }); + } catch (error) { + showMsg({ + type: "error", + content: ( +
+
js运算错误!
+
请检查js运算语法!
+
js运算内容:
+
{stringValue}
+
赋值运算被替代后的结果:
+
{JSON.stringify(strNew)}
+
请联系开发人员或用window.debuggerValue功能调试!
+
+ ) + }); + throw new Error("js运算错误"); + } + } +}; + +export default instructSet; diff --git a/src/components/Common/CommonList.js b/src/components/Common/CommonList.js new file mode 100644 index 0000000..5637122 --- /dev/null +++ b/src/components/Common/CommonList.js @@ -0,0 +1,526 @@ +import React, { Component, useMemo, useState } from 'react'; +import { Form } from '@ant-design/compatible'; +import '@ant-design/compatible/assets/index.css'; +import { Layout, Spin, Slider, Button } from 'antd-v4'; +import { MessageOutlined, MinusOutlined } from '@ant-design/icons'; +import CommonListEvent from '@/components/Common/CommonListEvent';/* 继承销售模块业务功能 */ +import * as commonFunc from '@/components/Common/commonFunc';/* 通用单据方法 */ /* 通用单据方法 */ +import Toolbar from '@/components/Common/ToolBar/ToolBarNew'; +import StaticEditTable from '@/components/Common/CommonTable';/* 可编辑表格 */ +import StaticEditTableNew from '@/components/Common/CommonTableNew';/* 可编辑表格 */ +import styles from '@/index.less'; +import CommonBase from '@/components/Common/CommonBase';/* 获取配置及数据 */ +import * as commonBusiness from '@/components/Common/commonBusiness';/* 单据业务功能 */ +import SearchComponent from '@/components/Common/SearchComponent';/* 搜索组件 */ +import commonConfig from '@/utils/config'; +import * as commonUtils from '@/utils/utils'; +import StaticEditTree from '@/components/Common/Tree/StaticTree'; +import Eject from '@/assets/eject.svg';/* 弹出图标 */ +import Close from '@/assets/close.svg';/* 关闭图标 */ +import AntdDraggableModal from '@/components/Common/AntdDraggableModal'; +import CommonListSelect from '@/components/Common/CommonListSelect';/* 选择界面 */ +import WorkOrderSystemAddModal from '@/components/Common/WorkOrderSystem/WorkOrderSystemAdd'; +import WorkOrderSystemDetailModal from '@/components/Common/WorkOrderSystem/WorkOrderSystemDetail'; + +const { Header, Content } = Layout; +let NoTotalData = ''; +class CommonList extends Component { + handleEject = () => { + const { currentPane, panes } = this.props.app; + if (commonUtils.isNotEmptyArr(panes) && commonUtils.isNotEmptyObject(currentPane)) { + // const index = panes.indexOf(currentPane); + const index = panes.findIndex(item => item.formId === currentPane.formId && item.key === currentPane.key && item.notCurrentPane === currentPane.notCurrentPane && item.route === currentPane.route && item.title === currentPane.title && item.sModelsType === currentPane.sModelsType && item.sProcName === currentPane.sProcName); + /* 当前页签 */ + let currentTab = document.getElementById('navTabWrap').children[index]; + if (commonUtils.isEmpty(currentTab)) { + const oChildren = document.getElementById('navTabWrap').getElementsByClassName('ant-tabs-content')[0].children; + for (const child of oChildren) { + if (child.nodeName === 'DIV' && index !== undefined && child.getAttribute('id') === `navTabWrap-panel-${panes[index].key}`) { + currentTab = child; + } + } + } + if (!commonUtils.isEmpty(currentTab)) { + const filterTreeArr = currentTab.getElementsByClassName('xly-filter-tree');/* 获取当前页签下的树组件 */ + if (commonUtils.isNotEmptyArr(filterTreeArr)) { + const filterTree = filterTreeArr[0]; + if (filterTree.style.display === 'block') { + filterTree.style.display = 'none'; + } else { + filterTree.style.display = 'block'; + } + } + } + } + }; + /** 树节点选中 */ + handleTreeSelect = (name, checkedKeys, e) => { + this.props.onSelect(name, checkedKeys, e); /* 调用CommonListEvent通用处理 */ + }; + + handleCancelModal = (modelVisible) => { + this.props.onSaveState({ + [modelVisible]: false, + }); + } + + handleSelectModal = (modelVisible) => { + this.props.onSaveState({ + [modelVisible]: false, + }); + } + + render() { + const { pageLoading } = this.props; + return ( +
+ +
+ +
+
+
+ ); + } +} + +const CommonListComponent = Form.create({ + mapPropsToFields(props) { + const { masterData, masterConfig } = props; + const obj = commonFunc.mapPropsToFields(masterData, Form, masterConfig); + return obj; + }, +})((props) => { + const { + form, onReturnForm, slavePagination, slaveConfig, slaveColumn, iHeight, logVisible, slaveFilterCondition, + flowHistroyId, flowHistroyVisible, app, + } = props; + const { userinfo, token } = app; + // isSmall将分页变小,以及去掉跳转页面和总条数记录 + /* 回带表单 */ + if (commonUtils.isNotEmptyObject(slavePagination)) { + // if (isSmall) { + // slavePagination.showTotal = null; + // } + } + onReturnForm(form); + + const masterSum = commonUtils.isNotEmptyObject(slaveConfig) ? slaveConfig.gdsconfigformslave.filter(item => item.bSum && item.sName !== '') : []; + const masterTitleGroup = commonUtils.isNotEmptyObject(slaveColumn) ? slaveColumn.filter(item => commonUtils.isNotEmptyObject(item.title) && item.title.indexOf('-') > -1) : []; + const hasColumnGroup = masterTitleGroup.length; + if (masterSum.length > 0) { + NoTotalData = hasColumnGroup > 0 ? 'TitleGroup' : 'NoTitleGroup'; + } else { + NoTotalData = hasColumnGroup > 0 ? 'NoTotalData TitleGroup' : 'NoTotalData NoTitleGroup'; + } + // const mProps = { ...commonBusiness.createMemoProps('master', props)}; + + const name = 'filterTree'; + const treeProps = { + ...commonBusiness.getTreeTypes('tree', props), + isSearch: false, + checkable: false, + disabled: false, + checkedAll: false, + unChecked: false, + [`${name}Column`]: props[`${name}Column`], + [`${name}Config`]: props[`${name}Config`], + [`${name}Data`]: props[`${name}Data`], + getFloatNum: props.getFloatNum, + getSqlDropDownData: props.getSqlDropDownData, + getSqlCondition: props.getSqlCondition, + handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord, + getDateFormat: props.getDateFormat, + onDoubleClick: props.onDoubleClick, + onSelect: props.onSelectTree, + expandedKeys: props.expandedKeys, + }; + const logProps = { + app: { + ...props.app, + currentPane: { + ...props.app.currentPane, + formRoute: '/indexPage/commonList', + route: '/indexPage/commonList', + name: 'logView', + config: props.logConfig, + select: props.onSelectModal.bind(this, 'logVisible'), + selectCancel: props.onCancelModal.bind(this, 'logVisible'), + sModelsType: 'modal/logView', + }, + }, + token: props.app.token, + slaveColumn: props.logColumn, /* 表头 */ + slaveConfig: props.logConfig, + slaveData: props.logData, + dispatch: props.dispatch, + content: props.content, + id: new Date().getTime().toString(), + pageLoading: false, + }; + + const refreshSlaveTable = () => { + props.handleGetDataSet({ + name: 'slave', + configData: props.slaveConfig, + condition: { + pageNum: 1, + pageSize: slavePagination.pageSize, + bFilter: slaveFilterCondition, + }, + flag: true, + clearSelectData: true, + }); + }; + const workOrderSystemAddProps = { + ...props, + onAddWorkOrderSuccess: () => { + props.onSaveState({ workOrderSystemAddModalVisible: false }); + refreshSlaveTable(); + }, + }; + + let workOrderSystemDetailTitle = ''; + if (commonUtils.isNotEmptyObject(props.slaveCurrentData)) { + const { sTitle, sModuleName, tCreateDate } = props.slaveCurrentData; + /* eslint-disable */ + workOrderSystemDetailTitle = ( + <> + {sTitle} + {`菜单名称: ${sModuleName} ${Array(10) + .fill('\xa0') + .join('')} 创建时间: ${tCreateDate.split(' ')[0]}`} + + + ); + /* eslint-enable */ + } + + const workOrderSystemDetailProps = { + ...props, + sId: commonUtils.isNotEmptyObject(props.slaveCurrentData) ? props.slaveCurrentData.sId : '', + refreshSlaveTable, + }; + + let addressStr = `${location.protocol}//${location.host}`; + if (props.sModelsType && props.sModelsType.includes('http')) { + addressStr = location.host; + } + + const sFlowUrl = `${commonConfig.server_host}process/historyListerp/{sBillId}/{sBrandsId}/{sSubsidiaryId}/{sUserName}/{token}`; + const flowHistrory = sFlowUrl !== undefined ? sFlowUrl.replace('{sBrandsId}', userinfo.sBrandsId).replace('{sSubsidiaryId}', userinfo.sSubsidiaryId).replace('{sUserName}', userinfo.sUserName).replace('{sUserId}', userinfo.sId) + .replace('{token}', token) + .replace('{ipAddress}', addressStr) + .replace('{sBillId}', flowHistroyId) : ''; + + // 获取树位置的配置 + let bTreeLeft = false; + let treeLeftWidth = 300; + let defaultExpand = true; + const treeLeftIndex = + commonUtils.isNotEmptyObject(slaveConfig) + ? slaveConfig.gdsconfigformslave.findIndex(item => item.sControlName === 'bTreeLeft') : -1; + if (treeLeftIndex !== -1) { + bTreeLeft = true; + const treeLeftConfig = slaveConfig.gdsconfigformslave[treeLeftIndex]; + treeLeftWidth = treeLeftConfig.iFitWidth || treeLeftWidth; + defaultExpand = treeLeftConfig.bVisible; + } + + return ( +
+ + {!commonUtils.isEmpty(props.routing) ? '' : +
+ +
} + +
+ +
+ + {bTreeLeft && } + + +
+
+ {/* {!commonUtils.isEmpty(props.routing) ? '' : } */} + {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */} + {!bTreeLeft && } + { + logVisible ? + + + : '' + } + { + props.bDataAuditProgress ? +
+ +
: '' + + } + { + commonUtils.isNotEmptyObject(slaveConfig) && + slaveConfig.sTbName === 'sys_workorder' && + props.bMin && + + } + { + props.workOrderSystemAddModalVisible && + + 新增 + + + /* eslint-enable */ + } + style={{ top: 10 }} + className={styles.workOrderSystemModal} + visible={props.workOrderSystemAddModalVisible && !props.bMin} + onCancel={props.onCancelModal.bind(this, 'workOrderSystemAddModalVisible')} + onOk={props.onSelectModal.bind(this, 'workOrderSystemAddModalVisible')} + footer={null} + > + + + } + { + props.workOrderSystemDetailModalVisible && + + + + } + { + flowHistroyVisible ? + + {/* eslint-disable-next-line jsx-a11y/iframe-has-title */} + '); + // window.open(urlPrint); + } else { + message.error('未找到对应过程名'); + } + }; + + /* 右箭头点击 */ + handleRightArrow = (name, sName, record, index, showConfig) => { + if(this.props.onRightArrow) { + this.props.onRightArrow(name, sName, record, index, showConfig); + } + + } + + /* 确定按钮:复制多行 */ + handleOperateMoreOk = () => { + const sNumber = document.getElementById('iNumber').value; + console.log('sNumber', sNumber); + if(commonUtils.isNotEmptyObject(iNumber) && Number(sNumber) > 0 ) { + const iNumber = Number(sNumber); + for(let i = 0; i< iNumber ; i++) { + this.handleCopyRow(0); + } + } + this.setState({ bOperateMoreVisible: false }) + } + + + showimg = (i) => { + this.setState({ showimgs: true, firstIndex: i }); + }; + toggleshow = () => { + this.setState({ showimgs: false, previewVisible: false }); + }; + handleOk = () => { + this.props.onSaveState({ + previewVisible: false, + }); + }; + handleCancelModal = (modelVisible) => { + this.props.onSaveState({ + [modelVisible]: false, + }); + }; + + /** 调整列宽 */ + handleResize = (index, column, isSlaveInfo) => { + return (e, { size }) => { + if (e) { + this.resize = true; + } + if (size.width === column.width) { + return; + } + this.setState(({ tableColumn, tableInfoColumn }) => { + let nextColumns; + if (isSlaveInfo) { + nextColumns = [...tableInfoColumn]; + } else { + nextColumns = [...tableColumn]; + } + + let iIndexList = []; + let iWidth = 0; + let offset = 0; + const iIndex = nextColumns.findIndex(item => item.dataIndex === column.dataIndex); + if (iIndex !== -1) { // 单层表头 + iIndexList = [iIndex, -1]; + iWidth = nextColumns[iIndex].width === undefined ? this.countOperate() : nextColumns[iIndex].width; + offset = size.width - iWidth; + nextColumns[iIndex].width = size.width; + } else { // 双层表头 + for (let i = 0; i < nextColumns.length; i++) { + const item = nextColumns[i]; + const { children } = item; + if (commonUtils.isNotEmptyArr(children)) { + const childIndex = children.findIndex(child => child.dataIndex === column.dataIndex); + if (childIndex !== -1) { + iIndexList = [i, childIndex]; + iWidth = nextColumns[i].children[childIndex].width === undefined ? this.countOperate() : nextColumns[i].children[childIndex].width; + offset = size.width - iWidth; + // const iWidthTemp = nextColumns[i].width === undefined ? this.countOperate() : nextColumns[i].width; + // nextColumns[i].width = iWidthTemp + offset; + nextColumns[i].children[childIndex].width = size.width; + break; + } + } + } + } + + if (commonUtils.isNotEmptyArr(iIndexList)) { + let lastIndexList = []; + let lastIndex = nextColumns.findIndex(item => item.dataIndex === 'tableLastEmpty') - 1; + if (lastIndex < -1) { + lastIndexList = [nextColumns.length - 1, -1]; + } else if (commonUtils.isNotEmptyArr(nextColumns[lastIndex].children)) { + lastIndexList = [lastIndex, nextColumns[lastIndex].children.length - 1]; + } else { + lastIndexList = [lastIndex, -1]; + } + const oBody = this.mydiv.querySelector('.ant-table-body'); + const { scrollWidth, clientWidth, scrollLeft } = oBody; + const scrollRight = scrollWidth - clientWidth - scrollLeft; + + // 判断当前拖动列是否在最后一列前面 + if (iIndexList[0] < lastIndexList[0] || (iIndexList[0] === lastIndexList[0] && iIndexList[1] < lastIndexList[1])) { + const lastColumn = lastIndexList[1] === -1 ? nextColumns[lastIndexList[0]] : nextColumns[lastIndexList[0]].children[lastIndexList[1]]; + const iWidthExtra = lastColumn.widthExtra || 0; // 最后一列额外的宽度 + if (offset > 0) { // 向右拉伸 + if (iWidthExtra) { //有额外宽度 + if (iWidthExtra >= offset) { + lastColumn.width -= offset; + lastColumn.widthExtra -= offset; + offset = 0; + } else { + const diffWidth = offset - iWidthExtra; + lastColumn.width -= iWidthExtra; + lastColumn.widthExtra = 0; + offset = diffWidth; + } + } else if (!iWidthExtra && lastColumn.width - offset > 150) { // 没有额外宽度,但是减去位移后宽度大于150 + lastColumn.width -= offset; + offset = 0; + } + } else if (offset < 0) { // 向左拉伸 + if (scrollRight < -offset) { // 滚动条距离表格右边距离小于拉伸距离 + const diffWidth = -offset - scrollRight; + lastColumn.width += diffWidth; + lastColumn.widthExtra ? (lastColumn.widthExtra += diffWidth) : (lastColumn.widthExtra = diffWidth); + offset = -diffWidth; + } + } + + // 处理拖动幅度太大时,空白列会显示问题 + const oCol = this.mydiv.querySelector('colgroup'); + const oCols = oCol ? oCol.childNodes : []; + const oColsWithList = Array.from(oCols).filter(item => !item.className).map(item => parseInt(item.style.width)); + if (!oColsWithList.includes(0)) { + lastColumn.width += oColsWithList[lastIndex + 1]; + } + } + } + + if (isSlaveInfo) { + if (this.scrollInfoX) { + this.scrollInfoX += offset; + } else { + this.scrollInfoX = 0; + this.scrollInfoX = this.countScrollX(nextColumns, true); + } + return { tableInfoColumn: nextColumns }; + } else { + if (this.scrollX) { + this.scrollX += offset; + } else { + this.scrollX = 0; + this.scrollX = this.countScrollX(nextColumns); + } + return { tableColumn: nextColumns }; + } + }, () => { + this.resize = false; + this.initColumn = null; + if (isSlaveInfo) { + sessionStorage.setItem(`${this.props.formId}_${this.props.config.sId}_info`, JSON.stringify(this.state.tableInfoColumn)); + } else { + sessionStorage.setItem(`${this.props.formId}_${this.props.config.sId}`, JSON.stringify(this.state.tableColumn)); + } + }); + }; + } + + genFooter= () => { + const { tableColumn, totalData, totalData1 } = this.state; + const { dNetMoney, dNetPrice } = this.props.app.decimals; + const sModelsType = commonUtils.isNotEmptyObject(this.props) && commonUtils.isNotEmptyObject(this.props.app) ? this.props.app.currentPane.sModelsType : ''; + let colSpan = 0; + if ((!totalData.length && !totalData1.length) || this.props.footer !== undefined) { + return (<>); + } + if(this.props.tableProps.rowSelection !== null && !(this.props.config && !this.props.config.bisMutiSelect)) { + colSpan = colSpan + 1; + } + if(this.props.slaveInfo) { + colSpan = colSpan + 1; + } + if(this.props.dragHandle) { + // colSpan = colSpan + 1; // 临时处理标准精准报价单据工序信息表合计错位问题 + } + const cells = []; + const cells1 = []; + if (totalData.length) { + let summaryCellTotal = ''; + summaryCellTotal = ( + + 合计 + + ); + // if(this.props.slaveInfo) { + // summaryCellTotal = ( + // + // 合计 + // + // ); + // } else { + // summaryCellTotal = ( + // + // 合计 + // + // ); + // } + + cells.push(summaryCellTotal); + tableColumn.forEach((item, index) => { + if(colSpan === 0 && index === 0) { + return; + } + let iTag = index + colSpan; + if (tableColumn[index].children !== undefined && tableColumn[index].children.length > 0) { /* 循环嵌套标题行 */ + tableColumn[index].children.forEach((itemChild, i) => { + /* 合计 格式化单价、金额 */ + let sValue = totalData[0][itemChild.dataIndex]; + const columnConfig = this.props.config.gdsconfigformslave.find(item => item.sName === itemChild.dataIndex); + if (commonUtils.isNotEmptyObject(itemChild.dataIndex) && itemChild.dataIndex.substring(0, 1) === 'd' && columnConfig?.sDateFormat === 'decimalPoint' && columnConfig?.sFieldValidation) { + /* 取小数点位数 */ + const point = columnConfig.sFieldValidation.split(',')[1] || 2; + if(commonUtils.isNotEmptyNumber(sValue) && sValue !== null) { + const dConfigResult = commonUtils.convertFixNum(Number(sValue), point).toFixed(point); + if(!isNaN(dConfigResult)) { + sValue = dConfigResult; + } + } + } else if( commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase().indexOf('commonList') || (sModelsType && sModelsType.indexOf('commonMultiList') > -1)) { + /* 有配置以配置为主 否则以系统设定为主 */ + if(commonUtils.isNotEmptyObject(itemChild.dataIndex) && itemChild.dataIndex.substring(0, 1) === 'd' && commonUtils.isNotEmptyObject(itemChild.sDateFormat)) { + /* 取小数点位数 */ + let point = 0; + let strIndex = itemChild.sDateFormat.indexOf('.'); + if(strIndex > -1 && itemChild.sDateFormat.length > 1) { + point = itemChild.sDateFormat.substring(strIndex + 1, itemChild.sDateFormat.length).length; + if(commonUtils.isNotEmptyNumber(sValue) && sValue !== null) { + const dConfigResult = commonUtils.convertFixNum(Number(sValue), point).toFixed(point); + if(!isNaN(dConfigResult)) { + sValue = dConfigResult; + } + } + } + } else { + if ( commonUtils.isNotEmptyObject(itemChild.dataIndex) && itemChild.dataIndex.toLowerCase().endsWith('price')) { /* 列表单价格式化显示1 */ + if(commonUtils.isNotEmptyNumber(sValue) && sValue !== null) { + const dResult = commonUtils.convertFixNum(Number(sValue), dNetPrice).toFixed(dNetPrice); + if(!isNaN(dResult)) { + sValue = dResult; + } + } + } else if (commonUtils.isNotEmptyObject(itemChild.dataIndex) && itemChild.dataIndex.toLowerCase().endsWith('money')) { /* 列表金额格式化显示 */ + if(commonUtils.isNotEmptyNumber(sValue) && sValue !== null) { + const dResult = commonUtils.convertFixNum(Number(sValue), dNetMoney).toFixed(dNetMoney); + if(!isNaN(dResult)) { + sValue = dResult; + } + } + } + } + } + const cellChild = ( + + {sValue} + + ); + cells.push(cellChild); + }); + } else { /* 正常单层标题行 */ + let cell = ''; + /* commonList 格式化单价、金额 */ + let sValue = totalData[0][item.dataIndex]; + if( commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase().indexOf('commonList') || (sModelsType && sModelsType.indexOf('commonMultiList') > -1)) { + /* 有配置以配置为主 否则以系统设定为主 */ + const columnConfig = this.props.config.gdsconfigformslave.find(item1 => item1.sName === item.dataIndex); + if (commonUtils.isNotEmptyObject(item.dataIndex) && item.dataIndex.substring(0, 1) === 'd' && columnConfig?.sDateFormat === 'decimalPoint' && columnConfig?.sFieldValidation) { + /* 取小数点位数 */ + const point = columnConfig.sFieldValidation.split(',')[1] || 2; + if(commonUtils.isNotEmptyNumber(sValue) && sValue !== null) { + const dConfigResult = commonUtils.convertFixNum(Number(sValue), point).toFixed(point); + if(!isNaN(dConfigResult)) { + sValue = dConfigResult; + } + } + } else if ( commonUtils.isNotEmptyObject(item.sDateFormat)) { + /* 取小数点位数 */ + let point = 0; + let strIndex = item.sDateFormat.indexOf('.'); + if (strIndex > -1 && item.sDateFormat.length > 1) { + point = item.sDateFormat.substring(strIndex + 1, item.sDateFormat.length).length; + if (commonUtils.isNotEmptyNumber(sValue) && sValue !== null) { + const dConfigResult = commonUtils.convertFixNum(Number(sValue), point).toFixed(point); + if (!isNaN(dConfigResult)) { + sValue = dConfigResult; + } + } + } + } else { + if (commonUtils.isNotEmptyObject(item.dataIndex) && item.dataIndex.toLowerCase().endsWith('price')) { /* 列表单价格式化显示1 */ + if (commonUtils.isNotEmptyNumber(sValue) && sValue !== null) { + const dResult = commonUtils.convertFixNum(Number(sValue), dNetPrice); + if (!isNaN(dResult)) { + sValue = dResult; + } + } + } else if (commonUtils.isNotEmptyObject(item.dataIndex) && item.dataIndex.toLowerCase().endsWith('money')) { /* 列表金额格式化显示 */ + if (commonUtils.isNotEmptyNumber(sValue) && sValue !== null) { + const dResult = commonUtils.convertFixNum(Number(sValue), dNetMoney); + if (!isNaN(dResult)) { + sValue = dResult; + } + } + } + } + } + cell = ( + + {sValue} + + ); + cells.push(cell); + } + }); + } + + if (totalData1.length) { + let summaryCellTotal1 = ''; + summaryCellTotal1 = ( + + 总计 + + ); + cells1.push(summaryCellTotal1); + tableColumn.forEach((item, index) => { + if(colSpan === 0 && index === 0) { + return; + } + let iTag = index + colSpan; + if (tableColumn[index].children !== undefined && tableColumn[index].children.length > 0) { /* 循环嵌套标题行 */ + tableColumn[index].children.forEach((itemChild, i) => { + /* 合计 格式化单价、金额 */ + let sValue = totalData1[0][itemChild.dataIndex]; + const cellChild = ( + + {sValue} + + ); + cells1.push(cellChild); + }); + } else { /* 正常单层标题行 */ + let cell = ''; + /* commonList 格式化单价、金额 */ + let sValue = totalData1[0][item.dataIndex]; + cell = ( + + {sValue} + + ); + cells1.push(cell); + } + }); + } + return ( + + { + totalData.length ? ( + + {cells} + + ) : '' + } + { + totalData1.length ? ( + + {cells1} + + ) : '' + } + + ); + } + + handleSearch = (selectedKeys, confirm, searchColumnName, clearFilters) => { + confirm(); + if (this.mounted) { + this.setState({ searchText: selectedKeys[0], searchColumnName }); + } + let { clearArray } = this.props; + if (commonUtils.isEmptyArr(clearArray)) { + clearArray = []; + } + clearArray.push({ confirm, clearFilters }); + this.props.onSaveState({ clearArray }); + }; + + handleReset = (clearFilters, confirm) => { + clearFilters(); + if (this.mounted) { + this.setState({ searchText: '' }, () => { + // 重置搜索条件 + confirm(); + }); + } + }; + + + /** 求和所有列 */ + handleSumAllColumn = (config, dataSource) => { + const tableDataTotal = {}; + const sumConfig = config.gdsconfigformslave.filter(item => item.sName !== '' && item.bVisible && item.bSum); + if (commonUtils.isNotEmptyArr(sumConfig)) { + if (commonUtils.isNotEmptyObject(config) && commonUtils.isNotEmptyArr(dataSource)) { + dataSource.forEach((tableDataRow) => { + sumConfig.forEach((sumItem) => { + if (tableDataRow.handleType !== 'del') { + if (sumItem.sName.substring(sumItem.sName.length - 5, sumItem.sName.length).toLowerCase() === 'Price'.toLowerCase()) { + tableDataTotal[sumItem.sName] = commonUtils.convertFixNum(commonUtils.convertToNum(tableDataTotal[sumItem.sName]) + + commonUtils.convertToNum(tableDataRow[sumItem.sName]), this.props.getFloatNum(sumItem.sName)); + } else { + /* 如果设置格式 按照设置格式来,否则按照系统设定 */ + const sFieldConfigArr = config.gdsconfigformslave.filter(item => item.sName === sumItem.sName && item.bVisible); + if(commonUtils.isNotEmptyArr(sFieldConfigArr)) { + const { sFieldValidation: sFieldValidationOld, sName } = sFieldConfigArr[0]; + if(commonUtils.isNotEmptyObject(sFieldValidationOld)) { + const [length1, length2] = sFieldValidationOld.split(','); + if(commonUtils.isNotEmptyNumber(length2)) { + tableDataTotal[sumItem.sName] = commonUtils.convertFixNum(commonUtils.convertToNum(tableDataTotal[sumItem.sName]) + + commonUtils.convertToNum(tableDataRow[sumItem.sName]), this.props.getFloatNum(length2)); + } + }else { + tableDataTotal[sumItem.sName] = commonUtils.convertFixNum(commonUtils.convertToNum(tableDataTotal[sumItem.sName]) + + commonUtils.convertToNum(tableDataRow[sumItem.sName]), this.props.getFloatNum(sumItem.sName)); + } + } + + } + } + }); + }); + } else { + sumConfig.forEach((sumItem) => { + tableDataTotal[sumItem.sName] = 0; + }); + } + tableDataTotal.bSum = true; + tableDataTotal.key = '0000'; + + if (this.mounted) { + this.setState({ totalData: [tableDataTotal] }); + } + } + } + + handleSumOtherColumn = (config, dataSource) => { + const tableDataTotal = {}; + const sumConfig = config.gdsconfigformslave.filter(item => item.sName !== '' && item.bVisible && item.bSum); + if (commonUtils.isNotEmptyArr(sumConfig)) { + if (commonUtils.isNotEmptyObject(config) && commonUtils.isNotEmptyArr(dataSource)) { + const { selectedRowKeys } =this.state; + /* 生产排程对选中行进行汇总 */ + if(commonUtils.isNotEmptyArr(selectedRowKeys)) { + const selectedData = dataSource.filter(item => selectedRowKeys.includes(item.sSlaveId)); + if(commonUtils.isNotEmptyArr(selectedData)) { + selectedData.forEach((tableDataRow) => { + sumConfig.forEach((sumItem) => { + if (tableDataRow.handleType !== 'del') { + if (sumItem.sName.substring(sumItem.sName.length - 5, sumItem.sName.length).toLowerCase() === 'Price'.toLowerCase()) { + tableDataTotal[sumItem.sName] = commonUtils.convertFixNum(commonUtils.convertToNum(tableDataTotal[sumItem.sName]) + + commonUtils.convertToNum(tableDataRow[sumItem.sName]), this.props.getFloatNum(sumItem.sName)); + } else { + tableDataTotal[sumItem.sName] = commonUtils.convertFixNum(commonUtils.convertToNum(tableDataTotal[sumItem.sName]) + + commonUtils.convertToNum(tableDataRow[sumItem.sName]), this.props.getFloatNum(sumItem.sName)); + } + } + }); + }); + } + } else { + dataSource.forEach((tableDataRow) => { + sumConfig.forEach((sumItem) => { + if (tableDataRow.handleType !== 'del') { + if (sumItem.sName.substring(sumItem.sName.length - 5, sumItem.sName.length).toLowerCase() === 'Price'.toLowerCase()) { + tableDataTotal[sumItem.sName] = commonUtils.convertFixNum(commonUtils.convertToNum(tableDataTotal[sumItem.sName]) + + commonUtils.convertToNum(tableDataRow[sumItem.sName]), this.props.getFloatNum(sumItem.sName)); + } else { + tableDataTotal[sumItem.sName] = commonUtils.convertFixNum(commonUtils.convertToNum(tableDataTotal[sumItem.sName]) + + commonUtils.convertToNum(tableDataRow[sumItem.sName]), this.props.getFloatNum(sumItem.sName)); + } + } + }); + }); + } + } else { + sumConfig.forEach((sumItem) => { + tableDataTotal[sumItem.sName] = 0; + }); + } + tableDataTotal.bSum = true; + tableDataTotal.key = '0000'; + if (this.mounted) { + this.setState({ totalData: [tableDataTotal] }); + } + } + } + + handleSumChildColumn = (config, dataSource) => { + const tableDataTotal = {}; + const { filteredValue } =this.state; + const sumConfig = config.gdsconfigformslave.filter(item => item.sName !== '' && item.bVisible && item.bSum); + if (commonUtils.isNotEmptyArr(sumConfig)) { + if (commonUtils.isNotEmptyObject(config) && commonUtils.isNotEmptyArr(dataSource) && commonUtils.isNotEmptyArr(filteredValue)) { + /* 序号根据sSqlConditonId分组 序号重排 */ + const groupedData = commonUtils.groupBy(dataSource, item => item.sSqlConditionId); + let selectedData = []; + if (commonUtils.isNotEmptyObject(groupedData)) { + for (const key of Object.keys(groupedData)) { + const eachData = groupedData[key]; + if (commonUtils.isNotEmptyArr(eachData)) { + /* 看当前选中在哪个组里 */ + const iIndex = eachData.findIndex(item => filteredValue.includes(item.sSqlConditionId)); + if(iIndex > -1){ + selectedData = eachData; + } + } + } + } + + if(commonUtils.isNotEmptyArr(selectedData)) { + selectedData.forEach((tableDataRow) => { + sumConfig.forEach((sumItem) => { + if (tableDataRow.handleType !== 'del') { + if (sumItem.sName.substring(sumItem.sName.length - 5, sumItem.sName.length).toLowerCase() === 'Price'.toLowerCase()) { + tableDataTotal[sumItem.sName] = commonUtils.convertFixNum(commonUtils.convertToNum(tableDataTotal[sumItem.sName]) + + commonUtils.convertToNum(tableDataRow[sumItem.sName]), this.props.getFloatNum(sumItem.sName)); + } else { + tableDataTotal[sumItem.sName] = commonUtils.convertFixNum(commonUtils.convertToNum(tableDataTotal[sumItem.sName]) + + commonUtils.convertToNum(tableDataRow[sumItem.sName]), this.props.getFloatNum(sumItem.sName)); + } + } + }); + }); + } + } else { + sumConfig.forEach((sumItem) => { + tableDataTotal[sumItem.sName] = 0; + }); + } + tableDataTotal.bSum = true; + tableDataTotal.key = '0000'; + if (this.mounted) { + this.setState({ totalData: [tableDataTotal] }); + } + } + } + // 表格按钮点击后调用指令集 + handleInstruct = (btnName, callback) => { + const { sInstruct:sInstructStr } = this.props.config; + const sInstruct = commonUtils.convertStrToObj(sInstructStr, {}); + const { data = [] } = sInstruct; + + const btnConfig = data.find(item => item && item.name === btnName && item.click); + if (btnConfig) { + const { click, afterClick, clickOnly } = btnConfig; + if (clickOnly) { + // 只执行指令集 + this.props.onExecInstructSet({ sInstruct: click, showName: "表格按钮only" }); + } else if (afterClick) { + // 先按钮再指令集 + callback && callback(); + setTimeout(() => { + this.props.onExecInstructSet({ sInstruct: click, showName: "表格按钮->指令集" }); + }, 1000); + } else { + // 先指令集再按钮 + this.props.onExecInstructSet({ sInstruct: click, showName: "指令集->表格按钮", callback }); + } + } else { + callback && callback(); + } + } + + /** 查看行 */ + handleLookRow = () => { + this.props.onLookRow(this.props.name); + }; + /** 材料备注行 */ + handleModalRemarkRow = (index) => { + this.props.onModalRow(index); + }; + /** modal行 */ + handleModalRow = (recordIndex, tableName) => { + if (commonUtils.isNotEmptyObject(this.props.tableProps.chooseMaterialsConfigRow)) { + this.handleInstruct('BtnChooseMaterials', () => { + const iIndex = this.props.tableProps.chooseMaterialsConfigRow; + this.props.onBtnChoose('materials', 'BtnChooseMaterials', iIndex, recordIndex, tableName); // recordIndex选中行的索引 + }); + } + }; + handleChooseProcessRow = (record) => { + if (commonUtils.isNotEmptyObject(this.props.tableProps.chooseProcessConfigRow)) { + this.handleInstruct('BtnChooseProcess', () => { + const iIndex = this.props.tableProps.chooseProcessConfigRow; + if(this.props.name === 'slave0Child1') { + const { name } = this.props; + let btnPupopConfig = this.props.tableProps.chooseProcessConfigRow; + this.setState({ + commonPopupVisible: true, + commonPopupTbName: name, + commonPopupShowConfig: btnPupopConfig, + commonPopupRecord: record, + }); + + } else { + this.props.onBtnChoose('process', 'BtnChooseProcess', iIndex); + } + }); + } + }; + + /* 成品工序弹窗 */ + handleChooseProductProcessRow = (recordIndex) => { + /* recordIndex 为选中行下标 */ + if (commonUtils.isNotEmptyObject(this.props.tableProps.chooseProductProcessConfigRow)) { + const btnConfig = this.props.tableProps.chooseProductProcessConfigRow; + this.props.onBtnChoose('productProcess', 'BtnChooseProductProcess', btnConfig, recordIndex); + } + }; + + /* 成品材料弹窗 */ + handleChooseProductMaterialsRow = (recordIndex) => { + /* recordIndex 为选中行下标 */ + if (commonUtils.isNotEmptyObject(this.props.tableProps.chooseProductMaterialsConfigRow)) { + const btnConfig = this.props.tableProps.chooseProductMaterialsConfigRow; + this.props.onBtnChoose('productMaterials', 'BtnChooseProductMaterials', btnConfig, recordIndex); + } + }; + + /** 添加行 */ + handleAddRow = (index, bModalAdd) => { + this.stopRowClick = true; + /* 多表树形删除 */ + if(this.props && this.props.slaveInfo && this.props.slaveInfo.tableProps && this.props.slaveInfo.tableProps.bSlaveInfo) { + this.handleAddInfoRow(index); + return; + } + setTimeout(() => { + if (this.props.onAddRow) { + this.handleInstruct('BtnAdd', () => { + this.props.onAddRow(this.props.name, null, index, this.props.bFinished, bModalAdd); + }); + } + }, 0) + }; + handleAddInfoRow = (index) => { + const tableInfoName = this.props.slaveInfo.name; + setTimeout(() => { + if (this.props.onAddRow) { + this.handleInstruct('BtnAdd', () => { + this.props.onAddRow(tableInfoName, null, index, false, false); + }); + } + }, 0) + }; + + handleTreeAdd = () => { + setTimeout(() => { + this.handleInstruct('BtnAdd', () => { + if (this.props.onTreeAdd) { + this.props.onTreeAdd(this.props.name, true, 'sameNode'); + } + }); + }, 0) + }; + handleTreeAddChild = () => { + setTimeout(() => { + this.handleInstruct('BtnAddChildNode', () => { + if (this.props.onTreeAddChild) { + this.props.onTreeAddChild(this.props.name, true, 'childNode'); + } + }); + }, 0) + }; + handleTreeCopyAll = () => { + setTimeout(() => { + this.handleInstruct('BtnCopyAll', () => { + if (this.props.onTreeCopyAll) { + this.props.onTreeCopyAll(this.props.name, false, 'isChild'); + } + }); + }, 0) + }; + handleTreeDel = (index, record) => { + if(this.props.name === 'control') { + const _this = this; + confirm({ + title: '确认要删除吗?', + onOk() { + _this.handleTreeDelOk(index, record); + }, + onCancel() { + return false; + }, + okText: '确定', + cancelText: '取消' + }); + } else { + this.handleTreeDelOk(index, record); + } + }; + handleTreeDelOk = () => { + setTimeout(() => { + this.handleInstruct('BtnDel', () => { + if (this.props.onTreeDel) { + this.props.onTreeDel(this.props.name, true, ''); + } + }); + },0); + }; + /** 复制 */ + handleCopyRow = (index) => { + setTimeout(() => { + this.handleInstruct('BtnCopy', () => { + if (this.props.onCopyRow) { + this.props.onCopyRow(this.props.name, undefined, undefined, index); + } + }); + },0) + }; + /** 复制全部 */ + handleCopyAllRow = () => { + setTimeout(() => { + this.handleInstruct('BtnCopyAll', () => { + if (this.props.onCopyAllRow) { + this.props.onCopyAllRow(this.props.name); + } + }); + }, 0) + }; + /** 删除行 */ + handleDelRow = (index, record) => { + if(this.props.name !== 'slaveFilter') { + const _this = this; + confirm({ + title: '确认要删除吗?', + onOk() { + _this.handleDelOkRow(index, record); + }, + onCancel() { + return false; + }, + okText: '确定', + cancelText: '取消' + }); + } else { + this.handleDelOkRow(index, record); + } + }; + + /** 删除行 */ + handleDelOkRow = (index, record) => { + const tableSelectedRowKeys = []; + if(this.props?.formId === '12710101117043535363530') { + tableSelectedRowKeys.push(record[this.rowKey]); + } else { + tableSelectedRowKeys.push(record.sId); + } + /* 多表树形删除 */ + if(this.props && this.props.slaveInfo && this.props.slaveInfo.tableProps && this.props.slaveInfo.tableProps.bSlaveInfo) { + this.handleDelInfoRow(index, record); + return; + } + setTimeout(() => { + this.handleInstruct('BtnDel', () => { + if (this.props.onDelRow(this.props.name, false, tableSelectedRowKeys, undefined, index)) { + this.handleSumAllColumn(this.props.config, this.state.dataSource); + } + }); + }, 0); + // if (this.props.formRoute === '/indexOee/processReport') { + // localStorage.setItem(`${commonConfig.prefix}oeeEmployeeData`, JSON.stringify(this.props.data)); + // this.props.onSaveState({ + // employeeData: JSON.parse(localStorage.getItem(`${commonConfig.prefix}oeeEmployeeData`)), + // }); + // } + }; + + handleDelInfoRow = (index, record) => { + const tableSelectedRowKeys = []; + tableSelectedRowKeys.push(record.sId); + const tableInfoName = this.props.slaveInfo.name; + setTimeout(() => { + this.handleInstruct('BtnDel', () => { + this.props.onDelRow(tableInfoName, false, tableSelectedRowKeys) + }); + }, 0); + }; + + /** 复制 */ + handleCopyMoreRow = (index) => { + this.setState({ bOperateMoreVisible : true}); + }; + + /** 提取数据 */ + handleReplaceRow = (index, record) => { + if (this.props.onReplaceRow) { + this.props.onReplaceRow(this.props.name, record); + } + }; + + /** 下载行 */ + handleDownloadRow = (index, record) => { + const tableSelectedRowKeys = []; + tableSelectedRowKeys.push(record.sId); + if (this.props.onDownloadRow) { + this.props.onDownloadRow(this.props.name, false, tableSelectedRowKeys); + } + }; + /** 通用弹窗新增行 */ + handlePopupRow = (index, record, btnName) => { + const { name, config } = this.props; + let btnPupopConfig = {}; + if (commonUtils.isNotEmptyArr(config) && commonUtils.isNotEmptyArr(config.gdsconfigformslave)) { + let controlConfig = config.gdsconfigformslave.filter(item => commonUtils.isNotEmptyObject(item.sControlName) && (item.sControlName.includes('BtnPopup') || item.sControlName.includes('BtnHeadPopup'))); + if(btnName && typeof btnName === 'string') { + controlConfig = config.gdsconfigformslave.filter(item => commonUtils.isNotEmptyObject(item.sControlName) && item.sControlName === btnName); + } + if (commonUtils.isNotEmptyArr(controlConfig)) { + if (controlConfig[0].bVisible && controlConfig[0].sDropDownType === 'popup') { + btnPupopConfig = controlConfig[0]; + this.setState({ + commonPopupVisible:true, + commonPopupTbName:name, + commonPopupShowConfig:btnPupopConfig, + commonPopupRecord:record, + }); + } + } + } + }; + /** 查看工艺参数 */ + handleParamRow = (index, record) => { + const tableSelectedRowKeys = []; + tableSelectedRowKeys.push(record.sId); + this.props.onShowParamRow(this.props.name, record, tableSelectedRowKeys); + }; + + /** 拖动排序 */ + handleSaveOrder = (sortItems, isSlaveInfo) => { + const { formSrcRoute } = isSlaveInfo ? this.props.slaveInfo : this.props; + const { token } = isSlaveInfo ? this.props.slaveInfo.app : this.props.app; + const sActiveId = isSlaveInfo ? this.props.slaveInfo.app.currentPane.formId : this.props.app.currentPane.formId; + const url = `${commonConfig.server_host}configform/sHandleConfigform?sModelsId=${sActiveId}&sName=${formSrcRoute}`; + const headerArr = isSlaveInfo ? this.props.slaveInfo.headerColumn.map(item => item.dataIndex) : this.props.headerColumn.map(item => item.dataIndex); + const handleData = isSlaveInfo ? this.props.slaveInfo.config.gdsconfigformslave.filter(item => headerArr.indexOf(item.sName) !== -1) : this.props.config.gdsconfigformslave.filter(item => headerArr.indexOf(item.sName) !== -1); + let sortIndexFirst = 0; + let sortIndexLast = 0; + + handleData.forEach((item, index) => { + if (item.sName === sortItems[0]) { + sortIndexFirst = index; + } + if (item.sName === sortItems[1]) { + sortIndexLast = index; + } + }); + + const tempOrder = handleData[sortIndexFirst].iOrder; + handleData[sortIndexFirst].iOrder = handleData[sortIndexLast].iOrder; + handleData[sortIndexLast].iOrder = tempOrder; + + const postData = isSlaveInfo ? { + [this.props.slaveInfo.config.sId]: handleData, + } : { + [this.props.config.sId]: handleData, + }; + // console.log(postData, 'postData'); + // console.log(sortItems, 'sortItems'); + + const value = { + handleType: 'group', + sJurisdictionClassifyId: '', + bDefault: true, + handleData: postData, + }; + + const options = { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + authorization: token, + }, + body: JSON.stringify(value), + }; + const { dispatch } = this.props; + fetch(url, options).then(response => response.json()).then((json) => { + if (json.code === 1) { + this.forceUpdate(); + } else if (json.code === -2) { + dispatch({ type: 'app/throwError', payload: json }); + } + }); + }; + + /** 查找控件名是否存在 */ + findIsExistByControlName = (props, controlName) => { + // 解决操作栏按钮没显示但是加上了宽度问题 + let propsIcon = true; + switch (controlName) { + // case 'BtnUpload': + // propsIcon = ''; + // break; + // case 'BtnLook': + // propsIcon = ''; + // break; + // case 'BtnAdd': + // propsIcon = props.tableProps.setAdd; + // break; + case 'BtnChooseMaterials': + propsIcon = props.tableProps.setMaterial; + break; + case 'BtnChooseProcess': + propsIcon = props.tableProps.setProcess; + break; + // case 'BtnCopy': + // propsIcon = props.tableProps.setCopy; + // break; + // case 'BtnCopyAll': + // propsIcon = props.tableProps.setCopyAll; + // break; + // case 'BtnDel': + // propsIcon = props.tableProps.setDelete; + // break; + default: + break; + } + + /* 返回值声明 */ + let ret = false; + /* 查询控件名是否存在 */ + if (commonUtils.isNotEmptyArr(props.config) && commonUtils.isNotEmptyArr(props.config.gdsconfigformslave) && commonUtils.isNotEmptyStr(controlName)) { + const controlConfig = props.config.gdsconfigformslave.filter(item => item.sControlName === controlName); + ret = commonUtils.isEmptyArr(controlConfig) ? ( propsIcon ? true : false ) : commonUtils.converStrToBoolean(controlConfig[0].bVisible); + } + /* 返回值 */ + return ret; + }; + + BtnUploadDivPropsAttr = React.createRef(); + + /** 查找控件名是否存在 */ + findIsUpdByControlName = (props, controlName) => { + /* 返回值声明 */ + let ret = false; + /* 查询控件名是否存在 */ + if (commonUtils.isNotEmptyArr(props.config) && commonUtils.isNotEmptyArr(props.config.gdsconfigformslave) && commonUtils.isNotEmptyStr(controlName)) { + const controlConfig = props.config.gdsconfigformslave.filter(item => item.sControlName === controlName); + ret = commonUtils.isNotEmptyArr(controlConfig) && commonUtils.converStrToBoolean(controlConfig[0].iTag === 3); + if(ret && controlName === 'BtnUpload' && Array.isArray(controlConfig)) { + this.BtnUploadDivPropsAttr.current = controlConfig[0]; + } + } + /* 返回值 */ + return ret; + }; + + /** 查找控件名是否显示 */ + findVisibleControlName = (props, controlName) => { + /* 返回值声明 */ + let ret = false; + /* 查询控件名是否存在 */ + if (commonUtils.isNotEmptyArr(props.config) && commonUtils.isNotEmptyArr(props.config.gdsconfigformslave) && commonUtils.isNotEmptyStr(controlName)) { + const controlConfig = props.config.gdsconfigformslave.filter(item => item.sControlName === controlName); + ret = commonUtils.isNotEmptyArr(controlConfig) && commonUtils.converStrToBoolean(controlConfig[0].bVisible); + } + /* 返回值 */ + return ret; + }; + /** 查找控件名是否存在 */ + findIsExistByControlPopup = (props, controlName) => { + /* 返回值声明 */ + let ret = false; + /* 查询控件名是否存在 */ + if (commonUtils.isNotEmptyArr(props.config) && commonUtils.isNotEmptyArr(props.config.gdsconfigformslave) && commonUtils.isNotEmptyStr(controlName)) { + const controlConfig = props.config.gdsconfigformslave.filter(item => commonUtils.isNotEmptyObject(item.sControlName) && item.sControlName.includes(controlName) && !item.sControlName.includes('.')); + if (commonUtils.isNotEmptyArr(controlConfig)) { + if (controlConfig[0].bVisible && controlConfig[0].sDropDownType === 'popup') { + ret = true; + } + } + } + /* 返回值 */ + return ret; + }; + + handleGetRjRes = (res, index, sName) => { + const { masterData = {}, formId, enabled } = this.props; + if (enabled && formId === "12710101117225611571970" && masterData.sTeamName?.includes('质检') && sName === "sInspectionCode") { + return ( + <> + {res} +
+ + + + ); + }; + } + + if (commonUtils.isNotEmptyArr(tableProps.columns)) { + const lastColumn = tableProps.columns[tableProps.columns.length - 1]; + if (lastColumn.title && typeof lastColumn.title === 'string' && lastColumn.title.indexOf('-') === -1) { + lastColumn.width && delete lastColumn.width; + } + } + + const { officePreviewVisible, officeFileUrl } = this.state; + const officePreviewProps = { + app: this.props.app, + officePreviewVisible, + officeFileUrl, + bFullUrl: false, + onCancel: () => { + this.setState({ officePreviewVisible: false }); + } + }; + + let layoutScrollY; + if (this.props.layoutH) { + layoutScrollY = this.props.layoutH * 40 - 10 - 30 - 2; + if (this.props.bInTab) { + layoutScrollY -= 30; + } + } else if (this.props.fixedHeight) { + layoutScrollY = this.props.fixedHeight; + } + let bShowBtnUpload = true; + if(commonUtils.isNotEmptyObject(this.props.masterData) && commonUtils.isNotEmptyObject(this.props.masterData.sZczlxShowName)) { + bShowBtnUpload = this.props.masterData.sZczlxShowName !== '删除' && this.props.masterData.sZczlxShowName !== '恢复'; + } + + const hasColorInfo = this.props?.masterConfig?.sTableColorTs; + + return ( + +
+ { + this.props.name === 'picFile' || (commonUtils.isNotEmptyObject(this.props.name) && this.props.name.indexOf('file') > -1) || + (this.props.name.startsWith('slave') && this.findIsUpdByControlName(this.props, 'BtnUpload') && bShowBtnUpload ) ? + + + + : null } +
+
{ + this.mydiv = ref; + if (this.mydiv) { + this.computedTdWidth(); + if (false && commonUtils.isNotEmptyObject(location.pathname) && location.pathname.includes('commonListTab')) { + this.mydiv.getElementsByClassName('ant-table-body')[0].style.height = this.tableHeight ? this.tableHeight + 'px': 80 + 'px'; + } + if (layoutScrollY) { + this.mydiv.getElementsByClassName('ant-table-body')[0].style.height = typeof layoutScrollY === 'number' ? layoutScrollY + 'px' : layoutScrollY; + } + } + }} + id={`table_${this.props.formId}_${this.props.config?.sId}`} + > + { + this.isDragAndDrop ? + +
+ : +
+
+ + } + + { hasColorInfo && + this.colorInfo = e}> + + + { tableProps.pagination && {this.onChange({ current: page, pageSize })}} + /> } + + + } + + + { + previewVisible ? + +
+ {/* 图片正常的列表显示 */} +
+ {commonUtils.isNotEmptyArr(data) ? data.map((item, i) => { + return ( + // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions + example this.showimg(i)} + key={item} + /> + ); + }) : ''} +
+ {/* 引入的image组件s */} + +
+
+ : '' + }{ + commonPopupVisible ? + + {bCommonPopup ? + + : bCommonPopup1 ? + + : bCommonPopupTree ? + : '' + } + + : '' + } + { + commonFieldPopupVisible ? + + {[''].map(() => { + if (commonFieldPopupShowConfig.sControlName?.includes("popupSingle")) { + if (this.props.enabled && commonFieldPopupShowConfig.sControlName?.includes("edit")) { + commonFieldPopupProps.editable = true; + } + return ; + } else { + return isBtnPopupEdit ? : bFieldPopup ? : ; + } + })} + + : '' + } + + { + commonModalVisible ? + + + + : '' + } + + { + commonFileDownloadVisible ? + { + const newList = [...commonFileDownloadList]; + const checkState = newList.find(item => !item.checked); + newList.forEach(item => item.checked = checkState); + this.setState({ + commonFileDownloadList: newList + }) + } + }>全选/取消全选, + , + , + ]} + > +
{ + commonFileDownloadList.map(item => { + const { url, checked } = item; + const fileName = url.split('/').pop().split('_').pop(); + const fileType = fileName.split('.').pop().toLowerCase(); + const previewFileList = ['jpg', 'png', 'jepg', 'webp', 'svg', 'bmp', 'apng', 'pdf']; + return ( + +
+ { + if (sessionStorage.previewFlag) { + sessionStorage.removeItem('previewFlag'); + } else { + const newList = [...commonFileDownloadList]; + newList.find(item => item.url === url).checked = e.target.checked; + this.setState({ + commonFileDownloadList: newList + }) + } + }} + > + { + sessionStorage.previewFlag = 1; + if (fileType === 'pdf') { + this.setState({ + pdfFileVisible: true, + pdfFileUrl: url, + }); + } else { + this.handlePreviewImage(e, [url]); + } + }} title="预览"> + {fileName} + +
+
+ ) + }) + }
+
+ : '' + } + { + pdfFileVisible ? + { + this.setState({ + pdfFileVisible: false + }); + }} + > +
+ +
+
: '' + } + { + bOperateMoreVisible ? + { + this.setState({ + bOperateMoreVisible: false + }); + }} + > +
+ +
+
: '' + } + + {officePreviewVisible && } + {/* 简单对话框 */} + { this.state.simpleModalVisible && this.setState({ simpleModalVisible: false, simpleModalWord: '' })} + > +
+ } + + ); + } +} + +const CommonTable = (props) => { + const { name, data = [] } = props; + const [headerColumn, setHeaderColumn] = useState([]); + const addState = {}; + if (name !== 'master') { + const config = props.onMergeSlaveConfig && props.onMergeSlaveConfig(props.config); + if (commonUtils.isNotEmptyObject(config)) { + addState.config = config; + addState.headerColumn = commonFunc.getHeaderConfig(addState.config).map(i => { + const value = Array.isArray(headerColumn) && headerColumn.find(j => j && j.dataIndex === i.dataIndex); + value && (i.width = value.width); + return i; + }); + } + } + + // 增加行号iRowNum + const [updateRowNumTime, setUpdateRowNumTime] = useState(0); + addState.updateRowNumTime = updateRowNumTime; + useEffect(() => { + handleSetIRowNum(data, props); + setUpdateRowNumTime(pre => pre + 1); + }, [JSON.stringify(data)]); + + if (props.defaultExpandAllRows !== undefined && props.data === undefined) { + return ''; + } + + const handleMoveLine = ({ index, direction }) => { + if (direction === "up" && index === 0) { + message.error("当前已是首行,无法上移!"); + return; + } else if (direction === "down" && index === data.length - 1) { + message.error("当前已是末行,无法下移!"); + return; + } + + const indexNew = direction === "up" ? index - 1 : index + 1; + const iOrder1 = data[index].iOrder; + const iOrder2 = data[indexNew].iOrder; + data[index].iOrder = iOrder2; + data[indexNew].iOrder = iOrder1; + + const tempItem = data[index]; + data[index] = {...data[indexNew], handleType: data[indexNew].handleType || "update"}; + data[indexNew] = {...tempItem, handleType: tempItem.handleType || "update"}; + + props.onSaveState({ + [`${props.name}Data`]: data + }); + }; + + addState.onMoveLine = handleMoveLine; + + if (sessionStorage.getItem(`${props.formId}_${props.config?.sId}_tableHeight`)) { + addState.fixedHeight = Number(sessionStorage.getItem(`${props.formId}_${props.config.sId}_tableHeight`)); + if (props.tableProps?.AutoTableHeight) { + delete props.tableProps.AutoTableHeight; + } + } + const setTempFixedHeight = (height) => { + sessionStorage.setItem(`${props.formId}_${props.config.sId}_tableHeight`, height); + window.vlistNewSearh = true; + setUpdateRowNumTime(pre => pre + 1); + } + const uniqueTableId = `table_${props.formId}_${props.config?.sId}`; + + return ( + + + + + ); +}; + +const handleSetIRowNum = (data, props) => { + data.forEach((item, index) => { + item.iRowNum = index + 1; + if (['12710101117007068710620'].includes(props?.app?.currentPane?.formId)) { + item.sVersionNum = item.iRowNum.toString().padStart(2, 0); + } + + // 排除成品盘点、材料盘点(数据太多,循环页面卡死) + if (props.name === 'slaveChild' && !['192116810113315264733417750', '192116810113315228128521360'].includes(props?.app?.currentPane?.formId)) { + /* 序号根据sSqlConditonId分组 序号重排 */ + const groupedData = commonUtils.groupBy(data, item => item.sSqlConditionId); + if (commonUtils.isNotEmptyObject(groupedData)) { + for (const key of Object.keys(groupedData)) { + const eachData = groupedData[key]; + if (commonUtils.isNotEmptyArr(eachData)) { + eachData.forEach((item, index) => { + /* 采购 */ + item.iRowNum = index +1; + const iIndex = data.findIndex(row => row.sId === item.sId); + if(iIndex > -1) { + data[iIndex] ={...data[iIndex], iRowNum: index +1} + } + + }); + } + } + } + } + if(location.pathname !== '/indexPage/commonClassify'){ + if (commonUtils.isNotEmptyArr(item.children)) { + handleSetIRowNum(item.children, props); + } + } + }); +} + +const MoveLineComponent = (props) => { + + if (!location.pathname.includes('commonSubBill')) { + return ""; + } + + const [position, setPosition] = useState({ bottom: 0 }); + const positionRef = useRef(position); + positionRef.current = position; + + const divProps = { + className: styles.moveLine, + style: position, + onMouseDown: e => { + const initialBottom = position.bottom; + const initialY = e.clientY; + + const moveHandler = (moveEvent) => { + const newY = moveEvent.clientY; + const newBottom = initialBottom - (newY - initialY); + setPosition({ bottom: newBottom }); + }; + + const upHandler = () => { + const preHeight = document.querySelector(`#${props.uniqueTableId}`).querySelector('.ant-table-body').getBoundingClientRect().height; + props.setTempFixedHeight(Math.max(preHeight - positionRef.current.bottom, 37)); + setPosition({ bottom: 0 }); + document.body.onselectstart = () => true; + document.removeEventListener('mousemove', moveHandler); + document.removeEventListener('mouseup', upHandler); + }; + + document.body.onselectstart = () => false; + document.addEventListener('mousemove', moveHandler); + document.addEventListener('mouseup', upHandler); + } + }; + + return
; +} + +export default CommonTable; diff --git a/src/components/Common/CommonTable/index.less b/src/components/Common/CommonTable/index.less new file mode 100644 index 0000000..1513909 --- /dev/null +++ b/src/components/Common/CommonTable/index.less @@ -0,0 +1,141 @@ +.subForm { + margin-bottom: 10px; + position: relative; + .extraAction { + position: absolute; + top: -30px; + right: 0; + .del { + background: #fd674a; + border: 1px solid #fd674a; + &:hover { + color: #fff; + border: 1px solid #fb795f!important; + background: #fb795f!important; + } + } + } + .summaryCell{ + color: red; + font-weight: bold; + white-space:nowrap; /* 合计不换行 */ + overflow: hidden;/*超出部分隐藏*/ + text-overflow:ellipsis;/*超出部分文字以...显示*/ + display: block; + } + .summaryCellTotal{ + color: black; + font-weight: bold; + } +} +.disabledProup { + .iconAdd i:hover:before { + color: rgba(0, 0, 0, 0.43); + } + .editSelect > div:hover { + border-color: transparent!important; + background: transparent!important; + } + .editSelect > div:hover span { + color: rgba(0, 0, 0, 0.25); + } + .editSelect > div > div > div { + color: #000!important; + } + .inputNum input:hover { + border: 2px solid transparent!important; + background: transparent!important; + } + input[disabled]:hover { + background: none!important; + } + .tableDataPicker input:hover { + border: 1px solid #e6d8d8!important; + } +} +.disabledProup, .proup { + :global { + .ant-table-scroll > div:last-child { + position: relative; + } + + } +} +:global { + .react-resizable { + position: relative; + background-clip: padding-box; + } + .react-resizable-handle { + position: absolute; + width: 10px; + height: 100%; + bottom: 0; + right: -5px; + cursor: col-resize; + z-index: 1; + } + th[bnotresize] .react-resizable-handle{ + cursor: default; + } + .tableNoPadding { + .ant-table-row { + td{ + padding: 0 !important; + } + } + } + .vlist-td-display { + display: none; + } + .virtuallist>table>tbody>tr:nth-of-type(2) { + .vlist-td-display { + display: table-cell; + } + } +} + +.tdCell { + .fastSearchBtn { + position: absolute; + top: 0; + right: 0; + background-color: #fff7e6; + display: none; + &:hover { + color: #2f54eb; + zoom: 1.1; + } + } + &:hover { + .fastSearchBtn { + display: block; + } + } +} + +.colorInfo { + display: flex; + flex-wrap: wrap; + font-size: 10px; +} + +.moveLine { + position: absolute; + bottom: 0; + left: 0; + width: 100%; + height: 2px; + border: 2px dashed #448ef7; + z-index: 2; + cursor: ns-resize; + opacity: 0; + + &:hover { + opacity: 1; + } + + &:active { + border-color: #72c240; + } +} \ No newline at end of file diff --git a/src/components/Common/CommonTableNew/index.less b/src/components/Common/CommonTableNew/index.less new file mode 100644 index 0000000..b5beeb7 --- /dev/null +++ b/src/components/Common/CommonTableNew/index.less @@ -0,0 +1,5 @@ +.tableNew { + border: 1px solid red; + width: 100%; + height: 100%; +} \ No newline at end of file diff --git a/src/components/Common/CommonTableNew/index.tsx b/src/components/Common/CommonTableNew/index.tsx new file mode 100644 index 0000000..1a27e62 --- /dev/null +++ b/src/components/Common/CommonTableNew/index.tsx @@ -0,0 +1,65 @@ +import React from 'react'; +import { Table } from 'antd'; +import type { TableProps } from 'antd'; +import * as commonUtils from '@/utils/utils'; + +import style from './index.less'; + + +interface PropsType { + data: TableProps['dataSource']; + headerColumn: TableProps['columns']; +} + +const TableNew: React.FC = (props) => { + const tableProps = { + columns: TableHeader(props), + dataSource: TableData(props), + scroll: { + // x: 'max-content', + y: '100%', + } + }; + + return ( +
+ {...tableProps} /> +
+ ); +}; + + +// 处理数据 +const TableData = (props: PropsType): PropsType['data'] => { + const { data = [] } = props; + return data; +} + +// 处理表头 +const TableHeader = (props: PropsType): PropsType['headerColumn'] => { + const { headerColumn = [], data = [] } = props; + + return headerColumn.map((colunm) => { + colunm.ellipsis = true; + // colunm.textWrap = 'word-break', + if (!('dataIndex' in colunm)) return colunm; + const { dataIndex } = colunm; + if (dataIndex === 'sPartNameStatus') { + interface TextJsonItem { + sProcessName: string; + sState: number; + } + return { + ...colunm, + render: (text: string, record: object) => { + const textJson: TextJsonItem[] = commonUtils.convertStrToObj(text.replace(",]", ']'), []) as TextJsonItem[]; + console.log('=====xxx', text, textJson); + return textJson.map(item => item.sProcessName).join('->'); + }, + }; + } + return colunm; + }); +} + +export default TableNew; \ No newline at end of file diff --git a/src/components/Common/EditorModal/index.js b/src/components/Common/EditorModal/index.js new file mode 100644 index 0000000..6800951 --- /dev/null +++ b/src/components/Common/EditorModal/index.js @@ -0,0 +1,101 @@ +/* eslint-disable */ +import React, { Component } from 'react'; +import '@ant-design/compatible/assets/index.css'; +import AntdDraggableModal from '@/components/Common/AntdDraggableModal'; +import BraftEditor from 'braft-editor' +import 'braft-editor/dist/index.css' + +export default class EditorModal extends Component { + /** 构造函数 */ + constructor(props) { + super(props); + this.controls = [ + 'undo', 'redo', 'separator', + 'font-size', 'line-height', 'letter-spacing', 'separator', + 'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator', + 'superscript', 'subscript', 'remove-styles',  'separator', 'text-indent', 'text-align', 'separator', + 'headings', 'list-ul', 'list-ol', 'blockquote', 'code', 'separator', + 'link', 'separator', 'hr', 'separator', + 'separator', + 'clear', 'media', + ] + this.state = { + editorState: BraftEditor.createEditorState(null) + }; + } + + componentWillReceiveProps(nextProps) { + if (nextProps.curEditorProps) { + if (nextProps.curEditorProps.value) { + this.setState({ + editorState: BraftEditor.createEditorState(nextProps.curEditorProps.value) + }) + } else { + this.setState({ + editorState: BraftEditor.createEditorState(null) + }) + } + } + } + + handleEditorChange = (editorState) => { + this.setState({ editorState }) + } + + handleCloseModal = () => { + this.props.onSaveState({ + curEditorProps: { + ...this.props.curEditorProps, + visible: false + } + }) + } + + handleOk = () => { + let { masterData, curEditorProps } = this.props; + let addState = {}; + const value = this.state.editorState.toHTML(); + let handleType = masterData.handleType ? masterData.handleType : 'update';/* 获取操作类型 */ + addState.handleType = handleType; + addState[curEditorProps.sName] = value; + this.props.onSaveState({ masterData: {...masterData, ...addState}, curEditorProps: {...curEditorProps, value} }); + this.handleCloseModal(); + }; + + handleCancel = () => { + this.handleCloseModal(); + }; + + /** 渲染 */ + render() { + const { curEditorProps = {} } = this.props; + let visible = false; + if (Object.keys(curEditorProps).length) { + visible = curEditorProps.visible; + } + return ( +
+ { + visible ? + + : '' + } +
+ ); + } +} diff --git a/src/components/Common/FileImposition/index.js b/src/components/Common/FileImposition/index.js new file mode 100644 index 0000000..33e7209 --- /dev/null +++ b/src/components/Common/FileImposition/index.js @@ -0,0 +1,485 @@ +/* eslint-disable */ +import React, { useState, useEffect } from "react"; +import { + Button, + Upload, + message, + Progress, + Modal, + notification, + Spin +} from "antd"; +import { UploadOutlined } from "@ant-design/icons"; +import AntdDraggableModal from "@/components/Common/AntdDraggableModal"; +import * as commonBusiness from "@/components/Common/commonBusiness"; +import * as commonFunc from "@/components/Common/commonFunc"; +import StaticEditTable from "@/components/Common/CommonTable"; +import * as commonUtils from "@/utils/utils"; +import * as commonServices from "@/services/services"; +import styles from "./index.less"; + +const FileImpositionEvent = props => { + const [mianhuaUrl, setMiaohuaUrl] = useState(""); + const [fileQueryUrl, setFileQueryUrl] = useState(""); + const [uploadFileUrl, setUploadFileUrl] = useState(""); + + useEffect(() => { + fetch("/pinban.json") + .then(response => response.json()) + .then(data => { + const { mianhuaUrl, fileQueryUrl, uploadFileUrl } = data; + setMiaohuaUrl(mianhuaUrl); + setFileQueryUrl(fileQueryUrl); + setUploadFileUrl(uploadFileUrl); + }) + .catch(error => { + console.error("Error fetching JSON data:", error); + }); + + const { masterData = {} } = props; + const { sGenerate_files } = masterData; + const { fileList = [] } = commonUtils.convertStrToObj(sGenerate_files); + const pinbanData = fileList.map((filename, index) => ({ + sId: index, + fileType: filename.split(".").pop(), + sFileName: filename + })); + props.onSaveState({ + pinbanData + }); + }, []); + + const [bCreating, setBCreating] = useState(false); + + return { + ...props, + mianhuaUrl, + fileQueryUrl, + uploadFileUrl, + bCreating, + setBCreating + }; +}; + +const FileImposition = baseProps => { + const { visible } = baseProps; + if (!visible) return ""; + const props = FileImpositionEvent(baseProps); + const { onCancel, onOk, fileName, bCreating } = props; + + const divProps = { + action: props.uploadFileUrl, + onChange: handleUploadChange.bind(this, props), + accept: "*/*", + showUploadList: false, + multiple: true + // customRequest: async options => { + // const { file, onSuccess, onError } = options; + // const formData = new FormData(); + // formData.append("file", file); + + // formData.append("savePathStr", "24120138_3"); + // try { + // const response = await fetch( + // `${commonConfig.file_host}file/uploadMultiMh`, + // { + // method: "POST", + // body: formData + // } + // ); + + // if (response.ok) { + // const result = await response.json(); + // console.log("=====result", result); + // } else { + // onError(new Error("文件上传失败")); + // } + // } catch (error) { + // onError(error); + // } + // } + }; + + const sGenerate_files = commonUtils.convertStrToObj( + props.masterData.sGenerate_files + ); + const { previewUrl } = sGenerate_files; + + return ( + { + if (previewUrl) { + Modal.confirm({ + title: "温馨提示:", + content:
已生成拼板,是否需要合成新拼板?
, + onOk() { + handleCreateFile(props); + } + }); + } else { + handleCreateFile(props); + } + }} + > + 合成拼板 + , + , + , + + ]} + > + + + {fileName} + +
+ +
+ +
+ ); +}; + +const handleCreateFile = async props => { + props.setBCreating(true); + const { pinbanSelectedRowKeys = [], pinbanData = [] } = props; + + if (!pinbanData.length) { + message.info("请先上传附件!"); + return; + } + + let rowKeys = pinbanSelectedRowKeys; + + if (!pinbanSelectedRowKeys.length) { + const result = await new Promise(resolve => { + Modal.confirm({ + title: "温馨提示:", + content:
未勾选附件,是否用全部附件合成拼板?
, + okText: "是", + cancelText: "否", + onOk() { + resolve(true); + }, + onCancel() { + resolve(false); + } + }); + }); + if (!result) { + props.setBCreating(false); + return; + } + + rowKeys = pinbanData.map(item => item.sId); + } + + const returnData = await commonServices.postValueService( + "miaohua", + { + method: "auth.create_session", + user_name: "xly", + user_pass: "1234" + }, + props.mianhuaUrl + ); + + const { data = {} } = returnData; + const { session } = data; + if (!session) { + handleDealError(props); + return; + } + + const files = pinbanData + .filter(item => rowKeys.includes(item.sId)) + .map(item => item.sFileName); + + const returnData1 = await commonServices.postValueService( + "miaohua", + { + method: "hub.start_from_whitepaper_with_files_and_variables", + session, + whitepaper_name: "XLY-SR", + input_name: "erp-s&r", + options: { + variables: { + OrderID: "20250222001", + srheight: "957", + srwidth: "275", + fcounts: "616,176", + StyleP: "label" + }, + files + } + }, + props.mianhuaUrl + ); + + const { data: data1 = {} } = returnData1; + const { workable_id } = data1; + if (!workable_id) { + handleDealError(props); + return; + } + + notification.open({ + key: "fileCreating", + placement: "topRight", + message: "温馨提示", + description: ( +
+ + {" 拼板文件生成中..."} +
+ ) + }); + + let times = 0; + const timer = setInterval(() => { + times += 1; + commonServices + .postValueService("miaohua", { workable_id }, props.fileQueryUrl) + .then(({ data }) => { + const { code } = data; + if (code === 0) { + props.setBCreating(false); + const { sGenerate_files: previewUrl } = + data.data?.dataList?.[0] || {}; + if (previewUrl) { + const sGenerate_files = commonUtils.convertStrToObj( + props.masterData.sGenerate_files + ); + + clearInterval(timer); + notification.open({ + key: "fileCreating", + placement: "topRight", + message: "温馨提示", + description:
拼板文件生成完成!
, + duration: 3 + }); + + props.onSaveState1({ + masterData: { + ...props.masterData, + sGenerate_files: JSON.stringify({ + ...sGenerate_files, + workableId: workable_id, + previewUrl + }), + handleType: props.masterData.handleType || "update" + } + }); + } + } + }) + .catch(e => { + console.log("=====e", e); + }); + + if (times > 100) { + clearInterval(timer); + notification.open({ + key: "fileCreating", + placement: "topRight", + message: "温馨提示", + description:
拼板文件生成完成!
, + duration: 3 + }); + handleDealError(props); + } + }, 5000); +}; + +const handleDealError = props => { + message.error("获取数据失败"); + props.setBCreating(false); +}; + +const handleGetStrokeColor = percent => { + if (percent < 30) { + return "#F50"; + } else if (percent >= 30 && percent < 90) { + return "#FF9900"; + } else { + return "#87D068"; + } +}; + +const handleUploadChange = (props, info) => { + const { file } = info; + const { status, percent } = file; + if (status === undefined) return; + const percentNew = Number(percent.toFixed(2)); + if (["done", "error"].includes(status)) { + message.open({ + type: status === "done" ? "success" : "error", + content: status === "done" ? "文件上传成功" : "文件上传失败", + duration: 3 + }); + if (status === "done") { + const sPicturePath = file.response.dataset.rows[0].savePathStr; + const sGenerate_files = commonUtils.convertStrToObj( + props.masterData.sGenerate_files + ); + let { fileList = [] } = sGenerate_files; + fileList = [ + ...fileList, + ...sPicturePath.split(",").map(item => item.split("/").pop()) + ]; + props.onSaveState1({ + masterData: { + ...props.masterData, + sGenerate_files: JSON.stringify({ + ...sGenerate_files, + fileList + }), + handleType: props.masterData.handleType || "update" + } + }); + } + } else { + message.open({ + key: "xlyupload", + type: percent === 100 ? "success" : "loading", + content: ( + <> + 上传进度: + + + + + ), + duration: percent === 100 ? 3 : 0 + }); + } +}; + +const FileTable = props => { + const pinbanConfig = {}; + pinbanConfig.gdsconfigformslave = [ + { + bVisible: true, + sName: "sFileName", + showName: "附件名称", + iFitWidth: 400 + }, + { + bVisible: true, + sName: "fileType", + showName: "附件类型" + } + ]; + pinbanConfig.bMutiSelect = true; + pinbanConfig.bisMutiSelect = true; + + const pinbanColumn = commonFunc.getHeaderConfig(pinbanConfig); + + const tableProps = { + ...commonBusiness.getTableTypes("pinban", { + ...props, + pinbanConfig + }), + headerColumn: pinbanColumn, + fixedHeight: 311, + enabled: false + }; + return ; +}; + +const RreviewModal = props => { + const { pdfFileVisible, previewUrl, previeTitle } = props; + + return ( + { + props.onSaveState({ + pdfFileVisible: false + }); + }} + > +
+