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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(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; }

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import moment from 'moment';
import Overlay from '../overlay';
import Input from '../input';
import Calendar from '../calendar';
import nextLocale from '../locale/zh-cn';
import { func, obj } from '../util';
import { checkDateValue, formatDateValue, onDateKeydown } from './util';
var Popup = Overlay.Popup;
/**
 * DatePicker.MonthPicker
 */

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

  function MonthPicker(props, context) {
    var _this;

    _classCallCheck(this, MonthPicker);

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

    _defineProperty(_assertThisInitialized(_this), "getOverlay", function () {
      return _this.popup && _this.popup.getInstance() && _this.popup.getInstance().getOverlay();
    });

    _defineProperty(_assertThisInitialized(_this), "onValueChange", function (newValue) {
      var ret = _this.inputAsString && newValue ? newValue.format(_this.props.format) : newValue;

      _this.props.onChange(ret);
    });

    _defineProperty(_assertThisInitialized(_this), "onSelectCalendarPanel", function (value) {
      // const { format } = this.props;
      var prevSelectedMonth = _this.state.value;
      var selectedMonth = value.clone().date(1).hour(0).minute(0).second(0);

      _this.handleChange(selectedMonth, prevSelectedMonth, {
        inputing: false
      }, function () {
        _this.onVisibleChange(false, 'calendarSelect');
      });
    });

    _defineProperty(_assertThisInitialized(_this), "clearValue", function () {
      _this.setState({
        dateInputStr: ''
      });

      _this.handleChange(null, _this.state.value);
    });

    _defineProperty(_assertThisInitialized(_this), "onDateInputChange", function (inputStr, e, eventType) {
      if (eventType === 'clear' || !inputStr) {
        e.stopPropagation();

        _this.clearValue();
      } else {
        _this.setState({
          dateInputStr: inputStr,
          inputing: true
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onDateInputBlur", function () {
      var dateInputStr = _this.state.dateInputStr;

      if (dateInputStr) {
        var _this$props = _this.props,
            disabledDate = _this$props.disabledDate,
            format = _this$props.format;
        var parsed = moment(dateInputStr, format, true);

        _this.setState({
          dateInputStr: '',
          inputing: false
        });

        if (parsed.isValid() && !disabledDate(parsed, 'month')) {
          _this.handleChange(parsed, _this.state.value);
        }
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onKeyDown", function (e) {
      var format = _this.props.format;
      var _this$state = _this.state,
          dateInputStr = _this$state.dateInputStr,
          value = _this$state.value;
      var dateStr = onDateKeydown(e, {
        format: format,
        dateInputStr: dateInputStr,
        value: value
      }, 'month');
      if (!dateStr) return;

      _this.onDateInputChange(dateStr);
    });

    _defineProperty(_assertThisInitialized(_this), "handleChange", function (newValue, prevValue) {
      var others = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      var callback = arguments.length > 3 ? arguments[3] : undefined;

      if (!('value' in _this.props)) {
        _this.setState(_objectSpread({
          value: newValue
        }, others));
      } else {
        _this.setState(_objectSpread({}, others));
      }

      var format = _this.props.format;
      var newValueOf = newValue ? newValue.format(format) : null;
      var preValueOf = prevValue ? prevValue.format(format) : null;

      if (newValueOf !== preValueOf) {
        _this.onValueChange(newValue);

        if (typeof callback === 'function') {
          return callback();
        }
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onVisibleChange", function (visible, type) {
      if (!('visible' in _this.props)) {
        _this.setState({
          visible: visible
        });
      }

      _this.props.onVisibleChange(visible, type);
    });

    var _value = formatDateValue(props.value || props.defaultValue, props.format);

    _this.inputAsString = typeof (props.value || props.defaultValue) === 'string'; // 判断用户输入是否是字符串

    _this.state = {
      value: _value,
      dateInputStr: '',
      inputing: false,
      visible: props.visible || props.defaultVisible
    };
    _this.popup = null;
    return _this;
  }

  _createClass(MonthPicker, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      if ('value' in nextProps) {
        var value = formatDateValue(nextProps.value, nextProps.format || this.props.format);
        this.setState({
          value: value
        });
        this.inputAsString = typeof nextProps.value === 'string';
      }

      if ('visible' in nextProps) {
        this.setState({
          visible: nextProps.visible
        });
      }
    } // 获取底层的overlay实例

  }, {
    key: "render",
    value: function render() {
      var _classnames2,
          _this2 = this;

      var _this$props2 = this.props,
          prefix = _this$props2.prefix,
          rtl = _this$props2.rtl,
          locale = _this$props2.locale,
          label = _this$props2.label,
          state = _this$props2.state,
          format = _this$props2.format,
          defaultVisibleYear = _this$props2.defaultVisibleYear,
          disabledDate = _this$props2.disabledDate,
          footerRender = _this$props2.footerRender,
          placeholder = _this$props2.placeholder,
          size = _this$props2.size,
          disabled = _this$props2.disabled,
          hasClear = _this$props2.hasClear,
          popupTriggerType = _this$props2.popupTriggerType,
          popupAlign = _this$props2.popupAlign,
          popupContainer = _this$props2.popupContainer,
          popupStyle = _this$props2.popupStyle,
          popupClassName = _this$props2.popupClassName,
          popupProps = _this$props2.popupProps,
          followTrigger = _this$props2.followTrigger,
          className = _this$props2.className,
          inputProps = _this$props2.inputProps,
          monthCellRender = _this$props2.monthCellRender,
          yearCellRender = _this$props2.yearCellRender,
          dateInputAriaLabel = _this$props2.dateInputAriaLabel,
          others = _objectWithoutProperties(_this$props2, ["prefix", "rtl", "locale", "label", "state", "format", "defaultVisibleYear", "disabledDate", "footerRender", "placeholder", "size", "disabled", "hasClear", "popupTriggerType", "popupAlign", "popupContainer", "popupStyle", "popupClassName", "popupProps", "followTrigger", "className", "inputProps", "monthCellRender", "yearCellRender", "dateInputAriaLabel"]);

      var _this$state2 = this.state,
          visible = _this$state2.visible,
          value = _this$state2.value,
          dateInputStr = _this$state2.dateInputStr,
          inputing = _this$state2.inputing;
      var monthPickerCls = classnames(_defineProperty({}, "".concat(prefix, "month-picker"), true), className);
      var triggerInputCls = classnames((_classnames2 = {}, _defineProperty(_classnames2, "".concat(prefix, "month-picker-input"), true), _defineProperty(_classnames2, "".concat(prefix, "error"), false), _classnames2));
      var panelBodyClassName = classnames(_defineProperty({}, "".concat(prefix, "month-picker-body"), true));

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

      var panelInputCls = "".concat(prefix, "month-picker-panel-input");

      var sharedInputProps = _objectSpread({}, inputProps, {
        size: size,
        disabled: disabled,
        onChange: this.onDateInputChange,
        onBlur: this.onDateInputBlur,
        onPressEnter: this.onDateInputBlur,
        onKeyDown: this.onKeyDown
      });

      var dateInputValue = inputing ? dateInputStr : value && value.format(format) || '';
      var triggerInputValue = dateInputValue;
      var dateInput = React.createElement(Input, _extends({}, sharedInputProps, {
        hasClear: true,
        size: "xs",
        value: dateInputValue,
        "aria-label": dateInputAriaLabel,
        onFocus: this.onFoucsDateInput,
        placeholder: format,
        className: panelInputCls
      }));
      var datePanel = React.createElement(Calendar, {
        shape: "panel",
        modes: ['month', 'year'],
        monthCellRender: monthCellRender,
        yearCellRender: yearCellRender,
        value: value,
        onSelect: this.onSelectCalendarPanel,
        defaultVisibleMonth: defaultVisibleYear,
        disabledDate: disabledDate
      });
      var panelBody = datePanel;
      var panelFooter = footerRender();
      var allowClear = value && hasClear;
      var trigger = React.createElement("div", {
        className: "".concat(prefix, "month-picker-trigger")
      }, React.createElement(Input, _extends({}, sharedInputProps, {
        label: label,
        state: state,
        readOnly: true,
        value: triggerInputValue,
        placeholder: placeholder || locale.monthPlaceholder,
        hint: "calendar",
        hasClear: allowClear,
        className: triggerInputCls
      })));
      return React.createElement("div", _extends({}, obj.pickOthers(MonthPicker.propTypes, others), {
        className: monthPickerCls
      }), React.createElement(Popup, _extends({
        offset: [0, 4]
      }, popupProps, {
        followTrigger: followTrigger,
        autoFocus: true,
        ref: function ref(popup) {
          _this2.popup = popup;
        },
        role: "combobox",
        "aria-expanded": visible,
        disabled: disabled,
        visible: visible,
        onVisibleChange: this.onVisibleChange,
        align: popupAlign,
        triggerType: popupTriggerType,
        container: popupContainer,
        style: popupStyle,
        className: popupClassName,
        trigger: trigger
      }), React.createElement("div", {
        className: panelBodyClassName,
        dir: others.dir
      }, React.createElement("div", {
        className: "".concat(prefix, "month-picker-panel-header")
      }, dateInput), panelBody, panelFooter)));
    }
  }]);

  return MonthPicker;
}(Component);

_defineProperty(MonthPicker, "propTypes", {
  prefix: PropTypes.string,
  rtl: PropTypes.bool,

  /**
   * 输入框内置标签
   */
  label: PropTypes.node,

  /**
   * 输入框状态
   */
  state: PropTypes.oneOf(['success', 'loading', 'error']),

  /**
   * 输入提示
   */
  placeholder: PropTypes.string,

  /**
   * 默认展现的年
   * @return {MomentObject} 返回包含指定年份的 moment 对象实例
   */
  defaultVisibleYear: PropTypes.func,

  /**
   * 日期值（受控）moment 对象
   */
  value: checkDateValue,

  /**
   * 初始日期值，moment 对象
   */
  defaultValue: checkDateValue,

  /**
   * 日期值的格式（用于限定用户输入和展示）
   */
  format: PropTypes.string,

  /**
   * 禁用日期函数
   * @param {MomentObject} 日期值
   * @param {String} view 当前视图类型，year: 年， month: 月, date: 日
   * @return {Boolean} 是否禁用
   */
  disabledDate: PropTypes.func,

  /**
   * 自定义面板页脚
   * @return {Node} 自定义的面板页脚组件
   */
  footerRender: PropTypes.func,

  /**
   * 日期值改变时的回调
   * @param {MomentObject|String} value 日期值
   */
  onChange: PropTypes.func,

  /**
   * 输入框尺寸
   */
  size: PropTypes.oneOf(['small', 'medium']),

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

  /**
   * 是否显示清空按钮
   */
  hasClear: PropTypes.bool,

  /**
   * 弹层显示状态
   */
  visible: PropTypes.bool,

  /**
   * 弹层默认是否显示
   */
  defaultVisible: PropTypes.bool,

  /**
   * 弹层展示状态变化时的回调
   * @param {Boolean} visible 弹层是否显示
   * @param {String} type 触发弹层显示和隐藏的来源 calendarSelect 表示由日期表盘的选择触发； fromTrigger 表示由trigger的点击触发； docClick 表示由document的点击触发
   */
  onVisibleChange: PropTypes.func,

  /**
   * 弹层触发方式
   */
  popupTriggerType: PropTypes.oneOf(['click', 'hover']),

  /**
   * 弹层对齐方式, 具体含义见 OverLay文档
   */
  popupAlign: PropTypes.string,

  /**
   * 弹层容器
   * @param {Element} target 目标元素
   * @return {Element} 弹层的容器元素
   */
  popupContainer: PropTypes.func,

  /**
   * 弹层自定义样式
   */
  popupStyle: PropTypes.object,

  /**
   * 弹层自定义样式类
   */
  popupClassName: PropTypes.string,

  /**
   * 弹层其他属性
   */
  popupProps: PropTypes.object,

  /**
   * 是否跟随滚动
   */
  followTrigger: PropTypes.bool,

  /**
   * 输入框其他属性
   */
  inputProps: PropTypes.object,

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

  /**
   * 日期输入框的 aria-label 属性
   */
  dateInputAriaLabel: PropTypes.string,
  locale: PropTypes.object,
  className: PropTypes.string
});

_defineProperty(MonthPicker, "defaultProps", {
  prefix: 'next-',
  rtl: false,
  format: 'YYYY/MM',
  size: 'medium',
  disabledDate: function disabledDate() {
    return false;
  },
  footerRender: function footerRender() {
    return null;
  },
  hasClear: true,
  popupTriggerType: 'click',
  popupAlign: 'tl bl',
  locale: nextLocale.DatePicker,
  onChange: func.noop,
  onVisibleChange: func.noop
});

export default MonthPicker;