king
2021-01-07 0da0262bc236cfce928429fc4c48e1666eab3402
src/menu/components/table/normal-table/columns/index.jsx
@@ -2,56 +2,89 @@
import PropTypes from 'prop-types'
import { is, fromJS } from 'immutable'
import { DndProvider, DragSource, DropTarget } from 'react-dnd'
import { Table, Form, Popover, Icon } from 'antd'
import { Table, Popover, Icon, Modal, message } from 'antd'
import asyncComponent from '@/utils/asyncComponent'
import asyncIconComponent from '@/utils/asyncIconComponent'
import Utils from '@/utils/utils.js'
import zhCN from '@/locales/zh-CN/model.js'
import enUS from '@/locales/en-US/model.js'
import MKEmitter from '@/utils/events.js'
import './index.scss'
const coldict = localStorage.getItem('lang') !== 'en-US' ? zhCN : enUS
const { confirm } = Modal
const EditColumn = asyncIconComponent(() => import('./editColumn'))
const MarkColumn = asyncIconComponent(() => import('@/menu/components/share/markcomponent'))
const CardCellComponent = asyncComponent(() => import('@/menu/components/card/cardcellcomponent'))
class HeaderCol extends Component {
  updateCol = (values) => {
    const { column } = this.props
    this.props.updateCol({...column, ...values})
  deleteCol = () => {
    const _this = this
    confirm({
      content: '确定删除显示列吗?',
      onOk() {
        _this.props.deleteCol(_this.props.column)
      },
      onCancel() {}
    })
  }
  deleteCol = () => {
    this.props.deleteCol(this.props.column)
  updateMarks = (vals) => {
    const { column } = this.props
    this.props.updateCol({...column, marks: vals})
  }
  shouldComponentUpdate (nextProps, nextState) {
    if (!nextProps.column) return false
    return !is(fromJS(this.props.column), fromJS(nextProps.column)) ||
      !is(fromJS(this.props.fields), fromJS(nextProps.fields)) ||
      this.props.index !== nextProps.index ||
      this.props.rowSpan !== nextProps.rowSpan ||
      this.props.colSpan !== nextProps.colSpan
  }
  render() {
    const { connectDragSource, connectDropTarget, moveCol, updateCol, deleteCol, index, column, fields, children, ...restProps } = this.props
    const { connectDragSource, connectDropTarget, moveCol, addElement, updateCol, editColumn, deleteCol, index, column, align, fields, children, ...restProps } = this.props
    if (index !== undefined) {
      return connectDragSource(
        connectDropTarget(<th {...restProps} index={index} style={{ cursor: 'move' }}>
        connectDropTarget(<th {...restProps} index={index} style={{ cursor: 'move', textAlign: align }}>
          <Popover overlayClassName="mk-popover-control-wrap" mouseLeaveDelay={0.2} mouseEnterDelay={0.2} content={
            <div className="mk-popover-control">
              <EditColumn column={column} dict={coldict} fields={fields} updateCol={this.updateCol} deleteCol={this.deleteCol}/>
              <Icon className="close" title="delete" type="delete" onClick={this.deleteCol} />
              {column && ['custom', 'colspan', 'action'].includes(column.type) ?
                <Icon className="plus" title="添加" type="plus" onClick={() => this.props.addElement(column)} /> : null
              }
              <Icon className="edit" title="编辑" type="edit" onClick={() => this.props.editColumn(column)} />
              <Icon className="close" title="删除" type="delete" onClick={this.deleteCol} />
              {column && ['text', 'number'].includes(column.type) ? <MarkColumn columns={fields} marks={column.marks} onSubmit={this.updateMarks} /> : null }
            </div>
          } trigger="hover">
            {children}
          </Popover>
        </th>),
      )
    } else {
    } else if (column) {
      return (
        <th {...restProps}>
        <th {...restProps} key={column.uuid}>
          <Popover overlayClassName="mk-popover-control-wrap" mouseLeaveDelay={0.2} mouseEnterDelay={0.2} content={
            <div className="mk-popover-control">
              <EditColumn column={column} dict={coldict} fields={fields} updateCol={this.updateCol} deleteCol={this.deleteCol}/>
              <Icon className="close" title="delete" type="delete" onClick={this.deleteCol} />
              {column && ['custom', 'colspan'].includes(column.type) ?
                <Icon className="plus" title="添加" type="plus" onClick={() => this.props.addElement(column)} /> : null
              }
              <Icon className="edit" title="编辑" type="edit" onClick={() => this.props.editColumn(column)} />
              <Icon className="close" title="删除" type="delete" onClick={this.deleteCol} />
              {column && ['text', 'number'].includes(column.type) ? <MarkColumn columns={fields} marks={column.marks} onSubmit={this.updateMarks} /> : null }
            </div>
          } trigger="hover">
            {children}
          </Popover>
        </th>
      )
    } else {
      return (<th {...restProps}>{children}</th>)
    }
  }
}
@@ -86,19 +119,48 @@
  }))(HeaderCol),
)
class EditableCell extends Component {
  render() {
    const { column, children, style } = this.props
class EditableColumnCell extends Component {
  updateCard = (vals, action) => {
    const { column } = this.props
    this.props.upComponent({...column, elements: vals}, action)
  }
    if (column) {
  shouldComponentUpdate (nextProps, nextState) {
    const { config, column } = this.props
    if (!nextProps.column) return true
    return !is(fromJS(column), fromJS(nextProps.column)) ||
      !is(fromJS(config.columns), fromJS(nextProps.config.columns)) ||
      !is(fromJS(config.action), fromJS(nextProps.config.action)) ||
      !is(fromJS(config.search), fromJS(nextProps.config.search))
  }
  render() {
    const { column, config, children, className, style } = this.props
    if (column && column.type === 'custom') {
      return (
        <td style={style}>
        <td style={{padding: 0, minWidth: column.Width || 100}} className={className}>
          <CardCellComponent cards={config} cardCell={column} elements={column.elements} updateElement={this.updateCard}/>
        </td>
      )
    } else if (column && column.type === 'action') {
      return (
        <td style={{padding: '0 5px', textAlign: column.Align, minWidth: column.Width || 100}} className={'action-column ' + className}>
          <CardCellComponent cards={config} cardCell={column} elements={column.elements} updateElement={this.updateCard}/>
        </td>
      )
    } else if (column) {
      return (
        <td style={{...style, minWidth: column.Width || 100}} className={className}>
          {column.field}
          {column.marks && column.marks.length ? <Icon className="profile" type="ant-design"/> : null}
        </td>
      )
    } else {
      return (
        <td style={style}>
        <td style={style} className={className}>
          {children}
        </td>
      )
@@ -106,36 +168,75 @@
  }
}
class EditTable extends Component {
class NormalTableColumns extends Component {
  static propTpyes = {
    actions: PropTypes.any,         // 操作项
    data: PropTypes.any,            // 数据列表
    columns: PropTypes.array,       // 显示列
    onChange: PropTypes.func        // 数据变化
    config: PropTypes.object,       // 配置信息
    updatecolumn: PropTypes.func    // 数据变化
  }
  state = {
    dict: localStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    tableId: '',
    data: [{uuid: Utils.getuuid()}],
    refresh: false,    // 强制刷新
    columns: [],
    fields: []
    fields: [],
    lineMarks: []
  }
  UNSAFE_componentWillMount () {
    const { config } = this.props
    let tableId = (() => {
      let uuid = []
      let _options = 'abcdefghigklmnopqrstuv'
      for (let i = 0; i < 19; i++) {
        uuid.push(_options.substr(Math.floor(Math.random() * 0x20), 1))
      }
      return uuid.join('')
    }) ()
    if (config.wrap && config.wrap.borderColor) { // 边框颜色
      let style = `#${tableId} table, #${tableId} tr, #${tableId} th, #${tableId} td {border-color: ${config.wrap.borderColor}}`
      let ele = document.createElement('style')
      ele.innerHTML = style
      document.getElementsByTagName('head')[0].appendChild(ele)
    }
    this.setState({
      columns: fromJS(this.props.config.cols).toJS(),
      fields: fromJS(this.props.config.columns).toJS()
      tableId,
      columns: fromJS(config.cols).toJS(),
      fields: fromJS(config.columns).toJS(),
      lineMarks: config.lineMarks ? fromJS(config.lineMarks).toJS() : []
    })
  }
  UNSAFE_componentWillReceiveProps (nextProps) {
    if (!is(fromJS(this.state.columns), fromJS(nextProps.config.cols))) {
      this.setState({columns: fromJS(nextProps.config.cols).toJS()})
      let _columns = fromJS(nextProps.config.cols).toJS()
      this.setState({columns: _columns})
      let lastcol = _columns.slice(-1)[0]
      if (lastcol && lastcol.focus) {
        this.editColumn(lastcol)
      }
    } else if (!is(fromJS(this.state.fields), fromJS(nextProps.config.columns))) {
      this.setState({fields: fromJS(nextProps.config.columns).toJS()})
    } else if (this.props.config.wrap.borderColor !== nextProps.config.wrap.borderColor) {
      let style = `#${this.state.tableId} table, #${this.state.tableId} tr, #${this.state.tableId} th, #${this.state.tableId} td {border-color: ${nextProps.config.wrap.borderColor}}`
      let ele = document.createElement('style')
      ele.innerHTML = style
      document.getElementsByTagName('head')[0].appendChild(ele)
    }
  }
  shouldComponentUpdate (nextProps, nextState) {
    return !is(fromJS(this.state), fromJS(nextState))
    const { config } = this.props
    return !is(fromJS(this.state), fromJS(nextState)) ||
      !is(fromJS(config.wrap), fromJS(nextProps.config.wrap)) ||
      !is(fromJS(config.search), fromJS(nextProps.config.search)) ||
      !is(fromJS(config.action), fromJS(nextProps.config.action)) ||
      config.setting.laypage !== nextProps.config.setting.laypage
  }
  moveCol = (dragIndex, hoverIndex) => {
@@ -146,77 +247,270 @@
    this.setState({
      columns: _columns
    }, () => {
      // this.props.onChange(_data)
      this.props.updatecolumn({...this.props.config, cols: _columns})
    })
  }
  updateCol = (col) => {
  loopCol = (columns, col) => {
    return columns.map(column => {
      if (column.type === 'colspan') {
        column.subcols = this.loopCol(column.subcols, col)
      }
      if (column.uuid === col.uuid) {
        return col
      }
      return column
    })
  }
  updateCol = (col, action) => {
    let _columns = fromJS(this.state.columns).toJS()
    _columns = this.loopCol(_columns, col)
    this.setState({
      columns: _columns,
    }, () => {
      if (action) {
        this.props.updatecolumn({...this.props.config, cols: _columns, action})
      } else {
        this.props.updatecolumn({...this.props.config, cols: _columns})
      }
    })
  }
  editColumn = (col) => {
    this.setState({
      card: fromJS(col).toJS()
    })
  }
  addElement = (col) => {
    const { config } = this.props
    let column = fromJS(col).toJS()
    if (column.type === 'colspan') {
      column.subcols = column.subcols || []
      let subcol = { isSub: true, focus: true, uuid: Utils.getuuid(), label: 'label', field: '', type: 'text' }
      column.subcols.push(subcol)
      this.setState({
        card: subcol
      })
      this.updateCol(column)
    } else if (column.type === 'custom') {
      let newcard = {uuid: Utils.getuuid(), focus: true, eleType: 'text', datatype: 'dynamic'}
      // 注册事件-添加元素
      MKEmitter.emit('cardAddElement', [config.uuid, column.uuid], newcard)
    } else if (column.type === 'action') {
      let newcard = {
        uuid: Utils.getuuid(),
        focus: true,
        eleType: 'button',
        label: 'button',
        OpenType: 'prompt',
        class: 'primary',
        intertype: 'system',
        execSuccess: 'grid',
        execError: 'never',
        show: 'link',
        $type: 'tableButton'
      }
      // 注册事件-添加元素
      MKEmitter.emit('cardAddElement', [config.uuid, column.uuid], newcard)
    }
  }
  submitCol = (col) => {
    const { card } = this.state
    col.uuid = card.uuid
    col.isSub = card.isSub === true
    col.marks = card.marks || []
    if (col.type === 'colspan') {
      col.subcols = card.subcols || []
    } else if (col.type === 'custom') {
      col.elements = card.type === 'custom' ? (card.elements || []) : []
    } else if (col.type === 'action') {
      col.elements = card.type === 'action' ? (card.elements || []) : []
    }
    this.setState({card: null})
    this.updateCol(col)
  }
  cancelCol = () => {
    const { card } = this.state
    if (card.focus) {
      this.deleteCol(card)
    }
    this.setState({card: null})
  }
  loopDelCol = (columns, col) => {
    return columns.filter(column => {
      if (column.type === 'colspan') {
        column.subcols = this.loopDelCol(column.subcols, col)
      }
      return column.uuid !== col.uuid
    })
  }
  deleteCol = (col) => {
    let _columns = fromJS(this.state.columns).toJS()
    _columns = this.loopDelCol(_columns, col)
    if (col.type === 'action') {
      let uuids = []
      col.elements && col.elements.forEach(c => {
        uuids.push(c.uuid)
      })
      MKEmitter.emit('delButtons', uuids)
    }
    this.setState({
      columns: _columns
    }, () => {
      this.props.updatecolumn({...this.props.config, cols: _columns})
    })
  }
  updateLineMarks = (vals) => {
    this.setState({
      lineMarks: vals
    }, () => {
      this.props.updatecolumn({...this.props.config, lineMarks: vals})
    })
  }
  /**
   * @description 显示列复制
   */
  copycolumn = () => {
    const { columns } = this.state
    let oInput = document.createElement('input')
    let val = {
      copyType: 'columns',
      columns: columns
    }
    oInput.value = window.btoa(window.encodeURIComponent(JSON.stringify(val)))
    document.body.appendChild(oInput)
    oInput.select()
    document.execCommand('Copy')
    oInput.className = 'oInput'
    oInput.style.display = 'none'
    message.success('复制成功。')
    document.body.removeChild(oInput)
  }
  handlecolumns = (columns, fields, config, isSub) => {
    return columns.map((col, index) => {
      return {
        title: col.label,
        dataIndex: col.uuid,
        align: col.Align,
        sorter: !isSub && col.IsSort === 'true',
        onCell: () => ({
          column: col,
          width: col.Width,
          config: config,
          upComponent: this.updateCol
        }),
        onHeaderCell: () => ({
          index: isSub ? undefined : index,
          column: col,
          fields: fields,
          align: col.Align,
          moveCol: this.moveCol,
          updateCol: this.updateCol,
          addElement: this.addElement,
          editColumn: this.editColumn,
          deleteCol: this.deleteCol,
        }),
        children: col.subcols && col.subcols.length ? this.handlecolumns(col.subcols, fields, config, true) : null,
      }
    })
  }
  syncfield = () => {
    const { fields } = this.state
    let columns = fromJS(this.state.columns).toJS()
    columns = columns.filter(c => !c.origin)
    let keys = columns.map(col => col.field)
    fields.forEach(item => {
      if (keys.includes(item.field)) return
      let cell = { uuid: Utils.getuuid(), label: item.label, field: item.field, Align: 'left', Hide: 'false', IsSort: 'true', Width: 120, blacklist: [], postfix: '', prefix: '', linkmenu: [], marks: [], perspective: 'linkmenu' }
      if (/Nvarchar/ig.test(item.datatype)) {
        cell.type = 'text'
        cell.rowspan = 'false'
        cell.textFormat = 'none'
      } else {
        cell.type = 'number'
        cell.format = 'none'
        cell.sum = 'false'
        cell.decimal = item.decimal || 0
      }
      columns.push(cell)
    })
    const _this = this
    confirm({
      content: '确定同步字段集吗?',
      onOk() {
        _this.setState({columns}, () => {
          _this.props.updatecolumn({..._this.props.config, cols: columns})
        })
      },
      onCancel() {}
    })
  }
  render() {
    const { fields } = this.state
    const { config } = this.props
    const { fields, card, lineMarks, dict, tableId } = this.state
    const components = {
      header: {
        cell: DragableHeaderCol
      },
      body: {
        cell: EditableCell
        cell: EditableColumnCell
      }
    }
    const columns = this.state.columns.map((col, index) => {
      return {
        title: col.label,
        dataIndex: col.field,
        align: 'right',
        sorter: col.IsSort === 'true',
        onCell: () => ({
          column: col,
          fields: fields
        }),
        children: col.subcols && col.subcols.length > 0 ? col.subcols.map(cell => ({
          align: 'left',
          title: cell.label,
          key: cell.uuid,
          onCell: () => ({
            column: cell,
            fields: fields
          }),
          onHeaderCell: () => ({
            column: cell,
            fields: fields,
            updateCol: this.updateCol,
            deleteCol: this.deleteCol,
          })
        })) : null,
        onHeaderCell: () => ({
          index,
          column: col,
          fields: fields,
          moveCol: this.moveCol,
          updateCol: this.updateCol,
          deleteCol: this.deleteCol,
        })
      }
    })
    const columns = this.handlecolumns(this.state.columns, fields, config)
    return (
      <div className="normal-table-columns">
      <div className={`normal-table-columns ${config.setting.laypage} ${config.wrap.tableType}`} id={tableId}>
        <div className="col-control">
          <Icon title="复制" type="copy" onClick={this.copycolumn} />
          <MarkColumn columns={fields} type="line" marks={lineMarks} onSubmit={this.updateLineMarks} />
          <Icon title="同步" type="file-sync" onClick={this.syncfield} />
        </div>
        <DndProvider>
          <Table
            bordered
            rowKey="uuid"
            // bordered={false}
            size={config.wrap.size || 'middle'}
            rowClassName="editable-row"
            bordered={config.wrap.bordered !== 'false'}
            components={components}
            dataSource={this.state.data}
            rowSelection={{type: 'radio'}}
            rowSelection={config.wrap.tableType ? { type: 'radio' } : null}
            columns={columns}
            rowClassName="editable-row"
            pagination={{
              current: 1,
              pageSize: 10,
@@ -225,15 +519,12 @@
              total: 58,
              showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条`
            }}
            // onRow={(record, index) => ({
            //   index,
            //   moveRow: this.moveRow,
            // })}
          />
        </DndProvider>
        <EditColumn column={card} dict={dict} fields={fields} submitCol={this.submitCol} cancelCol={this.cancelCol}/>
      </div>
    )
  }
}
export default Form.create()(EditTable)
export default NormalTableColumns