function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

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

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

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

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

/* tslint:disable jsx-no-multiline-js */
import * as React from 'react';
import * as moment from 'moment';
import { polyfill } from 'react-lifecycles-compat';
import RangeCalendar from "rc-calendar/es/RangeCalendar";
import RcDatePicker from "rc-calendar/es/Picker";
import classNames from 'classnames';
import shallowequal from 'shallowequal';
import Icon from '../icon';
import Tag from '../tag';
import { ConfigConsumer } from '../config-provider';
import warning from '../_util/warning';
import interopDefault from '../_util/interopDefault';
import { formatDate } from './utils';

function getShowDateFromValue(value) {
  var _value = _slicedToArray(value, 2),
      start = _value[0],
      end = _value[1]; // value could be an empty array, then we should not reset showDate


  if (!start && !end) {
    return;
  }

  var newEnd = end && end.isSame(start, 'month') ? end.clone().add(1, 'month') : end;
  return [start, newEnd];
}

function pickerValueAdapter(value) {
  if (!value) {
    return;
  }

  if (Array.isArray(value)) {
    return value;
  }

  return [value, value.clone().add(1, 'month')];
}

function isEmptyArray(arr) {
  if (Array.isArray(arr)) {
    return arr.length === 0 || arr.every(function (i) {
      return !i;
    });
  }

  return false;
}

function fixLocale(value, localeCode) {
  if (!localeCode) {
    return;
  }

  if (!value || value.length === 0) {
    return;
  }

  var _value2 = _slicedToArray(value, 2),
      start = _value2[0],
      end = _value2[1];

  if (start) {
    start.locale(localeCode);
  }

  if (end) {
    end.locale(localeCode);
  }
}

var RangePicker = /*#__PURE__*/function (_React$Component) {
  _inherits(RangePicker, _React$Component);

  var _super = _createSuper(RangePicker);

  function RangePicker(props) {
    var _this;

    _classCallCheck(this, RangePicker);

    _this = _super.call(this, props);

    _this.clearSelection = function (e) {
      e.preventDefault();
      e.stopPropagation();

      _this.setState({
        value: []
      });

      _this.handleChange([]);
    };

    _this.clearHoverValue = function () {
      return _this.setState({
        hoverValue: []
      });
    };

    _this.handleChange = function (value) {
      var props = _this.props;

      if (!('value' in props)) {
        _this.setState(function (_ref) {
          var showDate = _ref.showDate;
          return {
            value: value,
            showDate: getShowDateFromValue(value) || showDate
          };
        });
      }

      var _value3 = _slicedToArray(value, 2),
          start = _value3[0],
          end = _value3[1];

      props.onChange(value, [formatDate(start, props.format), formatDate(end, props.format)]);
    };

    _this.handleOpenChange = function (open) {
      if (!('open' in _this.props)) {
        _this.setState({
          open: open
        });
      }

      if (open === false) {
        _this.clearHoverValue();
      }

      var onOpenChange = _this.props.onOpenChange;

      if (onOpenChange) {
        onOpenChange(open);
      }
    };

    _this.handleShowDateChange = function (showDate) {
      return _this.setState({
        showDate: showDate
      });
    };

    _this.handleHoverChange = function (hoverValue) {
      return _this.setState({
        hoverValue: hoverValue
      });
    };

    _this.handleRangeMouseLeave = function () {
      if (_this.state.open) {
        _this.clearHoverValue();
      }
    };

    _this.handleCalendarInputSelect = function (value) {
      var _value4 = _slicedToArray(value, 1),
          start = _value4[0];

      if (!start) {
        return;
      }

      _this.setState(function (_ref2) {
        var showDate = _ref2.showDate;
        return {
          value: value,
          showDate: getShowDateFromValue(value) || showDate
        };
      });
    };

    _this.handleRangeClick = function (value) {
      if (typeof value === 'function') {
        value = value();
      }

      _this.setValue(value, true);

      var _this$props = _this.props,
          onOk = _this$props.onOk,
          onOpenChange = _this$props.onOpenChange;

      if (onOk) {
        onOk(value);
      }

      if (onOpenChange) {
        onOpenChange(false);
      }
    };

    _this.savePicker = function (node) {
      _this.picker = node;
    };

    _this.renderFooter = function () {
      var _this$props2 = _this.props,
          ranges = _this$props2.ranges,
          renderExtraFooter = _this$props2.renderExtraFooter;

      var _assertThisInitialize = _assertThisInitialized(_this),
          prefixCls = _assertThisInitialize.prefixCls,
          tagPrefixCls = _assertThisInitialize.tagPrefixCls;

      if (!ranges && !renderExtraFooter) {
        return null;
      }

      var customFooter = renderExtraFooter ? /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-footer-extra"),
        key: "extra"
      }, renderExtraFooter.apply(void 0, arguments)) : null;
      var operations = Object.keys(ranges || {}).map(function (range) {
        var value = ranges[range];
        return /*#__PURE__*/React.createElement(Tag, {
          key: range,
          prefixCls: tagPrefixCls,
          color: "blue",
          onClick: function onClick() {
            return _this.handleRangeClick(value);
          },
          onMouseEnter: function onMouseEnter() {
            return _this.setState({
              hoverValue: value
            });
          },
          onMouseLeave: _this.handleRangeMouseLeave
        }, range);
      });
      var rangeNode = operations && operations.length > 0 ? /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-footer-extra ").concat(prefixCls, "-range-quick-selector"),
        key: "range"
      }, operations) : null;
      return [rangeNode, customFooter];
    };

    _this.renderRangePicker = function (_ref3) {
      var _classNames, _classNames2;

      var getPrefixCls = _ref3.getPrefixCls;

      var _assertThisInitialize2 = _assertThisInitialized(_this),
          state = _assertThisInitialize2.state,
          props = _assertThisInitialize2.props;

      var value = state.value,
          showDate = state.showDate,
          hoverValue = state.hoverValue,
          open = state.open;
      var customizePrefixCls = props.prefixCls,
          customizeTagPrefixCls = props.tagPrefixCls,
          popupStyle = props.popupStyle,
          style = props.style,
          disabledDate = props.disabledDate,
          disabledTime = props.disabledTime,
          showTime = props.showTime,
          showToday = props.showToday,
          ranges = props.ranges,
          onOk = props.onOk,
          locale = props.locale,
          localeCode = props.localeCode,
          format = props.format,
          dateRender = props.dateRender,
          onCalendarChange = props.onCalendarChange,
          suffixIcon = props.suffixIcon,
          separator = props.separator;
      var prefixCls = getPrefixCls('calendar', customizePrefixCls);
      var tagPrefixCls = getPrefixCls('tag', customizeTagPrefixCls); // To support old version react.
      // Have to add prefixCls on the instance.
      // https://github.com/facebook/react/issues/12397

      _this.prefixCls = prefixCls;
      _this.tagPrefixCls = tagPrefixCls;
      fixLocale(value, localeCode);
      fixLocale(showDate, localeCode);
      warning(!('onOK' in props), 'RangePicker', 'It should be `RangePicker[onOk]`, instead of `onOK`!');
      var calendarClassName = classNames((_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-time"), showTime), _defineProperty(_classNames, "".concat(prefixCls, "-range-with-ranges"), ranges), _classNames)); // 需要选择时间时，点击 ok 时才触发 onChange

      var pickerChangeHandler = {
        onChange: _this.handleChange
      };
      var calendarProps = {
        onOk: _this.handleChange
      };

      if (props.timePicker) {
        pickerChangeHandler.onChange = function (changedValue) {
          return _this.handleChange(changedValue);
        };
      } else {
        calendarProps = {};
      }

      if ('mode' in props) {
        calendarProps.mode = props.mode;
      }

      var startPlaceholder = 'placeholder' in props ? props.placeholder[0] : locale.lang.rangePlaceholder[0];
      var endPlaceholder = 'placeholder' in props ? props.placeholder[1] : locale.lang.rangePlaceholder[1];
      var calendar = /*#__PURE__*/React.createElement(RangeCalendar, _extends({}, calendarProps, {
        seperator: separator,
        onChange: onCalendarChange,
        format: format,
        prefixCls: prefixCls,
        className: calendarClassName,
        renderFooter: _this.renderFooter,
        timePicker: props.timePicker,
        disabledDate: disabledDate,
        disabledTime: disabledTime,
        dateInputPlaceholder: [startPlaceholder, endPlaceholder],
        locale: locale.lang,
        onOk: onOk,
        dateRender: dateRender,
        value: showDate,
        onValueChange: _this.handleShowDateChange,
        hoverValue: hoverValue,
        onHoverChange: _this.handleHoverChange,
        onPanelChange: props.onPanelChange,
        showToday: showToday,
        onInputSelect: _this.handleCalendarInputSelect
      })); // default width for showTime

      var pickerStyle = {};

      if (props.showTime) {
        if (style && style.width) {
          pickerStyle.width = style.width;
        }
      }

      var _value5 = _slicedToArray(value, 2),
          startValue = _value5[0],
          endValue = _value5[1];

      var clearIcon = !props.disabled && props.allowClear && value && (startValue || endValue) ? /*#__PURE__*/React.createElement(Icon, {
        type: "close-circle",
        className: "".concat(prefixCls, "-picker-clear"),
        onClick: _this.clearSelection,
        theme: "filled"
      }) : null;
      var inputIcon = suffixIcon && ( /*#__PURE__*/React.isValidElement(suffixIcon) ? /*#__PURE__*/React.cloneElement(suffixIcon, {
        className: classNames((_classNames2 = {}, _defineProperty(_classNames2, suffixIcon.props.className, suffixIcon.props.className), _defineProperty(_classNames2, "".concat(prefixCls, "-picker-icon"), true), _classNames2))
      }) : /*#__PURE__*/React.createElement("span", {
        className: "".concat(prefixCls, "-picker-icon")
      }, suffixIcon)) || /*#__PURE__*/React.createElement(Icon, {
        type: "calendar",
        className: "".concat(prefixCls, "-picker-icon")
      });

      var input = function input(_ref4) {
        var inputValue = _ref4.value;

        var _inputValue = _slicedToArray(inputValue, 2),
            start = _inputValue[0],
            end = _inputValue[1];

        return /*#__PURE__*/React.createElement("span", {
          className: props.pickerInputClass
        }, /*#__PURE__*/React.createElement("input", {
          disabled: props.disabled,
          readOnly: true,
          value: formatDate(start, props.format),
          placeholder: startPlaceholder,
          className: "".concat(prefixCls, "-range-picker-input"),
          tabIndex: -1
        }), /*#__PURE__*/React.createElement("span", {
          className: "".concat(prefixCls, "-range-picker-separator")
        }, " ", separator, " "), /*#__PURE__*/React.createElement("input", {
          disabled: props.disabled,
          readOnly: true,
          value: formatDate(end, props.format),
          placeholder: endPlaceholder,
          className: "".concat(prefixCls, "-range-picker-input"),
          tabIndex: -1
        }), clearIcon, inputIcon);
      };

      return /*#__PURE__*/React.createElement("span", {
        ref: _this.savePicker,
        id: props.id,
        className: classNames(props.className, props.pickerClass),
        style: _extends(_extends({}, style), pickerStyle),
        tabIndex: props.disabled ? -1 : 0,
        onFocus: props.onFocus,
        onBlur: props.onBlur,
        onMouseEnter: props.onMouseEnter,
        onMouseLeave: props.onMouseLeave
      }, /*#__PURE__*/React.createElement(RcDatePicker, _extends({}, props, pickerChangeHandler, {
        calendar: calendar,
        value: value,
        open: open,
        onOpenChange: _this.handleOpenChange,
        prefixCls: "".concat(prefixCls, "-picker-container"),
        style: popupStyle
      }), input));
    };

    var value = props.value || props.defaultValue || [];

    var _value6 = _slicedToArray(value, 2),
        start = _value6[0],
        end = _value6[1];

    if (start && !interopDefault(moment).isMoment(start) || end && !interopDefault(moment).isMoment(end)) {
      throw new Error('The value/defaultValue of RangePicker must be a moment object array after `ygd@2.0`, ' + 'see: https://u.ant.design/date-picker-value');
    }

    var pickerValue = !value || isEmptyArray(value) ? props.defaultPickerValue : value;
    _this.state = {
      value: value,
      showDate: pickerValueAdapter(pickerValue || interopDefault(moment)()),
      open: props.open,
      hoverValue: []
    };
    return _this;
  }

  _createClass(RangePicker, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(_, prevState) {
      if (!('open' in this.props) && prevState.open && !this.state.open) {
        this.focus();
      }
    }
  }, {
    key: "setValue",
    value: function setValue(value, hidePanel) {
      this.handleChange(value);

      if ((hidePanel || !this.props.showTime) && !('open' in this.props)) {
        this.setState({
          open: false
        });
      }
    }
  }, {
    key: "focus",
    value: function focus() {
      this.picker.focus();
    }
  }, {
    key: "blur",
    value: function blur() {
      this.picker.blur();
    }
  }, {
    key: "render",
    value: function render() {
      return /*#__PURE__*/React.createElement(ConfigConsumer, null, this.renderRangePicker);
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      var state = null;

      if ('value' in nextProps) {
        var value = nextProps.value || [];
        state = {
          value: value
        };

        if (!shallowequal(nextProps.value, prevState.value)) {
          state = _extends(_extends({}, state), {
            showDate: getShowDateFromValue(value) || prevState.showDate
          });
        }
      }

      if ('open' in nextProps && prevState.open !== nextProps.open) {
        state = _extends(_extends({}, state), {
          open: nextProps.open
        });
      }

      return state;
    }
  }]);

  return RangePicker;
}(React.Component);

RangePicker.defaultProps = {
  allowClear: true,
  showToday: false,
  separator: '~'
};
polyfill(RangePicker);
export default RangePicker;