import React from 'react'
import ReactEcharts from 'echarts-for-react'
import { isEqual } from 'lodash'
import { guid } from '../../../utils/common'

class ChartLine extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      xAxis: [],
      data: [],
      legend: [],
      chartId: guid()
    }
  };
  componentDidMount () {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  };
  setValue = (xAxis, data, legend) => {
    if (!isEqual(data, this.state.data)) {
      this.setState({
        xAxis: xAxis,
        data: data,
        legend: legend,
        chartId: guid()
      }) 
    }
  }

  getOption = () => {
    let unitData = this.state.data
    let colors = ['#FD2446', '#248EFD', '#C916F2', '#6669B1']
    let option = {
      legend: {
        top: '5%',
        textStyle: {
          color: '#333333'
        },
        data: this.state.legend
      },
      grid: {
        left: '2%',
        right: '6%',
        bottom: '2%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: this.state.xAxis
        }
      ],
      yAxis: {
          type: 'value',
      },
      dataZoom: [
        {
          type: 'inside',
          xAxisIndex: [0]
        }
      ],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
          textStyle: {
            color: '#B8B8B8'
          }
        },
        formatter: function (params) {
          var relVal = params[0].name
          for (var i = 0, l = params.length; i < l; i++) {
            relVal += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + params[i].value + (unitData[i] == undefined ? '' : unitData[i].Unit)
          }
          return relVal
        }
      },
      toolbox: {
        show: true,
        orient: 'vertical',
        right: '2%',
        top: 'center',
        feature: {
          magicType: { show: true, type: ['line', 'bar', 'stack', 'tiled'] },
          restore: { show: true },
          saveAsImage: { show: true }
        }
      },
      series: []
    }
    unitData.forEach((item, index) => {
      let dataseries = {
        name: item.Name,
        itemStyle: {
          color: colors[index]
        },
        data: item.DataValue
      }
      dataseries.type = "line";
      option.series.push(dataseries);
    })

    return option
  }

  render () {
    return (
      <ReactEcharts key={this.state.chartId} option={this.getOption()} />
    )
  }
}

export default ChartLine