function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

var Range = require('./component/range');

var Chart = require('../chart/chart');

var Util = require('../util');

var G = require('../renderer');

var Global = require('../global');

var Interaction = require('./base');

var getColDef = require('./helper/get-col-def');

var getColDefs = require('./helper/get-col-defs');

var Canvas = G.Canvas;
var DomUtil = Util.DomUtil,
    isNumber = Util.isNumber;

var Slider = /*#__PURE__*/function (_Interaction) {
  _inheritsLoose(Slider, _Interaction);

  var _proto = Slider.prototype;

  _proto.getDefaultCfg = function getDefaultCfg() {
    var cfg = _Interaction.prototype.getDefaultCfg.call(this);

    return Util.mix({}, cfg, {
      startEvent: null,
      processEvent: null,
      endEvent: null,
      resetEvent: null,
      height: 26,
      width: 'auto',
      // 默认自适应
      padding: Global.plotCfg.padding,
      container: null,
      xAxis: null,
      yAxis: null,
      // 选中区域的样式
      fillerStyle: {
        fill: '#BDCCED',
        fillOpacity: 0.3
      },
      // 滑动条背景样式
      backgroundStyle: {
        stroke: '#CCD6EC',
        fill: '#CCD6EC',
        fillOpacity: 0.3,
        lineWidth: 1
      },
      range: [0, 100],
      layout: 'horizontal',
      // 文本颜色
      textStyle: {
        fill: '#545454'
      },
      // 滑块的样式
      handleStyle: {
        img: 'https://gw.alipayobjects.com/zos/rmsportal/QXtfhORGlDuRvLXFzpsQ.png',
        width: 5
      },
      // 背景图表的配置，如果为 false 则表示不渲染
      backgroundChart: {
        type: ['area'],
        // 图表的类型，可以是字符串也可是是数组
        color: '#CCD6EC'
      }
    });
  };

  _proto._initContainer = function _initContainer() {
    var me = this;
    var container = me.container;

    if (!container) {
      throw new Error('Please specify the container for the Slider!');
    }

    if (Util.isString(container)) {
      me.domContainer = document.getElementById(container);
    } else {
      me.domContainer = container;
    }
  };

  _proto.forceFit = function forceFit() {
    var me = this;

    if (!me || me.destroyed) {
      return;
    }

    var width = DomUtil.getWidth(me.domContainer);
    var height = me.height;

    if (width !== me.domWidth) {
      var canvas = me.canvas;
      canvas.changeSize(width, height); // 改变画布尺寸

      me.bgChart && me.bgChart.changeWidth(width);
      canvas.clear();

      me._initWidth();

      me._initSlider(); // 初始化滑动条


      me._bindEvent();

      canvas.draw();
    }
  };

  _proto._initForceFitEvent = function _initForceFitEvent() {
    var me = this;
    var timer = setTimeout(Util.wrapBehavior(me, 'forceFit'), 200);
    clearTimeout(me.resizeTimer);
    me.resizeTimer = timer;
  };

  _proto._initStyle = function _initStyle() {
    var me = this;
    me.handleStyle = Util.mix({
      width: me.height,
      height: me.height
    }, me.handleStyle);

    if (me.width === 'auto') {
      // 宽度自适应
      window.addEventListener('resize', Util.wrapBehavior(me, '_initForceFitEvent'));
    }
  };

  _proto._initWidth = function _initWidth() {
    var me = this;
    var width;

    if (me.width === 'auto') {
      width = DomUtil.getWidth(me.domContainer);
    } else {
      width = me.width;
    }

    me.domWidth = width;
    var padding = Util.toAllPadding(me.padding);

    if (me.layout === 'horizontal') {
      me.plotWidth = width - padding[1] - padding[3];
      me.plotPadding = padding[3];
      me.plotHeight = me.height;
    } else if (me.layout === 'vertical') {
      me.plotWidth = me.width;
      me.plotHeight = me.height - padding[0] - padding[2];
      me.plotPadding = padding[0];
    }
  };

  _proto._initCanvas = function _initCanvas() {
    var me = this;
    var width = me.domWidth;
    var height = me.height;
    var canvas = new Canvas({
      width: width,
      height: height,
      containerDOM: me.domContainer,
      capture: false
    });
    var node = canvas.get('el');
    node.style.position = 'absolute';
    node.style.top = 0;
    node.style.left = 0;
    node.style.zIndex = 3;
    me.canvas = canvas;
  };

  _proto._initBackground = function _initBackground() {
    var _Util$deepMix;

    var me = this;
    var chart = this.chart;
    var geom = chart.getAllGeoms[0];
    var data = me.data = me.data || chart.get('data');
    var xScale = chart.getXScale();
    var xAxis = me.xAxis || xScale.field;
    var yAxis = me.yAxis || chart.getYScales()[0].field;
    var scales = Util.deepMix((_Util$deepMix = {}, _Util$deepMix["" + xAxis] = {
      range: [0, 1]
    }, _Util$deepMix), getColDefs(chart), me.scales); // 用户列定义

    delete scales[xAxis].min;
    delete scales[xAxis].max;

    if (!data) {
      // 没有数据，则不创建
      throw new Error('Please specify the data!');
    }

    if (!xAxis) {
      throw new Error('Please specify the xAxis!');
    }

    if (!yAxis) {
      throw new Error('Please specify the yAxis!');
    }

    var backgroundChart = me.backgroundChart;
    var type = backgroundChart.type || geom.get('type');
    var color = backgroundChart.color || 'grey';
    var shape = backgroundChart.shape;

    if (!Util.isArray(type)) {
      type = [type];
    }

    var padding = Util.toAllPadding(me.padding);
    var bgChart = new Chart({
      container: me.container,
      width: me.domWidth,
      height: me.height,
      padding: [0, padding[1], 0, padding[3]],
      animate: false
    });
    bgChart.source(data);
    bgChart.scale(scales);
    bgChart.axis(false);
    bgChart.tooltip(false);
    bgChart.legend(false);
    Util.each(type, function (eachType, index) {
      var bgGeom = bgChart[eachType]().position(xAxis + '*' + yAxis).opacity(1);
      var colorItem = Util.isArray(color) ? color[index] : color;

      if (colorItem) {
        if (Util.isObject(colorItem)) {
          // 通过 { field: 'ss', colors: [ ] } 的方式申明color
          if (colorItem.field) {
            bgGeom.color(colorItem.field, colorItem.colors);
          }
        } else {
          bgGeom.color(colorItem);
        }
      }

      var shapeItem = Util.isArray(shape) ? shape[index] : shape;

      if (shapeItem) {
        if (Util.isObject(shapeItem)) {
          // 通过 { field: 'ss', shapes: [ ], callback } 的方式申明shape
          if (shapeItem.field) {
            bgGeom.shape(shapeItem.field, shapeItem.callback || shapeItem.shapes);
          }
        } else {
          bgGeom.shape(shapeItem);
        }
      }
    });
    bgChart.render();
    me.bgChart = bgChart;
    me.scale = me.layout === 'horizontal' ? bgChart.getXScale() : bgChart.getYScales()[0];

    if (me.layout === 'vertical') {
      bgChart.destroy();
    }
  };

  _proto._initRange = function _initRange() {
    var me = this;
    var startRadio = me.startRadio;
    var endRadio = me.endRadio;
    var start = me._startValue;
    var end = me._endValue;
    var scale = me.scale;
    var min = 0;
    var max = 1; // startRadio 优先级高于 start

    if (isNumber(startRadio)) {
      min = startRadio;
    } else if (start) {
      min = scale.scale(scale.translate(start));
    } // endRadio 优先级高于 end


    if (isNumber(endRadio)) {
      max = endRadio;
    } else if (end) {
      max = scale.scale(scale.translate(end));
    }

    var minSpan = me.minSpan,
        maxSpan = me.maxSpan;
    var totalSpan = 0;

    if (scale.type === 'time' || scale.type === 'timeCat') {
      // 时间类型已排序
      var values = scale.values;
      var firstValue = values[0];
      var lastValue = values[values.length - 1];
      totalSpan = lastValue - firstValue;
    } else if (scale.isLinear) {
      totalSpan = scale.max - scale.min;
    }

    if (totalSpan && minSpan) {
      me.minRange = minSpan / totalSpan * 100;
    }

    if (totalSpan && maxSpan) {
      me.maxRange = maxSpan / totalSpan * 100;
    }

    var range = [min * 100, max * 100];
    me.range = range;
    return range;
  };

  _proto._getHandleValue = function _getHandleValue(type) {
    var me = this;
    var value;
    var range = me.range;
    var min = range[0] / 100;
    var max = range[1] / 100;
    var scale = me.scale;

    if (type === 'min') {
      value = me._startValue ? me._startValue : scale.invert(min);
    } else {
      value = me._endValue ? me._endValue : scale.invert(max);
    }

    return value;
  };

  _proto._initSlider = function _initSlider() {
    var me = this;
    var canvas = me.canvas;

    var range = me._initRange();

    var scale = me.scale;
    var rangeElement = canvas.addGroup(Range, {
      middleAttr: me.fillerStyle,
      range: range,
      minRange: me.minRange,
      maxRange: me.maxRange,
      layout: me.layout,
      width: me.plotWidth,
      height: me.plotHeight,
      backgroundStyle: me.backgroundStyle,
      textStyle: me.textStyle,
      handleStyle: me.handleStyle,
      minText: scale.getText(me._getHandleValue('min')),
      maxText: scale.getText(me._getHandleValue('max'))
    });

    if (me.layout === 'horizontal') {
      rangeElement.translate(me.plotPadding, 0);
    } else if (me.layout === 'vertical') {
      rangeElement.translate(0, me.plotPadding);
    }

    me.rangeElement = rangeElement;
  };

  _proto._updateElement = function _updateElement(minRatio, maxRatio) {
    var me = this;
    var chart = me.chart,
        scale = me.scale,
        rangeElement = me.rangeElement;
    var field = scale.field;
    var minTextElement = rangeElement.get('minTextElement');
    var maxTextElement = rangeElement.get('maxTextElement');
    var min = scale.invert(minRatio);
    var max = scale.invert(maxRatio);
    var minText = scale.getText(min);
    var maxText = scale.getText(max);
    minTextElement.attr('text', minText);
    maxTextElement.attr('text', maxText);
    me._startValue = minText;
    me._endValue = maxText;

    if (me.onChange) {
      me.onChange({
        startText: minText,
        endText: maxText,
        startValue: min,
        endValue: max,
        startRadio: minRatio,
        endRadio: maxRatio
      });
    }

    chart.scale(field, Util.mix({}, getColDef(chart, field), {
      nice: false,
      min: min,
      max: max
    }));
    chart.repaint();
  };

  _proto._bindEvent = function _bindEvent() {
    var me = this;
    var rangeElement = me.rangeElement;
    rangeElement.on('sliderchange', function (ev) {
      var range = ev.range;
      var minRatio = range[0] / 100;
      var maxRatio = range[1] / 100;

      me._updateElement(minRatio, maxRatio);
    });
  };

  function Slider(cfg, chart) {
    var _this;

    _this = _Interaction.call(this, cfg, chart) || this;

    var me = _assertThisInitialized(_this);

    me._initContainer();

    me._initStyle();

    me.render();
    return _this;
  }

  _proto.clear = function clear() {
    var me = this;
    me.canvas.clear();
    me.bgChart && me.bgChart.destroy();
    me.bgChart = null;
    me.scale = null;
    me.canvas.draw();
  };

  _proto.repaint = function repaint() {
    var me = this;
    me.clear();
    me.render();
  };

  _proto.render = function render() {
    var me = this;

    me._initWidth();

    me._initCanvas();

    me._initBackground();

    me._initSlider();

    me._bindEvent();

    me.canvas.draw();
  };

  _proto.destroy = function destroy() {
    var me = this;
    clearTimeout(me.resizeTimer);
    var rangeElement = me.rangeElement;
    rangeElement.off('sliderchange');
    me.bgChart && me.bgChart.destroy();
    me.canvas.destroy();
    var container = me.domContainer;

    while (container.hasChildNodes()) {
      container.removeChild(container.firstChild);
    }

    window.removeEventListener('resize', Util.getWrapBehavior(me, '_initForceFitEvent'));
    me.destroyed = true;
  };

  return Slider;
}(Interaction);

module.exports = Slider;