"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _get3 = _interopRequireDefault(require("@babel/runtime/helpers/get"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _tslib = require("tslib");

var _react = _interopRequireWildcard(require("react"));

var _moment = _interopRequireWildcard(require("moment"));

var _classnames = _interopRequireDefault(require("classnames"));

var _raf = _interopRequireDefault(require("raf"));

var _defaultTo = _interopRequireDefault(require("lodash/defaultTo"));

var _isPlainObject = _interopRequireDefault(require("lodash/isPlainObject"));

var _isString = _interopRequireDefault(require("lodash/isString"));

var _isNil = _interopRequireDefault(require("lodash/isNil"));

var _noop = _interopRequireDefault(require("lodash/noop"));

var _mobxReact = require("mobx-react");

var _mobx = require("mobx");

var _KeyCode = _interopRequireDefault(require("../../../lib/_util/KeyCode"));

var _warning = _interopRequireDefault(require("../../../lib/_util/warning"));

var _TriggerField2 = _interopRequireDefault(require("../trigger-field/TriggerField"));

var _DaysView = _interopRequireDefault(require("./DaysView"));

var _DateTimesView = _interopRequireDefault(require("./DateTimesView"));

var _WeeksView = _interopRequireDefault(require("./WeeksView"));

var _TimesView = _interopRequireDefault(require("./TimesView"));

var _MonthsView = _interopRequireDefault(require("./MonthsView"));

var _YearsView = _interopRequireDefault(require("./YearsView"));

var _DecadeYearsView = _interopRequireDefault(require("./DecadeYearsView"));

var _autobind = _interopRequireDefault(require("../_util/autobind"));

var _enum = require("./enum");

var _EventManager = require("../_util/EventManager");

var _localeContext = require("../locale-context");

var _isSame = _interopRequireDefault(require("../_util/isSame"));

var _measureTextWidth = _interopRequireDefault(require("../_util/measureTextWidth"));

var _TextField = _interopRequireDefault(require("../text-field/TextField"));

var _viewComponents;

var viewComponents = (_viewComponents = {}, (0, _defineProperty2["default"])(_viewComponents, _enum.ViewMode.decade, _DecadeYearsView["default"]), (0, _defineProperty2["default"])(_viewComponents, _enum.ViewMode.year, _YearsView["default"]), (0, _defineProperty2["default"])(_viewComponents, _enum.ViewMode.month, _MonthsView["default"]), (0, _defineProperty2["default"])(_viewComponents, _enum.ViewMode.date, _DaysView["default"]), (0, _defineProperty2["default"])(_viewComponents, _enum.ViewMode.dateTime, _DateTimesView["default"]), (0, _defineProperty2["default"])(_viewComponents, _enum.ViewMode.week, _WeeksView["default"]), (0, _defineProperty2["default"])(_viewComponents, _enum.ViewMode.time, _TimesView["default"]), _viewComponents);

function createDefaultTime() {
  return (0, _moment["default"])('00:00:00', 'HH:mm:ss');
}

function getInRangeDefaultTime() {
  var defaultTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : createDefaultTime();
  var min = arguments.length > 1 ? arguments[1] : undefined;
  var max = arguments.length > 2 ? arguments[2] : undefined;
  var viewMode = arguments.length > 3 ? arguments[3] : undefined;

  if (min && defaultTime.isBefore(min)) {
    defaultTime.year(min.year());
    defaultTime.month(min.month());
    defaultTime.date(min.date());

    if (defaultTime.isBefore(min) && viewMode !== _enum.ViewMode.time) {
      defaultTime.add(1, 'd');
    }
  }

  if (max && defaultTime.isAfter(max)) {
    defaultTime.year(max.year());
    defaultTime.month(max.month());
    defaultTime.date(max.date());

    if (defaultTime.isAfter(max) && viewMode !== _enum.ViewMode.time) {
      defaultTime.subtract(1, 'd');
    }
  }

  return defaultTime;
}

var DatePicker = /*#__PURE__*/function (_TriggerField) {
  (0, _inherits2["default"])(DatePicker, _TriggerField);

  var _super = (0, _createSuper2["default"])(DatePicker);

  function DatePicker() {
    var _this;

    (0, _classCallCheck2["default"])(this, DatePicker);
    _this = _super.apply(this, arguments);

    _this.handleDateMouseEnter = function (currentDate) {
      _this.hoverValue = currentDate;
    };

    _this.handleDateMouseLeave = function () {
      _this.hoverValue = undefined;
    };

    return _this;
  }

  (0, _createClass2["default"])(DatePicker, [{
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.timeID) {
        clearTimeout(this.timeID);
        delete this.timeID;
      }
    }
  }, {
    key: "value",
    get: function get() {
      var _this2 = this;

      var value = this.observableProps.value;
      var range = this.range;

      if ((0, _mobx.isArrayLike)(value)) {
        return value.map(function (item) {
          if ((0, _mobx.isArrayLike)(item)) {
            return item.map(_this2.checkMoment, _this2);
          }

          return _this2.checkMoment(item);
        });
      }

      if ((0, _mobx.isArrayLike)(range)) {
        if ((0, _isPlainObject["default"])(value)) {
          var _ref;

          var _range = (0, _slicedToArray2["default"])(range, 2),
              start = _range[0],
              end = _range[1];

          return _ref = {}, (0, _defineProperty2["default"])(_ref, start, this.checkMoment(value[start])), (0, _defineProperty2["default"])(_ref, end, this.checkMoment(value[end])), _ref;
        }
      }

      return this.checkMoment(value);
    },
    set: function set(value) {
      var _this3 = this;

      (0, _mobx.runInAction)(function () {
        _this3.observableProps.value = value;
      });
    }
  }, {
    key: "defaultValidationMessages",
    get: function get() {
      var label = this.getProp('label');
      return {
        valueMissing: (0, _localeContext.$l)('DatePicker', label ? 'value_missing' : 'value_missing_no_label', {
          label: label
        })
      };
    }
  }, {
    key: "min",
    get: function get() {
      return this.getLimit('min');
    }
  }, {
    key: "max",
    get: function get() {
      return this.getLimit('max');
    }
  }, {
    key: "savePopupInputEditor",
    value: function savePopupInputEditor(node) {
      this.popupInputEditor = node;

      if (node && this.popup) {
        (0, _raf["default"])(function () {
          node.focus();
        });
      }
    }
  }, {
    key: "isEditable",
    value: function isEditable() {
      return (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "isEditable", this).call(this) && !this.isEditableLike() && this.getViewMode() !== _enum.ViewMode.week;
    }
  }, {
    key: "isEditableLike",
    value: function isEditableLike() {
      return this.popup && this.observableProps.editorInPopup;
    }
  }, {
    key: "getOmitPropsKeys",
    value: function getOmitPropsKeys() {
      return (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "getOmitPropsKeys", this).call(this).concat(['mode', 'filter', 'cellRenderer', 'maxLength', 'minLength', 'timeZone', 'editorInPopup', 'defaultTime', 'useInvalidDate']);
    }
  }, {
    key: "getOtherProps",
    value: function getOtherProps() {
      var otherProps = (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "getOtherProps", this).call(this);
      delete otherProps.maxLength;
      return otherProps;
    }
  }, {
    key: "getObservableProps",
    value: function getObservableProps(props, context) {
      return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "getObservableProps", this).call(this, props, context)), {}, {
        editorInPopup: props.editorInPopup
      });
    }
  }, {
    key: "defaultRenderer",
    value: function defaultRenderer(props) {
      var renderedText = (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "defaultRenderer", this).call(this, props);
      var mode = this.getDefaultViewMode();
      var value = props.value;

      if (value && [_enum.ViewMode.time, _enum.ViewMode.dateTime].includes(mode)) {
        var _this$props$timeZone = this.props.timeZone,
            timeZone = _this$props$timeZone === void 0 ? this.getContextConfig('formatter').timeZone : _this$props$timeZone;

        if (timeZone) {
          var renderedTimeZone = typeof timeZone === 'function' ? timeZone(value) : value.format(timeZone);

          if ((0, _isString["default"])(renderedTimeZone)) {
            return "".concat(renderedText).concat(renderedTimeZone);
          }

          return [renderedText, renderedTimeZone];
        }
      }

      return renderedText;
    }
  }, {
    key: "getDefaultTime",
    value: function getDefaultTime() {
      var _this$props$defaultTi = this.props.defaultTime,
          defaultTime = _this$props$defaultTi === void 0 ? createDefaultTime() : _this$props$defaultTi;
      var viewMode = this.getDefaultViewMode();
      var min = this.min,
          max = this.max;

      if ((0, _mobx.isArrayLike)(defaultTime)) {
        return [getInRangeDefaultTime(defaultTime[0], min, max, viewMode), getInRangeDefaultTime(defaultTime[1], min, max, viewMode)];
      }

      var inRangeDefaultTime = getInRangeDefaultTime(defaultTime, min, max, viewMode);
      return [inRangeDefaultTime, inRangeDefaultTime];
    }
  }, {
    key: "getDefaultViewMode",
    value: function getDefaultViewMode() {
      var mode = this.getProp('mode', 'dateMode');

      if (mode === _enum.ViewMode.decade || mode === undefined) {
        return _enum.ViewMode.date;
      }

      return mode;
    }
  }, {
    key: "getPopupClassName",
    value: function getPopupClassName(defaultClassName) {
      var viewMode = this.getViewMode();
      return (0, _classnames["default"])((0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "getPopupClassName", this).call(this, defaultClassName), (0, _defineProperty2["default"])({}, "".concat(this.prefixCls, "-popup-").concat(String(viewMode).toLowerCase()), viewMode));
    }
  }, {
    key: "handlePopupRangeEditorBlur",
    value: function handlePopupRangeEditorBlur() {
      var text = this.text;

      if (text) {
        this.syncValueOnBlur(text);
      }
    }
  }, {
    key: "getDefaultAction",
    value: function getDefaultAction() {
      return this.getContextConfig('selectTrigger') || (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "getDefaultAction", this).call(this);
    }
  }, {
    key: "getPopupEditor",
    value: function getPopupEditor() {
      var editorInPopup = this.observableProps.editorInPopup;

      if (editorInPopup) {
        var _classNames2;

        var prefixCls = this.prefixCls,
            range = this.range,
            text = this.text,
            rangeTarget = this.rangeTarget,
            multiple = this.multiple;
        var popupHoverValue = this.getHoverValue(true);
        var className = (0, _classnames["default"])("".concat(prefixCls, "-popup-editor"), (_classNames2 = {}, (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-popup-hover-value"), !(0, _isNil["default"])(popupHoverValue) && !range), (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-popup-hover-value-start"), !(0, _isNil["default"])(popupHoverValue) && range && rangeTarget === 0), (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-popup-hover-value-end"), !(0, _isNil["default"])(popupHoverValue) && range && rangeTarget === 1), _classNames2));

        var _this$getPlaceholders = this.getPlaceholders(),
            _this$getPlaceholders2 = (0, _slicedToArray2["default"])(_this$getPlaceholders, 2),
            startPlaceholder = _this$getPlaceholders2[0],
            _this$getPlaceholders3 = _this$getPlaceholders2[1],
            endPlaceHolder = _this$getPlaceholders3 === void 0 ? startPlaceholder : _this$getPlaceholders3;

        if (range) {
          var _this$processRangeVal = this.processRangeValue(this.rangeValue),
              _this$processRangeVal2 = (0, _slicedToArray2["default"])(_this$processRangeVal, 2),
              _this$processRangeVal3 = _this$processRangeVal2[0],
              startValue = _this$processRangeVal3 === void 0 ? '' : _this$processRangeVal3,
              _this$processRangeVal4 = _this$processRangeVal2[1],
              endValue = _this$processRangeVal4 === void 0 ? '' : _this$processRangeVal4;

          var startText = this.getText(startValue);
          var endText = this.getText(endValue);
          return /*#__PURE__*/_react["default"].createElement("span", {
            key: "popup-editor",
            className: (0, _classnames["default"])(className, "".concat(prefixCls, "-range-text"))
          }, /*#__PURE__*/_react["default"].createElement("input", {
            className: "".concat(prefixCls, "-range-start"),
            onChange: this.handleChange,
            onFocus: this.handleRangeStart,
            onBlur: this.handlePopupRangeEditorBlur,
            value: rangeTarget === 0 ? (0, _defaultTo["default"])((0, _defaultTo["default"])(popupHoverValue, text), startText) : startText,
            placeholder: startPlaceholder,
            ref: rangeTarget === 0 ? this.savePopupInputEditor : undefined,
            onKeyDown: this.handlePopupEditorKeyDown
          }), /*#__PURE__*/_react["default"].createElement("span", {
            className: "".concat(prefixCls, "-range-split")
          }, "~"), /*#__PURE__*/_react["default"].createElement("input", {
            className: "".concat(prefixCls, "-range-end"),
            onChange: this.handleChange,
            onFocus: this.handleRangeEnd,
            onBlur: this.handlePopupRangeEditorBlur,
            value: rangeTarget === 1 ? (0, _defaultTo["default"])((0, _defaultTo["default"])(popupHoverValue, text), endText) : endText,
            placeholder: endPlaceHolder,
            ref: rangeTarget === 1 ? this.savePopupInputEditor : undefined,
            onKeyDown: this.handlePopupEditorKeyDown
          }));
        }

        var value = (0, _isNil["default"])(popupHoverValue) ? multiple ? (0, _defaultTo["default"])(text, '') : this.getTextNode() : popupHoverValue;
        return /*#__PURE__*/_react["default"].createElement(_TextField["default"], {
          key: "popup-editor",
          value: value,
          onInput: this.handleChange,
          border: false,
          className: className,
          placeholder: startPlaceholder,
          onKeyDown: this.handlePopupEditorKeyDown,
          ref: this.savePopupInputEditor
        });
      }
    }
  }, {
    key: "getHoverValue",
    value: function getHoverValue(isPopup) {
      var editorInPopup = this.props.editorInPopup;

      if (isPopup && editorInPopup || !isPopup && !editorInPopup) {
        var hoverValue = this.hoverValue;

        if (hoverValue) {
          return hoverValue.format(this.getDateFormat());
        }
      }
    } // 处理 hover 值显示

  }, {
    key: "getEditorTextInfo",
    value: function getEditorTextInfo(rangeTarget) {
      var isFlat = this.props.isFlat;
      var hoverValue = this.getHoverValue(false);

      if (hoverValue !== undefined) {
        if (rangeTarget === undefined || rangeTarget === 0 && this.rangeTarget === 0 || rangeTarget === 1 && this.rangeTarget === 1) {
          return {
            text: hoverValue,
            width: isFlat ? (0, _measureTextWidth["default"])(hoverValue) : 0
          };
        }
      }

      return (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "getEditorTextInfo", this).call(this, rangeTarget);
    }
  }, {
    key: "getRangeInputValue",
    value: function getRangeInputValue(startText, endText) {
      var hoverValue = this.getHoverValue(false);

      if (hoverValue === undefined) {
        return (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "getRangeInputValue", this).call(this, startText, endText);
      }

      return hoverValue;
    }
  }, {
    key: "getInputClassString",
    value: function getInputClassString(className) {
      var prefixCls = this.prefixCls;
      var hoverValue = this.getHoverValue(false);
      return (0, _classnames["default"])(className, (0, _defineProperty2["default"])({}, "".concat(prefixCls, "-hover-value"), !(0, _isNil["default"])(hoverValue)));
    }
  }, {
    key: "getPopupContent",
    value: function getPopupContent() {
      var _this4 = this;

      var mode = this.getViewMode();
      var date = this.getCursorDate();
      return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, this.getPopupEditor(), /*#__PURE__*/(0, _react.createElement)(viewComponents[mode], {
        ref: function ref(node) {
          return _this4.view = node;
        },
        date: date,
        mode: this.getDefaultViewMode(),
        disabledNow: !this.isValidNowDate(date),
        isExistValue: this.isExistValue(),
        renderer: this.getCellRenderer(mode),
        onSelect: this.handleSelect,
        onSelectedDateChange: this.handleSelectedDateChange,
        onCursorDateChange: this.handleCursorDateChange,
        onViewModeChange: this.handelViewModeChange,
        isValidDate: this.isValidDate,
        format: this.getDateFormat(),
        step: this.getProp('step') || {},
        renderExtraFooter: this.getProp('renderExtraFooter'),
        extraFooterPlacement: this.getProp('extraFooterPlacement') || 'bottom',
        onDateMouseEnter: this.handleDateMouseEnter,
        onDateMouseLeave: this.handleDateMouseLeave,
        okButton: this.getContextConfig('dateTimePickerOkButton')
      }));
    }
  }, {
    key: "getCellRenderer",
    value: function getCellRenderer(mode) {
      var _this$props$cellRende = this.props.cellRenderer,
          cellRenderer = _this$props$cellRende === void 0 ? _noop["default"] : _this$props$cellRende;
      return cellRenderer(mode);
    }
  }, {
    key: "getTriggerIconFont",
    value: function getTriggerIconFont() {
      return 'date_range';
    }
  }, {
    key: "getFieldType",
    value: function getFieldType() {
      return viewComponents[this.getDefaultViewMode()].type;
    }
  }, {
    key: "getViewMode",
    value: function getViewMode() {
      var _this$mode = this.mode,
          mode = _this$mode === void 0 ? this.getDefaultViewMode() : _this$mode;
      return mode;
    }
  }, {
    key: "toMoment",
    value: function toMoment(item) {
      var field = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.field;
      var noCheck = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

      if ((0, _isNil["default"])(item)) {
        return undefined;
      }

      if ((0, _moment.isMoment)(item)) {
        return item;
      }

      (0, _warning["default"])(noCheck, "DatePicker: The value of DatePicker is not moment.");
      var format = this.getDateFormat(field);

      if (item instanceof Date) {
        item = (0, _moment["default"])(item).format(format);
      }

      var range = this.range,
          rangeTarget = this.rangeTarget;
      var date = (0, _moment["default"])(item, format);

      if (date.isValid()) {
        var _date$parsingFlags = date.parsingFlags(),
            unusedTokens = _date$parsingFlags.unusedTokens;

        if (unusedTokens.includes('HH') && unusedTokens.includes('mm') && unusedTokens.includes('ss')) {
          var defaultTime = this.getDefaultTime()[range && rangeTarget !== undefined ? rangeTarget : 0];
          date.hour(defaultTime.hour());
          date.minute(defaultTime.minute());
          date.second(defaultTime.second());
        }
      }

      return date;
    }
  }, {
    key: "checkMoment",
    value: function checkMoment(item) {
      return this.toMoment(item);
    }
  }, {
    key: "compare",
    value: function compare(oldValue, newValue) {
      return (0, _isSame["default"])(this.momentToTimestamp(oldValue), this.momentToTimestamp(newValue));
    }
  }, {
    key: "setText",
    value: function setText(text) {
      (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "setText", this).call(this, text);

      if (text) {
        var date = this.toMoment(text);

        if (date && date.isValid()) {
          this.changeCursorDate(date);
        }
      }
    }
  }, {
    key: "afterSetValue",
    value: function afterSetValue() {
      (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "afterSetValue", this).call(this);
      this.setText(undefined);
    }
  }, {
    key: "momentToTimestamp",
    value: function momentToTimestamp(value) {
      if ((0, _moment.isMoment)(value)) {
        return (0, _moment["default"])(value).valueOf();
      }

      return value;
    }
  }, {
    key: "getSelectedDate",
    value: function getSelectedDate() {
      return this.getCursorDate();
    }
  }, {
    key: "getCursorDate",
    value: function getCursorDate() {
      var range = this.range,
          multiple = this.multiple,
          rangeTarget = this.rangeTarget,
          rangeValue = this.rangeValue;
      var cursorDate = this.cursorDate || range && rangeTarget !== undefined && rangeValue && rangeValue[rangeTarget] || !multiple && this.getValue();

      if (range && !multiple && rangeTarget !== undefined && !(0, _isNil["default"])(cursorDate) && !(0, _moment.isMoment)(cursorDate)) {
        cursorDate = (0, _typeof2["default"])(range) === 'object' ? cursorDate[range[rangeTarget]] : cursorDate[rangeTarget];
      }

      if ((0, _moment.isMoment)(cursorDate) && cursorDate.isValid()) {
        return cursorDate.clone();
      }

      return this.getValidDate(this.getDefaultTime()[range && rangeTarget !== undefined ? rangeTarget : 0]);
    }
  }, {
    key: "getLimit",
    value: function getLimit(minOrMax) {
      var limit = this.getProp(minOrMax);

      if ((0, _isNil["default"])(limit)) {
        var configLimit = this.getContextConfig(minOrMax);

        if (configLimit) {
          limit = configLimit(this.getFieldType());
        }
      }

      if (!(0, _isNil["default"])(limit)) {
        var record = this.record;

        if (record && (0, _isString["default"])(limit)) {
          var field = record.dataSet.getField(limit);

          if (field) {
            var value = record.get(limit);

            if (value) {
              var momentValue = this.toMoment(value, field, true);

              if (momentValue) {
                return this.getLimitWithType(momentValue.clone(), minOrMax);
              }
            }

            return undefined;
          }
        }

        return this.getLimitWithType((0, _moment["default"])(limit), minOrMax);
      }
    }
  }, {
    key: "getLimitWithType",
    value: function getLimitWithType(limit, minOrMax) {
      if (minOrMax === 'min') {
        return limit.startOf('d');
      }

      return limit.endOf('d');
    }
  }, {
    key: "getPopupStyleFromAlign",
    value: function getPopupStyleFromAlign() {
      return undefined;
    }
  }, {
    key: "handleCursorDateChange",
    value: function handleCursorDateChange(cursorDate, selectedDate, mode) {
      var nowDate = (0, _moment["default"])();

      if (this.getDefaultViewMode() === _enum.ViewMode.time && cursorDate.format('YYYY-MM-DD') !== nowDate.format('YYYY-MM-DD')) {
        // 更改为当天的 时间
        cursorDate = cursorDate.set({
          'year': nowDate.year(),
          'month': nowDate.month(),
          'date': nowDate.date()
        });
      }

      var min = this.min,
          max = this.max;

      if (!this.isUnderRange(cursorDate, mode)) {
        if (min && cursorDate.isSameOrBefore(min) && selectedDate.isSameOrBefore(cursorDate)) {
          // 往后翻页，跳转到 min
          cursorDate = min;
        } else if (max && cursorDate.isSameOrAfter(max) && selectedDate.isSameOrAfter(cursorDate)) {
          // 往前翻页，跳转到 max
          cursorDate = max;
        }
      }

      if (this.isUnderRange(cursorDate, mode) && (mode && mode !== _enum.ViewMode.date || this.isDateOutOfFilter(cursorDate, selectedDate, mode))) {
        this.changeCursorDate(cursorDate);
      }
    }
  }, {
    key: "handleSelectedDateChange",
    value: function handleSelectedDateChange(selectedDate, mode) {
      if (this.isUnderRange(selectedDate, mode) && this.isDateOutOfFilter(selectedDate, selectedDate, mode)) {
        this.setText(selectedDate.format(this.getDateFormat()));
      }
    }
  }, {
    key: "handelViewModeChange",
    value: function handelViewModeChange(mode) {
      var _this5 = this;

      (0, _mobx.runInAction)(function () {
        _this5.hoverValue = undefined;
        _this5.mode = mode;
      });
    }
  }, {
    key: "handlePopupAnimateAppear",
    value: function handlePopupAnimateAppear() {// noop
    }
  }, {
    key: "handlePopupAnimateEnd",
    value: function handlePopupAnimateEnd(key, exists) {
      var _this6 = this;

      if (key === 'align') {
        if (exists) {
          var popupInputEditor = this.popupInputEditor;

          if (popupInputEditor) {
            (0, _raf["default"])(function () {
              popupInputEditor.focus();
            });
          }
        } else {
          (0, _mobx.runInAction)(function () {
            _this6.cursorDate = undefined;
            _this6.mode = undefined;
          });
        }
      }
    }
  }, {
    key: "handleSelect",
    value: function handleSelect(date, expand) {
      var mode = this.getDefaultViewMode();
      var formatDate = date;

      if (mode !== _enum.ViewMode.week) {
        var format = this.getDateFormat();
        formatDate = (0, _moment["default"])(date.format(format), format);
      }

      if (this.multiple && this.isSelected(formatDate)) {
        this.unChoose(formatDate);
      } else {
        this.choose(formatDate, expand);
      }
    }
  }, {
    key: "handleKeyDown",
    value: function handleKeyDown(e) {
      if (!this.disabled && !this.readOnly) {
        var el = this.popup ? this.view || this : this;

        switch (e.keyCode) {
          case _KeyCode["default"].RIGHT:
            el.handleKeyDownRight(e);
            break;

          case _KeyCode["default"].LEFT:
            el.handleKeyDownLeft(e);
            break;

          case _KeyCode["default"].DOWN:
            el.handleKeyDownDown(e);
            break;

          case _KeyCode["default"].UP:
            el.handleKeyDownUp(e);
            break;

          case _KeyCode["default"].END:
            el.handleKeyDownEnd(e);
            break;

          case _KeyCode["default"].HOME:
            el.handleKeyDownHome(e);
            break;

          case _KeyCode["default"].PAGE_UP:
            el.handleKeyDownPageUp(e);
            break;

          case _KeyCode["default"].PAGE_DOWN:
            el.handleKeyDownPageDown(e);
            break;

          case _KeyCode["default"].ENTER:
            el.handleKeyDownEnter(e);
            break;

          case _KeyCode["default"].TAB:
            this.handleKeyDownTab();
            break;

          case _KeyCode["default"].ESC:
            this.handleKeyDownEsc(e);
            break;

          case _KeyCode["default"].SPACE:
            this.handleKeyDownSpace(e);
            break;

          case _KeyCode["default"].BACKSPACE:
            this.handleKeyDownBackSpace(e);
            break;

          case _KeyCode["default"].DELETE:
            this.handleKeyDownDelete(e);
            break;

          default:
        }
      }

      (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "handleKeyDown", this).call(this, e);
    }
  }, {
    key: "handleKeyDownHome",
    value: function handleKeyDownHome(e) {
      if (!this.multiple && !this.editable) {
        (0, _EventManager.stopEvent)(e);
        this.choose(this.getCursorDate().startOf('M'));
      }
    }
  }, {
    key: "handleKeyDownEnd",
    value: function handleKeyDownEnd(e) {
      if (!this.multiple && !this.editable) {
        (0, _EventManager.stopEvent)(e);
        this.choose(this.getCursorDate().endOf('M'));
      }
    }
  }, {
    key: "handleKeyDownLeft",
    value: function handleKeyDownLeft(e) {
      if (!this.multiple && !this.editable) {
        (0, _EventManager.stopEvent)(e);
        this.choose(this.getCursorDate().subtract(1, 'd'));
      }
    }
  }, {
    key: "handleKeyDownRight",
    value: function handleKeyDownRight(e) {
      if (!this.multiple && !this.editable) {
        (0, _EventManager.stopEvent)(e);
        this.choose(this.getCursorDate().add(1, 'd'));
      }
    }
  }, {
    key: "handleKeyDownUp",
    value: function handleKeyDownUp(e) {
      if (!this.multiple && !this.editable) {
        (0, _EventManager.stopEvent)(e);
        this.choose(this.getCursorDate().subtract(1, 'w'));
      }
    }
  }, {
    key: "handleKeyDownDown",
    value: function handleKeyDownDown(e) {
      if (this.multiple) {
        this.expand();
      } else if (!this.editable) {
        (0, _EventManager.stopEvent)(e);
        this.choose(this.getCursorDate().add(1, 'w'));
      }
    }
  }, {
    key: "handleKeyDownPageUp",
    value: function handleKeyDownPageUp(e) {
      if (!this.multiple && !this.editable) {
        (0, _EventManager.stopEvent)(e);
        this.choose(this.getCursorDate().subtract(1, e.altKey ? 'y' : 'M'));
      }
    }
  }, {
    key: "handleKeyDownPageDown",
    value: function handleKeyDownPageDown(e) {
      if (!this.multiple && !this.editable) {
        (0, _EventManager.stopEvent)(e);
        this.choose(this.getCursorDate().add(1, e.altKey ? 'y' : 'M'));
      }
    }
  }, {
    key: "handleKeyDownEnter",
    value: function handleKeyDownEnter(_e) {
      if (!this.multiple && !this.editable) {
        this.choose(this.getCursorDate());
      }
    }
  }, {
    key: "handleKeyDownEsc",
    value: function handleKeyDownEsc(e) {
      if (this.popup) {
        e.preventDefault();
        this.collapse();
      }
    }
  }, {
    key: "handleKeyDownTab",
    value: function handleKeyDownTab() {
      // this.collapse();
      if ((!this.range || this.rangeTarget === 1) && !(0, _isNil["default"])(this.hoverValue)) {
        this.hoverValue = undefined;
      }
    }
  }, {
    key: "handleKeyDownSpace",
    value: function handleKeyDownSpace(e) {
      if (!this.isEditable()) {
        e.preventDefault();
      }

      if (!this.popup) {
        this.expand();
      }
    }
  }, {
    key: "handleKeyDownBackSpace",
    value: function handleKeyDownBackSpace(e) {
      var _this7 = this;

      if (!this.isEditable() && !this.popup) {
        e.preventDefault();
      }

      if (this.cursorDate && this.afterKeyDownInputIsClear(e)) {
        (0, _mobx.runInAction)(function () {
          _this7.cursorDate = undefined;
        });
      }
    }
  }, {
    key: "handleKeyDownDelete",
    value: function handleKeyDownDelete(e) {
      this.handleKeyDownBackSpace(e);
    }
  }, {
    key: "afterKeyDownInputIsClear",
    value: function afterKeyDownInputIsClear(event) {
      var keyCode = event.keyCode,
          _event$target = event.target,
          value = _event$target.value,
          selectionStart = _event$target.selectionStart,
          selectionEnd = _event$target.selectionEnd;

      if ((0, _isNil["default"])(value)) {
        return true;
      }

      var length = String(value).length;
      var selectedLength = Math.abs(selectionEnd - selectionStart);

      if (length === selectedLength) {
        return true;
      }

      if (selectedLength !== 0) {
        return false;
      }

      if (keyCode === _KeyCode["default"].BACKSPACE && length === 1 && selectionStart === 1 || keyCode === _KeyCode["default"].DELETE && length === 1 && selectionStart === 0) {
        return true;
      }

      return false;
    }
  }, {
    key: "handlePopupEditorKeyDown",
    value: function handlePopupEditorKeyDown(e) {
      if (!this.disabled && !this.readOnly) {
        switch (e.keyCode) {
          case _KeyCode["default"].BACKSPACE:
            this.handleKeyDownBackSpace(e);
            break;

          case _KeyCode["default"].DELETE:
            this.handleKeyDownDelete(e);
            break;

          default:
        }
      }
    }
  }, {
    key: "handleEnterDown",
    value: function handleEnterDown(e) {
      (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "handleEnterDown", this).call(this, e);

      if (this.multiple && this.range) {
        this.setRangeTarget(0);
        this.beginRange();
        this.expand();
      }
    }
  }, {
    key: "prepareSetValue",
    value: function prepareSetValue() {
      var _get2,
          _this8 = this;

      var cursorDate;
      var useInvalidDate = this.props.useInvalidDate;

      for (var _len = arguments.length, value = new Array(_len), _key = 0; _key < _len; _key++) {
        value[_key] = arguments[_key];
      }

      (_get2 = (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "prepareSetValue", this)).call.apply(_get2, [this].concat((0, _toConsumableArray2["default"])(value.reduce(function (values, v) {
        if (v === null) {
          values.push(null);
        } else {
          var m = _this8.checkMoment(v);

          if (m) {
            if (useInvalidDate || m.isValid()) {
              cursorDate = cursorDate || _this8.getCursorDate();

              if (_this8.isDateOutOfFilter(m, cursorDate)) {
                values.push(m);
              }
            } else {
              _this8.setText();
            }
          } else {
            values.push(m);
          }
        }

        return values;
      }, []))));
    }
  }, {
    key: "syncValueOnBlur",
    value: function syncValueOnBlur(value) {
      if (value) {
        this.prepareSetValue(value);
      } else if (!this.multiple) {
        this.prepareSetValue(this.emptyValue);
      } else if (this.getProp('required')) {
        var oldValues = this.getValues();
        this.validate(oldValues, false);
      }
    }
  }, {
    key: "getValueKey",
    value: function getValueKey(v) {
      if ((0, _mobx.isArrayLike)(v)) {
        return v.map(this.getValueKey, this).join(',');
      }

      if ((0, _moment.isMoment)(v)) {
        return v.format();
      }

      return v;
    }
  }, {
    key: "exchangeRangeValue",
    value: function exchangeRangeValue(start, end) {
      this.rangeValueExchange = true;
      var defaultTime = this.props.defaultTime;

      if (defaultTime) {
        var _this$getDefaultTime = this.getDefaultTime(),
            _this$getDefaultTime2 = (0, _slicedToArray2["default"])(_this$getDefaultTime, 2),
            startDefaultTime = _this$getDefaultTime2[0],
            endDefaultTime = _this$getDefaultTime2[1];

        var startHour = start.hour();
        var startMinute = start.minute();
        var startSecond = start.second();
        var startDefaultHour = startDefaultTime.hour();
        var startDefaultMinute = startDefaultTime.minute();
        var startDefaultSecond = startDefaultTime.second();
        var endHour = end.hour();
        var endMinute = end.minute();
        var endSecond = end.second();
        var endDefaultHour = endDefaultTime.hour();
        var endDefaultMinute = endDefaultTime.minute();
        var endDefaultSecond = endDefaultTime.second();

        if (startHour === startDefaultHour && startMinute === startDefaultMinute && startSecond === startDefaultSecond) {
          end.hour(startHour);
          end.minute(startMinute);
          end.second(startSecond);
        }

        if (endHour === endDefaultHour && endMinute === endDefaultMinute && endSecond === endDefaultSecond) {
          start.hour(endHour);
          start.minute(endMinute);
          start.second(endSecond);
        }
      }

      (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "exchangeRangeValue", this).call(this, start, end);
    }
  }, {
    key: "changeCursorDate",
    value: function changeCursorDate(cursorDate) {
      if (this.rangeValueExchange) {
        if (this.range && !(0, _isNil["default"])(this.rangeTarget) && this.rangeValue) {
          var _ref2 = (0, _toConsumableArray2["default"])(this.rangeValue),
              start = _ref2[0],
              end = _ref2[1];

          cursorDate = this.rangeTarget === 0 ? start : end;
        }

        this.setText(undefined);
      }

      this.rangeValueExchange = false;
      this.cursorDate = cursorDate && this.getValidDate(cursorDate);
    }
  }, {
    key: "isSelected",
    value: function isSelected(date) {
      return this.getValues().some(function (value) {
        return date.isSame(value);
      });
    }
  }, {
    key: "unChoose",
    value: function unChoose(date) {
      this.removeValue(date, -1);
    }
    /**
     *
     * @param date 返回的时间
     * @param expand 是否保持时间选择器的展开
     */

  }, {
    key: "choose",
    value: function choose(date, expand) {
      var _this9 = this;

      date = this.getValidDate(date);

      if (this.isDateOutOfFilter(date, date)) {
        this.prepareSetValue(date);
        this.changeCursorDate(date);
        var range = this.range,
            rangeTarget = this.rangeTarget;

        if (range ? rangeTarget === 1 : !this.multiple) {
          if (!expand) {
            (0, _mobx.runInAction)(function () {
              _this9.hoverValue = undefined;
            });
            this.collapse();
          }
        }

        if (range && rangeTarget === 0 && this.popup && !expand) {
          this.setRangeTarget(1);
        }
      }
    }
  }, {
    key: "setRangeTarget",
    value: function setRangeTarget(target) {
      var _this10 = this;

      if (this.isFocused && target !== undefined && target !== this.rangeTarget) {
        this.expand();
      }

      if (!(0, _isNil["default"])(target)) {
        this.cursorDate = undefined;
      } else {
        if ((0, _isNil["default"])(this.cursorDate)) {
          this.cursorDate = this.getCursorDate();
        }

        this.timeID = window.setTimeout((0, _mobx.action)(function () {
          _this10.cursorDate = undefined;
        }), (this.props.triggerHiddenDelay || 50) + 20);
      }

      (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "setRangeTarget", this).call(this, target);
    }
  }, {
    key: "getValidDate",
    value: function getValidDate(date) {
      var min = this.min,
          max = this.max;

      if (min && date.isSameOrBefore(min)) {
        date = min;
      } else if (max && date.isSameOrAfter(max)) {
        date = max;
      }

      return date;
    }
  }, {
    key: "isLowerRange",
    value: function isLowerRange(m1, m2) {
      var moment1 = this.toMoment(m1);

      if (moment1) {
        return moment1.isBefore(this.toMoment(m2));
      }

      return false;
    }
  }, {
    key: "isUnderRange",
    value: function isUnderRange(date, mode) {
      var min = this.min,
          max = this.max;

      if (min || max) {
        var start = (min || date).clone();
        var end = (max || date).clone();

        switch (mode || this.getViewMode()) {
          case _enum.ViewMode.month:
            start = start.startOf('M');
            end = end.endOf('M');
            break;

          case _enum.ViewMode.year:
            start = start.startOf('y');
            end = end.endOf('y');
            break;

          case _enum.ViewMode.decade:
            start = start.startOf('y').subtract(start.year() % 10, 'y').startOf('d');
            end = end.endOf('y').add(9 - end.year() % 10, 'y').endOf('d');
            break;

          case _enum.ViewMode.dateTime:
            start = start.startOf('d');
            end = end.endOf('d');
            break;

          default:
        }

        return date.isBetween(start, end, undefined, '[]');
      }

      return true;
    }
  }, {
    key: "isDateOutOfFilter",
    value: function isDateOutOfFilter(currentDate, selected, mode) {
      var filter = this.props.filter;

      if (filter) {
        return filter(currentDate, selected, mode || this.getViewMode(), this.rangeTarget, (0, _mobx.toJS)(this.rangeValue));
      }

      return true;
    }
  }, {
    key: "isValidDate",
    value: function isValidDate(currentDate, selected, mode) {
      return this.isUnderRange(currentDate, mode) && this.isDateOutOfFilter(currentDate, selected, mode);
    }
  }, {
    key: "isValidNowDate",
    value: function isValidNowDate(selected) {
      var filter = this.props.filter;
      var isValid = this.isUnderRange((0, _moment["default"])());

      if (isValid && filter) {
        return filter((0, _moment["default"])(), selected, this.getViewMode(), this.rangeTarget, (0, _mobx.toJS)(this.rangeValue));
      }

      return isValid;
    }
  }, {
    key: "isExistValue",
    value: function isExistValue() {
      var value = this.value,
          multiple = this.multiple,
          range = this.range;
      var exist = false;

      if (multiple && (0, _mobx.isArrayLike)(value) && !range) {
        var mode = this.getDefaultViewMode();
        var format = this.getDateFormat();
        var now = (0, _moment["default"])().format(format);

        switch (mode) {
          case _enum.ViewMode.date:
            exist = value.some(function (x) {
              return x && x.isSame(now);
            });
            break;

          case _enum.ViewMode.week:
            exist = value.some(function (x) {
              return x && x.format(format) === now;
            });
            break;

          default:
            break;
        }
      }

      return exist;
    }
  }, {
    key: "getValidatorProp",
    value: function getValidatorProp(key) {
      if (['maxLength', 'minLength'].includes(key)) {
        return;
      }

      switch (key) {
        case 'min':
        case 'max':
          return this[key];

        case 'format':
          return this.getDateFormat();

        default:
          return (0, _get3["default"])((0, _getPrototypeOf2["default"])(DatePicker.prototype), "getValidatorProp", this).call(this, key);
      }
    }
  }, {
    key: "renderLengthInfo",
    value: function renderLengthInfo() {
      return undefined;
    }
  }]);
  return DatePicker;
}(_TriggerField2["default"]);

DatePicker.displayName = 'DatePicker';
DatePicker.defaultProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _TriggerField2["default"].defaultProps), {}, {
  suffixCls: 'calendar-picker',
  mode: _enum.ViewMode.date,
  useInvalidDate: true
});
(0, _tslib.__decorate)([_mobx.computed], DatePicker.prototype, "value", null);
(0, _tslib.__decorate)([_mobx.computed], DatePicker.prototype, "min", null);
(0, _tslib.__decorate)([_mobx.computed], DatePicker.prototype, "max", null);
(0, _tslib.__decorate)([_mobx.observable], DatePicker.prototype, "cursorDate", void 0);
(0, _tslib.__decorate)([_mobx.observable], DatePicker.prototype, "mode", void 0);
(0, _tslib.__decorate)([_mobx.observable], DatePicker.prototype, "hoverValue", void 0);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "savePopupInputEditor", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "defaultRenderer", null);
(0, _tslib.__decorate)([_autobind["default"], _mobx.action], DatePicker.prototype, "handlePopupRangeEditorBlur", null);
(0, _tslib.__decorate)([_mobx.action], DatePicker.prototype, "handleDateMouseEnter", void 0);
(0, _tslib.__decorate)([_mobx.action], DatePicker.prototype, "handleDateMouseLeave", void 0);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "compare", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "handleCursorDateChange", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "handleSelectedDateChange", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "handelViewModeChange", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "handlePopupAnimateEnd", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "handleSelect", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "handleKeyDown", null);
(0, _tslib.__decorate)([_mobx.action], DatePicker.prototype, "handleKeyDownTab", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "handlePopupEditorKeyDown", null);
(0, _tslib.__decorate)([_mobx.action], DatePicker.prototype, "handleEnterDown", null);
(0, _tslib.__decorate)([_mobx.action], DatePicker.prototype, "prepareSetValue", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "getValueKey", null);
(0, _tslib.__decorate)([_mobx.action], DatePicker.prototype, "changeCursorDate", null);
(0, _tslib.__decorate)([_mobx.action], DatePicker.prototype, "setRangeTarget", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "isUnderRange", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "isValidDate", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "isValidNowDate", null);
(0, _tslib.__decorate)([_autobind["default"]], DatePicker.prototype, "isExistValue", null);
DatePicker = (0, _tslib.__decorate)([_mobxReact.observer], DatePicker);
var _default = DatePicker;
exports["default"] = _default;
//# sourceMappingURL=DatePicker.js.map
