"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; 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); }

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

var _vue = _interopRequireWildcard(require("vue"));

var _select = _interopRequireDefault(require("../select"));

var _radio = require("../radio");

var _vueTypes = _interopRequireDefault(require("../_util/vue-types"));

var _propsUtil = require("../_util/props-util");

var _configProvider = require("../config-provider");

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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var Option = _select.default.Option;

function getMonthsLocale(value) {
  var current = value.clone();
  var localeData = value.localeData();
  var months = [];

  for (var i = 0; i < 12; i++) {
    current.month(i);
    months.push(localeData.monthsShort(current));
  }

  return months;
}

var HeaderProps = {
  prefixCls: _vueTypes.default.string,
  locale: _vueTypes.default.any,
  fullscreen: _vueTypes.default.boolean,
  yearSelectOffset: _vueTypes.default.number,
  yearSelectTotal: _vueTypes.default.number,
  type: _vueTypes.default.string,
  value: _vueTypes.default.any,
  validRange: _vueTypes.default.array,
  headerRender: _vueTypes.default.func,
  onValueChange: _vueTypes.default.func,
  onTypeChange: _vueTypes.default.func
};
exports.HeaderProps = HeaderProps;
var _default2 = {
  name: 'CalendarHeader',
  inheritAttrs: false,
  props: (0, _propsUtil.initDefaultProps)(HeaderProps, {
    yearSelectOffset: 10,
    yearSelectTotal: 20
  }),
  setup: function setup() {
    return {
      configProvider: (0, _vue.inject)('configProvider', _configProvider.ConfigConsumerProps)
    };
  },
  // private calendarHeaderNode: HTMLDivElement;
  methods: {
    getYearSelectElement: function getYearSelectElement(prefixCls, year) {
      var _this = this;

      var yearSelectOffset = this.yearSelectOffset,
          yearSelectTotal = this.yearSelectTotal,
          _this$locale = this.locale,
          locale = _this$locale === void 0 ? {} : _this$locale,
          fullscreen = this.fullscreen,
          validRange = this.validRange;
      var start = year - yearSelectOffset;
      var end = start + yearSelectTotal;

      if (validRange) {
        start = validRange[0].get('year');
        end = validRange[1].get('year') + 1;
      }

      var suffix = locale.year === '年' ? '年' : '';
      var options = [];

      var _loop = function _loop(index) {
        options.push(_vue.createVNode(Option, {
          "key": "".concat(index)
        }, {
          default: function _default() {
            return [function () {
              return index + suffix;
            }()];
          }
        }));
      };

      for (var index = start; index < end; index++) {
        _loop(index);
      }

      return _vue.createVNode(_select.default, {
        "size": fullscreen ? 'default' : 'small',
        "dropdownMatchSelectWidth": false,
        "class": "".concat(prefixCls, "-year-select"),
        "onChange": this.onYearChange,
        "value": String(year),
        "getPopupContainer": function getPopupContainer() {
          return _this.calendarHeaderNode;
        }
      }, {
        default: function _default() {
          return [options];
        }
      });
    },
    getMonthSelectElement: function getMonthSelectElement(prefixCls, month, months) {
      var _this2 = this;

      var fullscreen = this.fullscreen,
          validRange = this.validRange,
          value = this.value;
      var options = [];
      var start = 0;
      var end = 12;

      if (validRange) {
        var _validRange = _slicedToArray(validRange, 2),
            rangeStart = _validRange[0],
            rangeEnd = _validRange[1];

        var currentYear = value.get('year');

        if (rangeEnd.get('year') === currentYear) {
          end = rangeEnd.get('month') + 1;
        }

        if (rangeStart.get('year') === currentYear) {
          start = rangeStart.get('month');
        }
      }

      var _loop2 = function _loop2(index) {
        options.push(_vue.createVNode(Option, {
          "key": "".concat(index)
        }, {
          default: function _default() {
            return [function () {
              return months[index];
            }()];
          }
        }));
      };

      for (var index = start; index < end; index++) {
        _loop2(index);
      }

      return _vue.createVNode(_select.default, {
        "size": fullscreen ? 'default' : 'small',
        "dropdownMatchSelectWidth": false,
        "class": "".concat(prefixCls, "-month-select"),
        "value": String(month),
        "onChange": this.onMonthChange,
        "getPopupContainer": function getPopupContainer() {
          return _this2.calendarHeaderNode;
        }
      }, {
        default: function _default() {
          return [options];
        }
      });
    },
    onYearChange: function onYearChange(year) {
      var value = this.value,
          validRange = this.validRange;
      var newValue = value.clone();
      newValue.year(parseInt(year, 10)); // switch the month so that it remains within range when year changes

      if (validRange) {
        var _validRange2 = _slicedToArray(validRange, 2),
            start = _validRange2[0],
            end = _validRange2[1];

        var newYear = newValue.get('year');
        var newMonth = newValue.get('month');

        if (newYear === end.get('year') && newMonth > end.get('month')) {
          newValue.month(end.get('month'));
        }

        if (newYear === start.get('year') && newMonth < start.get('month')) {
          newValue.month(start.get('month'));
        }
      }

      this.$emit('valueChange', newValue);
    },
    onMonthChange: function onMonthChange(month) {
      var newValue = this.value.clone();
      newValue.month(parseInt(month, 10));
      this.$emit('valueChange', newValue);
    },
    onInternalTypeChange: function onInternalTypeChange(e) {
      this.triggerTypeChange(e.target.value);
    },
    triggerTypeChange: function triggerTypeChange(val) {
      this.$emit('typeChange', val);
    },
    getMonthYearSelections: function getMonthYearSelections(getPrefixCls) {
      var _this$$props = this.$props,
          customizePrefixCls = _this$$props.prefixCls,
          type = _this$$props.type,
          value = _this$$props.value;
      var prefixCls = getPrefixCls('fullcalendar', customizePrefixCls);
      var yearReactNode = this.getYearSelectElement(prefixCls, value.year());
      var monthReactNode = type === 'month' ? this.getMonthSelectElement(prefixCls, value.month(), getMonthsLocale(value)) : null;
      return {
        yearReactNode: yearReactNode,
        monthReactNode: monthReactNode
      };
    },
    getTypeSwitch: function getTypeSwitch() {
      var _this$$props2 = this.$props,
          _this$$props2$locale = _this$$props2.locale,
          locale = _this$$props2$locale === void 0 ? {} : _this$$props2$locale,
          type = _this$$props2.type,
          fullscreen = _this$$props2.fullscreen;
      var size = fullscreen ? 'default' : 'small';
      return _vue.createVNode(_radio.Group, {
        "onChange": this.onInternalTypeChange,
        "value": type,
        "size": size
      }, {
        default: function _default() {
          return [_vue.createVNode(_radio.Button, {
            "value": "month"
          }, {
            default: function _default() {
              return [locale.month];
            }
          }), _vue.createVNode(_radio.Button, {
            "value": "year"
          }, {
            default: function _default() {
              return [locale.year];
            }
          })];
        }
      });
    },
    triggerValueChange: function triggerValueChange() {
      this.$emit.apply(this, ['valueChange'].concat(Array.prototype.slice.call(arguments)));
    },
    saveCalendarHeaderNode: function saveCalendarHeaderNode(node) {
      this.calendarHeaderNode = node;
    },
    headerRenderCustom: function headerRenderCustom(headerRender) {
      var _this$$props3 = this.$props,
          type = _this$$props3.type,
          value = _this$$props3.value;
      return headerRender({
        value: value,
        type: type || 'month',
        onChange: this.triggerValueChange,
        onTypeChange: this.triggerTypeChange
      });
    }
  },
  render: function render() {
    var customizePrefixCls = this.prefixCls,
        headerRender = this.headerRender;
    var getPrefixCls = this.configProvider.getPrefixCls;
    var prefixCls = getPrefixCls('fullcalendar', customizePrefixCls);
    var typeSwitch = this.getTypeSwitch();

    var _this$getMonthYearSel = this.getMonthYearSelections(getPrefixCls),
        yearReactNode = _this$getMonthYearSel.yearReactNode,
        monthReactNode = _this$getMonthYearSel.monthReactNode;

    return headerRender ? this.headerRenderCustom(headerRender) : _vue.createVNode("div", {
      "class": "".concat(prefixCls, "-header"),
      "ref": this.saveCalendarHeaderNode
    }, [yearReactNode, monthReactNode, typeSwitch]);
  }
};
exports.default = _default2;