import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _typeof from "@babel/runtime/helpers/typeof";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _get from "@babel/runtime/helpers/get";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/inherits";
import _createSuper from "@babel/runtime/helpers/createSuper";
import _defineProperty from "@babel/runtime/helpers/defineProperty";

var _viewComponents;

import { __decorate } from "tslib";
import React, { createElement } from 'react';
import moment, { isMoment } from 'moment';
import classNames from 'classnames';
import raf from 'raf';
import defaultTo from 'lodash/defaultTo';
import isPlainObject from 'lodash/isPlainObject';
import isString from 'lodash/isString';
import isNil from 'lodash/isNil';
import noop from 'lodash/noop';
import { observer } from 'mobx-react';
import { action, computed, isArrayLike, observable, runInAction, toJS } from 'mobx';
import KeyCode from '../../../es/_util/KeyCode';
import warning from '../../../es/_util/warning';
import TriggerField from '../trigger-field/TriggerField';
import DaysView from './DaysView';
import DateTimesView from './DateTimesView';
import WeeksView from './WeeksView';
import TimesView from './TimesView';
import MonthsView from './MonthsView';
import YearsView from './YearsView';
import DecadeYearsView from './DecadeYearsView';
import autobind from '../_util/autobind';
import { ViewMode } from './enum';
import { stopEvent } from '../_util/EventManager';
import { $l } from '../locale-context';
import isSame from '../_util/isSame';
import measureTextWidth from '../_util/measureTextWidth';
import ObserverTextField from '../text-field/TextField';
var viewComponents = (_viewComponents = {}, _defineProperty(_viewComponents, ViewMode.decade, DecadeYearsView), _defineProperty(_viewComponents, ViewMode.year, YearsView), _defineProperty(_viewComponents, ViewMode.month, MonthsView), _defineProperty(_viewComponents, ViewMode.date, DaysView), _defineProperty(_viewComponents, ViewMode.dateTime, DateTimesView), _defineProperty(_viewComponents, ViewMode.week, WeeksView), _defineProperty(_viewComponents, ViewMode.time, TimesView), _viewComponents);

function createDefaultTime() {
  return moment('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 !== 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 !== ViewMode.time) {
      defaultTime.subtract(1, 'd');
    }
  }

  return defaultTime;
}

var DatePicker = /*#__PURE__*/function (_TriggerField) {
  _inherits(DatePicker, _TriggerField);

  var _super = _createSuper(DatePicker);

  function DatePicker() {
    var _this;

    _classCallCheck(this, DatePicker);

    _this = _super.apply(this, arguments);

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

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

    return _this;
  }

  _createClass(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 (isArrayLike(value)) {
        return value.map(function (item) {
          if (isArrayLike(item)) {
            return item.map(_this2.checkMoment, _this2);
          }

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

      if (isArrayLike(range)) {
        if (isPlainObject(value)) {
          var _ref;

          var _range = _slicedToArray(range, 2),
              start = _range[0],
              end = _range[1];

          return _ref = {}, _defineProperty(_ref, start, this.checkMoment(value[start])), _defineProperty(_ref, end, this.checkMoment(value[end])), _ref;
        }
      }

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

      runInAction(function () {
        _this3.observableProps.value = value;
      });
    }
  }, {
    key: "defaultValidationMessages",
    get: function get() {
      var label = this.getProp('label');
      return {
        valueMissing: $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) {
        raf(function () {
          node.focus();
        });
      }
    }
  }, {
    key: "isEditable",
    value: function isEditable() {
      return _get(_getPrototypeOf(DatePicker.prototype), "isEditable", this).call(this) && !this.isEditableLike() && this.getViewMode() !== ViewMode.week;
    }
  }, {
    key: "isEditableLike",
    value: function isEditableLike() {
      return this.popup && this.observableProps.editorInPopup;
    }
  }, {
    key: "getOmitPropsKeys",
    value: function getOmitPropsKeys() {
      return _get(_getPrototypeOf(DatePicker.prototype), "getOmitPropsKeys", this).call(this).concat(['mode', 'filter', 'cellRenderer', 'maxLength', 'minLength', 'timeZone', 'editorInPopup', 'defaultTime', 'useInvalidDate']);
    }
  }, {
    key: "getOtherProps",
    value: function getOtherProps() {
      var otherProps = _get(_getPrototypeOf(DatePicker.prototype), "getOtherProps", this).call(this);

      delete otherProps.maxLength;
      return otherProps;
    }
  }, {
    key: "getObservableProps",
    value: function getObservableProps(props, context) {
      return _objectSpread(_objectSpread({}, _get(_getPrototypeOf(DatePicker.prototype), "getObservableProps", this).call(this, props, context)), {}, {
        editorInPopup: props.editorInPopup
      });
    }
  }, {
    key: "defaultRenderer",
    value: function defaultRenderer(props) {
      var renderedText = _get(_getPrototypeOf(DatePicker.prototype), "defaultRenderer", this).call(this, props);

      var mode = this.getDefaultViewMode();
      var value = props.value;

      if (value && [ViewMode.time, 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 (isString(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 (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 === ViewMode.decade || mode === undefined) {
        return ViewMode.date;
      }

      return mode;
    }
  }, {
    key: "getPopupClassName",
    value: function getPopupClassName(defaultClassName) {
      var viewMode = this.getViewMode();
      return classNames(_get(_getPrototypeOf(DatePicker.prototype), "getPopupClassName", this).call(this, defaultClassName), _defineProperty({}, "".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') || _get(_getPrototypeOf(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 = classNames("".concat(prefixCls, "-popup-editor"), (_classNames2 = {}, _defineProperty(_classNames2, "".concat(prefixCls, "-popup-hover-value"), !isNil(popupHoverValue) && !range), _defineProperty(_classNames2, "".concat(prefixCls, "-popup-hover-value-start"), !isNil(popupHoverValue) && range && rangeTarget === 0), _defineProperty(_classNames2, "".concat(prefixCls, "-popup-hover-value-end"), !isNil(popupHoverValue) && range && rangeTarget === 1), _classNames2));

        var _this$getPlaceholders = this.getPlaceholders(),
            _this$getPlaceholders2 = _slicedToArray(_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 = _slicedToArray(_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.createElement("span", {
            key: "popup-editor",
            className: classNames(className, "".concat(prefixCls, "-range-text"))
          }, /*#__PURE__*/React.createElement("input", {
            className: "".concat(prefixCls, "-range-start"),
            onChange: this.handleChange,
            onFocus: this.handleRangeStart,
            onBlur: this.handlePopupRangeEditorBlur,
            value: rangeTarget === 0 ? defaultTo(defaultTo(popupHoverValue, text), startText) : startText,
            placeholder: startPlaceholder,
            ref: rangeTarget === 0 ? this.savePopupInputEditor : undefined,
            onKeyDown: this.handlePopupEditorKeyDown
          }), /*#__PURE__*/React.createElement("span", {
            className: "".concat(prefixCls, "-range-split")
          }, "~"), /*#__PURE__*/React.createElement("input", {
            className: "".concat(prefixCls, "-range-end"),
            onChange: this.handleChange,
            onFocus: this.handleRangeEnd,
            onBlur: this.handlePopupRangeEditorBlur,
            value: rangeTarget === 1 ? defaultTo(defaultTo(popupHoverValue, text), endText) : endText,
            placeholder: endPlaceHolder,
            ref: rangeTarget === 1 ? this.savePopupInputEditor : undefined,
            onKeyDown: this.handlePopupEditorKeyDown
          }));
        }

        var value = isNil(popupHoverValue) ? multiple ? defaultTo(text, '') : this.getTextNode() : popupHoverValue;
        return /*#__PURE__*/React.createElement(ObserverTextField, {
          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 ? measureTextWidth(hoverValue) : 0
          };
        }
      }

      return _get(_getPrototypeOf(DatePicker.prototype), "getEditorTextInfo", this).call(this, rangeTarget);
    }
  }, {
    key: "getRangeInputValue",
    value: function getRangeInputValue(startText, endText) {
      var hoverValue = this.getHoverValue(false);

      if (hoverValue === undefined) {
        return _get(_getPrototypeOf(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 classNames(className, _defineProperty({}, "".concat(prefixCls, "-hover-value"), !isNil(hoverValue)));
    }
  }, {
    key: "getPopupContent",
    value: function getPopupContent() {
      var _this4 = this;

      var mode = this.getViewMode();
      var date = this.getCursorDate();
      return /*#__PURE__*/React.createElement(React.Fragment, null, this.getPopupEditor(), /*#__PURE__*/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 : _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 (isNil(item)) {
        return undefined;
      }

      if (isMoment(item)) {
        return item;
      }

      warning(noCheck, "DatePicker: The value of DatePicker is not moment.");
      var format = this.getDateFormat(field);

      if (item instanceof Date) {
        item = moment(item).format(format);
      }

      var range = this.range,
          rangeTarget = this.rangeTarget;
      var date = moment(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 isSame(this.momentToTimestamp(oldValue), this.momentToTimestamp(newValue));
    }
  }, {
    key: "setText",
    value: function setText(text) {
      _get(_getPrototypeOf(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() {
      _get(_getPrototypeOf(DatePicker.prototype), "afterSetValue", this).call(this);

      this.setText(undefined);
    }
  }, {
    key: "momentToTimestamp",
    value: function momentToTimestamp(value) {
      if (isMoment(value)) {
        return moment(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 && !isNil(cursorDate) && !isMoment(cursorDate)) {
        cursorDate = _typeof(range) === 'object' ? cursorDate[range[rangeTarget]] : cursorDate[rangeTarget];
      }

      if (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 (isNil(limit)) {
        var configLimit = this.getContextConfig(minOrMax);

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

      if (!isNil(limit)) {
        var record = this.record;

        if (record && isString(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(moment(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 = moment();

      if (this.getDefaultViewMode() === 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 !== 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;

      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) {
            raf(function () {
              popupInputEditor.focus();
            });
          }
        } else {
          runInAction(function () {
            _this6.cursorDate = undefined;
            _this6.mode = undefined;
          });
        }
      }
    }
  }, {
    key: "handleSelect",
    value: function handleSelect(date, expand) {
      var mode = this.getDefaultViewMode();
      var formatDate = date;

      if (mode !== ViewMode.week) {
        var format = this.getDateFormat();
        formatDate = moment(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.RIGHT:
            el.handleKeyDownRight(e);
            break;

          case KeyCode.LEFT:
            el.handleKeyDownLeft(e);
            break;

          case KeyCode.DOWN:
            el.handleKeyDownDown(e);
            break;

          case KeyCode.UP:
            el.handleKeyDownUp(e);
            break;

          case KeyCode.END:
            el.handleKeyDownEnd(e);
            break;

          case KeyCode.HOME:
            el.handleKeyDownHome(e);
            break;

          case KeyCode.PAGE_UP:
            el.handleKeyDownPageUp(e);
            break;

          case KeyCode.PAGE_DOWN:
            el.handleKeyDownPageDown(e);
            break;

          case KeyCode.ENTER:
            el.handleKeyDownEnter(e);
            break;

          case KeyCode.TAB:
            this.handleKeyDownTab();
            break;

          case KeyCode.ESC:
            this.handleKeyDownEsc(e);
            break;

          case KeyCode.SPACE:
            this.handleKeyDownSpace(e);
            break;

          case KeyCode.BACKSPACE:
            this.handleKeyDownBackSpace(e);
            break;

          case KeyCode.DELETE:
            this.handleKeyDownDelete(e);
            break;

          default:
        }
      }

      _get(_getPrototypeOf(DatePicker.prototype), "handleKeyDown", this).call(this, e);
    }
  }, {
    key: "handleKeyDownHome",
    value: function handleKeyDownHome(e) {
      if (!this.multiple && !this.editable) {
        stopEvent(e);
        this.choose(this.getCursorDate().startOf('M'));
      }
    }
  }, {
    key: "handleKeyDownEnd",
    value: function handleKeyDownEnd(e) {
      if (!this.multiple && !this.editable) {
        stopEvent(e);
        this.choose(this.getCursorDate().endOf('M'));
      }
    }
  }, {
    key: "handleKeyDownLeft",
    value: function handleKeyDownLeft(e) {
      if (!this.multiple && !this.editable) {
        stopEvent(e);
        this.choose(this.getCursorDate().subtract(1, 'd'));
      }
    }
  }, {
    key: "handleKeyDownRight",
    value: function handleKeyDownRight(e) {
      if (!this.multiple && !this.editable) {
        stopEvent(e);
        this.choose(this.getCursorDate().add(1, 'd'));
      }
    }
  }, {
    key: "handleKeyDownUp",
    value: function handleKeyDownUp(e) {
      if (!this.multiple && !this.editable) {
        stopEvent(e);
        this.choose(this.getCursorDate().subtract(1, 'w'));
      }
    }
  }, {
    key: "handleKeyDownDown",
    value: function handleKeyDownDown(e) {
      if (this.multiple) {
        this.expand();
      } else if (!this.editable) {
        stopEvent(e);
        this.choose(this.getCursorDate().add(1, 'w'));
      }
    }
  }, {
    key: "handleKeyDownPageUp",
    value: function handleKeyDownPageUp(e) {
      if (!this.multiple && !this.editable) {
        stopEvent(e);
        this.choose(this.getCursorDate().subtract(1, e.altKey ? 'y' : 'M'));
      }
    }
  }, {
    key: "handleKeyDownPageDown",
    value: function handleKeyDownPageDown(e) {
      if (!this.multiple && !this.editable) {
        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) && !isNil(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)) {
        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 (isNil(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.BACKSPACE && length === 1 && selectionStart === 1 || keyCode === KeyCode.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.BACKSPACE:
            this.handleKeyDownBackSpace(e);
            break;

          case KeyCode.DELETE:
            this.handleKeyDownDelete(e);
            break;

          default:
        }
      }
    }
  }, {
    key: "handleEnterDown",
    value: function handleEnterDown(e) {
      _get(_getPrototypeOf(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 = _get(_getPrototypeOf(DatePicker.prototype), "prepareSetValue", this)).call.apply(_get2, [this].concat(_toConsumableArray(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 (isArrayLike(v)) {
        return v.map(this.getValueKey, this).join(',');
      }

      if (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 = _slicedToArray(_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);
        }
      }

      _get(_getPrototypeOf(DatePicker.prototype), "exchangeRangeValue", this).call(this, start, end);
    }
  }, {
    key: "changeCursorDate",
    value: function changeCursorDate(cursorDate) {
      if (this.rangeValueExchange) {
        if (this.range && !isNil(this.rangeTarget) && this.rangeValue) {
          var _ref2 = _toConsumableArray(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) {
            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 (!isNil(target)) {
        this.cursorDate = undefined;
      } else {
        if (isNil(this.cursorDate)) {
          this.cursorDate = this.getCursorDate();
        }

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

      _get(_getPrototypeOf(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 ViewMode.month:
            start = start.startOf('M');
            end = end.endOf('M');
            break;

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

          case 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 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, 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(moment());

      if (isValid && filter) {
        return filter(moment(), selected, this.getViewMode(), this.rangeTarget, 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 && isArrayLike(value) && !range) {
        var mode = this.getDefaultViewMode();
        var format = this.getDateFormat();
        var now = moment().format(format);

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

          case 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 _get(_getPrototypeOf(DatePicker.prototype), "getValidatorProp", this).call(this, key);
      }
    }
  }, {
    key: "renderLengthInfo",
    value: function renderLengthInfo() {
      return undefined;
    }
  }]);

  return DatePicker;
}(TriggerField);

DatePicker.displayName = 'DatePicker';
DatePicker.defaultProps = _objectSpread(_objectSpread({}, TriggerField.defaultProps), {}, {
  suffixCls: 'calendar-picker',
  mode: ViewMode.date,
  useInvalidDate: true
});

__decorate([computed], DatePicker.prototype, "value", null);

__decorate([computed], DatePicker.prototype, "min", null);

__decorate([computed], DatePicker.prototype, "max", null);

__decorate([observable], DatePicker.prototype, "cursorDate", void 0);

__decorate([observable], DatePicker.prototype, "mode", void 0);

__decorate([observable], DatePicker.prototype, "hoverValue", void 0);

__decorate([autobind], DatePicker.prototype, "savePopupInputEditor", null);

__decorate([autobind], DatePicker.prototype, "defaultRenderer", null);

__decorate([autobind, action], DatePicker.prototype, "handlePopupRangeEditorBlur", null);

__decorate([action], DatePicker.prototype, "handleDateMouseEnter", void 0);

__decorate([action], DatePicker.prototype, "handleDateMouseLeave", void 0);

__decorate([autobind], DatePicker.prototype, "compare", null);

__decorate([autobind], DatePicker.prototype, "handleCursorDateChange", null);

__decorate([autobind], DatePicker.prototype, "handleSelectedDateChange", null);

__decorate([autobind], DatePicker.prototype, "handelViewModeChange", null);

__decorate([autobind], DatePicker.prototype, "handlePopupAnimateEnd", null);

__decorate([autobind], DatePicker.prototype, "handleSelect", null);

__decorate([autobind], DatePicker.prototype, "handleKeyDown", null);

__decorate([action], DatePicker.prototype, "handleKeyDownTab", null);

__decorate([autobind], DatePicker.prototype, "handlePopupEditorKeyDown", null);

__decorate([action], DatePicker.prototype, "handleEnterDown", null);

__decorate([action], DatePicker.prototype, "prepareSetValue", null);

__decorate([autobind], DatePicker.prototype, "getValueKey", null);

__decorate([action], DatePicker.prototype, "changeCursorDate", null);

__decorate([action], DatePicker.prototype, "setRangeTarget", null);

__decorate([autobind], DatePicker.prototype, "isUnderRange", null);

__decorate([autobind], DatePicker.prototype, "isValidDate", null);

__decorate([autobind], DatePicker.prototype, "isValidNowDate", null);

__decorate([autobind], DatePicker.prototype, "isExistValue", null);

DatePicker = __decorate([observer], DatePicker);
export default DatePicker;
//# sourceMappingURL=DatePicker.js.map
