import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import Input from '../input';
import CalendarToday from '../icons/internals/CalendarToday';
import Calendar from './Calendar';
import Button from '../button';
import Tooltip from '../tooltip';

function getPanelDate(value) {
  if (moment(value[0]).isSameOrAfter(moment(value[1]), 'month')) {
    return {
      startPanelDate: moment(value[0]),
      endPanelDate: moment(value[0]).add(1, 'month')
    };
  }

  return {
    startPanelDate: value[0] ? value[0] : moment(value[0]),
    endPanelDate: value[1] ? value[1] : moment(value[1])
  };
}

var DateRangePicker =
/*#__PURE__*/
function (_Component) {
  _inherits(DateRangePicker, _Component);

  _createClass(DateRangePicker, null, [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(props, state) {
      var defaultValue = props.defaultValue;

      if (defaultValue !== state.prevDefaultValue) {
        return {
          value: defaultValue,
          prevDefaultValue: defaultValue
        };
      }

      return null;
    }
  }]);

  function DateRangePicker(props) {
    var _this;

    _classCallCheck(this, DateRangePicker);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(DateRangePicker).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "handleValueChange", function (date) {
      var onChange = _this.props.onChange;
      if (_this.inputRef) _this.inputRef.focus();
      var newValue = [];

      _this.setState(function (state) {
        if (state.value.length === 0 || state.value.length === 2) {
          newValue = [date];
        } else if (!state.value[0].isSame(date)) {
          newValue = [state.value[0], date];
        } else {
          newValue = [state.value[0], moment(date).add(1, 'second')];
        }

        newValue.sort(function (a, b) {
          return a > b ? 1 : -1;
        });

        if (onChange && newValue.length !== 1) {
          onChange(newValue);
        }

        return {
          value: newValue
        };
      });
    });

    _defineProperty(_assertThisInitialized(_this), "handleTimeChange", function (time, type) {
      var onChange = _this.props.onChange;
      if (_this.inputRef) _this.inputRef.focus();

      _this.setState(function (state) {
        var newValue = _toConsumableArray(state.value);

        if (type === 'start') {
          newValue[0] = time;
        } else {
          newValue[1] = time;
        }

        if (onChange && newValue.length !== 1) {
          onChange(newValue);
        }

        return {
          value: newValue
        };
      });
    });

    _defineProperty(_assertThisInitialized(_this), "handlePanelTypeChange", function (type) {
      _this.setState({
        panelType: type
      });
    });

    _defineProperty(_assertThisInitialized(_this), "handleClose", function () {
      var value = _this.state.value;
      var onChange = _this.props.onChange;

      if (value && value.length !== 2) {
        if (onChange) {
          onChange([]);
        }

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

    _defineProperty(_assertThisInitialized(_this), "handleClear", function () {
      var onChange = _this.props.onChange;

      if (onChange) {
        onChange([]);
      }

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

    _defineProperty(_assertThisInitialized(_this), "handleStartPanelDateChange", function (value) {
      _this.setState({
        startPanelDate: value
      });
    });

    _defineProperty(_assertThisInitialized(_this), "handleEndPanelDateChange", function (value) {
      _this.setState(function (state) {
        return {
          endPanelDate: moment(state.startPanelDate).isSameOrAfter(moment(value), 'month') ? value.add(1, 'month') : value
        };
      });
    });

    _defineProperty(_assertThisInitialized(_this), "startDisabledMonth", function (date) {
      var endPanelDate = _this.state.endPanelDate;
      return date >= moment(endPanelDate).startOf('month');
    });

    _defineProperty(_assertThisInitialized(_this), "endDisabledMonth", function (date) {
      var startPanelDate = _this.state.startPanelDate;
      return date <= moment(startPanelDate).endOf('month');
    });

    _defineProperty(_assertThisInitialized(_this), "startDisabledYear", function (date) {
      var value = _this.state.value;
      return date.isAfter(moment(value[1]), 'year');
    });

    _defineProperty(_assertThisInitialized(_this), "endDisabledYear", function (date) {
      var value = _this.state.value;
      return date.isBefore(moment(value[0]), 'year');
    });

    _defineProperty(_assertThisInitialized(_this), "startDisabledDate", function (date) {
      var disabledDate = _this.props.disabledDate;
      var endPanelDate = _this.state.endPanelDate;
      return date > moment(endPanelDate).startOf('month') || disabledDate && disabledDate(date);
    });

    _defineProperty(_assertThisInitialized(_this), "endDisabledDate", function (date) {
      var disabledDate = _this.props.disabledDate;
      var startPanelDate = _this.state.startPanelDate;
      return date < moment(startPanelDate).endOf('month') || disabledDate && disabledDate(date);
    });

    _defineProperty(_assertThisInitialized(_this), "getInputRef", function (el) {
      _this.inputRef = el;
    });

    var defaultValue = props.defaultValue,
        selectType = props.selectType;
    _this.state = _objectSpread({
      prevDefaultValue: defaultValue,
      value: defaultValue,
      panelType: selectType
    }, getPanelDate(defaultValue));
    return _this;
  }

  _createClass(DateRangePicker, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          prefixCls = _this$props.prefixCls,
          format = _this$props.format,
          disabled = _this$props.disabled,
          inputProps = _this$props.inputProps,
          size = _this$props.size,
          readOnly = _this$props.readOnly,
          separator = _this$props.separator,
          showTime = _this$props.showTime,
          status = _this$props.status,
          clearable = _this$props.clearable,
          onChange = _this$props.onChange,
          clearIcon = _this$props.clearIcon,
          errorIcon = _this$props.errorIcon,
          loadingIcon = _this$props.loadingIcon,
          showStatusIcon = _this$props.showStatusIcon,
          suffix = _this$props.suffix,
          disabledDate = _this$props.disabledDate,
          successIcon = _this$props.successIcon,
          prefix = _this$props.prefix,
          scrollContainer = _this$props.scrollContainer,
          other = _objectWithoutProperties(_this$props, ["prefixCls", "format", "disabled", "inputProps", "size", "readOnly", "separator", "showTime", "status", "clearable", "onChange", "clearIcon", "errorIcon", "loadingIcon", "showStatusIcon", "suffix", "disabledDate", "successIcon", "prefix", "scrollContainer"]);

      var _this$state = this.state,
          value = _this$state.value,
          startPanelDate = _this$state.startPanelDate,
          endPanelDate = _this$state.endPanelDate,
          panelType = _this$state.panelType;
      return React.createElement(Tooltip, {
        position: "bottom",
        onClose: this.handleClose,
        className: prefixCls,
        trigger: "click",
        autoAdjustPosition: true,
        scrollContainer: scrollContainer,
        content: React.createElement(Input, _extends({
          "aria-haspopup": "true",
          prefix: prefix,
          className: "".concat(prefixCls, "-input-container"),
          disabled: disabled,
          clearable: clearable,
          onClear: this.handleClear,
          clearIcon: clearIcon,
          errorIcon: errorIcon,
          loadingIcon: loadingIcon,
          suffix: suffix,
          inputRef: this.getInputRef,
          successIcon: successIcon,
          status: status,
          showStatusIcon: showStatusIcon,
          value: value[0] ? value[0].format(format) : ''
        }, inputProps, {
          mask: React.createElement("div", {
            className: "".concat(prefixCls, "-input")
          }, React.createElement("span", {
            className: "".concat(prefixCls, "-input-base ").concat(prefixCls, "-input-base-begin")
          }, value[0] ? value[0].format(format) : ''), React.createElement("span", {
            className: "".concat(prefixCls, "-input-seperator")
          }, separator), React.createElement("span", {
            className: "".concat(prefixCls, "-input-base ").concat(prefixCls, "-input-base-end")
          }, value[1] ? value[1].format(format) : '')),
          size: size
        }))
      }, React.createElement("div", {
        className: "".concat(prefixCls, "-calendar-unity")
      }, React.createElement(Calendar, _extends({}, other, {
        endPanelDate: endPanelDate // forceUpdate
        ,
        panelType: panelType,
        onPanelTypeChange: this.handlePanelTypeChange,
        onPanelDateChange: this.handleStartPanelDateChange,
        disabledMonth: this.startDisabledMonth,
        disabledYear: this.startDisabledYear,
        rangeType: "start",
        value: value,
        disabledDate: this.startDisabledDate,
        onValueChange: this.handleValueChange,
        onTimeChange: this.handleTimeChange,
        panelDate: startPanelDate
      })), React.createElement(Calendar, _extends({}, other, {
        startPanelDate: startPanelDate // forceUpdate
        ,
        panelType: panelType,
        disabledMonth: this.endDisabledMonth,
        disabledYear: this.endDisabledYear,
        rangeType: "end",
        value: value,
        onPanelDateChange: this.handleEndPanelDateChange,
        onPanelTypeChange: this.handlePanelTypeChange,
        onValueChange: this.handleValueChange,
        onTimeChange: this.handleTimeChange,
        disabledDate: this.endDisabledDate,
        panelDate: endPanelDate
      }))), value && value.length === 2 && showTime && (panelType === 'date' || panelType === 'time') ? React.createElement("div", {
        className: "".concat(prefixCls, "-footer")
      }, panelType === 'date' ? React.createElement(Button, {
        variant: "text",
        onClick: function onClick() {
          return _this2.handlePanelTypeChange('time');
        }
      }, "\u65F6\u95F4") : panelType === 'time' ? React.createElement(Button, {
        variant: "text",
        onClick: function onClick() {
          return _this2.handlePanelTypeChange('date');
        }
      }, "\u65E5\u671F") : null) : null);
    }
  }]);

  return DateRangePicker;
}(Component);

_defineProperty(DateRangePicker, "propTypes", {
  /**
   * 类前缀
   * */
  prefixCls: PropTypes.string,

  /**
   * 分隔符
   * */
  separator: PropTypes.node,

  /**
   * 选择类型
   * */
  selectType: PropTypes.oneOf(['date', 'month', 'year']),

  /**
   * 是否禁用
   */
  disabled: PropTypes.bool,

  /**
   * 日期显示格式
   */
  format: PropTypes.string,

  /**
   * 是否可以选择时刻
   */
  showTime: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),

  /**
   * 后缀
   */
  suffix: PropTypes.node,

  /**
   * 占位文本
   */
  placeholder: PropTypes.node,

  /**
   * input元素的值，受控模式下使用
   */
  defaultValue: PropTypes.arrayOf(PropTypes.object),

  /**
   * 不可选择的时间范围
   */
  disabledTime: PropTypes.func,

  /**
   *  scrollContainer Tooltip兼容自定义可滚动容器
   */
  scrollContainer: PropTypes.node
});

_defineProperty(DateRangePicker, "defaultProps", {
  disabled: false,
  format: 'YYYY-MM-DD',
  clearable: false,
  separator: '~',
  selectType: 'date',
  showTime: false,
  suffix: React.createElement(CalendarToday, null),
  prefixCls: 'ne-date-range-picker',
  defaultValue: [],
  scrollContainer: ''
});

export default DateRangePicker;