"use strict";

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

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

var _propTypes = _interopRequireDefault(require("prop-types"));

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

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

var _zhCn = _interopRequireDefault(require("../locale/zh-cn"));

var _util = require("../util");

var _cardHeader = _interopRequireDefault(require("./head/card-header"));

var _datePanelHeader = _interopRequireDefault(require("./head/date-panel-header"));

var _monthPanelHeader = _interopRequireDefault(require("./head/month-panel-header"));

var _yearPanelHeader = _interopRequireDefault(require("./head/year-panel-header"));

var _dateTable = _interopRequireDefault(require("./table/date-table"));

var _monthTable = _interopRequireDefault(require("./table/month-table"));

var _yearTable = _interopRequireDefault(require("./table/year-table"));

var _utils = require("./utils");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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

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

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

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

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

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

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

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

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

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

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

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

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

  function Calendar(props, context) {
    var _this;

    _classCallCheck(this, Calendar);

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

    _defineProperty(_assertThisInitialized(_this), "onSelectCell", function (date, nextMode) {
      var shape = _this.props.shape;

      _this.changeVisibleMonth(date, 'cellClick'); // 当用户所在的面板为初始化面板时，则选择动作为触发 onSelect 回调


      if (_this.state.mode === _this.MODES[0]) {
        _this.props.onSelect(date);
      }

      if (shape === 'panel') {
        _this.changeMode(nextMode);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "changeMode", function (nextMode) {
      if (nextMode && _this.MODES.indexOf(nextMode) > -1 && nextMode !== _this.state.mode) {
        _this.setState({
          mode: nextMode
        });

        _this.props.onModeChange(nextMode);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "changeVisibleMonth", function (date, reason) {
      if (!(0, _utils.isSameYearMonth)(date, _this.state.visibleMonth)) {
        _this.setState({
          visibleMonth: date
        });

        _this.props.onVisibleMonthChange(date, reason);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "goPrevDecade", function () {
      _this.changeVisibleMonthByOffset(-12, 'years');
    });

    _defineProperty(_assertThisInitialized(_this), "goNextDecade", function () {
      _this.changeVisibleMonthByOffset(12, 'years');
    });

    _defineProperty(_assertThisInitialized(_this), "goPrevYear", function () {
      _this.changeVisibleMonthByOffset(-1, 'years');
    });

    _defineProperty(_assertThisInitialized(_this), "goNextYear", function () {
      _this.changeVisibleMonthByOffset(1, 'years');
    });

    _defineProperty(_assertThisInitialized(_this), "goPrevMonth", function () {
      _this.changeVisibleMonthByOffset(-1, 'months');
    });

    _defineProperty(_assertThisInitialized(_this), "goNextMonth", function () {
      _this.changeVisibleMonthByOffset(1, 'months');
    });

    var value = (0, _utils.formatDateValue)(props.value || props.defaultValue);
    var visibleMonth = (0, _utils.getVisibleMonth)(props.defaultVisibleMonth, value);
    _this.MODES = props.modes;
    _this.today = (0, _moment["default"])();
    _this.state = {
      value: value,
      mode: props.mode || _this.MODES[0],
      visibleMonth: visibleMonth
    };
    return _this;
  }

  _createClass(Calendar, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      if ('value' in nextProps && nextProps.value !== this.props.value) {
        var value = (0, _utils.formatDateValue)(nextProps.value);
        this.setState({
          value: value
        });

        if (value) {
          this.setState({
            visibleMonth: value
          });
        }
      }

      if (nextProps.mode && this.MODES.indexOf(nextProps.mode) > -1) {
        this.setState({
          mode: nextProps.mode
        });
      }
    }
  }, {
    key: "changeVisibleMonthByOffset",

    /**
     * 根据日期偏移量设置当前展示的月份
     * @param {Number} offset 日期偏移的数量
     * @param {String} type 日期偏移的类型 days, months, years
     */
    value: function changeVisibleMonthByOffset(offset, type) {
      var cloneValue = this.state.visibleMonth.clone();
      cloneValue.add(offset, type);
      this.changeVisibleMonth(cloneValue, 'buttonClick');
    }
  }, {
    key: "render",
    value: function render() {
      var _classnames, _tables, _panelHeaders;

      var _this$props = this.props,
          prefix = _this$props.prefix,
          rtl = _this$props.rtl,
          className = _this$props.className,
          shape = _this$props.shape,
          showOtherMonth = _this$props.showOtherMonth,
          format = _this$props.format,
          locale = _this$props.locale,
          dateCellRender = _this$props.dateCellRender,
          monthCellRender = _this$props.monthCellRender,
          yearCellRender = _this$props.yearCellRender,
          disabledDate = _this$props.disabledDate,
          yearRange = _this$props.yearRange,
          others = _objectWithoutProperties(_this$props, ["prefix", "rtl", "className", "shape", "showOtherMonth", "format", "locale", "dateCellRender", "monthCellRender", "yearCellRender", "disabledDate", "yearRange"]);

      var state = this.state;
      var classNames = (0, _classnames2["default"])((_classnames = {}, _defineProperty(_classnames, "".concat(prefix, "calendar"), true), _defineProperty(_classnames, "".concat(prefix, "calendar-").concat(shape), shape), _classnames), className);

      if (rtl) {
        others.dir = 'rtl';
      }

      var visibleMonth = state.visibleMonth; // reset moment locale

      if (locale.momentLocale) {
        state.value && state.value.locale(locale.momentLocale);
        visibleMonth.locale(locale.momentLocale);
      }

      var localeData = (0, _utils.getLocaleData)(locale.format || {}, visibleMonth.localeData());
      var headerProps = {
        prefix: prefix,
        lang: locale.momentLocale,
        value: state.value,
        mode: state.mode,
        modes: this.MODES,
        locale: locale,
        rtl: rtl,
        visibleMonth: visibleMonth,
        momentLocale: localeData,
        changeMode: this.changeMode,
        changeVisibleMonth: this.changeVisibleMonth,
        goNextDecade: this.goNextDecade,
        goNextYear: this.goNextYear,
        goNextMonth: this.goNextMonth,
        goPrevDecade: this.goPrevDecade,
        goPrevYear: this.goPrevYear,
        goPrevMonth: this.goPrevMonth
      };
      var tableProps = {
        prefix: prefix,
        visibleMonth: visibleMonth,
        showOtherMonth: showOtherMonth,
        value: state.value,
        mode: state.mode,
        locale: locale,
        dateCellRender: dateCellRender,
        monthCellRender: monthCellRender,
        yearCellRender: yearCellRender,
        disabledDate: disabledDate,
        momentLocale: localeData,
        today: this.today,
        goPrevDecade: this.goPrevDecade,
        goNextDecade: this.goNextDecade
      };
      var tables = (_tables = {}, _defineProperty(_tables, _utils.CALENDAR_MODE_DATE, _react["default"].createElement(_dateTable["default"], _extends({
        format: format
      }, tableProps, {
        onSelectDate: this.onSelectCell
      }))), _defineProperty(_tables, _utils.CALENDAR_MODE_MONTH, _react["default"].createElement(_monthTable["default"], _extends({}, tableProps, {
        onSelectMonth: this.onSelectCell
      }))), _defineProperty(_tables, _utils.CALENDAR_MODE_YEAR, _react["default"].createElement(_yearTable["default"], _extends({}, tableProps, {
        rtl: rtl,
        onSelectYear: this.onSelectCell
      }))), _tables);
      var panelHeaders = (_panelHeaders = {}, _defineProperty(_panelHeaders, _utils.CALENDAR_MODE_DATE, _react["default"].createElement(_datePanelHeader["default"], headerProps)), _defineProperty(_panelHeaders, _utils.CALENDAR_MODE_MONTH, _react["default"].createElement(_monthPanelHeader["default"], headerProps)), _defineProperty(_panelHeaders, _utils.CALENDAR_MODE_YEAR, _react["default"].createElement(_yearPanelHeader["default"], headerProps)), _panelHeaders);
      return _react["default"].createElement("div", _extends({}, _util.obj.pickOthers(Calendar.propTypes, others), {
        className: classNames
      }), shape === 'panel' ? panelHeaders[state.mode] : _react["default"].createElement(_cardHeader["default"], _extends({}, headerProps, {
        yearRange: yearRange
      })), tables[state.mode]);
    }
  }]);

  return Calendar;
}(_react.Component);

_defineProperty(Calendar, "displayName", 'Calendar');

_defineProperty(Calendar, "propTypes", {
  prefix: _propTypes["default"].string,
  rtl: _propTypes["default"].bool,

  /**
   * 默认选中的日期（moment 对象）
   */
  defaultValue: _utils.checkMomentObj,

  /**
   * 选中的日期值 (moment 对象)
   */
  value: _utils.checkMomentObj,

  /**
   * 面板模式
   */
  mode: _propTypes["default"].oneOf(_utils.CALENDAR_MODES),
  // 生成 API 文档需要手动改回 ['date', 'month', 'year']
  // 面板可变化的模式列表，仅初始化时接收一次
  modes: _propTypes["default"].array,
  // 日期值的格式（用于日期title显示的格式）
  format: _propTypes["default"].string,

  /**
   * 是否展示非本月的日期
   */
  showOtherMonth: _propTypes["default"].bool,

  /**
   * 默认展示的月份
   */
  defaultVisibleMonth: _propTypes["default"].func,

  /**
   * 展现形态
   */
  shape: _propTypes["default"].oneOf(['card', 'fullscreen', 'panel']),

  /**
   * 选择日期单元格时的回调
   * @param {Object} value 对应的日期值 (moment 对象)
   */
  onSelect: _propTypes["default"].func,

  /**
   * 面板模式变化时的回调
   * @param {String} mode 对应面板模式 date month year
   */
  onModeChange: _propTypes["default"].func,

  /**
   * 展现的月份变化时的回调
   * @param {Object} value 显示的月份 (moment 对象)
   * @param {String} reason 触发月份改变原因
   */
  onVisibleMonthChange: _propTypes["default"].func,

  /**
   * 自定义样式类
   */
  className: _propTypes["default"].string,

  /**
   * 自定义日期渲染函数
   * @param {Object} value 日期值（moment对象）
   * @returns {ReactNode}
   */
  dateCellRender: _propTypes["default"].func,

  /**
   * 自定义月份渲染函数
   * @param {Object} calendarDate 对应 Calendar 返回的自定义日期对象
   * @returns {ReactNode}
   */
  monthCellRender: _propTypes["default"].func,
  yearCellRender: _propTypes["default"].func,
  // 兼容 0.x yearCellRender

  /**
   * 年份范围，[START_YEAR, END_YEAR] (只在shape 为 ‘card’, 'fullscreen' 下生效)
   */
  yearRange: _propTypes["default"].arrayOf(_propTypes["default"].number),

  /**
   * 不可选择的日期
   * @param {Object} calendarDate 对应 Calendar 返回的自定义日期对象
   * @param {String} view 当前视图类型，year: 年， month: 月, date: 日
   * @returns {Boolean}
   */
  disabledDate: _propTypes["default"].func,

  /**
   * 国际化配置
   */
  locale: _propTypes["default"].object
});

_defineProperty(Calendar, "defaultProps", {
  prefix: 'next-',
  rtl: false,
  shape: 'fullscreen',
  modes: _utils.CALENDAR_MODES,
  format: 'YYYY-MM-DD',
  onSelect: _util.func.noop,
  onVisibleMonthChange: _util.func.noop,
  onModeChange: _util.func.noop,
  dateCellRender: function dateCellRender(value) {
    return value.date() < 10 ? "0".concat(value.date()) : value.date();
  },
  locale: _zhCn["default"].Calendar,
  showOtherMonth: true
});

var _default = Calendar;
exports["default"] = _default;