import React, { Component } from 'react'
import { connect } from 'dva'
import AutoPlayChart from '../../Chart/AutoPlayChart'
import option from '../config/consumOption'
import { $consts } from '../../../plugins'

class ChartConsum extends Component {
  constructor (props) {
    super(props)
    this.chartRef = null
    this.timer = -1
  }

  componentDidMount () {
    this.getData()
    this.timer = setInterval(this.getData, $consts['COMMON/REQUEST_INTERVAL_TIME'])
  }

  shouldComponentUpdate () {
    // return false 不需要更新 echarts 组件（避免重绘），通过 setOption 更新 echarts 数据即可
    return false
  }

  componentWillUnmount () {
    clearInterval(this.timer)
  }

  getData = () => {
    const { OrgId } = this.props.login
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'KR/DynamicData/EquipEneryUse',
      payload: { OrgId }
    }).then(data => {
      const seriesData = []
      const legendData = []
      data.forEach(({ Name, Color, Total, Percent }) => {
        if (Percent >= 0.0001) {
          seriesData.push({
            name: Name,
            value: Percent, // 因为percent合起来也是100%，所以可以直接拿percent当value
            itemStyle: {
              color: Color
            },
            Total // 用于 tooltip 展示
          })
          legendData.push(Name)
        }
      })
      this.updateData({ seriesData, legendData })
    })
  }

  updateData = ({ seriesData, legendData }) => {
    this.chartRef && this.chartRef.setOption({
      legend: { data: legendData },
      series: [{}, {}, { data: seriesData }]
    })
  }

  render () {
    return (
      <div className='overview__box-large'>
        <AutoPlayChart
          autoPlay
          chartType='pie'
          seriesIndex={2}
          onRef={ref => { this.chartRef = ref.getEchartsInstance() }}
          option={option}
        />
      </div>
    )
  }
}

export default connect(({ login }) => ({ login }))(ChartConsum)
