king
2021-11-12 0c84df247914f893ef5e41d57a422e10a2dc814c
src/templates/sharecomponent/tablecomponent/index.jsx
@@ -1,10 +1,12 @@
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { fromJS } from 'immutable'
import { Icon, Tooltip, Select, List, notification } from 'antd'
import { Tooltip, Select, List, notification } from 'antd'
import { QuestionCircleOutlined, CloseOutlined } from '@ant-design/icons'
import moment from 'moment'
import Api from '@/api'
import options from '@/store/options.js'
import Utils from '@/utils/utils.js'
import zhCN from '@/locales/zh-CN/model.js'
import enUS from '@/locales/en-US/model.js'
@@ -14,7 +16,6 @@
const { Option } = Select
// **悲观者往往正确,乐观者往往成功
class TablesComponent extends Component {
  static propTpyes = {
    config: PropTypes.object,        // 容器Id
@@ -23,12 +24,10 @@
  }
  state = {
    dict: (!localStorage.getItem('lang') || localStorage.getItem('lang') === 'zh-CN') ? zhCN : enUS,
    dict: sessionStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    tables: [],          // 系统表
    tableFields: [],    // 已选表字段集
    tableFields: [],     // 已选表字段集
    selectedTables: [],  // 已选表
    searchlist: null,    // 搜索条件集
    visible: false       // 模态框控制
  }
  /**
@@ -60,10 +59,17 @@
    }
    param.LText = Utils.formatOptions(param.LText)
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
    param.secretkey = Utils.encrypt(param.LText, param.timestamp)
    param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp) // 云端数据验证
    Api.getSystemConfig(param).then(res => {
    if (options.cloudServiceApi) { // 且存在云端地址
      param.rduri = options.cloudServiceApi
      param.userid = sessionStorage.getItem('CloudUserID') || ''
      param.LoginUID = sessionStorage.getItem('CloudLoginUID') || ''
    }
    Api.getSystemCacheConfig(param).then(res => {
      if (res.status) {
        this.setState({
          tables: res.data
@@ -81,7 +87,14 @@
  gettableFields = () => {
    let deffers = this.state.selectedTables.map(item => {
      return new Promise(resolve => {
        Api.getSystemConfig({func: 'sPC_Get_FieldName', TBName: item.TbName}).then(res => {
        let param = {func: 'sPC_Get_FieldName', TBName: item.TbName}
        if (options.cloudServiceApi) { // 且存在云端地址
          param.rduri = options.cloudServiceApi
          param.userid = sessionStorage.getItem('CloudUserID') || ''
          param.LoginUID = sessionStorage.getItem('CloudLoginUID') || ''
        }
        Api.getSystemCacheConfig(param).then(res => {
          res.TBName = item.TbName
          resolve(res)
        })
@@ -96,23 +109,19 @@
            columns: res.FDName.map(item => {
              let _type = item.FieldType.toLowerCase()
              let _decimal = 0
              let _length = 50
              if (/^nvarchar/.test(_type)) {
                try { // 存在max
                  _length = +_type.match(/\d+/)[0] || 50
                } catch (e) {
                  _length = 2048
                }
                _type = 'text'
              } else if (/^int/.test(_type)) {
                _type = 'number'
              } else if (/^decimal/.test(_type)) {
                _decimal = _type.split(',')[1]
                _decimal = parseInt(_decimal)
                if (_decimal > 4) {
                  _decimal = 4
                }
                _type = 'number'
              } else if (/^decimal/.test(_type)) {
                _decimal = _type.split(',')[1]
                _decimal = parseInt(_decimal)
                if (_decimal > 4) {
                  _decimal = 4
                }
                _type = 'number'
              } else if (/^datetime/.test(_type)) {
                _type = 'datetime'
@@ -123,11 +132,13 @@
              }
  
              return {
                field: item.FieldName,
                field: item.FieldName || '',
                label: item.FieldDec,
                type: _type,
                datatype: _type,
                decimal: _decimal
                decimal: _decimal,
                length: _length,
                $datatype: item.FieldType.toLowerCase()
              }
            })
          }
@@ -144,184 +155,13 @@
      this.setState({
        tableFields: _columns
      })
      this.props.updatetable(this.props.config, _columns)
      window.GLOB.tableFields = _columns
    })
  }
  queryField = (type) => {
    const {selectedTables, tableFields, config} = this.state
    // 判断是否已选择表名
    if (selectedTables.length === 0) {
      notification.warning({
        top: 92,
        message: '请选择表名!',
        duration: 5
      })
      return
    }
    // 表字段集转为map数据
    let columns = new Map()
    tableFields.forEach(table => {
      table.columns.forEach(column => {
        columns.set(column.field, column)
      })
    })
    if (type === 'search') {
      // 添加搜索条件,字段集中存在搜索条件字段,使用搜索条件对象替换字段集,设置数据类型
      config.search.forEach(item => {
        if (columns.has(item.field)) {
          let _datatype = columns.get(item.field).datatype
          columns.set(item.field, {...item, selected: true, datatype: _datatype})
        }
      })
    } else if (type === 'columns') {
      // 添加显示列,字段集中存在显示列字段,使用显示列对象替换字段集,设置数据类型
      config.columns.forEach(item => {
        if (columns.has(item.field)) {
          let _datatype = columns.get(item.field).datatype
          columns.set(item.field, {...item, selected: true, datatype: _datatype})
        }
      })
    }
    // 显示字段集弹窗
    this.setState({
      addType: type,
      tableVisible: true,
      fields: [...columns.values()]
    })
  }
  addFieldSubmit = () => {
    // 字段集为空,关闭弹窗
    if (!this.state.fields || this.state.fields.length === 0) {
      this.setState({
        tableVisible: false,
        addType: ''
      })
    }
    const {addType, config} = this.state
    // 获取已选字段集合
    let cards = this.refs.searchcard.state.selectCards
    let columnsMap = new Map()
    cards.forEach(card => {
      columnsMap.set(card.field, card)
    })
    let items = []
    if (addType === 'search') {
      config.search.forEach(item => {
        if (columnsMap.has(item.field)) {
          let cell = columnsMap.get(item.field)
          if (cell.selected && cell.type === item.type) { // 数据未修改
            items.push(item)
          } else if (cell.selected) { // 数据类型修改
            if (cell.type === 'select') {
              item.match = '='
            } else if (cell.type === 'daterange') {
              item.match = 'between'
            } else {
              cell.type = 'text'
              item.match = 'like'
            }
            item.type = cell.type
            item.initval = ''
            items.push(item)
          }
          columnsMap.delete(item.field)
        } else if (!item.origin) {
          items.push(item)
        }
      })
      let _columns = [...columnsMap.values()]
      _columns.forEach(item => {
        if (item.selected) {
          let _match = ''
          if (item.type === 'select') {
            _match = '='
          } else if (item.type === 'daterange') {
            _match = 'between'
          } else {
            item.type = 'text'
            _match = 'like'
          }
          let newcard = {
            uuid: Utils.getuuid(),
            label: item.label,
            field: item.field,
            initval: '',
            type: item.type,
            resourceType: '0',
            setAll: 'false',
            options: [],
            dataSource: '',
            linkField: '',
            valueField: '',
            valueText: '',
            orderBy: '',
            orderType: 'asc',
            match: _match,
            display: 'dropdown'
          }
          items.push(newcard)
        }
      })
    } else {
      config.columns.forEach(item => {
        if (columnsMap.has(item.field)) {
          let cell = columnsMap.get(item.field)
          if (cell.selected) {
            items.push(item)
          }
          columnsMap.delete(item.field)
        } else if (!item.origin) {
          items.push(item)
        }
      })
      let _columns = [...columnsMap.values()]
      _columns.forEach(item => {
        if (item.selected) {
          let newcard = {
            uuid: Utils.getuuid(),
            Align: 'left',
            label: item.label,
            field: item.field,
            Hide: 'false',
            IsSort: item.type === 'picture' ? 'false' : 'true',
            type: item.type,
            Width: 120
          }
          items.push(newcard)
        }
      })
    }
    this.setState({
      config: {...config, [addType]: items}
    })
    notification.success({
      top: 92,
      message: '操作成功',
      duration: 2
    })
  }
  /**
   * @description 添加表名
   */
  onTableChange = (value) => {
    const { config } = this.props
    const { tables, tableFields, selectedTables } = this.state
@@ -334,15 +174,22 @@
      })
      let _config = {...config, tables: [...selectedTables, _table]}
      Api.getSystemConfig({func: 'sPC_Get_FieldName', TBName: value}).then(res => {
        if (res.status) {
          let tabmsg = {
            tableName: _table.name,
            tableName: _table.TbName,
            columns: res.FDName.map(item => {
              let _type = item.FieldType.toLowerCase()
              let _decimal = 0
              let _length = 50
              if (/^nvarchar/.test(_type)) {
                try { // 存在max
                  _length = +_type.match(/\d+/)[0] || 50
                } catch (e) {
                  _length = 2048
                }
                _type = 'text'
              } else if (/^int/.test(_type)) {
                _type = 'number'
@@ -363,15 +210,22 @@
                label: item.FieldDec,
                type: _type,
                datatype: _type,
                decimal: _decimal
                decimal: _decimal,
                length: _length,
                $datatype: item.FieldType.toLowerCase()
              }
            })
          }
          let _columns = [...tableFields, tabmsg]
          this.setState({
            tableFields: [...tableFields, tabmsg]
            tableFields: _columns
          })
          this.props.updatetable(_config, [...tableFields, tabmsg])
          window.GLOB.tableFields = _columns
          this.props.updatetable(_config)
        } else {
          notification.warning({
            top: 92,
@@ -383,9 +237,12 @@
    }
  }
  /**
   * @description 删除表名
   */
  deleteTable = (table) => {
    const { config } = this.props
    const {selectedTables, tableFields} = this.state
    const { selectedTables, tableFields } = this.state
    let _tables = selectedTables.filter(item => item.TbName !== table.TbName)
    let _fields = tableFields.filter(item => item.tableName !== table.TbName)
@@ -395,13 +252,18 @@
      tableFields: _fields
    })
    this.props.updatetable({...config, tables: _tables}, _fields)
    window.GLOB.tableFields = _fields
    this.props.updatetable({...config, tables: _tables})
  }
  changeSetting = () => {
    this.setState({
      settingVisible: true
    })
  /**
   * @description 组件销毁,清除state更新
   */
  componentWillUnmount () {
    this.setState = () => {
      return
    }
  }
  render() {
@@ -414,7 +276,7 @@
        <div className="ant-col ant-form-item-label">
          <label>
            <Tooltip placement="topLeft" title={dict['model.tooltip.table.guide']}>
              <Icon type="question-circle" />
              <QuestionCircleOutlined className="mk-form-tip" />
              {dict['header.menu.table.add']}
            </Tooltip>
          </label>
@@ -427,7 +289,7 @@
          value={dict['header.menu.table.placeholder']}
          onChange={this.onTableChange}
          showArrow={false}
          getPopupContainer={() => document.getElementById(containerId)}
          getPopupContainer={() => containerId ? document.getElementById(containerId) : document.body}
          filterOption={(input, option) => {
            return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
              option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
@@ -443,7 +305,7 @@
          dataSource={selectedTables}
          renderItem={(item, index) => <List.Item key={index} title={item.Remark + ' (' + item.TbName + ')'}>
            {item.Remark + ' (' + item.TbName + ')'}
            <Icon type="close" onClick={() => this.deleteTable(item)}/>
            <CloseOutlined onClick={() => this.deleteTable(item)}/>
            <div className="bottom-mask"></div>
          </List.Item>}
        />}