import React, { Component } from 'react'
|
import PropTypes from 'prop-types'
|
import { fromJS } from 'immutable'
|
import { DndProvider, DragSource, DropTarget } from 'react-dnd'
|
import { Table, Input, InputNumber, Popconfirm, Form, Select, Radio, Cascader, notification, Typography, Button } from 'antd'
|
import { PlusOutlined, EditOutlined, DeleteOutlined, ArrowRightOutlined } from '@ant-design/icons'
|
|
import Utils from '@/utils/utils.js'
|
import MKEmitter from '@/utils/events.js'
|
import ColorSketch from '@/mob/colorsketch'
|
import asyncComponent from '@/utils/asyncComponent'
|
import './index.scss'
|
|
const MkEditIcon = asyncComponent(() => import('@/components/mkIcon'))
|
const EditableContext = React.createContext()
|
let dragingIndex = -1
|
const { Paragraph } = Typography
|
|
class BodyRow extends React.Component {
|
render() {
|
const { isOver, moveAble, connectDragSource, connectDropTarget, moveRow, ...restProps } = this.props
|
|
let { className } = restProps
|
if (isOver && moveAble) {
|
if (restProps.index > dragingIndex) {
|
className += ' drop-over-downward'
|
}
|
if (restProps.index < dragingIndex) {
|
className += ' drop-over-upward'
|
}
|
}
|
|
if (moveAble) {
|
return connectDragSource(
|
connectDropTarget(<tr {...restProps} className={className} style={{ ...restProps.style, cursor: 'move' }} />),
|
)
|
} else {
|
return (<tr {...restProps} className={className} style={restProps.style} />)
|
}
|
}
|
}
|
|
const rowSource = {
|
beginDrag(props) {
|
dragingIndex = props.index
|
return {
|
index: props.index,
|
}
|
}
|
}
|
|
const rowTarget = {
|
drop(props, monitor) {
|
const dragIndex = monitor.getItem().index
|
const hoverIndex = props.index
|
|
if (dragIndex === hoverIndex) {
|
return
|
}
|
|
props.moveRow(dragIndex, hoverIndex)
|
|
monitor.getItem().index = hoverIndex
|
},
|
}
|
|
const DragableBodyRow = DropTarget('row', rowTarget, (connect, monitor) => ({
|
connectDropTarget: connect.dropTarget(),
|
isOver: monitor.isOver(),
|
}))(
|
DragSource('row', rowSource, connect => ({
|
connectDragSource: connect.dragSource(),
|
}))(BodyRow),
|
)
|
|
class EditableCell extends Component {
|
getInput = (form) => {
|
const { inputType, options, min, max, unlimit } = this.props
|
|
if (inputType === 'number' && unlimit) {
|
return <InputNumber onPressEnter={() => this.getValue(form)} />
|
} else if (inputType === 'number') {
|
return <InputNumber min={min} max={max} precision={0} onPressEnter={() => this.getValue(form)} />
|
} else if (inputType === 'color') {
|
return <ColorSketch />
|
} else if (inputType === 'icon') {
|
return <MkEditIcon allowClear/>
|
} else if (inputType === 'select') {
|
return (
|
<Select showSearch filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
|
{options.map((item, i) => (<Select.Option key={i} value={item.field || item.value}>{item.label || item.text}</Select.Option>))}
|
</Select>
|
)
|
} else if (inputType === 'multiStr') {
|
return (
|
<Select mode="multiple">
|
{options.map((item, i) => (<Select.Option key={i} value={item.field || item.value}> {item.label || item.text} </Select.Option>))}
|
</Select>
|
)
|
} else if (inputType === 'cascader') {
|
return (
|
<Cascader options={options} placeholder=""/>
|
)
|
} else if (inputType === 'radio') {
|
return (
|
<Radio.Group>
|
{options.map((item, i) => (<Radio key={i} value={item.field || item.value}> {item.label || item.text} </Radio>))}
|
</Radio.Group>
|
)
|
} else {
|
return <Input onPressEnter={() => this.getValue(form)}/>
|
}
|
}
|
|
getValue = (form) => {
|
form.validateFields((error, row) => {
|
if (error) {
|
return
|
}
|
this.props.onSave(row)
|
})
|
}
|
|
renderCell = (form) => {
|
const { getFieldDecorator } = form
|
const { editing, dataIndex, title, record, children, className, required, inputType } = this.props
|
|
return (
|
<td className={className}>
|
{editing ? (
|
<Form.Item style={{ margin: 0 }}>
|
{getFieldDecorator(dataIndex, {
|
rules: [
|
{
|
required: required,
|
message: ['number', 'text', 'input'].includes(inputType) ? `请输入 ${title}!` : `请选择 ${title}!`,
|
}
|
],
|
initialValue: inputType === 'multiStr' ? (record[dataIndex] ? record[dataIndex].split(',') : []) : record[dataIndex],
|
})(this.getInput(form))}
|
</Form.Item>
|
) : (
|
children
|
)}
|
</td>
|
)
|
}
|
|
render() {
|
return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
|
}
|
}
|
|
class EditTable extends Component {
|
static propTpyes = {
|
columns: PropTypes.array, // 显示列
|
onChange: PropTypes.func // 数据变化
|
}
|
|
state = {
|
data: [],
|
editLine: null,
|
editingKey: '',
|
visible: false,
|
columns: []
|
}
|
|
UNSAFE_componentWillMount () {
|
let actions = this.props.actions || []
|
let columns = fromJS(this.props.columns).toJS()
|
|
let operation = {
|
title: '操作',
|
dataIndex: 'operation',
|
width: '120px',
|
render: (text, record) => {
|
const { editingKey } = this.state
|
const editable = this.isEditing(record)
|
return editable ? (
|
<div style={{textAlign: 'center', minWidth: '110px'}}>
|
<EditableContext.Consumer>
|
{form => (
|
<span onClick={() => this.save(form)} style={{ marginRight: 8 , color: '#1890ff', cursor: 'pointer'}}>
|
保存
|
</span>
|
)}
|
</EditableContext.Consumer>
|
<span style={{ color: '#1890ff', cursor: 'pointer'}} onClick={() => this.cancel(record.uuid)}>取消</span>
|
</div>
|
) : (
|
<div className={'edit-operation-btn' + (editingKey !== '' ? ' disabled' : '')} style={{minWidth: '110px', whiteSpace: 'nowrap'}}>
|
<span className="primary" onClick={() => {editingKey === '' && this.edit(record)}}><EditOutlined /></span>
|
{editingKey === '' ? <Popconfirm
|
overlayClassName="popover-confirm"
|
title="确定删除吗?"
|
onConfirm={() => this.handleDelete(record.uuid)
|
}>
|
<span className="danger"><DeleteOutlined /></span>
|
</Popconfirm> : null}
|
{editingKey !== '' ? <span className="danger"><DeleteOutlined /></span> : null}
|
{actions.includes('view') ? <span className="copy" onClick={() => {editingKey === '' && this.changeMenu(record.menu)}}><ArrowRightOutlined /></span> : null}
|
</div>
|
)
|
}
|
}
|
|
columns.push(operation)
|
|
this.setState({
|
data: fromJS(this.props.value || []).toJS(),
|
operation,
|
columns
|
})
|
}
|
|
// shouldComponentUpdate (nextProps, nextState) {
|
// return !is(fromJS(this.state), fromJS(nextState))
|
// }
|
|
changeMenu = (MenuId) => {
|
if (MenuId === 'IM') {
|
if (!sessionStorage.getItem('instantMessage')) return
|
|
let param = {
|
MenuID: sessionStorage.getItem('instantMessage'),
|
copyMenuId: '',
|
type: 'view'
|
}
|
|
param = window.btoa(window.encodeURIComponent(JSON.stringify(param)))
|
|
MKEmitter.emit('changeEditMenu', {routerUrl: '/imdesign/' + param})
|
} else {
|
MKEmitter.emit('changeEditMenu', {MenuID: MenuId})
|
}
|
}
|
|
isEditing = record => record.uuid === this.state.editingKey
|
|
cancel = () => {
|
this.setState({ editingKey: '', data: this.state.data.filter(item => !item.isnew) })
|
}
|
|
handleDelete = (uuid) => {
|
const { data } = this.state
|
let _data = data.filter(item => uuid !== item.uuid)
|
|
this.setState({
|
data: _data
|
}, () => {
|
this.props.onChange(_data)
|
})
|
}
|
|
save(form) {
|
form.validateFields((error, row) => {
|
if (error) {
|
return;
|
}
|
this.execSave(row)
|
})
|
}
|
|
execSave = (row) => {
|
const { columns, editLine } = this.state
|
|
let newData = [...this.state.data]
|
let record = {...editLine, ...row}
|
let index = newData.findIndex(item => record.uuid === item.uuid)
|
|
if (index === -1) return
|
|
let unique = true
|
columns.forEach(col => {
|
if (col.unique !== true || !unique) return
|
|
let _index = newData.findIndex(item => record.uuid !== item.uuid && record[col.dataIndex] === item[col.dataIndex])
|
|
if (_index > -1) {
|
notification.warning({
|
top: 92,
|
message: col.title + '不可重复!',
|
duration: 5
|
})
|
unique = false
|
}
|
})
|
|
if (!unique) return
|
|
columns.forEach(col => {
|
if (!col.extends) return
|
|
if (col.extends === 'Menu') {
|
let menu = record[col.dataIndex]
|
let fId = menu[0] || ''
|
let sId = menu[1] || ''
|
let tId = menu[2] || ''
|
let label = ''
|
|
col.options.forEach(f => {
|
if (!fId || fId !== f.value) return
|
label = f.label
|
|
f.children.forEach(s => {
|
if (!sId || sId !== s.value) return
|
label += ' / ' + s.label
|
|
s.children.forEach(t => {
|
if (!tId || tId !== t.value) return
|
label += ' / ' + t.label
|
|
record.MenuID = t.MenuID
|
record.MenuName = t.MenuName
|
record.MenuNo = t.MenuNo
|
record.tabType = t.type
|
record.label = label
|
})
|
})
|
})
|
} else if (col.inputType === 'cascader') {
|
let keys = record[col.dataIndex]
|
let _options = []
|
let rematch = (options, level) => {
|
options.some(m => {
|
if (!m.value || m.value !== keys[level]) return false
|
|
_options.push(m)
|
|
if (m.children && keys[level + 1]) {
|
rematch(m.children, level + 1)
|
}
|
return true
|
})
|
}
|
|
rematch(col.options, 0)
|
|
if (_options.length) {
|
col.extends.forEach(n => {
|
record[n.value] = _options.map(o => o[n.key]).join(' / ')
|
})
|
}
|
} else {
|
let key = record[col.dataIndex]
|
let option = col.options.filter(m => m.value === key)[0]
|
|
if (option) {
|
col.extends.forEach(n => {
|
record[n.value] = option[n.key]
|
})
|
}
|
}
|
})
|
|
delete record.isnew
|
|
newData.splice(index, 1, record)
|
this.setState({ data: newData, editingKey: '', editLine: null }, () => {
|
this.props.onChange(newData)
|
})
|
}
|
|
edit(item) {
|
this.setState({ editLine: item, editingKey: item.uuid })
|
}
|
|
addline = () => {
|
let item = {
|
uuid: Utils.getuuid(),
|
isnew: true
|
}
|
|
this.setState({ data: [...this.state.data, item], editingKey: '' }, () => {
|
this.setState({ editLine: item, editingKey: item.uuid })
|
})
|
}
|
|
moveRow = (dragIndex, hoverIndex) => {
|
const { editingKey } = this.state
|
let _data = fromJS(this.state.data).toJS()
|
|
if (editingKey) return
|
|
_data.splice(hoverIndex, 0, ..._data.splice(dragIndex, 1))
|
|
this.setState({
|
data: _data
|
}, () => {
|
this.props.onChange(_data)
|
})
|
}
|
|
render() {
|
let components = {
|
body: {
|
cell: EditableCell
|
}
|
}
|
|
let moveprops = {}
|
components.body.row = DragableBodyRow
|
moveprops.moveAble = !this.state.editingKey
|
moveprops.moveRow = this.moveRow
|
|
let columns = this.state.columns.map(col => {
|
if (col.copy) {
|
col.render = (text) => (<Paragraph copyable>{text}</Paragraph>)
|
}
|
if (!col.editable) return col
|
return {
|
...col,
|
onCell: record => ({
|
record,
|
inputType: col.inputType,
|
dataIndex: col.dataIndex,
|
options: col.options || [],
|
min: col.min || 0,
|
max: col.max || 500,
|
unlimit: col.unlimit,
|
required: col.required !== false ? true : false,
|
title: col.title,
|
editing: this.isEditing(record),
|
onSave: this.execSave,
|
}),
|
}
|
})
|
|
const data = this.state.data.map((item, index) => {
|
item.$index = index + 1
|
|
return item
|
})
|
|
return (
|
<EditableContext.Provider value={this.props.form}>
|
<div className="modal-editable-table">
|
<Button disabled={!!this.state.editingKey} type="link" onClick={this.addline}><PlusOutlined style={{}}/></Button>
|
<DndProvider>
|
<Table
|
bordered
|
rowKey="uuid"
|
size="middle"
|
components={components}
|
dataSource={data}
|
columns={columns}
|
rowClassName="editable-row"
|
pagination={false}
|
onRow={(record, index) => ({
|
index,
|
...moveprops
|
})}
|
/>
|
</DndProvider>
|
</div>
|
</EditableContext.Provider>
|
)
|
}
|
}
|
|
export default Form.create()(EditTable)
|