import React, { PureComponent } from 'react';
import { Chart } from '@antv/g2';
import DataSet from '@antv/data-set';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import equal from '../equal';

class EqualColumnarStack extends PureComponent {
  componentDidMount() {
    this.renderChart(this.props);
    window.addEventListener('resize', this.resize);
  }

  componentWillReceiveProps(nextProps) {
    if (!equal(this.props, nextProps)) {
      this.renderChart(nextProps);
    }
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resize);
    if (this.chart) {
      this.chart.destroy();
    }
    this.resize.cancel();
  }

  @Bind()
  @Debounce(200)
  resize() {
    if (!this.node) {
      return;
    }
    this.renderChart(this.props);
  }

  handleRef = (n) => {
    this.node = n;
  };

  renderChart(props) {
    const {
      fields, yName: value, xName: currkey, onChartClick, chartName, height,
    } = props;
    const ds = new DataSet();
    const dv = ds.createView().source(props.data);
    dv.transform({
      type: 'fold',
      fields,
      key: currkey,
      value,
    });
    if (this.chart) {
      this.chart.destroy();
    }
    this.node.innerHTML = '';
    const chart = new Chart({
      container: this.node,
      autoFit: true,
      height,
    });
    chart.data(dv.rows);
    chart.axis(currkey, {
      label: {
        autoHide: false, // 关闭label默认的自动隐藏
        autoEllipsis: false, // 关闭lable自动省略
        autoRotate: true, // 关闭默认的label超长自动旋转 默认时右下45度旋转
        formatter: (val) => {
          return `${val}`;
        },
      },
    });
    chart.interval().adjust('stack')
      .position(`${currkey}*${value}`)
      .color('name');
    /*  .active(true)
      .tooltip(false); */
    chart.on('interval:dblclick', (ev) => {
      const cdata = ev.data;
      if (cdata) {
        const { data } = cdata;
        onChartClick(chartName, data);
      }
    });
    chart.render();
    this.chart = chart;
  }
  render() {
    return (
      <div ref={this.handleRef} />
    );
  }
}

export default EqualColumnarStack;
