king
2022-03-03 cadfd4ed559fb170bb81d5bafbb6ae9775ba1ddc
src/tabviews/custom/components/table/edit-table/normalTable/index.jsx
@@ -1,17 +1,19 @@
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { is, fromJS } from 'immutable'
import { Table, Typography, Switch, Modal, Input, InputNumber, Tooltip, Button, notification, message } from 'antd'
import { ExclamationCircleOutlined, EditOutlined } from '@ant-design/icons'
import { Table, Typography, Switch, Modal, Input, InputNumber, Tooltip, Button, notification, message, Select } from 'antd'
import { ExclamationCircleOutlined, EditOutlined, PlusOutlined, PlusCircleOutlined, DeleteOutlined } from '@ant-design/icons'
import moment from 'moment'
import Api from '@/api'
import options from '@/store/options.js'
import asyncComponent from '@/utils/asyncComponent'
import Utils, { getEditTableSql, getMark } from '@/utils/utils.js'
import MkIcon from '@/components/mk-icon'
import MKEmitter from '@/utils/events.js'
import zhCN from '@/locales/zh-CN/main.js'
import enUS from '@/locales/en-US/main.js'
import CusSwitch from './cusSwitch'
import '@/assets/css/table.scss'
import './index.scss'
@@ -124,7 +126,7 @@
  tdFocus = (id) => {
    const { col, record } = this.props
    if (id !== col.uuid + record.$Index) return
    if (id !== col.uuid + record.$$uuid) return
    this.focus()
  }
@@ -135,9 +137,9 @@
    this.setState({editing: false})
    setTimeout(() => {
      if (col.enter === '$next') {
        MKEmitter.emit('nextLine', col, record.$Index)
        MKEmitter.emit('nextLine', col, record.$$uuid)
      } else {
        MKEmitter.emit('tdFocus', col.enter + record.$Index)
        MKEmitter.emit('tdFocus', col.enter + record.$$uuid)
      }
    }, 50)
@@ -149,27 +151,34 @@
  focus = () => {
    const { col, record } = this.props
    let err = null
    let val = record[col.field] !== undefined ? record[col.field] : ''
    if (col.type === 'number') {
      val = +val
      if (isNaN(val)) {
        val = 0
    if (col.editType === 'switch' || col.editType === 'select') {
      this.setState({editing: true}, () => {
        let node = document.getElementById(col.uuid + record.$$uuid)
        node && node.click()
      })
    } else {
      let err = null
      let val = record[col.field] !== undefined ? record[col.field] : ''
      if (col.type === 'number') {
        val = +val
        if (isNaN(val)) {
          val = 0
        }
        if (typeof(col.max) === 'number' && val > col.max) {
          err = col.label + '最大为' + col.max
        } else if (typeof(col.min) === 'number' && val < col.min) {
          err = col.label + '最小为' + col.min
        }
      } else if (col.required === 'true' && !val) {
        err = '请填写' + col.label
      }
      if (typeof(col.max) === 'number' && val > col.max) {
        err = col.label + '最大为' + col.max
      } else if (typeof(col.min) === 'number' && val < col.min) {
        err = col.label + '最小为' + col.min
      }
    } else if (col.required === 'true' && !val) {
      err = '请填写' + col.label
      this.setState({editing: true, value: val, err}, () => {
        let node = document.getElementById(col.uuid + record.$$uuid)
        node && node.select()
      })
    }
    this.setState({editing: true, value: val, err}, () => {
      let node = document.getElementById(col.uuid + record.$Index)
      node && node.select()
    })
  }
  onBlur = () => {
@@ -202,6 +211,62 @@
      err = '请填写' + col.label
    }
    this.setState({value: val, err})
  }
  onSwitchChange = (val) => {
    const { col, record } = this.props
    this.setState({editing: false})
    setTimeout(() => {
      if (col.enter === '$next') {
        MKEmitter.emit('nextLine', col, record.$$uuid)
      } else {
        MKEmitter.emit('tdFocus', col.enter + record.$$uuid)
      }
    }, 50)
    MKEmitter.emit('changeRecord', col.tableId, {...record, [col.field]: val})
  }
  onSelectChange = (val, option) => {
    const { col, record } = this.props
    let values = {}
    let _option = col.options.filter(m => m.key === option.key)[0]
    if (_option) {
      if (col.linkSubField) {
        col.linkSubField.forEach(m => {
          values[m] = _option[m] !== undefined ? _option[m] : ''
        })
      }
      if (col.editField) {
        values[col.field] = _option.label
        values[col.editField] = val
      } else {
        values[col.field] = val
      }
    }
    this.setState({editing: false})
    setTimeout(() => {
      if (col.enter === '$next') {
        MKEmitter.emit('nextLine', col, record.$$uuid)
      } else {
        MKEmitter.emit('tdFocus', col.enter + record.$$uuid)
      }
    }, 50)
    MKEmitter.emit('changeRecord', col.tableId, {...record, ...values})
  }
  switchBlur = () => {
    setTimeout(() => {
      this.setState({editing: false})
    }, 10)
  }
  render() {
@@ -241,10 +306,31 @@
      if (col.editable === 'true') {
        if (editing) {
          return (<td className="editing_table_cell">
            <Input id={col.uuid + record.$Index} defaultValue={value} onChange={(e) => this.onChange(e.target.value)} onPressEnter={this.enterPress} onBlur={this.onBlur}/>
            {err ? <Tooltip title={err}><ExclamationCircleOutlined /></Tooltip> : null}
          </td>)
          if (!col.editType || col.editType === 'text') {
            return (<td className="editing_table_cell">
              <Input id={col.uuid + record.$$uuid} defaultValue={value} onChange={(e) => this.onChange(e.target.value)} onPressEnter={this.enterPress} onBlur={this.onBlur}/>
              {err ? <Tooltip title={err}><ExclamationCircleOutlined /></Tooltip> : null}
            </td>)
          } else if (col.editType === 'switch') {
            let _value = record[col.field] !== undefined ? record[col.field] : ''
            return (<td className="editing_table_cell">
              <CusSwitch config={col} defaultValue={_value} onChange={this.onSwitchChange} onBlur={this.switchBlur}/>
            </td>)
          } else {
            let _value = record[col.field] !== undefined ? record[col.field] : ''
            return (<td className="editing_table_cell">
              <Select
                showSearch
                defaultValue={_value}
                id={col.uuid + record.$$uuid}
                onBlur={() => this.setState({editing: false})}
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                onSelect={this.onSelectChange}
              >
                {col.options.map((item, i) => (<Select.Option key={item.key} disabled={item.$disabled} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            </td>)
          }
        } else {
          return (<td className={className + ' pointer'} style={style}><div className="mk-mask" onClick={this.focus}></div>{content}</td>)
        }
@@ -267,6 +353,8 @@
        if (col.format === 'percent') {
          content = content * 100
          decimal = decimal > 2 ? decimal - 2 : 0
        } else if (col.format === 'abs') {
          content = Math.abs(content)
        }
  
        content = content.toFixed(decimal)
@@ -295,7 +383,7 @@
      if (col.editable === 'true') {
        if (editing) {
          return (<td className="editing_table_cell">
            <InputNumber id={col.uuid + record.$Index} defaultValue={value} onChange={(val) => this.onChange(val)} onPressEnter={this.enterPress} onBlur={this.onBlur}/>
            <InputNumber id={col.uuid + record.$$uuid} defaultValue={value} onChange={(val) => this.onChange(val)} onPressEnter={this.enterPress} onBlur={this.onBlur}/>
            {err ? <Tooltip title={err}><ExclamationCircleOutlined /></Tooltip> : null}
          </td>)
        } else {
@@ -382,7 +470,8 @@
      )
    }
    return (<td className={className} style={style}>{children}</td>)
    return (<td className={className} style={style}>{col.addable ? <PlusCircleOutlined onClick={() => MKEmitter.emit('addRecord', col.tableId, {...record})} className="mk-editable mk-plus"/> : null}{children}{col.delable ? <DeleteOutlined onClick={() => MKEmitter.emit('delRecord', col.tableId, {...record})} className="mk-editable mk-del"/> : null}</td>)
    // return (<td className={className} style={style}>{children}</td>)
  }
}
@@ -423,31 +512,21 @@
    let orderfields = {}
    let initEditLine = null
    let edColumns = []
    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('')
    }) ()
    let _columns = []
    let deForms = []
    columns.forEach(item => {
      if (item.Hide === 'true') return
      if (item.type === 'index') {
        item.field = '$Index'
        item.type = 'text'
      }
      item.tableId = tableId
      if (!initEditLine && item.editable === 'true') {
        initEditLine = item
      }
      if (item.marks && item.marks.length === 0) {
        item.marks = ''
      if (item.type === 'text' && item.editable === 'true' && item.editType === 'select' && item.resourceType === '1') {
        let _option = Utils.getSelectQueryOptions(item)
        item.base_sql = window.btoa(window.encodeURIComponent(_option.sql))
        item.arr_field = _option.field
        deForms.push(item)
      }
      if (item.field) {
@@ -472,14 +551,14 @@
        _copy.sorter = false
        if (item.editable === 'true') {
          _copy.title = <span>{item.label}<EditOutlined className="system-color" style={{position: 'absolute', bottom: 0, right: 0}}/></span>
          _copy.title = <span>{item.label}<EditOutlined className="system-color" style={{position: 'absolute', bottom: '2px', right: '5px'}}/></span>
        }
        edColumns.push(_copy)
      }
      _columns.push(_item)
    })
    if (setting.delable !== 'false') {
    if (setting.delable !== 'false' && setting.operType !== 'buoyMode') {
      edColumns.push({
        align: 'center',
        dataIndex: 'mkoperation',
@@ -488,13 +567,13 @@
        width: 100,
        onCell: record => ({
          record,
          col: {type: 'operation', tableId: tableId},
          col: {type: 'operation', tableId: setting.tableId},
        })
      })
    }
    if (setting.borderColor) { // 边框颜色
      let style = `#${tableId} table, #${tableId} tr, #${tableId} th, #${tableId} td {border-color: ${setting.borderColor}}`
      let style = `#${setting.tableId} table, #${setting.tableId} tr, #${setting.tableId} th, #${setting.tableId} td {border-color: ${setting.borderColor}}`
      let ele = document.createElement('style')
      ele.innerHTML = style
      document.getElementsByTagName('head')[0].appendChild(ele)
@@ -514,10 +593,14 @@
      data,
      columns: _columns,
      edColumns,
      tableId,
      tableId: setting.tableId,
      orderfields,
      initEditLine,
      editable: setting.editable
    }, () => {
      if (deForms.length > 0) {
        this.improveActionForm(deForms)
      }
    })
  }
@@ -526,24 +609,11 @@
  }
  componentDidMount () {
    const { fields, columns } = this.props
    const { fields, setting } = this.props
    const { data, editable } = this.state
    let _fields = []
    let fieldType = {}
    fields.forEach(item => {
      fieldType[item.field] = item.datatype
    })
    columns.forEach(col => {
      if (!col.field || col.type === 'index') return
      _fields.push({...col, datatype: fieldType[col.field] || 'Nvarchar(50)'})
    })
    this.setState({
      fields: _fields,
      fields: fields.filter(item => item.field !== setting.primaryKey),
    })
    if (editable === 'true' && data && data.length > 0) {
@@ -553,6 +623,7 @@
    }
    MKEmitter.addListener('nextLine', this.nextLine)
    MKEmitter.addListener('addRecord', this.addLine)
    MKEmitter.addListener('delRecord', this.delRecord)
    MKEmitter.addListener('resetTable', this.resetTable)
    MKEmitter.addListener('changeRecord', this.changeRecord)
@@ -566,6 +637,7 @@
      return
    }
    MKEmitter.removeListener('nextLine', this.nextLine)
    MKEmitter.removeListener('addRecord', this.addLine)
    MKEmitter.removeListener('delRecord', this.delRecord)
    MKEmitter.removeListener('resetTable', this.resetTable)
    MKEmitter.removeListener('changeRecord', this.changeRecord)
@@ -574,12 +646,168 @@
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (!is(fromJS(this.props.data), fromJS(nextProps.data))) {
      this.setState({data: nextProps.data || []})
      if (this.state.editable === 'true') {
      if (this.state.editable === 'true' && !this.state.pickup) {
        setTimeout(() => {
          this.pickupChange()
        }, 200)
      }
    }
  }
  improveActionForm = (deForms) => {
    const { BID, setting } = this.props
    let deffers = []
    let mainItems = []  // 云端或单点数据
    let localItems = [] // 本地数据
    let cache = setting.cache !== 'false'
    deForms.forEach(item => {
      if (item.database === 'sso') {
        mainItems.push(`select '${item.uuid}' as obj_name,'${item.arr_field}' as arr_field,'${item.base_sql}' as LText`)
      } else {
        localItems.push(`select '${item.uuid}' as obj_name,'${item.arr_field}' as arr_field,'${item.base_sql}' as LText`)
      }
    })
    if (options.sysType !== 'local') {
      localItems = [...localItems, ...mainItems]
      mainItems = []
    }
    // 本地请求
    let param = {
      func: 'sPC_Get_SelectedList',
      LText: localItems.join(' union all '),
      obj_name: '',
      arr_field: '',
      table_type: 'Y',
      BID: BID || ''
    }
    if (param.LText) {
      param.LText = Utils.formatOptions(param.LText)
      param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
      param.secretkey = Utils.encrypt(param.LText, param.timestamp)
      deffers.push(
        new Promise(resolve => {
          Api.getSystemCacheConfig(param, cache).then(res => {
            if (!res.status) {
              notification.warning({
                top: 92,
                message: res.message,
                duration: 5
              })
            }
            resolve(res)
          })
        })
      )
    }
    // 系统请求
    let mainparam = {
      func: 'sPC_Get_SelectedList',
      LText: mainItems.join(' union all '),
      obj_name: '',
      arr_field: '',
      table_type: 'Y',
      BID: BID || ''
    }
    if (mainparam.LText) {
      mainparam.LText = Utils.formatOptions(mainparam.LText)
      mainparam.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
      mainparam.secretkey = Utils.encrypt(mainparam.LText, mainparam.timestamp)
      if (window.GLOB.mainSystemApi) {
        mainparam.rduri = window.GLOB.mainSystemApi
      }
      deffers.push(
        new Promise(resolve => {
          Api.getSystemCacheConfig(mainparam, cache).then(res => {
            if (!res.status) {
              notification.warning({
                top: 92,
                message: res.message,
                duration: 5
              })
            }
            resolve(res)
          })
        })
      )
    }
    Promise.all(deffers).then(response => {
      let result = {...response[0], ...(response[1] || {})}
      delete result.ErrCode
      delete result.ErrMesg
      delete result.message
      delete result.status
      this.resetFormList(result)
    })
  }
  resetFormList = (result) => {
    const { columns } = this.props
    const { edColumns } = this.state
    let _edColumns = []
    let reCols = {}
    columns.forEach(item => {
      if (item.resourceType === '1' && result[item.uuid] && result[item.uuid].length > 0) {
        let options = []
        let _map = new Map()
        result[item.uuid].forEach(cell => {
          let _cell = {key: Utils.getuuid()}
          _cell.value = cell[item.valueField]
          _cell.label = cell[item.valueText]
          if (!_cell.label && _cell.label !== 0) return
          if (_map.has(_cell.value)) return
          _map.set(_cell.value, true)
          if (item.linkSubField) {
            item.linkSubField.forEach(m => {
              _cell[m] = cell[m] === undefined ? '' : cell[m]
            })
          }
          if (item.disableField && cell[item.disableField] && /^true$/ig.test(cell[item.disableField])) {
            _cell.$disabled = true
          }
          options.push(_cell)
        })
        item.options = options
        reCols[item.uuid] = item
      }
    })
    _edColumns = edColumns.map(item => {
      if (reCols[item.dataIndex]) {
        item.onCell = record => ({
          record,
          col: reCols[item.dataIndex]
        })
      }
      return item
    })
    this.setState({edColumns: []}, () => {
      this.setState({edColumns: _edColumns})
    })
  }
  
  nextLine = (col, index) => {
@@ -594,7 +822,7 @@
      MKEmitter.emit('tdFocus', initEditLine.uuid + (index + 1))
    } else if (col.footEnter === 'add' && setting.addable === 'true') {
      setTimeout(() => {
        this.plusLine(initEditLine)
        this.plusLine()
      }, 10)
    } else if (col.footEnter === 'sub') {
      setTimeout(() => {
@@ -603,18 +831,16 @@
    }
  }
  plusLine = (initEditLine) => {
    const { edData, fields } = this.state
  plusLine = () => {
    const { edData, fields, initEditLine } = this.state
    let item = {...edData[edData.length - 1]}
    item.key = item.key + 1
    item.$$uuid = '$new'
    item.$Index = item.key + 1 + ''
    item.$$uuid = Utils.getguid()
    item.$type = 'add'
    item.$Index = ''
    fields.forEach(col => {
      item[col.field] = item[col.field] !== undefined ? item[col.field] : ''
      if (col.initval !== '$copy') {
        item[col.field] = col.initval
      }
@@ -624,10 +850,13 @@
          item[col.field] = 0
        }
      }
      if (item[col.field] === undefined) {
        item[col.field] = ''
      }
    })
    this.setState({edData: [...edData, item]}, () => {
      MKEmitter.emit('tdFocus', initEditLine.uuid + item.$Index)
      MKEmitter.emit('tdFocus', initEditLine.uuid + item.$$uuid)
    })
  }
@@ -638,17 +867,14 @@
    let _data = []
    if (record.$$uuid === '$new') {
      _data = edData.filter(item => item.$Index !== record.$Index)
      _data = _data.map((item, index) => {
        item.key = index
        item.$Index = 1 + index + ''
        return item
      })
    if (record.$type === 'add') {
      _data = edData.filter(item => item.$$uuid !== record.$$uuid)
    } else {
      _data = edData.map(item => {
        if (item.$Index === record.$Index) {
        if (item.$$uuid === record.$$uuid) {
          record.$deleted = true
          record.$origin = false
          record.$type = 'del'
          return record
        } else {
          return item
@@ -665,7 +891,8 @@
    if (id !== tableId) return
    let _data = this.state.edData.map(item => {
      if (item.$Index === record.$Index) {
      if (item.$$uuid === record.$$uuid) {
        record.$origin = false
        return record
      } else {
        return item
@@ -675,38 +902,73 @@
    this.setState({edData: _data})
  }
  addLine = () => {
  addLine = (id, record) => {
    const { BID } = this.props
    const { edData, fields } = this.state
    const { edData, fields, tableId } = this.state
    let item = {}
    if (edData.length > 0) {
      item = {...edData[edData.length - 1]}
      item.key = item.key + 1
      item.$$uuid = '$new'
      item.$Index = item.key + 1 + ''
    } else {
      item.key = 0
      item.$$uuid = '$new'
      item.$Index = item.key + 1 + ''
    if (id) {
      if (id !== tableId) return
      let _edData = fromJS(edData).toJS()
      let index = _edData.findIndex(item => record.$$uuid === item.$$uuid)
      let item = {}
      item.$$uuid = Utils.getguid()
      item.$type = 'add'
      item.$Index = ''
      item.$$BID = BID || ''
    }
    fields.forEach(col => {
      item[col.field] = item[col.field] !== undefined ? item[col.field] : ''
      if (col.initval !== '$copy') {
        item[col.field] = col.initval
      }
      if (col.type === 'number') {
        item[col.field] = +item[col.field]
        if (isNaN(item[col.field])) {
          item[col.field] = 0
      fields.forEach(col => {
        if (col.initval !== '$copy') {
          item[col.field] = col.initval
        }
      }
    })
        if (col.type === 'number') {
          item[col.field] = +item[col.field]
          if (isNaN(item[col.field])) {
            item[col.field] = 0
          }
        }
        if (item[col.field] === undefined) {
          item[col.field] = ''
        }
      })
    this.setState({edData: [...edData, item]})
      _edData.splice(index, 0, item)
      this.setState({edData: _edData})
    } else {
      let item = {}
      if (edData.length > 0) {
        item = {...edData[edData.length - 1]}
        item.$$uuid = Utils.getguid()
        item.$type = 'add'
        item.$Index = ''
      } else {
        item.$$uuid = Utils.getguid()
        item.$type = 'add'
        item.$Index = ''
        item.$$BID = BID || ''
      }
      fields.forEach(col => {
        if (col.initval !== '$copy') {
          item[col.field] = col.initval
        }
        if (col.type === 'number') {
          item[col.field] = +item[col.field]
          if (isNaN(item[col.field])) {
            item[col.field] = 0
          }
        }
        if (item[col.field] === undefined) {
          item[col.field] = ''
        }
      })
      this.setState({edData: [...edData, item]})
    }
  }
  checkData = () => {
@@ -721,6 +983,7 @@
      return
    }
    let err = ''
    let Index = 1
    let data = fromJS(edData).toJS().map(item => {
      let line = []
      fields.forEach(col => {
@@ -766,7 +1029,10 @@
      })
      if (line.length > 0) {
        err += `第${item.$Index}行:` + line.join(',') + ';'
        err += `第${Index}行:` + line.join(',') + ';'
      }
      if (!item.$deleted) {
        Index++
      }
      return item
@@ -784,8 +1050,21 @@
  }
  submit = (data) => {
    const { submit, BID } = this.props
    const { submit, BID, setting } = this.props
    const { fields } = this.state
    if (setting.commit === 'change') {
      data = data.filter(item => !item.$origin)
    }
    if (data.length === 0) {
      notification.warning({
        top: 92,
        message: '数据未修改,不可提交!',
        duration: 5
      })
      return
    }
    let result = getEditTableSql(submit, data, fields)
@@ -1042,10 +1321,11 @@
    let height = setting.height || false
    return (
      <div className={`edit-custom-table ${pickup ? 'editable' : ''} ${setting.tableHeader || ''} ${height ? 'fixed-height' : ''} ${setting.mode || ''}`} id={tableId}>
        <Switch title="编辑" className="main-pickup" checkedChildren="开" unCheckedChildren="关" checked={pickup} onChange={this.pickupChange} />
      <div className={`edit-custom-table ${pickup ? 'editable' : ''} ${setting.tableHeader || ''} ${setting.operType || ''} ${height ? 'fixed-height' : ''} ${setting.mode || ''}`} id={tableId}>
        <Switch title="编辑" className="main-pickup" checkedChildren="开" unCheckedChildren="关" disabled={loading || this.props.loading} checked={pickup} onChange={this.pickupChange} />
        {pickup ? <Button style={submit.style} onClick={() => setTimeout(() => {this.checkData()}, 10)} loading={loading} className="submit-table" type="link">提交</Button> : null}
        <Table
          rowKey="$$uuid"
          components={components}
          style={setting.style}
          size={setting.size || 'middle'}
@@ -1064,7 +1344,7 @@
          pagination={_pagination}
        />
        {_footer ? <div className={'normal-table-footer ' + (_pagination ? 'pagination' : '')}>{_footer}</div> : null}
        {pickup && setting.addable === 'true' ? <Button onClick={this.addLine} style={{display: 'block', width: '100%', color: '#26C281', border: '1px solid #dddddd', borderRadius: 0}} icon="plus" type="link"></Button> : null}
        {pickup && setting.addable === 'true' ? <Button className="mk-add-line" onClick={() => this.addLine()} disabled={this.props.loading} type="link"><PlusOutlined /></Button> : null}
      </div>
    )
  }