king
2021-05-24 f267d04e0561a0a20d1f2a9f558a273558ece90d
src/tabviews/custom/components/chart/antv-bar-line/index.jsx
@@ -4,17 +4,19 @@
import { Chart } from '@antv/g2'
import { connect } from 'react-redux'
import DataSet from '@antv/data-set'
import { Spin, Empty, Select, notification } from 'antd'
import { Spin, Empty, notification } from 'antd'
import moment from 'moment'
import asyncComponent from './asyncButtonComponent'
import { chartColors } from '@/utils/option.js'
// import searchLine from '../../share/searchLine'
import Api from '@/api'
import Utils from '@/utils/utils.js'
import UtilsDM from '@/utils/utils-datamanage.js'
import { modifyTabview } from '@/store/action'
import MKEmitter from '@/utils/events.js'
import './index.scss'
const NormalHeader = asyncComponent(() => import('@/tabviews/custom/components/share/normalheader'))
const ExcelOutButton = asyncComponent(() => import('@/tabviews/zshare/actionList/exceloutbutton'))
const ExcelInButton = asyncComponent(() => import('@/tabviews/zshare/actionList/excelInbutton'))
@@ -25,32 +27,26 @@
    config: PropTypes.object,        // 组件配置信息
    mainSearch: PropTypes.any,       // 外层搜索条件
    menuType: PropTypes.any,         // 菜单类型
    dataManager: PropTypes.any,      // 数据权限
  }
  state = {
    BID: '',                   // 主表ID
    config: null,              // 图表配置信息
    empty: true,               // 图表数据为空
    loading: false,            // 数据加载状态
    chartId: Utils.getuuid(),  // 图表Id
    transfield: {},            // 字段名称翻译
    title: '',                 // 组件标题
    sync: false,               // 是否统一请求数据
    plot: null,                // 图表设置
    data: null,                // 数据
    search: null,              // 搜索条件
    vFields: [],               // 数值字段
    vstFields: null,           // 统计数据值字段信息
    chartData: [],             // 图表数据
    chartFields: [],           // 统计图表生成字段集
    selectFields: [],          // 统计图表选择字段
    showHeader: false          // 存在标题、搜索、或统计数据时显示
  }
  UNSAFE_componentWillMount () {
    const { config, data, initdata } = this.props
    const { config, data, initdata, BID } = this.props
    let _config = fromJS(config).toJS()
    let _data = null
    let _sync = config.setting.sync === 'true'
@@ -99,19 +95,13 @@
      })
    }
    let showHeader = false
    if (config.plot.title || _config.plot.datatype === 'statistics' || config.search.length > 0) {
      showHeader = true
    if (config.plot.title || config.search.length > 0) {
      _config.plot.height = _config.plot.height - 80
    } else {
      _config.plot.height = _config.plot.height - 30
    }
    if (_config.style) {
      _config.style = {..._config.style, minHeight: (config.plot.height || 400)}
    } else {
      _config.style = {minHeight: (config.plot.height || 400)}
    }
    _config.style.height = config.plot.height || 400
    let transfield = {}
    _config.columns.forEach(col => {
@@ -120,7 +110,7 @@
      }
    })
    _config.plot.color = _config.plot.color || 'rgba(0, 0, 0, 0.85)'
    _config.plot.color = _config.plot.color || 'rgba(0, 0, 0, 0.65)'
    if (_config.plot.enabled === 'true' && _config.plot.customs && _config.plot.customs.length > 0) {
      let colors = new Map()
@@ -161,7 +151,7 @@
  
        if (item.axis === 'true' && axisIndex < 2) {
          if (axisIndex === 0) {
            item.axis = { grid: {style: { fill: _config.plot.color }}, title: { style: { fill: _config.plot.color } }, label: {style: { fill: _config.plot.color }} }
            item.axis = { title: { style: { fill: _config.plot.color } }, label: {style: { fill: _config.plot.color }} }
            fields.unshift(item)
          } else {
            item.axis = { grid: null, title: {style: { fill: _config.plot.color }}, label: {style: { fill: _config.plot.color }} }
@@ -190,15 +180,14 @@
    this.setState({
      config: _config,
      data: _data,
      BID: BID || '',
      vFields: vFields,
      vstFields: vstFields,
      arr_field: _config.columns.map(col => col.field).join(','),
      plot: _config.plot,
      sync: _sync,
      title: config.plot.title,
      search: Utils.initMainSearch(config.search),
      transfield,
      showHeader
      transfield
    }, () => {
      if (config.setting.sync !== 'true' && config.setting.onload === 'true') {
        this.loadData()
@@ -223,7 +212,7 @@
      this.setState({sync: false, data: _data}, () => {
        this.handleData()
      })
    } else if (!is(fromJS(this.props.mainSearch), fromJS(nextProps.mainSearch))) {
    } else if (nextProps.mainSearch && !is(fromJS(this.props.mainSearch), fromJS(nextProps.mainSearch))) {
      if (config.setting.syncRefresh === 'true') {
        this.setState({}, () => {
          this.loadData()
@@ -236,37 +225,166 @@
    return !is(fromJS(this.state), fromJS(nextState))
  }
  handleData = () => {
    const { data, plot } = this.state
  componentDidMount () {
    MKEmitter.addListener('reloadData', this.reloadData)
    MKEmitter.addListener('resetSelectLine', this.resetParentParam)
    MKEmitter.addListener('getexceloutparam', this.getexceloutparam)
    MKEmitter.addListener('refreshByButtonResult', this.refreshByButtonResult)
    this.handleTimer()
  }
    if (plot.datatype === 'statistics') {
      let result = this.getStaticMsg(data)
      this.setState({
        chartData: result.data,
        chartFields: result.chartFields,
        selectFields: result.selectFields
      }, () => {
        let _element = document.getElementById(this.state.chartId)
        if (_element) {
          _element.innerHTML = ''
        }
        this.viewrender()
      })
    } else {
      let _element = document.getElementById(this.state.chartId)
      if (_element) {
        _element.innerHTML = ''
  /**
   * @description 组件销毁,清除state更新,清除快捷键设置
   */
  componentWillUnmount () {
    clearTimeout(this.timer)
    this.setState = () => {
      return
    }
    MKEmitter.removeListener('reloadData', this.reloadData)
    MKEmitter.removeListener('resetSelectLine', this.resetParentParam)
    MKEmitter.removeListener('getexceloutparam', this.getexceloutparam)
    MKEmitter.removeListener('refreshByButtonResult', this.refreshByButtonResult)
  }
  handleTimer = () => {
    const { config } = this.state
    if (!config.timer) return
    const _change = { '15s': 15000, '30s': 30000, '1min': 60000, '5min': 300000, '10min': 600000, '15min': 900000, '30min': 1800000, '1hour': 3600000 }
    let timer = _change[config.timer]
    if (!timer) return
    let _param = {
      func: 's_get_timers_role',
      LText: `select '${window.GLOB.appkey || ''}','${config.uuid}'`,
      timer_type: config.timer,
      component_id: config.uuid
    }
    _param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')          // 时间戳
    _param.LText = Utils.formatOptions(_param.LText)                   // 关键字符替换,base64加密
    _param.secretkey = Utils.encrypt(_param.LText, _param.timestamp)   // md5密钥
    Api.getSystemConfig(_param).then(result => {
      if (!result.status) {
        notification.warning({
          top: 92,
          message: result.message,
          duration: 5
        })
        return
      } else if (result.run_type) {
        this.setState({timer})
        this.timer = setTimeout(() => {
          this.timerTask()
        }, timer)
      }
      this.viewrender()
    })
  }
  timerTask = () => {
    const { timer } = this.state
    if (!timer) return
    this.loadData(true)
    this.timer = setTimeout(() => {
      this.timerTask()
    }, timer)
  }
  /**
   * @description 按钮执行完成后页面刷新
   * @param {*} menuId     // 菜单Id
   * @param {*} position   // 刷新位置
   * @param {*} btn        // 执行的按钮
   */
  refreshByButtonResult = (menuId, position, btn) => {
    const { config, BID } = this.state
    if (config.uuid !== menuId) return
    this.loadData()                                                            // 数据刷新
    if (btn.syncComponentId && btn.syncComponentId !== config.uuid && btn.syncComponentId !== config.setting.supModule) {
      MKEmitter.emit('reloadData', btn.syncComponentId)                        // 同级标签刷新
    }
    if (position === 'mainline' && config.setting.supModule) {                 // 主表行刷新
      MKEmitter.emit('reloadData', config.setting.supModule, (BID || 'empty'))
    } else if (position === 'popclose') {                                      // 标签关闭刷新
      config.setting.supModule && MKEmitter.emit('reloadData', config.setting.supModule, (BID || 'empty'))
      btn.$tabId && MKEmitter.emit('refreshPopButton', btn.$tabId)
    }
  }
  async loadData () {
    const { mainSearch, BID, menuType, dataManager } = this.props
    const { config, arr_field, search } = this.state
  reloadData = (menuId) => {
    const { config } = this.state
    let searches = fromJS(search).toJS()
    if (config.uuid !== menuId) return
    this.loadData()
  }
  resetParentParam = (MenuID, id) => {
    const { config } = this.state
    if (!config.setting.supModule || config.setting.supModule !== MenuID) return
    if (id !== this.state.BID) {
      this.setState({ BID: id }, () => {
        this.loadData()
      })
    }
  }
  /**
   * @description 导出Excel时,获取页面搜索排序等参数
   */
  getexceloutparam = (menuId, btnId) => {
    const { mainSearch } = this.props
    const { arr_field, config, search } = this.state
    if (config.uuid !== menuId) return
    let searches = search ? fromJS(search).toJS() : []
    if (mainSearch && mainSearch.length > 0) { // 主表搜索条件
      let keys = searches.map(item => item.key.toLowerCase())
      mainSearch.forEach(item => {
        if (!keys.includes(item.key.toLowerCase())) {
          searches.push(item)
        }
      })
    }
    MKEmitter.emit('execExcelout', config.uuid, btnId, {
      arr_field: arr_field,
      orderBy: config.setting.order || '',
      search: searches,
      menuName: config.name
    })
  }
  /**
   * @description 数据加载
   */
  async loadData (hastimer) {
    const { mainSearch, menuType } = this.props
    const { config, arr_field, BID, search } = this.state
    if (config.setting.supModule && !BID) { // BID 不存在时,不做查询
      this.setState({
        data: []
      }, () => {
        this.handleData()
      })
      return
    }
    let searches = search ? fromJS(search).toJS() : []
    if (mainSearch && mainSearch.length > 0) { // 主表搜索条件
      let keys = searches.map(item => item.key)
      mainSearch.forEach(item => {
@@ -276,12 +394,22 @@
      })
    }
    this.setState({
      loading: true
    })
    let requireFields = searches.filter(item => item.required && (!item.value || item.value.length === 0))
    if (requireFields.length > 0) {
      this.setState({
        loading: false
      })
      return
    }
    if (!hastimer) {
      this.setState({
        loading: true
      })
    }
    let _orderBy = config.setting.order || ''
    let param = UtilsDM.getQueryDataParams(config.setting, arr_field, searches, _orderBy, '', '', BID, menuType, dataManager)
    let param = UtilsDM.getQueryDataParams(config.setting, arr_field, searches, _orderBy, '', '', BID, menuType)
    let result = await Api.genericInterface(param)
    if (result.status) {
@@ -293,7 +421,8 @@
      })
    } else {
      this.setState({
        loading: false
        loading: false,
        timer: null
      })
      notification.error({
        top: 92,
@@ -301,6 +430,17 @@
        duration: 10
      })
    }
  }
  /**
   * @description 数据预处理,统计数据需要重置
   */
  handleData = () => {
    let _element = document.getElementById(this.state.chartId)
    if (_element) {
      _element.innerHTML = ''
    }
    this.viewrender()
  }
  /**
@@ -312,7 +452,7 @@
  getdata = () => {
    const { data, plot, vFields } = this.state
    if (!data) {
    if (!data || data.length === 0) {
      this.setState({empty: true})
      return []
    }
@@ -420,36 +560,30 @@
  }
  /**
   * @description 统计数据预处理,动态生成统计字段并进行数据转换
   * @description 统计数据预处理
   */
  getStaticMsg = (data) => {
    const { plot, vstFields } = this.state
  getStaticMsg = () => {
    const { plot, vstFields, data } = this.state
    let percent = false
    let decimal = 0
    let decimal = vstFields ? vstFields.decimal : 0
    if (plot.show === 'percent') {
      percent = true
    }
    if (vstFields) {
      decimal = vstFields.decimal
    }
    if (!data) {
    if (!data || data.length === 0) {
      this.setState({empty: true})
      return {data: [], chartFields: [], selectFields: []}
      return []
    }
    let _data = []
    let _cdata = fromJS(data).toJS()
    let _chartFields = []
    let _selectFields = []
    if (plot.repeat === 'average') {
      let _mdata = new Map()
      _cdata.forEach(item => {
        if (!item[plot.InfoType] || !item[plot.Xaxis]) return
        _chartFields.push(item[plot.InfoType])
        item.$uuid = item[plot.InfoType] + item[plot.Xaxis]
        if (typeof(item[plot.InfoValue]) !== 'number') {
@@ -485,7 +619,6 @@
      let _mdata = new Map()
      _cdata.forEach(item => {
        if (!item[plot.InfoType] || !item[plot.Xaxis]) return
        _chartFields.push(item[plot.InfoType])
        item.$uuid = item[plot.InfoType] + item[plot.Xaxis]
@@ -519,7 +652,6 @@
      let _mdata = new Map()
      _cdata.forEach(item => {
        if (!item[plot.InfoType] || !item[plot.Xaxis]) return
        _chartFields.push(item[plot.InfoType])
        item.$uuid = item[plot.InfoType] + item[plot.Xaxis]
@@ -544,31 +676,8 @@
      _data = [..._mdata.values()]
    }
    _chartFields = Array.from(new Set(_chartFields))
    if (plot.InfoDefNumber >= _chartFields.length) {
      _selectFields = _chartFields
    } else {
      _selectFields = _chartFields.slice(0, plot.InfoDefNumber)
    }
    return {data: _data, chartFields: _chartFields, selectFields: _selectFields}
  }
  /**
   * @description 获取统计图表展示数据,通过选择类型筛选
   */
  getStaticData = () => {
    const { plot, chartData, chartFields, selectFields } = this.state
    let _data = []
    if (selectFields.length === chartFields.length) {
      _data = chartData
    } else {
      _data = chartData.filter(item => selectFields.includes(item[plot.InfoType]))
    }
    this.setState({empty: _data.length === 0})
    return _data
  }
@@ -610,7 +719,7 @@
        })
      }
      _data = this.getStaticData()
      _data = this.getStaticMsg()
    } else {
      let data = this.getdata()
@@ -680,9 +789,8 @@
        },
        style: { fill: plot.color }
      },
      line: { style: { fill: plot.color } }
    })
    chart.axis(_valfield, { grid: { style: { fill: plot.color } }, label: { style: { fill: plot.color } } })
    chart.axis(_valfield, { label: { style: { fill: plot.color } } })
    if (!plot.legend || plot.legend === 'hidden') {
      chart.legend(false)
@@ -832,7 +940,6 @@
        },
        style: { fill: plot.color }
      },
      line: { style: { fill: plot.color } }
    })
    if (!plot.legend || plot.legend === 'hidden') {
@@ -890,6 +997,9 @@
              }
            }
          })
        }
        if (plot.barRadius) {
          _chart.style({ radius: [plot.barRadius, plot.barRadius, 0, 0] })
        }
      } else if (item.chartType === 'line') {
        let _chart = chart
@@ -957,7 +1067,7 @@
        })
      }
      _data = this.getStaticData()
      _data = this.getStaticMsg()
    } else {
      let data = this.getdata()
@@ -1033,9 +1143,8 @@
        },
        style: { fill: plot.color }
      },
      line: { style: { fill: plot.color } }
    })
    chart.axis(_valfield, { grid: { style: { fill: plot.color } }, label: { style: { fill: plot.color } } })
    chart.axis(_valfield, { label: { style: { fill: plot.color } } })
    if (!plot.legend || plot.legend === 'hidden') {
      chart.legend(false)
@@ -1114,6 +1223,9 @@
      if (plot.barSize || plot.correction) {
        _chart.size(plot.barSize || 35)
      }
      if (plot.barRadius) {
        _chart.style({ radius: [plot.barRadius, plot.barRadius, 0, 0] })
      }
    } else if (plot.adjust === 'stack') {
      let _chart = chart
        .interval()
@@ -1157,10 +1269,13 @@
      if (plot.barSize || plot.correction) {
        _chart.size(plot.barSize || 35)
      }
      if (plot.barRadius) {
        _chart.style({ radius: [plot.barRadius, plot.barRadius, 0, 0] })
      }
    }
    if (plot.linkmenu && plot.linkmenu.length > 0) {
      let menu_id = plot.linkmenu[plot.linkmenu.length - 1]
      let menu_id = plot.linkmenu.slice(-1)[0]
      let menu = this.props.permMenus.filter(m => m.MenuID === menu_id)[0] || ''
      chart.on('element:dblclick', (ev) => {
@@ -1184,8 +1299,7 @@
            ...menu,
            selected: true,
            param: {
              BID: primaryId,
              data: data
              $BID: primaryId
            }
          }
  
@@ -1194,7 +1308,7 @@
            return tab.MenuID !== newtab.MenuID
          })
  
          if (this.props.tabviews.length !== tabs.length) {
          if (this.props.tabviews.length > tabs.length) {
            this.props.modifyTabview(fromJS(tabs).toJS())
          }
  
@@ -1211,22 +1325,14 @@
    chart.render()
  }
  /**
   * @description 统计图表,统计类型切换
   */
  handleChange = (val) => {
    this.setState({selectFields: val}, () => {
      let _element = document.getElementById(this.state.chartId)
      if (_element) {
        _element.innerHTML = ''
      }
      this.viewrender()
  refreshSearch = (list) => {
    this.setState({search: list}, () => {
      this.loadData()
    })
  }
  render() {
    const { BID } = this.props
    const { showHeader, config, loading, title, plot, empty, chartFields, selectFields } = this.state
    const { config, loading, empty, BID } = this.state
    return (
      <div className="custom-line-chart-plot-box" style={config.style}>
@@ -1236,23 +1342,9 @@
            <Spin />
          </div> : null
        }
        {showHeader ? <div className="chart-header" style={config.headerStyle}>
          <span className="chart-title">{title}</span>
          {/* <searchLine /> */}
          {plot.datatype === 'statistics' && chartFields.length > 0 ? <Select
            mode="multiple"
            showSearch
            showArrow={true}
            value={selectFields}
            onChange={this.handleChange}
            maxTagCount={0}
            maxTagPlaceholder={(option) => <div className="type-label">{option.join('、')}</div>}
          >
            {chartFields.map((item, i) => <Select.Option key={i} value={item}>{item}</Select.Option>)}
          </Select> : null}
        </div> : null}
        <NormalHeader config={config} BID={BID} menuType={this.props.menuType} refresh={this.refreshSearch} />
        <div className="canvas-wrap">
          <div className={'chart-action ' + (plot.title ? 'with-title' : '')}>
          <div className="chart-action">
            {config.action.map(item => {
              if (item.OpenType === 'excelOut') {
                return (
@@ -1262,8 +1354,6 @@
                    btn={item}
                    show="icon"
                    setting={config.setting}
                    getexceloutparam={this.props.getexceloutparam}
                    updateStatus={() => {}}
                  />
                )
              } else {
@@ -1274,7 +1364,6 @@
                    btn={item}
                    show="icon"
                    setting={config.setting}
                    updateStatus={() => {}}
                  />
                )
              }