king
2021-09-01 31ec63f0419895876cbaba99637a884a32d33d0d
src/tabviews/commontable/index.jsx
@@ -2,38 +2,32 @@
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import { is, fromJS } from 'immutable'
import { notification, Spin, Tabs, Icon, Switch, Modal, Button, message, Tree, Typography, Row, Col } from 'antd'
import { notification, Spin, Tabs, Icon, Switch, Row, Col } from 'antd'
import Api from '@/api'
import options from '@/store/options.js'
import zhCN from '@/locales/zh-CN/main.js'
import enUS from '@/locales/en-US/main.js'
import Utils from '@/utils/utils.js'
import options from '@/store/options.js'
import UtilsDM from '@/utils/utils-datamanage.js'
import UtilsUpdate from '@/utils/utils-update.js'
import { updateCommonTable } from '@/utils/utils-update.js'
import asyncComponent from '@/utils/asyncComponent'
import asyncSpinComponent from '@/utils/asyncSpinComponent'
import { refreshTabView } from '@/store/action'
import MKEmitter from '@/utils/events.js'
import MainSearch from '@/tabviews/zshare/topSearch'
import NotFount from '@/components/404'
import './index.scss'
// 通用组件
const MainSearch = asyncComponent(() => import('@/tabviews/zshare/topSearch'))
const MainAction = asyncSpinComponent(() => import('@/tabviews/zshare/actionList'))
const MainTable = asyncSpinComponent(() => import('@/tabviews/zshare/normalTable'))
const SettingComponent = asyncComponent(() => import('@/tabviews/zshare/settingcomponent'))
const SubTable = asyncSpinComponent(() => import('@/tabviews/subtable'))
const CardComponent = asyncSpinComponent(() => import('@/tabviews/zshare/cardcomponent'))
const ChartComponent = asyncSpinComponent(() => import('@/tabviews/zshare/chartcomponent'))
// 自定义标签
const SecretKeyTable = asyncSpinComponent(() => import('./secretKeyTable'))
const PagemsgComponent = asyncComponent(() => import('@/tabviews/zshare/pageMessage'))
const { TabPane } = Tabs
const { TreeNode } = Tree
const { Paragraph } = Typography
class NormalTable extends Component {
  static propTpyes = {
@@ -51,14 +45,13 @@
    viewlost: false,      // 页面丢失:1、未获取到配置-页面丢失;2、页面未启用
    lostmsg: '',          // 页面丢失时的提示信息
    config: {},           // 页面配置信息,包括按钮、搜索、显示列、标签等
    userConfig: null,     // 用户自定义设置
    shortcuts: null,      // 快捷键
    searchlist: null,     // 搜索条件
    actions: null,        // 按钮集
    columns: null,        // 显示列
    logcolumns: null,     // 日志中显示的列信息 (增加至全部列,除去合并列)
    arr_field: '',        // 使用 sPC_Get_TableData 时的查询字段集
    setting: null,        // 页面全局设置:数据源、按钮及显示列固定、主键等
    data: null,           // 列表数据集
    data: [],             // 列表数据集
    selectedData: [],     // 已选表格数据
    total: 0,             // 总数
    loading: false,       // 列表数据加载中
@@ -68,19 +61,19 @@
    search: '',           // 搜索条件数组,使用时需分场景处理
    BIDs: {},             // 上级表id
    pickup: false,        // 主表数据隐藏显示切换
    treevisible: false,   // 菜单结构树弹框显示隐藏控制
    refreshtabs: null,    // 需要刷新的标签集
    tabActive: null,      // 标签页展开控制
    chartId: '',          // 展开图表ID
    statFields: [],       // 合计字段
    statFValue: []        // 合计值
    statFValue: [],       // 合计值
    absFields: [],        // 绝对值字段
    loadCustomApi: true,  // 加载外部资源
    hasReqFields: false
  }
  /**
   * @description 获取页面配置信息
   */
  async loadconfig () {
    const { permAction, permMenus, param } = this.props
    const { permAction, permMenus, param, MenuName } = this.props
    let _param = {
      func: 'sPC_Get_LongParam',
@@ -90,11 +83,14 @@
    if (result.status) {
      let config = ''
      let userConfig = null
      let _curUserConfig = ''
      let shortcuts = []
      try { // 配置信息解析
        config = JSON.parse(window.decodeURIComponent(window.atob(result.LongParam)))
        config.MenuID = this.props.MenuID
        config.MenuName = MenuName
        config.setting.MenuName = MenuName
        config.setting.$name = MenuName
      } catch (e) {
        console.warn('Parse Failure')
        config = ''
@@ -103,11 +99,36 @@
      // HS不使用自定义设置
      if (result.LongParamUser && this.props.menuType !== 'HS') {
        try { // 配置信息解析
          userConfig = JSON.parse(window.decodeURIComponent(window.atob(result.LongParamUser)))
          _curUserConfig = userConfig[this.props.MenuID]
          let userConfig = JSON.parse(window.decodeURIComponent(window.atob(result.LongParamUser)))
          if (userConfig && !userConfig.version) {
            Object.keys(userConfig).forEach(key => {
              let component = userConfig[key]
              if (!component.action) return
              Object.keys(component.action).forEach(uuid => {
                let item = {uuid: uuid, parentId: key, shortcut: component.action[uuid].shortcut}
                let printer = component.action[uuid].printer
                if (item.shortcut) {
                  item.$shortcut = item.shortcut.join('+')
                  shortcuts.push(item)
                }
                if (printer) {
                  item.printer = printer.defaultPrinter || ''
                  item.printerList = printer.printerList || ''
                  window.GLOB.UserCacheMap.set(key + uuid, item)
                }
              })
            })
          } else if (userConfig) {
            shortcuts = userConfig.action
            userConfig.printers.forEach(item => {
              window.GLOB.UserCacheMap.set(item.parentId + item.uuid, item)
            })
          }
        } catch (e) {
          console.warn('Parse Failure')
          userConfig = null
        }
      }
@@ -131,7 +152,7 @@
      }
      // 版本兼容
      config = UtilsUpdate.updateCommonTable(config)
      config = updateCommonTable(config)
      // 权限过滤
      if (this.props.menuType !== 'HS') {
@@ -143,32 +164,12 @@
      // 去除空行标签
      config.tabgroups = config.tabgroups.filter(group => group.sublist.length > 0)
      // HS下自定义处理的标签
      if (this.props.menuType === 'HS') {
        config.tabgroups.forEach(group => {
          group.sublist = group.sublist.map(tab => {
            if (tab.linkTab === '1586577325055l2ng7t75g7i4ek2ng8o') {
              tab.type = 'SecretKeyTable'
            }
            return tab
          })
        })
      }
      let roleId = sessionStorage.getItem('role_id') || '' // 角色ID
      // 视图权限
      config.charts = config.charts.filter(item => {
        if (item.Hide === 'true') return false
        if (!item.blacklist || item.blacklist.length === 0) return true
        let _black = item.blacklist.filter(v => {
          return this.props.permRoles.indexOf(v) !== -1
        })
        if (_black.length > 0 || item.Hide === 'true') {
          return false
        } else {
          return true
        }
        return item.blacklist.filter(v => roleId.indexOf(v) > -1).length === 0
      })
      if (config.charts.length <= 1) {
@@ -176,40 +177,25 @@
      }
      let chartId = config.charts[0] ? config.charts[0].uuid : ''
      // 字段权限黑名单
      config.search = Utils.initSearchVal(config.search)
      // 字段透视及必填标志
      let hasReqFields = false
      config.search = config.search.map(item => {
        item.oriInitval = item.initval
        if (['text', 'select', 'link'].includes(item.type) && param) {
          if (param.searchkey === item.field) {
            item.initval = param.searchval
          } else if (param.BID && item.field.toLowerCase() === 'bid') {
            item.initval = param.BID
          } else if (param.data && param.data[item.field]) {
            item.initval = param.data[item.field]
          }
        if (['text', 'select', 'link'].includes(item.type) && param && param.$searchkey === item.field) {
          item.initval = param.$searchval
        }
        if (!item.blacklist || item.blacklist.length === 0) return item
        let _black = item.blacklist.filter(v => {
          return this.props.permRoles.indexOf(v) !== -1
        })
        if (_black.length > 0) {
          item.Hide = 'true'
        if (item.required) {
          hasReqFields = true
        }
        return item
      })
      config.columns = config.columns.map(col => {
        if (!col.field || !col.blacklist || col.blacklist.length === 0 || config.setting.primaryKey === col.field) return col
        let _black = col.blacklist.filter(v => {
          return this.props.permRoles.indexOf(v) !== -1
        })
        if (_black.length > 0) {
        if (!col.field || !col.blacklist || col.blacklist.length === 0) return col
        if (col.blacklist.filter(v => roleId.indexOf(v) > -1).length > 0) {
          col.Hide = 'true'
        }
@@ -223,8 +209,9 @@
      config.setting.laypage = config.setting.laypage !== 'false'     // 是否分页,转为boolean 统一格式
      config.setting.execute = config.setting.default !== 'false'     // 默认sql是否执行,转为boolean 统一格式
      config.setting.customScript = ''                                // 自定义脚本
      config.setting.dataresource = config.setting.dataresource || ''
      if (config.setting.interType === 'system') {
      if (config.setting.interType === 'system' || (config.setting.interType === 'custom' && config.setting.requestMode === 'system')) {
        if (config.setting.scripts && config.setting.scripts.length > 0) {
          let _customScript = ''
          config.setting.scripts.forEach(item => {
@@ -238,14 +225,11 @@
  
        if (!config.setting.execute) { // 默认sql 不执行时 置空
          config.setting.dataresource = ''
        } else {
          config.setting.dataresource = config.setting.dataresource || ''
        }
        if (/\s/.test(config.setting.dataresource)) {
        } else if (/\s/.test(config.setting.dataresource)) {
          config.setting.dataresource = '(' + config.setting.dataresource + ') tb'
        }
  
        if (this.props.dataManager) { // 数据权限
        if (sessionStorage.getItem('dataM') === 'true') { // 数据权限
          config.setting.dataresource = config.setting.dataresource.replace(/\$@/ig, '/*')
          config.setting.dataresource = config.setting.dataresource.replace(/@\$/ig, '*/')
          config.setting.customScript = config.setting.customScript.replace(/\$@/ig, '/*')
@@ -254,58 +238,68 @@
          config.setting.dataresource = config.setting.dataresource.replace(/@\$|\$@/ig, '')
          config.setting.customScript = config.setting.customScript.replace(/@\$|\$@/ig, '')
        }
      }
      if (_curUserConfig) {
        config.setting = {...config.setting, ..._curUserConfig.setting}
        config.easyCode = _curUserConfig.easyCode || config.easyCode || ''
        let userName = sessionStorage.getItem('User_Name') || ''
        let fullName = sessionStorage.getItem('Full_Name') || ''
        let city = sessionStorage.getItem('city') || ''
        config.action = config.action.map(item => {
          if (item.execMode) {
            item.OpenType = 'funcbutton'
          }
        if (sessionStorage.getItem('isEditState') === 'true') {
          userName = sessionStorage.getItem('CloudUserName') || ''
          fullName = sessionStorage.getItem('CloudFullName') || ''
        }
          if (_curUserConfig.action[item.uuid]) {
            delete _curUserConfig.action[item.uuid].label
            item = {...item, ..._curUserConfig.action[item.uuid]}
          }
          if (item.OpenType === 'funcbutton' && item.funcType === 'print' && item.verify && item.printer) {
            item.verify.defaultPrinter = item.printer.defaultPrinter || ''
            if (item.verify.printerTypeList && item.printer.printerList) {
              item.verify.printerTypeList = item.verify.printerTypeList.map(cell => {
                cell.printer = item.printer.printerList[cell.Value] || ''
        let regs = [
          { reg: /@userName@/ig, value: `'${userName}'` },
          { reg: /@fullName@/ig, value: `'${fullName}'` },
          { reg: /@login_city@/ig, value: `'${city}'` }
        ]
                return cell
              })
            }
          }
          return item
        regs.forEach(cell => {
          config.setting.dataresource = config.setting.dataresource.replace(cell.reg, cell.value)
          config.setting.customScript = config.setting.customScript.replace(cell.reg, cell.value)
        })
        if (config.urlFields) {
          let _param = param || {}
          config.urlFields.forEach(field => {
            let reg = new RegExp('@' + field + '@', 'ig')
            let val = `'${_param[field] || ''}'`
            config.setting.dataresource = config.setting.dataresource.replace(reg, val)
            config.setting.customScript = config.setting.customScript.replace(reg, val)
          })
        }
      }
      let _tabActive = {} // 筛选展开的tab页
      config.tabgroups.forEach(group => {
        _tabActive[group.uuid] = group.sublist[0].uuid
      })
      let _arrField = []     // 字段集
      let _columns = []      // 显示列
      let _logcolumns = []   // 日志显示列
      let _hideCol = []      // 隐藏及合并列中字段的uuid集
      let colMap = new Map() // 用于字段过滤
      let statFields = []    // 合计字段信息
      let absFields = []     // 绝对值字段
      let _actions = []      // 工具栏按钮
      let _operations = []   // 操作列按钮(存在时)
      config.action.forEach(item => {
        if (item.execMode) {
          item.OpenType = 'funcbutton'
        }
        item.logLabel = MenuName + '-' + item.label // 用于sPC_TableData_InUpDe记录操作按钮
        item.$menuId = this.props.MenuID
        if (item.OpenType === 'funcbutton' && item.funcType === 'print' && item.verify) { // 打印机设置
          let _item = window.GLOB.UserCacheMap.get(this.props.MenuID + item.uuid)
          if (_item) {
            item.printer = _item.printer || ''
            item.verify.defaultPrinter = _item.printer || ''
            if (item.verify.printerTypeList && _item.printerList) {
              item.verify.printerTypeList = item.verify.printerTypeList.map(cell => {
                cell.printer = _item.printerList[cell.Value] || ''
                return cell
              })
            }
          }
        }
        if (item.position === 'toolbar') {
          _actions.push(item)
        } else if (item.position === 'grid') {
@@ -317,17 +311,24 @@
      config.columns.forEach(col => {
        if (col.field) {
          _arrField.push(col.field)
          _logcolumns.push(col)
          if (col.linkmenu && col.linkmenu.length > 0) {
            let menu_id = col.linkmenu.slice(-1)[0]
            col.linkThdMenu = permMenus.filter(m => m.MenuID === menu_id)[0] || ''
          } else {
            col.linkThdMenu = ''
          }
          col.nameField && _arrField.push(col.nameField) // 链接名字段
          if (col.Hide !== 'true' && col.type === 'number' && col.sum === 'true') {
            statFields.push(col)
          }
          if (col.format === 'abs') {
            absFields.push(col.field)
          }
        }
        if (col.type === 'colspan' && col.sublist) { // 筛选隐藏列
          _hideCol = _hideCol.concat(col.sublist)
        } else if (col.Hide === 'true') {
          _hideCol.push(col.uuid)
        }
        colMap.set(col.uuid, col)
      })
@@ -336,22 +337,24 @@
      config.columns.forEach((col, index) => {
        if (_hideCol.includes(col.uuid)) return
        if (col.linkThdMenu && !permMenus[col.linkThdMenu.MenuID]) {
          col.linkThdMenu = ''
        }
        col.sort = index
        if (col.type === 'colspan' && col.sublist) {
        if (col.type === 'colspan') {
          if (col.unfold !== 'true') { // 不展开为旧版合并列
            col.type = 'old_colspan'
          }
          let _col = fromJS(col).toJS()
          let subColumn = []
          _col.sublist.forEach(sub => {
          let subcols = []
          _col.sublist && _col.sublist.forEach(sub => {
            if (colMap.has(sub)) {
              subColumn.push(colMap.get(sub))
              subcols.push(colMap.get(sub))
            }
          })
          _col.subColumn = subColumn
          _columns.push(_col)
          if (subcols.length > 0) {
            _col.subcols = subcols
            _columns.push(_col)
          }
        } else {
          _columns.push(col)
        }
@@ -362,50 +365,24 @@
        _columns.push(config.gridBtn)
      }
      let valid = true // 搜索条件必填验证, 初始搜索条件, 如通过上级透视,写入搜索条件
      let initSearch = config.search.map(item => {
        let _item = fromJS(item).toJS()
        if (_item.required === 'true' && !_item.initval) {
          valid = false
        }
        return _item
      })
      if (_curUserConfig) {
        _columns = _columns.map(item => {
          if (_curUserConfig.columns[item.uuid]) {
            delete _curUserConfig.columns[item.uuid].label
            item = {...item, ..._curUserConfig.columns[item.uuid]}
          }
          return item
        })
        _columns.sort((pre, next) => {
          return pre.sort - next.sort
        })
      }
      this.setState({
        BID: param && param.BID ? param.BID : '',
        loadingview: false,
        chartId: chartId,
        config: config,
        statFields: statFields,
        tabActive: _tabActive,
        userConfig: userConfig,
        absFields,
        chartId,
        config,
        statFields,
        shortcuts,
        setting: config.setting,
        searchlist: config.search,
        actions: _actions,
        columns: _columns,
        logcolumns: _logcolumns,
        arr_field: _arrField.join(','),
        search: Utils.initMainSearch(initSearch) // 搜索条件初始化(含有时间格式,需要转化)
        BID: param && param.$BID ? param.$BID : '',
        search: Utils.initMainSearch(config.search),
        hasReqFields
      }, () => {
        if (config.setting.onload !== 'false' && valid) { // 初始化可加载
          this.loadmaindata()
          this.getStatFieldsValue()
        if (config.setting.onload !== 'false') { // 初始化可加载
          this.loadData()
        }
        this.setShortcut()
      })
@@ -423,8 +400,12 @@
  }
  setShortcut = () => {
    const { actions, userConfig, config } = this.state
    if (!userConfig) return
    const { shortcuts } = this.state
    if (!shortcuts || shortcuts.length === 0) {
      document.onkeydown = () => {}
      return
    }
    document.onkeydown = (event) => {
      let e = event || window.event
@@ -439,86 +420,31 @@
        preKey = 'alt'
      }
      if (!preKey) return
      if (!preKey || !keyCode) return
      let triggerId = ''
      let _shortcut = `${preKey}+${keyCode}`
      actions.some(item => {
        if (Array.isArray(item.shortcut) && preKey === item.shortcut[0] && keyCode === item.shortcut[1]) {
          e.preventDefault()
          triggerId = item.uuid
      shortcuts.some(item => {
        if (item.$shortcut === _shortcut) {
          MKEmitter.emit('triggerBtnId', item.uuid)
          let element = item.parentId && item.parentId !== this.props.MenuID ? document.getElementById(item.parentId) : '' // 标签切换
          if (element && element.click) {
            element.click()
          }
          return true
        }
        return false
      })
      if (triggerId) {
        MKEmitter.emit('triggerBtnId', triggerId)
        return
      }
      Object.keys(userConfig).some(key => {
        if (key === this.props.MenuID || !userConfig[key].action) return false
        let _actions = userConfig[key].action
        Object.keys(_actions).some(btnkey => {
          let item = _actions[btnkey]
          if (Array.isArray(item.shortcut) && preKey === item.shortcut[0] && keyCode === item.shortcut[1]) {
            e.preventDefault()
            triggerId = btnkey
            let _groupId = ''
            let _ActiveTabId = ''
            config.tabgroups.forEach(group => {
              let _tab = group.sublist.filter(tab => tab.uuid === key)[0]
              if (!_tab) return
              _groupId = group.uuid
              _ActiveTabId = _tab.uuid
            })
            this.setState({
              tabActive: {...this.state.tabActive, [_groupId]: _ActiveTabId}
            }, () => {
              MKEmitter.emit('triggerBtnId', triggerId)
            })
            return true
          }
          return false
        })
        if (triggerId) return true
        return false
      })
    }
  }
  /**
   * @description 主表数据加载
   */
  async loadmaindata () {
    const { setting, arr_field, BIDs, search, orderBy, BID, pageIndex, pageSize } = this.state
    let requireFields = search.filter(item => item.required && (!item.value || item.value.length === 0))
    if (requireFields.length > 0) {
      let labels = requireFields.map(item => item.label)
      labels = Array.from(new Set(labels))
      notification.warning({
        top: 92,
        message: this.state.dict['form.required.input'] + labels.join('、') + ' !',
        duration: 3
      })
      return
    }
  loadData = () => {
    const { setting, search, BIDs, loadCustomApi, hasReqFields } = this.state
    this.setState({
      selectedData: [],
      loading: true,
      BIDs: {
        ...BIDs,
        mainTable: '',
@@ -526,14 +452,246 @@
      }
    })
    if (hasReqFields) {
      let requireFields = search.filter(item => item.required && item.value === '')
      if (requireFields.length > 0) {
        this.setState({
          loading: false
        })
        return
      }
    }
    if (window.GLOB.systemType === 'production' && setting.interType === 'custom' && !setting.proInterface) {
      notification.warning({
        top: 92,
        message: '未设置正式系统地址!',
        duration: 3
      })
      return
    }
    if (setting.interType === 'custom' && loadCustomApi) {
      if (setting.execTime === 'once') {
        this.setState({loadCustomApi: false})
      }
      this.loadOutResource()
      if (setting.execType === 'async') {
        this.loadmaindata()
      }
    } else {
      this.loadmaindata()
    }
  }
  loadOutResource = () => {
    const { setting, search, BID } = this.state
    let param = UtilsDM.getPrevQueryParams(setting, search, BID, this.props.menuType)
    if (setting.execType === 'sync') {
      this.setState({
        loading: true
      })
    }
    Api.genericInterface(param).then(res => {
      if (res.status) {
        if (res.mk_ex_invoke === 'false' || res.mk_ex_invoke === false) {
          this.loadmaindata()
        } else {
          this.customOuterRequest(res)
        }
      } else {
        this.setState({
          loading: false
        })
        notification.error({
          top: 92,
          message: res.message,
          duration: 10
        })
      }
    }, () => {
      this.setState({
        loading: false
      })
    })
  }
  customOuterRequest = (result) => {
    const { setting } = this.state
    let url = ''
    if (window.GLOB.systemType === 'production') {
      url = setting.proInterface
    } else {
      url = setting.interface
    }
    let mkey = result.mk_api_key || ''
    delete result.mk_ex_invoke // 是否继续执行
    delete result.status
    delete result.message
    delete result.ErrCode
    delete result.ErrMesg
    delete result.mk_api_key   // 当前请求的key值,用于回调
    let param = {}
    Object.keys(result).forEach(key => {
      key = key.replace(/^mk_/ig, '')
      param[key] = result[key]
    })
    Api.directRequest(url, setting.method, param, setting.cross).then(res => {
      if (typeof(res) !== 'object') {
        let error = '未知的返回结果!'
        if (typeof(res) === 'string') {
          error = res.replace(/'/ig, '"')
        }
        let _result = {
          mk_api_key: mkey,
          $ErrCode: 'E',
          $ErrMesg: error
        }
        this.customCallbackRequest(_result)
      } else {
        if (Array.isArray(res)) {
          res = { data: res }
        }
        res.mk_api_key = mkey
        this.customCallbackRequest(res)
      }
    }, (e) => {
      let _result = {
        mk_api_key: mkey,
        $ErrCode: 'E',
        $ErrMesg: e && e.statusText ? e.statusText : ''
      }
      this.customCallbackRequest(_result)
    })
  }
  customCallbackRequest = (result) => {
    const { setting } = this.state
    let errSql = ''
    if (result.$ErrCode === 'E') {
      errSql = `
        set @ErrorCode='E'
        set @retmsg='${result.$ErrMesg}'
      `
      delete result.$ErrCode
      delete result.$ErrMesg
    }
    let lines = UtilsDM.getCallBackSql(setting, result)
    let param = {}
    if (setting.callbackType === 'script') { // 使用自定义脚本
      let sql = lines.map(item => (`
        ${item.insert}
        ${item.selects.join(` union all
        `)}
      `))
      sql = sql.join('')
      param = UtilsDM.getCallBackQueryParams(setting, sql, errSql)
      if (this.state.BID) {
        param.BID = this.state.BID
      }
      if (this.props.menuType === 'HS') { // 函数 sPC_TableData_InUpDe 云端验证
        param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp)
      }
    } else {
      param.func = 's_ex_result_back'
      param.s_ex_result = lines.map((item, index) => ({
        MenuID: this.state.config.MenuID,
        MenuName: this.state.config.MenuName,
        TableName: item.table,
        LongText: window.btoa(window.encodeURIComponent(`${item.insert}  ${item.selects.join(` union all `)}`)),
        Sort: index + 1
      }))
      if ((window.GLOB.systemType !== 'production' && options.sysType !== 'cloud') || window.debugger === true) {
        let sql = lines.map(item => (`
          ${item.insert}
          ${item.selects.join(` union all
          `)}
        `))
        sql = sql.join('')
        console.info(sql.replace(/\n\s{10}/ig, '\n'))
      }
    }
    Api.genericInterface(param).then(res => {
      if (res.status) {
        this.loadmaindata()
      } else {
        this.setState({
          loading: false
        })
        notification.error({
          top: 92,
          message: res.message,
          duration: 10
        })
      }
    }, () => {
      this.setState({
        loading: false
      })
    })
  }
  /**
   * @description 主表数据加载
   */
  async loadmaindata () {
    const { setting, arr_field, search, orderBy, BID, pageIndex, pageSize, absFields } = this.state
    this.setState({
      loading: true
    })
    let _orderBy = orderBy || setting.order
    let param = UtilsDM.getQueryDataParams(setting, arr_field, search, _orderBy, pageIndex, pageSize, BID, this.props.menuType, this.props.dataManager)
    let param = UtilsDM.getQueryDataParams(setting, arr_field, search, _orderBy, pageIndex, pageSize, BID, this.props.menuType)
    let result = await Api.genericInterface(param)
    this.getStatFieldsValue()
    if (result.status) {
      let start = 1
      if (setting.laypage) {
        start = pageSize * (pageIndex - 1) + 1
      }
      this.setState({
        data: result.data.map((item, index) => {
          if (absFields.length) {
            absFields.forEach(field => {
              if (!item[field]) return
              if (isNaN(Math.abs(item[field]))) return
              item[field] = Math.abs(item[field])
            })
          }
          item.key = index
          item.$$uuid = item[setting.primaryKey] || ''
          item.$$BID = BID || ''
          item.$Index = start + index + ''
          return item
        }),
        total: result.total,
@@ -553,20 +711,84 @@
  }
  /**
   * @description 获取单行数据
   */
  async loadmainLinedata (id) {
    const { setting, arr_field, search, orderBy, BID, pageIndex, pageSize, absFields } = this.state
    this.setState({
      loading: true
    })
    let _orderBy = orderBy || setting.order
    let param = UtilsDM.getQueryDataParams(setting, arr_field, search, _orderBy, pageIndex, pageSize, BID, this.props.menuType, id)
    let result = await Api.genericInterface(param)
    if (result.status) {
      let data = fromJS(this.state.data).toJS()
      let selectedData = fromJS(this.state.selectedData).toJS()
      if (result.data && result.data[0]) {
        let _data = result.data[0] || {}
        if (absFields.length) {
          absFields.forEach(field => {
            if (!_data[field]) return
            if (isNaN(Math.abs(_data[field]))) return
            _data[field] = Math.abs(_data[field])
          })
        }
        _data.$$uuid = _data[setting.primaryKey] || ''
        _data.$$BID = BID || ''
        try {
          data = data.map(item => {
            if (item.$$uuid === _data.$$uuid) {
              _data.key = item.key
              _data.$Index = item.$Index
              return _data
            } else {
              return item
            }
          })
          selectedData = selectedData.map(item => {
            if (_data.$$uuid === item.$$uuid) {
              return _data
            }
            return item
          })
        } catch (e) {
          console.warn('数据查询错误')
        }
      }
      this.setState({
        data,
        selectedData,
        loading: false
      })
    } else {
      this.setState({
        loading: false
      })
      notification.error({
        top: 92,
        message: result.message,
        duration: 10
      })
    }
  }
  /**
   * @description 获取合计字段值
   */
  getStatFieldsValue = () => {
    const { setting, search, BID, orderBy, statFields } = this.state
    if (statFields.length === 0 || setting.interType !== 'system' || !setting.dataresource) return
    let requireFields = search.filter(item => item.required && (!item.value || item.value.length === 0))
    if (requireFields.length > 0) {
      return
    }
    if (statFields.length === 0 || !(setting.interType === 'system' || (setting.interType === 'custom' && setting.requestMode === 'system')) || !setting.dataresource) return
    let _orderBy = orderBy || setting.order
    let param = UtilsDM.getStatQueryDataParams(setting, statFields, search, _orderBy, BID, this.props.menuType, this.props.dataManager)
    let param = UtilsDM.getStatQueryDataParams(setting, statFields, search, _orderBy, BID, this.props.menuType)
    Api.genericInterface(param).then(res => {
      if (res.status) {
@@ -614,8 +836,7 @@
        search: searches,
        setting: {...setting, onload: 'true'}
      }, () => {
        this.loadmaindata()
        this.getStatFieldsValue()
        this.loadData()
      })
    } else {
      MKEmitter.emit('resetTable', this.props.MenuID + 'mainTable') // 列表重置
@@ -623,8 +844,7 @@
        pageIndex: 1,
        search: searches
      }, () => {
        this.loadmaindata()
        this.getStatFieldsValue()
        this.loadData()
      })
    }
  }
@@ -646,29 +866,33 @@
      pageSize: pagination.pageSize,
      orderBy: (sorter.field && sorter.order) ? `${sorter.field} ${sorter.order}` : ''
    }, () => {
      this.loadmaindata()
      this.loadData()
    })
  }
  /**
   * @description 表格刷新
   */
  reloadtable = () => {
    MKEmitter.emit('resetTable', this.props.MenuID + 'mainTable') // 列表重置
    this.setState({
      pageIndex: 1
    }, () => {
      this.loadmaindata()
      this.getStatFieldsValue()
    })
  reloadtable = (btn) => {
    if (!btn || btn.resetPageIndex !== 'false') {
      MKEmitter.emit('resetTable', this.props.MenuID + 'mainTable') // 列表重置
      this.setState({
        pageIndex: 1
      }, () => {
        this.loadData()
      })
    } else {
      MKEmitter.emit('resetTable', this.props.MenuID + 'mainTable', 'false') // 列表重置
      this.loadData()
    }
  }
  /**
   * @description 页面刷新,重新获取配置
   */
  reloadview = () => {
    this.setState({ loadingview: true, viewlost: false, lostmsg: '',
      data: null, total: 0, loading: false, pageIndex: 1,
    this.setState({ loadingview: true, viewlost: false, config: {}, setting: null,
      data: null, total: 0, loading: false, pageIndex: 1, shortcuts: null,
      pageSize: 10, orderBy: '', search: '', BIDs: {}, pickup: false
    }, () => {
      this.loadconfig()
@@ -676,56 +900,20 @@
  }
  /**
   * @description 按钮操作完成后(成功或失败),页面刷新,重置页码及选择项
   */
  refreshbyaction = (position) => {
    if (position === 'grid') {
      this.reloadtable()
    } else if (position === 'view') {
      this.reloadview()
    }
  }
  /**
   * @description 子表操作完成后刷新主表
   */
  handleMainTable = (type, tab) => {
    if (type === 'maingrid' && tab.supMenu === 'mainTable') {
      this.reloadtable()
    } else if (type === 'mainline' && tab.supMenu === 'mainTable') {
      this.reloadtable()
    } else if ((type === 'maingrid' || type === 'mainline') && tab.supMenu) {
      this.setState({
        refreshtabs: [type, tab.supMenu]
      }, () => {
        this.setState({
          refreshtabs: null
        })
      })
    } else if (type === 'equaltab' && tab.equalTab && tab.equalTab.length > 0) {
      this.setState({
        refreshtabs: tab.equalTab
      }, () => {
        this.setState({
          refreshtabs: null
        })
      })
    }
  }
  /**
   * @description 导出Excel时,获取页面搜索排序等参数
   */
  getexceloutparam = () => {
    const { MenuName } = this.props
  queryModuleParam = (menuId, btnId) => {
    const { MenuName, MenuID } = this.props
    const { arr_field, orderBy, search, setting} = this.state
    return {
    if (MenuID !== menuId) return
    MKEmitter.emit('returnModuleParam', MenuID, btnId, {
      arr_field: arr_field,
      orderBy: orderBy || setting.order,
      search: search,
      menuName: MenuName
    }
    })
  }
  /**
@@ -760,70 +948,63 @@
    })
  }
  handleviewconfig = (e) => {
    e.stopPropagation()
    const { MenuNo } = this.props
    const { config } = this.state
    if (config && config.funcs && config.funcs.length > 0) {
      this.setState({
        treevisible: true
      })
    } else {
      let oInput = document.createElement('input')
      oInput.value = MenuNo || ''
      document.body.appendChild(oInput)
      oInput.select()
      document.execCommand('Copy')
      document.body.removeChild(oInput)
      message.success(this.state.dict['main.copy.success'])
    }
  }
  getTreeNode = (data) => {
    let _type = {
      view: '页面',
      btn: '按钮',
      tab: '标签'
    }
    return data.map(item => {
      let _title = _type[item.subtype]
      let _others = []
      _others.push(
        (item.menuNo ? item.menuNo + '(菜单参数)' : ''),
        (item.tableName ? item.tableName + '(表名) ' : ''),
        (item.innerFunc ? item.innerFunc + '(内部函数) ' : ''),
        (item.outerFunc ? item.outerFunc + '(外部函数)' : '')
      )
      _others = _others.filter(Boolean)
      _others = _others.join('、')
      if (item.label) {
        _title = _title + '(' + item.label + ')'
      }
      if (_others) {
        _title = _title + ': ' + _others
      }
      if (item.subfuncs && item.subfuncs.length > 0) {
        return (
          <TreeNode title={_title} key={item.uuid} dataRef={item} selectable={false}>
            {this.getTreeNode(item.subfuncs)}
          </TreeNode>
        )
      }
      return <TreeNode key={item.uuid} title={_title} isLeaf selectable={false} />
    })
  }
  /**
   * @description 图表视图切换
   */
  changeChart = (uuid) => {
    this.setState({chartId: uuid})
  }
  reloadData = (menuId, id, btn) => {
    const { MenuID } = this.props
    if (MenuID !== menuId) return
    if (id === 'empty') return
    if (id === 'formtab') { // 表单标签页刷新
      this.reloadtable(btn)
      return
    }
    if (!id) {
      this.reloadtable()
    } else {
      this.loadmainLinedata(id)
    }
  }
  reloadMenuView = (menuId, position) => {
    const { MenuID } = this.props
    if (MenuID !== menuId) return
    if (position === 'table') {
      this.reloadtable()
    } else {
      this.reloadview()
    }
  }
  resetActiveMenu = (menuId) => {
    const { MenuID } = this.props
    if (MenuID !== menuId) return
    this.setShortcut()
  }
  /**
   * @description 按钮执行完成后页面刷新
   * @param {*} menuId     // 菜单Id
   * @param {*} position   // 刷新位置
   * @param {*} btn        // 执行的按钮
   */
  refreshByButtonResult = (menuId, position, btn) => {
    const { MenuID } = this.props
    if (MenuID !== menuId) return
    this.reloadtable(btn)
  }
  UNSAFE_componentWillMount () {
@@ -832,31 +1013,24 @@
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.refreshTab && nextProps.refreshTab.MenuID === this.props.MenuID) {
      if (nextProps.refreshTab.position === 'grid') {
        this.reloadtable()
      } else if (nextProps.refreshTab.position === 'view') {
        this.reloadview()
      }
      this.props.refreshTabView('')
    } else if (!is(fromJS(this.props.tabviews), fromJS(nextProps.tabviews))) {
    if (!is(fromJS(this.props.tabviews), fromJS(nextProps.tabviews))) {
      let selectTab = nextProps.tabviews.filter(tab => tab.selected)[0]
      if (selectTab && selectTab.MenuID === this.props.MenuID) {
        this.setShortcut()
      }
    } else if (nextProps.param && !is(fromJS(this.props.param), fromJS(nextProps.param))) {
      let search = this.state.search.map(item => {
        if (item.type === 'text' && item.key === nextProps.param.searchkey) {
          item.value = nextProps.param.searchval
        }
        return item
      })
      this.refreshbysearch(search)
    }
  }
  shouldComponentUpdate (nextProps, nextState) {
    return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state), fromJS(nextState))
  }
  componentDidMount () {
    MKEmitter.addListener('reloadData', this.reloadData)
    MKEmitter.addListener('reloadMenuView', this.reloadMenuView)
    MKEmitter.addListener('resetActiveMenu', this.resetActiveMenu)
    MKEmitter.addListener('queryModuleParam', this.queryModuleParam)
    MKEmitter.addListener('refreshByButtonResult', this.refreshByButtonResult)
  }
  /**
@@ -867,26 +1041,24 @@
      return
    }
    document.onkeydown = () => {}
    MKEmitter.removeListener('reloadData', this.reloadData)
    MKEmitter.removeListener('reloadMenuView', this.reloadMenuView)
    MKEmitter.removeListener('resetActiveMenu', this.resetActiveMenu)
    MKEmitter.removeListener('queryModuleParam', this.queryModuleParam)
    MKEmitter.removeListener('refreshByButtonResult', this.refreshByButtonResult)
  }
  render() {
    const { menuType } = this.props
    const { BID, setting, searchlist, pageSize, actions, columns, loadingview, viewlost, pickup, config, userConfig, tabActive, chartId, search, selectedData } = this.state
    const { BID, setting, searchlist, pageSize, actions, columns, loadingview, viewlost, pickup, config, chartId, search, selectedData, shortcuts } = this.state
    return (
      <div className="commontable" id={this.state.ContainerId}>
        {loadingview && <Spin size="large" />}
        {searchlist && searchlist.length > 0 ?
          <MainSearch
            BID={BID}
            dict={this.state.dict}
            searchlist={searchlist}
            menuType={this.props.menuType}
            dataManager={this.props.dataManager}
            refreshdata={this.refreshbysearch}
          /> : null
        {loadingview ? <Spin size="large" /> : null}
        {searchlist && searchlist.length ?
          <MainSearch BID={BID} searchlist={searchlist} setting={setting} menuType={this.props.menuType} refreshdata={this.refreshbysearch}/> : null
        }
        {setting && setting.onload !== 'false' ? <Row className="chart-view" gutter={16}>
        {setting ? <Row className="chart-view" gutter={16}>
          {/* 视图组 */}
          {!config.expand ? <Tabs activeKey={chartId} onChange={this.changeChart}>
            {config.charts.map(item => (
@@ -905,35 +1077,20 @@
                      BID={BID}
                      setting={setting}
                      actions={actions}
                      dict={this.state.dict}
                      MenuID={this.props.MenuID}
                      selectedData={selectedData}
                      logcolumns={this.state.logcolumns}
                      ContainerId={this.state.ContainerId}
                      refreshdata={this.refreshbyaction}
                      getexceloutparam={this.getexceloutparam}
                    />
                  </div>
                  <div className="main-table-box">
                    {this.props.menuType !== 'HS' ? <SettingComponent
                      config={config}
                      columns={columns}
                      dict={this.state.dict}
                      MenuID={this.props.MenuID}
                      MenuName={this.props.MenuName}
                      permAction={this.props.permAction}
                      permRoles={this.props.permRoles}
                      userConfig={this.state.userConfig}
                      reloadview={this.reloadview}
                    /> : null}
                      selectedData={selectedData}
                      ContainerId={this.state.ContainerId}
                    />
                  </div>
                  <div className="main-table-box">
                    {(setting.tableType === 'radio' || setting.tableType === 'checkbox') && this.state.data && this.state.data.length > 0 ?
                      <Switch title="收起" className="main-pickup" checkedChildren="开" unCheckedChildren="关" defaultChecked={pickup} onChange={this.pickupChange} /> : null
                      <Switch title="收起" className="main-pickup" checkedChildren="开" unCheckedChildren="关" checked={pickup} onChange={this.pickupChange} /> : null
                    }
                    <MainTable
                      tableId="mainTable"
                      BID={BID}
                      pickup={pickup}
                      config={config}
                      setting={setting}
                      columns={columns}
                      pageSize={pageSize}
@@ -942,12 +1099,10 @@
                      total={this.state.total}
                      MenuID={this.props.MenuID}
                      loading={this.state.loading}
                      refreshdata={this.refreshbytable}
                      logcolumns={this.state.logcolumns}
                      statFValue={this.state.statFValue}
                      handleTableId={this.handleTableId}
                      ContainerId={this.state.ContainerId}
                      refreshbyaction={this.refreshbyaction}
                      refreshdata={this.refreshbytable}
                      handleTableId={this.handleTableId}
                      chgSelectData={this.changeSelectedData}
                    />
                  </div>
@@ -960,14 +1115,12 @@
                    BID={BID}
                    plot={item}
                    config={config}
                    columns={columns}
                    tableId="mainTable"
                    data={this.state.data}
                    MenuID={this.props.MenuID}
                    loading={this.state.loading}
                    logcolumns={this.state.logcolumns}
                    ContainerId={this.state.ContainerId}
                    refreshdata={this.refreshbyaction}
                    getexceloutparam={this.getexceloutparam}
                    handleTableId={this.handleTableId}
                  />
                </Col>
@@ -980,7 +1133,6 @@
                    plot={item}
                    config={config}
                    data={this.state.data}
                    getexceloutparam={this.getexceloutparam}
                    loading={this.state.loading}
                  />
                </Col>
@@ -988,74 +1140,33 @@
            }
          })}
        </Row> : null }
        {setting && setting.onload !== 'false' &&
          config.tabgroups.map(group => (
            <Tabs activeKey={tabActive[group.uuid]} key={group.uuid} onChange={(key) => this.setState({tabActive: {...tabActive, [group.uuid]: key}})}>
              {group.sublist.map(_tab => {
                return (
                  <TabPane tab={
                    <span>
                      {_tab.icon ? <Icon type={_tab.icon} /> : null}
                      {_tab.label}
                    </span>
                  } key={_tab.uuid}>
                    {_tab.type === 'SubTable' ?
                      <SubTable
                        Tab={_tab}
                        MenuID={_tab.linkTab}
                        mainSearch={_tab.searchPass === 'true' ? search : null}
                        userConfig={userConfig ? userConfig[_tab.uuid] : null}
                        SupMenuID={this.props.MenuID}
                        refreshtabs={this.state.refreshtabs}
                        ContainerId={this.state.ContainerId}
                        BID={this.state.BIDs[_tab.supMenu] || ''}
                        BData={this.state.BIDs[_tab.supMenu + 'data'] || ''}
                        handleTableId={this.handleTableId}
                        handleMainTable={(type) => this.handleMainTable(type, _tab)}
                      /> : null}
                    {_tab.type === 'SecretKeyTable' ?
                      <SecretKeyTable
                        Tab={_tab}
                        MenuID={_tab.linkTab}
                        SupMenuID={this.props.MenuID}
                        refreshtabs={this.state.refreshtabs}
                        ContainerId={this.state.ContainerId}
                        BID={this.state.BIDs[_tab.supMenu] || ''}
                        BData={this.state.BIDs[_tab.supMenu + 'data'] || ''}
                        handleMainTable={(type) => this.handleMainTable(type, _tab)}
                      /> : null}
                  </TabPane>
                )
              })}
            </Tabs>)
          )
        {setting && config.tabgroups.map(group => (
          <Tabs key={group.uuid}>
            {group.sublist.map(_tab => {
              return (
                <TabPane tab={
                  <span id={_tab.uuid}>
                    {_tab.icon ? <Icon type={_tab.icon} /> : null}
                    {_tab.label}
                  </span>
                } key={_tab.uuid}>
                  <SubTable
                    Tab={_tab}
                    MenuID={_tab.linkTab}
                    mainSearch={_tab.searchPass === 'true' ? search : null}
                    SupMenuID={this.props.MenuID}
                    ContainerId={this.state.ContainerId}
                    BID={this.state.BIDs[_tab.supMenu] || ''}
                    BData={this.state.BIDs[_tab.supMenu + 'data'] || ''}
                    handleTableId={this.handleTableId}
                  />
                </TabPane>
              )
            })}
          </Tabs>))
        }
        {options.sysType !== 'cloud' && menuType !== 'HS' ? <Button
          icon="copy"
          shape="circle"
          className="common-table-copy"
          onClick={this.handleviewconfig}
        /> : null}
        <Modal
          className="menu-tree-modal"
          title={'菜单结构树'}
          width={'650px'}
          maskClosable={false}
          visible={this.state.treevisible}
          onCancel={() => this.setState({treevisible: false})}
          footer={[
            <Button key="close" onClick={() => this.setState({treevisible: false})}>{this.state.dict['main.close']}</Button>
          ]}
          destroyOnClose
        >
          <div className="menu-header">
            <span>菜单名称:{this.props.MenuName}</span>
            <span>菜单参数:{<Paragraph copyable>{this.props.MenuNo}</Paragraph>}</span>
          </div>
          {this.state.treevisible ? <Tree defaultExpandAll showLine={true}>
            {this.getTreeNode(config.funcs)}
          </Tree> : null}
        </Modal>
        {menuType !== 'HS' ? <PagemsgComponent menu={{MenuName: this.props.MenuName, MenuNo: this.props.MenuNo}} config={config} dict={this.state.dict} /> : null}
        {menuType !== 'HS' && shortcuts ? <SettingComponent config={config} dict={this.state.dict} shortcuts={shortcuts} permAction={this.props.permAction}/> : null}
        {viewlost ? <NotFount msg={this.state.lostmsg} /> : null}
      </div>
    )
@@ -1066,18 +1177,13 @@
  return {
    menuType: state.editLevel,
    tabviews: state.tabviews,
    refreshTab: state.refreshTab,
    permAction: state.permAction,
    permMenus: state.permMenus,
    permRoles: state.permRoles,
    dataManager: state.dataManager
    permMenus: state.permMenus
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    refreshTabView: (refreshTab) => dispatch(refreshTabView(refreshTab))
  }
const mapDispatchToProps = () => {
  return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(NormalTable)