import { createElement, Component, findDOMNode } from 'rax';
import { Env } from 'weex-nuke';
import GM from '@ali/g2-mobile';
import Canvas from './rax-canvas';

const { isWeex, isWeb } = Env;

if (isWeb) {
  GM.Global.pixelRatio = 2;
}

class Chart extends Component {
  constructor(props) {
    super(props);
    this.margin = 'margin' in props ? props.margin : 20;
    this.setRef = this.setRef.bind(this);
  }

  componentDidMount() {
    this.chartInstance.getContext().then((context) => {
      // 存储好ctx，不用再init一个canvas画布了
      this.ctx = context;

      this.draw(context);
    });
  }

  componentWillReceiveProps(nextProps) {
    if (isWeex) {
      if (!this.ctx || !this.ctx.clearRect) {
        return;
      }
      const { data, config, style } = nextProps;
      const el = findDOMNode(this.chartInstance);

      // 擦掉画布
      this.ctx.clearRect(0, 0, style.width, style.height);

      this.chart = new GM.Chart({
        el,
        context: this.ctx,
        margin: isWeex ? 2 * this.margin : this.margin,
      });

      this.chart.source(data, config);
      this.chart.axis(false);

      this.renderChildren(this.ctx);
    } else {
      // web就这么写吧，不管了
      this.chartInstance.getContext().then((context) => {
        this.draw(context);
      });
    }
  }
  shouldComponentUpdate() {
    return false;
  }
  setRef(ref) {
    this.chartInstance = ref;
  }
  draw(context) {
    const { children, data, config } = this.props;
    const el = findDOMNode(this.chartInstance);

    if (!children) {
      return;
    }

    // context.render();
    this.chart = new GM.Chart({
      el,
      context,
      margin: isWeex ? 2 * this.margin : this.margin,
    });
    this.chart.source(data, config);
    this.chart.axis(false);

    this.renderChildren(context);
  }
  renderChildren() {
    let { children } = this.props;

    if (children && !Array.isArray(children)) {
      children = [children];
    }

    children.forEach((item) => {
      if (item.type && item.type.draw) {
        item.type.draw(this.chart, item.props);
      }
    });

    this.chart.render();
  }
  render() {
    const { style } = this.props;
    const chartStyle = {
      ...style,
    };

    // weex canvas must have backgroundColor
    if (isWeex && !chartStyle.backgroundColor) {
      chartStyle.backgroundColor = 'transparent';
    }

    return <Canvas style={chartStyle} ref={this.setRef} />;
  }
}

export default Chart;
