import "core-js/modules/es6.number.constructor";
import _Number$isNaN from "@babel/runtime-corejs2/core-js/number/is-nan";
import _Array$isArray from "@babel/runtime-corejs2/core-js/array/is-array";
import "core-js/modules/es6.array.find";
import "core-js/modules/web.dom.iterable";
import _createClass from "@babel/runtime-corejs2/helpers/createClass";
import _inheritsLoose from "../../inheritsLoose";
import _defineProperty from "@babel/runtime-corejs2/helpers/defineProperty";

/**
 * Created by sylvia on 2017/10/18.
 */
import Intact from 'intact-angular';
import template from './index.vdt';
import '../../styles/kpc.css';
import './index.css';

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

  function Slider() {
    return _Intact.apply(this, arguments) || this;
  }

  var _proto = Slider.prototype;

  _proto.defaults = function defaults() {
    return {
      max: 100,
      min: 0,
      value: 0,
      isRange: false,
      unit: '',
      isShowEnd: true,
      isShowInput: true,
      step: 1,
      isShowStop: false,
      marks: undefined,
      disabled: false,
      _sliderValue: 0,
      _inputValue: 0,
      _isDragging: false,
      _isFirst: false,
      _isSecond: false
    };
  };

  _proto._init = function _init() {
    var _this = this;

    this.on("$change:_inputValue", function (c, val) {
      if (!_this.get('_isDragging')) {
        _this._setFixedValue(val, true);
      }
    }); // make sure the min/max/step is valid

    var defaults = this.defaults();
    ['min', 'max', 'step'].forEach(function (item) {
      _this.on("$receive:" + item, function (c, v) {
        if (typeof v !== 'number') {
          _this.set(item, defaults[item], {
            async: true
          });
        }
      });
    });
    var needFixedKeys = ['min', 'max', 'step', 'value'];
    this.on('$receive', function (c, keys) {
      if (!_this.get('_isDragging') && needFixedKeys.find(function (key) {
        return keys.indexOf(key) > -1;
      })) {
        _this._setFixedValue(_this.get('value'));
      }
    });
  };

  _proto._setFixedValue = function _setFixedValue(value, isFromSpinner) {
    var fixedValue = this._getFixedValue(value);

    this.set({
      value: fixedValue,
      _inputValue: isFromSpinner ? value : fixedValue,
      _sliderValue: fixedValue
    });
  };

  _proto._getFixedValue = function _getFixedValue(value) {
    var _this$get = this.get(),
        min = _this$get.min,
        isRange = _this$get.isRange;

    var fixedValue;

    if (isRange) {
      if (!_Array$isArray(value)) {
        fixedValue = [min, min];
      } else {
        fixedValue = [this._fix(value[0]), this._fix(value[1])];
      }
    } else {
      fixedValue = this._fix(value);
    }

    return fixedValue;
  };

  _proto._fix = function _fix(v) {
    var _this$get2 = this.get(),
        step = _this$get2.step,
        max = _this$get2.max,
        min = _this$get2.min;

    if (min > max) {
      Intact.utils.error(new Error("[Slider] min must less than or equal to max, but got min: " + min + " max: " + max));
      return 0;
    }

    if (_Number$isNaN(Number(v))) {
      return min;
    } else if (v < min) {
      return min;
    } else if (v > max) {
      return max;
    } else {
      // for the accuracy
      var fixedValue = Number((Math.round(v / step) * step).toFixed(10));

      if (fixedValue < min) {
        return min;
      } else if (fixedValue > max) {
        return max;
      } else {
        return fixedValue;
      }
    }
  };

  _proto._clickWrapper = function _clickWrapper(e) {
    if (this.get('disabled') || this.get('_isDragging')) return;
    var currentPosition = e.clientX;

    var newValue = this._getSlidingValue(currentPosition);

    if (this.get('isRange')) {
      newValue = this._generateRangeValue(newValue);
    }

    this._setFixedValue(newValue);
  };

  _proto._generateRangeValue = function _generateRangeValue(v) {
    var _this$get3 = this.get('value'),
        min = _this$get3[0],
        max = _this$get3[1];

    if (Math.abs(min - v) <= Math.abs(max - v)) {
      return [v, max];
    } else {
      return [min, v];
    }
  };

  _proto._getSlidingValue = function _getSlidingValue(pos) {
    var rect = this.$slider.getBoundingClientRect();
    var percent = (pos - rect.left) / rect.width;

    var _this$get4 = this.get(),
        max = _this$get4.max,
        min = _this$get4.min;

    var sliderWidth = max - min;

    if (percent <= 0) {
      return min;
    } else if (percent >= 1) {
      return max;
    } else {
      return min + sliderWidth * percent;
    }
  };

  _proto._onDrag = function _onDrag(indexFlag, e) {
    if (this.get('disabled')) return;
    this._isDragging = true; // when start drag, the element has been focusin
    // so we need not handle it here

    this.__onRangeSliding = this._onRangeSliding.bind(this, indexFlag);
    this.__onRangeSlideEnd = this._onRangeSlideEnd.bind(this, indexFlag);
    window.addEventListener('mousemove', this.__onRangeSliding);
    window.addEventListener('mouseup', this.__onRangeSlideEnd);
  };

  _proto._onRangeSliding = function _onRangeSliding(indexFlag, e) {
    var tempValue = this._getSlidingValue(e.clientX, this.get('_isDragging'));

    var fixedValue;
    tempValue = this._getTempValue(tempValue, indexFlag, this._min, this._max, indexFlag === '_isFirst');
    fixedValue = this._getFixedValue(tempValue);
    this.set({
      value: fixedValue,
      _inputValue: fixedValue,
      _sliderValue: tempValue
    });
  };

  _proto._getTempValue = function _getTempValue(value, isRange, min, max, isFirst) {
    if (isRange) {
      if (isFirst) {
        return [Math.min(value, max), Math.max(value, max)];
      } else {
        return [Math.min(value, min), Math.max(value, min)];
      }
    }

    return value;
  };

  _proto._onRangeSlideEnd = function _onRangeSlideEnd(indexFlag, e) {
    if (this.get('_isDragging')) {
      this.set('_isDragging', false, {
        async: true
      });

      var newValue = this._getSlidingValue(e.clientX);

      if (indexFlag) {
        if (indexFlag === '_isFirst') {
          this.$sliderFirstBtn.blur();
          this.set('_isFirst', false, {
            async: true
          });
          newValue = [Math.min(newValue, this._max), Math.max(newValue, this._max)];
        } else {
          this.$sliderSecondBtn.blur();
          this.set('_isSecond', false, {
            async: true
          });
          newValue = [Math.min(newValue, this._min), Math.max(newValue, this._min)];
        }
      } else {
        this.$sliderFirstBtn.blur();
      }

      this._setFixedValue(newValue);

      this.trigger('stop', this.get('value'));
      window.removeEventListener('mousemove', this.__onRangeSliding);
      window.removeEventListener('mouseup', this.__onRangeSlideEnd);
      this._isDragging = false;
    }
  };

  _proto._onFocusin = function _onFocusin(indexFlag, e) {
    if (this.get('disabled')) return; // if the focusin is invoked by dragging
    // let the handle element blur
    // because k-active will add focus style

    if (this._isDragging) {
      e.target.blur();
    }

    if (this.get('isRange')) {
      var value = this.get('value');
      this._min = value[0];
      this._max = value[1];

      if (indexFlag === '_isFirst') {
        this._initValue = this._min;
        this.set({
          _isDragging: true,
          _isFirst: true,
          _isSecond: false
        });
      } else {
        this._initValue = this._max;
        this.set({
          _isDragging: true,
          _isFirst: false,
          _isSecond: true
        });
      }
    } else {
      this.set('_isDragging', true);
    }
  };

  _proto._onFocusout = function _onFocusout(indexFlag) {
    if (this.get('disabled') || this._isDragging) return;

    if (this.get('isRange')) {
      if (indexFlag === '_isFirst') {
        this.set('_isFirst', false, {
          async: true
        });
      } else {
        this.set('_isSecond', false, {
          async: true
        });
      }
    }

    this.set('_isDragging', false, {
      async: true
    });
  };

  _proto._onKeydown = function _onKeydown(indexFlag, e) {
    if (this.get('disabled')) return;
    var step = this.get('step');

    if (e.keyCode === 37) {
      // left
      this._setValue(indexFlag, -step);
    } else if (e.keyCode === 39) {
      // right
      this._setValue(indexFlag, step);
    }
  };

  _proto._setValue = function _setValue(indexFlag, step) {
    var value = this.get('value');

    if (!this.get('isRange')) {
      return this._setFixedValue(value + step);
    }

    this._initValue += step;
    this._initValue = this._fix(this._initValue);

    var _value = this._getTempValue(this._initValue, indexFlag, this._min, this._max, indexFlag === '_isFirst');

    this._setFixedValue(_value); // if overstep the boundary, reverse it


    if (indexFlag === '_isFirst') {
      if (this._initValue > this._max) {
        this.$sliderFirstBtn.blur();
        this.$sliderSecondBtn.focus();
      }
    } else if (indexFlag === '_isSecond') {
      if (this._initValue < this._min) {
        this.$sliderSecondBtn.blur();
        this.$sliderFirstBtn.focus();
      }
    }
  } // only change the input value after change event tiggered, #294
  ;

  _proto._onChange = function _onChange() {
    this.set('_inputValue', this.get('value'));
  };

  _proto._setOneValue = function _setOneValue(v) {
    if (!this.get('isRange')) {
      this._setFixedValue(v);
    } else {
      this._setFixedValue(this._generateRangeValue(v));
    }
  };

  _proto._stopPropagation = function _stopPropagation(e) {
    /* istanbul ignore next */
    e.stopPropagation();
  };

  _proto._destory = function _destory() {
    this._onRangeSlideEnd();
  };

  _createClass(Slider, [{
    key: "template",
    get: function get() {
      return template;
    }
  }]);

  return Slider;
}(Intact);

_defineProperty(Slider, "propTypes", {
  max: Number,
  min: Number,
  value: [Number, Array],
  isRange: Boolean,
  unit: String,
  isShowEnd: Boolean,
  isShowInput: Boolean,
  step: Number,
  isShowStop: Boolean,
  marks: Object,
  disabled: Boolean
});

_defineProperty(Slider, "events", {
  stop: true
});

export { Slider as default };
export { Slider };