king
2021-01-12 c27d57333ed38c92f595219d2190ea63cef4d182
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { fromJS } from 'immutable'
import { Table, Form, Icon, Select, Cascader, notification, message } from 'antd'
 
import zhCN from '@/locales/zh-CN/model.js'
import enUS from '@/locales/en-US/model.js'
import './index.scss'
 
let eTDict = localStorage.getItem('lang') !== 'en-US' ? zhCN : enUS
const EditableContext = React.createContext()
 
class EditableCell extends Component {
  getInput = () => {
    const { inputType, options } = this.props
 
    if (inputType === 'select') {
      return (
        <Select>
          {options.map((item, i) => (<Select.Option key={i} value={item.value}> {item.text} </Select.Option>))}
        </Select>
      )
    } else if (inputType === 'cascader') {
      return (
        <Cascader options={options} placeholder=""/>
      )
    }
  }
 
  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) ? `${eTDict['form.required.input']} ${title}!` : `${eTDict['form.required.select']} ${title}!`,
                }
              ],
              initialValue: record[dataIndex],
            })(this.getInput())}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    )
  }
 
  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
  }
}
 
class EditTable extends Component {
  static propTpyes = {
    data: PropTypes.any,            // 数据列表
    columns: PropTypes.array,       // 显示列
    onChange: PropTypes.func        // 数据变化
  }
 
  state = {
    data: [],
    editingKey: '',
    visible: false,
    columns: []
  }
 
  UNSAFE_componentWillMount () {
    const { data } = this.props
    let columns = fromJS(this.props.columns).toJS()
 
    columns.push({
      title: '操作',
      dataIndex: 'operation',
      width: '140px',
      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, record.uuid)} style={{ marginRight: 8 , color: '#1890ff', cursor: 'pointer'}}>
                  {eTDict['model.save']}
                </span>
              )}
            </EditableContext.Consumer>
            <span style={{ color: '#1890ff', cursor: 'pointer'}} onClick={() => this.cancel(record.uuid)}>{eTDict['model.cancel']}</span>
          </div>
        ) : (
          <div className={'edit-operation-btn' + (editingKey !== '' ? ' disabled' : '')} style={{minWidth: '110px'}}>
            <span className="primary" onClick={() => {editingKey === '' && this.edit(record.uuid)}}><Icon type="edit" /></span>
          </div>
        )
      }
    })
 
    this.setState({
      data: data || [],
      columns
    })
  }
 
  isEditing = record => record.uuid === this.state.editingKey
 
  cancel = () => {
    this.setState({ editingKey: '' })
  }
 
  copy = (item) => {
    const { type } = this.props
    const { data } = this.state
 
    if (!data || data.length === 0) {
      message.warning('未获取到配置信息')
      return
    }
 
    let msg = { key: type }
 
    if (item) {
      msg.type = 'line'
      msg.data = item
    } else {
      msg.type = 'array'
      msg.data = data
    }
 
    try {
      msg = window.btoa(window.encodeURIComponent(JSON.stringify(msg)))
    } catch {
      console.warn('Stringify Failure')
      msg = ''
    }
 
    if (msg) {
      let oInput = document.createElement('input')
      oInput.value = msg
      document.body.appendChild(oInput)
      oInput.select()
      document.execCommand('Copy')
      document.body.removeChild(oInput)
      message.success('复制成功。')
    }
  }
  
  onSave = (record) => {
    const { columns } = this.state
    const newData = [...this.state.data]
    const index = newData.findIndex(item => record.uuid === item.uuid)
 
    if (index === -1) {
      notification.warning({
        top: 92,
        message: '数据错误,无法找到行ID!',
        duration: 5
      })
      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
 
    newData.splice(index, 1, record)
    this.setState({ data: newData, editingKey: '' }, () => {
      this.props.onChange(newData)
    })
  }
 
  handleDelete = (uuid) => {
    const { data } = this.state
    let _data = data.filter(item => uuid !== item.uuid)
 
    this.setState({
      data: _data
    }, () => {
      this.props.onChange(_data)
    })
  }
 
  save(form, uuid) {
    const { columns } = this.state
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = [...this.state.data]
      const index = newData.findIndex(item => uuid === item.uuid)
 
      let unique = true
      columns.forEach(col => {
        if (col.unique !== true || !unique) return
 
        let _index = newData.findIndex(item => uuid !== item.uuid && row[col.dataIndex] === item[col.dataIndex])
 
        if (_index > -1) {
          notification.warning({
            top: 92,
            message: col.title + '不可重复!',
            duration: 5
          })
          unique = false
        }
      })
 
      if (!unique) return
 
      if (index > -1) {
        const item = newData[index]
        newData.splice(index, 1, {
          ...item,
          ...row,
        })
        this.setState({ data: newData, editingKey: '' }, () => {
          this.props.onChange(newData)
        })
      } else {
        newData.push(row);
        this.setState({ data: newData, editingKey: '' }, () => {
          this.props.onChange(newData)
        })
      }
    })
  }
 
  edit(uuid) {
    this.setState({ editingKey: 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
      }
    }
    
    const columns = this.state.columns.map(col => {
      if (!col.editable) return col
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.inputType,
          dataIndex: col.dataIndex,
          options: col.options || [],
          required: col.required !== false ? true : false,
          title: col.title,
          editing: this.isEditing(record),
          onSave: this.onSave,
        }),
      }
    })
 
    return (
      <EditableContext.Provider value={this.props.form}>
        <div className="modal-edit-table">
          <Table
            bordered
            rowKey="uuid"
            components={components}
            dataSource={this.state.data}
            columns={columns}
            rowClassName="editable-row"
            pagination={false}
            onRow={(record, index) => ({
              index,
              moveAble: !this.state.editingKey,
              moveRow: this.moveRow,
            })}
          />
        </div>
      </EditableContext.Provider>
    )
  }
}
 
export default Form.create()(EditTable)