import React, { Component } from 'react'
import PropTypes from 'prop-types'
import ReactEchartsCore from 'echarts-for-react/lib/core'
import echarts from 'echarts/lib/echarts'

import { pick } from 'lodash'

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

  componentDidMount () {
    this.autoPlay()
  }

  componentWillUnmount () {
    this.stopPlay()
  }

  setRef = (ref) => {
    if (ref) {
      this.chartRef = ref.getEchartsInstance()
      this.props.onRef instanceof Function && this.props.onRef(ref)
    }
  }

  handleMouseEnter = () => {
    this.stopPlay()
  }

  handleMouseLeave = () => {
    this.autoPlay()
  }

  autoPlay = () => {
    if (this.chartRef && this.props.autoPlay) {
      this.timer = setInterval(() => {
        if (this.props.chartType === 'pie') {
          this.chartRef.dispatchAction({
            type: 'downplay'
          })
          this.chartRef.dispatchAction({
            type: 'highlight',
            seriesIndex: this.props.seriesIndex,
            dataIndex: this.startIndex
          })
        }
        this.chartRef.dispatchAction({
          type: 'showTip',
          seriesIndex: this.props.seriesIndex,
          dataIndex: this.startIndex
        })
        ++this.startIndex
        // 轮播最大索引次数
        let maxDataIndex = 0
        const option = this.chartRef.getOption()
        option.legend.forEach(item => {
          maxDataIndex += item.data.length
        })
        !maxDataIndex && (maxDataIndex = 5)
        this.startIndex >= maxDataIndex && (this.startIndex = 0)
      }, this.props.autoPlayTimer)
    }
  }

  stopPlay = () => {
    clearInterval(this.timer)
    const { autoPlay, chartType } = this.props
    if (this.chartRef && autoPlay && chartType === 'pie') {
      this.chartRef.dispatchAction({
        type: 'downplay'
      })
    }
  }

  render () {
    return (
      <div
        onMouseEnter={this.handleMouseEnter}
        onMouseLeave={this.handleMouseLeave}
        style={{ width: '100%', height: '100%' }}
      >
        <ReactEchartsCore
          ref={this.setRef}
          echarts={echarts}
          style={{ width: '100%', height: '100%' }}
          {...pick(this.props, Object.keys(ReactEchartsCore.propTypes))}
        />
      </div>
    )
  }
}

AutoPlayChart.propTypes = {
  ...ReactEchartsCore.propTypes,
  chartType: PropTypes.string,
  autoPlay: PropTypes.bool,
  autoPlayTimer: PropTypes.number,
  seriesIndex: PropTypes.number,
  dataIndex: PropTypes.number
}

AutoPlayChart.defaultProps = {
  chartType: 'line',
  autoPlay: false,
  autoPlayTimer: 2000,
  seriesIndex: 0,
  dataIndex: 0
}

export default AutoPlayChart