"use strict";

exports.__esModule = true;
exports.default = void 0;

var _tslib = require("tslib");

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

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

var _dayjs = _interopRequireDefault(require("dayjs"));

var _meetReactComponentOne = require("@alifd/meet-react-component-one");

var _view = _interopRequireDefault(require("../view"));

var _content = _interopRequireDefault(require("./content"));

var _header = _interopRequireDefault(require("./header"));

var _timePicker = _interopRequireDefault(require("./time-picker"));

var _locale = require("../locale");

var _types = require("./types");

var _date = require("../utils/date");

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

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 _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); }

var defaultLocale = {
  weekdays: ['日', '一', '二', '三', '四', '五', '六'],
  months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  year: '年',
  month: '月',
  day: '日',
  timePickerLabel: '选择时间'
};

function formatValue(value) {
  if (!value) {
    return undefined;
  }

  if (Array.isArray(value)) {
    return value.map(function (it) {
      return (0, _date.toDate)(it);
    });
  }

  return (0, _date.toDate)(value);
}

var Calendar = function (props, ref) {
  var _props$prefix = props.prefix,
      prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
      defaultValue = props.defaultValue,
      value = props.value,
      _props$shape = props.shape,
      shape = _props$shape === void 0 ? 'panel' : _props$shape,
      _props$mode = props.mode,
      mode = _props$mode === void 0 ? 'month' : _props$mode,
      validRange = props.validRange,
      _props$onSelect = props.onSelect,
      onSelect = _props$onSelect === void 0 ? function () {} : _props$onSelect,
      dateCellRender = props.dateCellRender,
      monthCellRender = props.monthCellRender,
      disabledDate = props.disabledDate,
      _onModeChange = props.onModeChange,
      _props$needSlider = props.needSlider,
      needSlider = _props$needSlider === void 0 ? false : _props$needSlider,
      _props$enableYearPick = props.enableYearPicker,
      enableYearPicker = _props$enableYearPick === void 0 ? false : _props$enableYearPick,
      _props$enableTimePick = props.enableTimePicker,
      enableTimePicker = _props$enableTimePick === void 0 ? false : _props$enableTimePick,
      _props$timeFormat = props.timeFormat,
      timeFormat = _props$timeFormat === void 0 ? 'HH:mm:ss' : _props$timeFormat,
      _props$sliderHeight = props.sliderHeight,
      sliderHeight = _props$sliderHeight === void 0 ? (0, _utils.genContentHeight)(mode) : _props$sliderHeight,
      _props$sliderWidth = props.sliderWidth,
      sliderWidth = _props$sliderWidth === void 0 ? '750' : _props$sliderWidth,
      renderCellBottom = props.renderCellBottom,
      renderCellRight = props.renderCellRight,
      renderHeadLeft = props.renderHeadLeft,
      renderHeadRight = props.renderHeadRight,
      firstDay = props.firstDay,
      fixSliderNumber = props.fixSliderNumber,
      others = (0, _tslib.__rest)(props, ["prefix", "defaultValue", "value", "shape", "mode", "validRange", "onSelect", "dateCellRender", "monthCellRender", "disabledDate", "onModeChange", "needSlider", "enableYearPicker", "enableTimePicker", "timeFormat", "sliderHeight", "sliderWidth", "renderCellBottom", "renderCellRight", "renderHeadLeft", "renderHeadRight", "firstDay", "fixSliderNumber"]);
  var locale = (0, _locale.useLocale)('Calendar', others, defaultLocale);

  var selectedDate = function genInitSelectedDate(sValue, dValue, vShape) {
    var tempSDate = sValue || dValue;

    if (tempSDate) {
      return tempSDate;
    }

    if (vShape === 'range') {
      return [];
    }

    if (vShape === 'multi') {
      return [];
    }

    return null;
  }(formatValue(value), formatValue(defaultValue), shape);

  var _useState = (0, _react.useState)(mode),
      currentMode = _useState[0],
      changeCurrentMode = _useState[1];

  var _useState2 = (0, _react.useState)(function genInitVisibleDate(sValue) {
    var date = _utils.NOW;

    if (sValue) {
      if (Array.isArray(sValue)) {
        if (sValue.length > 0) {
          date = sValue[0];
        }
      } else {
        date = sValue;
      }
    }

    if (firstDay && mode === 'week') {
      var tempDay = (0, _dayjs.default)(date).day(firstDay);
      date = new Date(tempDay.valueOf());
    }

    return (0, _utils.cloneDate)(date);
  }(selectedDate)),
      visibleDate = _useState2[0],
      changeVisibleDate = _useState2[1];

  var _getMaxMinDate = (0, _utils.getMaxMinDate)(validRange),
      minDate = _getMaxMinDate[0],
      maxDate = _getMaxMinDate[1];

  var _useState3 = (0, _react.useState)((0, _utils.getTargetDate)(mode, visibleDate, 'pre', maxDate, minDate)),
      preVisibleDate = _useState3[0],
      changePreVisibleDate = _useState3[1];

  var _useState4 = (0, _react.useState)(visibleDate),
      currentVisibleDate = _useState4[0],
      changeCurrentVisibleDate = _useState4[1];

  var _useState5 = (0, _react.useState)((0, _utils.getTargetDate)(mode, visibleDate, 'next', maxDate, minDate)),
      nextVisibleDate = _useState5[0],
      changeNextVisibleDate = _useState5[1];

  var totalPageDates = fixSliderNumber ? (0, _utils.genTotalPageDates)(minDate, maxDate, mode, visibleDate, firstDay) : [];
  var defaultIndex = (0, _utils.getSelectedIndex)(totalPageDates, visibleDate);

  var _useState6 = (0, _react.useState)(defaultIndex),
      currentPage = _useState6[0],
      changeCurrentPage = _useState6[1];

  var _useState7 = (0, _react.useState)(false),
      showYearPicker = _useState7[0],
      setYearPickerShow = _useState7[1];

  var _useState8 = (0, _react.useState)(false),
      showTimePicker = _useState8[0],
      setTimePickerShow = _useState8[1];

  var sliderRef = /*#__PURE__*/(0, _react.createRef)();
  var showTimePickerNode = enableTimePicker && mode === 'month' && shape === 'panel' && !needSlider;

  if (showTimePickerNode && !selectedDate) {
    selectedDate = new Date();
  }

  var renderContent = function () {
    return renderContentWithVisibleDate(visibleDate);
  };

  var renderContentWithVisibleDate = function (visibleD) {
    var contentType = {
      fullscreen: 'fullscreen',
      range: 'range',
      multi: 'multi'
    }[shape] || 'normal';
    return /*#__PURE__*/(0, _react.createElement)(_content.default, {
      prefix: prefix,
      selectedDate: selectedDate,
      visibleDate: visibleD,
      type: contentType,
      firstDay: firstDay,
      mode: _onModeChange ? mode : currentMode,
      enableTimePicker: showTimePickerNode,
      onDateChange: function onDateChange(newValue) {
        if (!onSelect) {
          return;
        }

        if (showTimePickerNode) {
          var _d = selectedDate ? (0, _dayjs.default)(selectedDate) : (0, _dayjs.default)(new Date());

          var h = _d.hour();

          var m = _d.minute();

          var s = _d.second();

          var newDate = (0, _dayjs.default)(newValue).hour(h).minute(m).second(s);
          onSelect(newDate.toDate());
        } else {
          onSelect(newValue);
        }
      },
      maxDate: maxDate,
      minDate: minDate,
      disabledDate: disabledDate,
      locale: locale,
      renderCellBottom: renderCellBottom,
      renderCellRight: renderCellRight,
      dateCellRender: dateCellRender,
      monthCellRender: monthCellRender
    });
  };

  var getShapeType = function () {
    var headerType = _types.HeaderType.normal;

    if (shape === 'fullscreen' || shape === 'card' && mode !== 'week') {
      headerType = _types.HeaderType.select;
    }

    return headerType;
  };

  var genSliderItems = function () {
    var preItem = /*#__PURE__*/(0, _react.createElement)(_meetReactComponentOne.Slider.Item, {
      key: "Slider.Item.0"
    }, renderContentWithVisibleDate(preVisibleDate));
    var currentItem = /*#__PURE__*/(0, _react.createElement)(_meetReactComponentOne.Slider.Item, {
      key: "Slider.Item.1"
    }, renderContentWithVisibleDate(currentVisibleDate));
    var nextItem = /*#__PURE__*/(0, _react.createElement)(_meetReactComponentOne.Slider.Item, {
      key: "Slider.Item.2"
    }, renderContentWithVisibleDate(nextVisibleDate));
    return [preItem, currentItem, nextItem];
  };

  var dealSliderChange = function (oldIndex, newIndex) {
    if (oldIndex === newIndex) {
      return;
    }

    var newVisible;
    var newPre = preVisibleDate;
    var newCurrent = currentVisibleDate;
    var newNext = nextVisibleDate;

    if (oldIndex === 2 && newIndex === 0) {
      newVisible = (0, _utils.getTargetDate)(mode, visibleDate, 'next', maxDate, minDate);
      newCurrent = (0, _utils.getTargetDate)(mode, newVisible, 'next', maxDate, minDate);
    } else {
      if (oldIndex === 0 && newIndex === 2) {
        newVisible = (0, _utils.getTargetDate)(mode, visibleDate, 'pre', maxDate, minDate);
        newCurrent = (0, _utils.getTargetDate)(mode, newVisible, 'pre', maxDate, minDate);
      } else {
        if (newIndex > oldIndex) {
          newVisible = (0, _utils.getTargetDate)(mode, visibleDate, 'next', maxDate, minDate);

          if (newIndex === 1) {
            newNext = (0, _utils.getTargetDate)(mode, newVisible, 'next', maxDate, minDate);
          }

          if (newIndex === 2) {
            newPre = (0, _utils.getTargetDate)(mode, newVisible, 'next', maxDate, minDate);
          }
        }

        if (newIndex < oldIndex) {
          newVisible = (0, _utils.getTargetDate)(mode, visibleDate, 'pre', maxDate, minDate);

          if (newIndex === 0) {
            newNext = (0, _utils.getTargetDate)(mode, newVisible, 'pre', maxDate, minDate);
          }

          if (newIndex === 1) {
            newPre = (0, _utils.getTargetDate)(mode, newVisible, 'pre', maxDate, minDate);
          }
        }
      }
    }

    changeVisibleDate(newVisible);
    changeCurrentVisibleDate(newCurrent);
    changeNextVisibleDate(newNext);
    changePreVisibleDate(newPre);
  };

  var renderFixSliderContent = function () {
    var items = [];

    for (var i = 0; i < totalPageDates.length; i++) {
      items.push( /*#__PURE__*/(0, _react.createElement)(_meetReactComponentOne.Slider.Item, {
        key: 'Slider.Item.' + 'i'
      }, renderContentWithVisibleDate(totalPageDates[i])));
    }

    return /*#__PURE__*/(0, _react.createElement)(_meetReactComponentOne.Slider, {
      ref: sliderRef,
      autoPlay: false,
      showsPagination: false,
      index: defaultIndex,
      loop: false,
      width: sliderWidth,
      height: sliderHeight,
      direction: "horizontal",
      onChange: function onChange(index) {
        changeCurrentPage(index.index);
      }
    }, items);
  };

  var renderSliderContent = function () {
    if (fixSliderNumber) {
      return renderFixSliderContent();
    }

    return /*#__PURE__*/(0, _react.createElement)(_meetReactComponentOne.Slider, {
      autoPlay: false,
      showsPagination: false,
      index: 1,
      width: sliderWidth,
      height: sliderHeight,
      direction: "horizontal",
      onChange: function onChange(index) {
        dealSliderChange(currentPage, index.index);
        changeCurrentPage(index.index);
      }
    }, genSliderItems());
  };

  return /*#__PURE__*/(0, _react.createElement)(_view.default, _extends({
    ref: ref
  }, others, {
    className: (0, _classnames.default)(prefix + "calendar", prefix + "calendar-" + shape, prefix + "calendar-" + shape + "-" + currentMode)
  }), !showTimePicker ? function renderHeader() {
    return /*#__PURE__*/(0, _react.createElement)(_header.default, {
      prefix: prefix,
      date: visibleDate,
      maxDate: maxDate,
      minDate: minDate,
      enableYearPicker: enableYearPicker && !needSlider,
      enableTimePicker: showTimePickerNode,
      mode: _onModeChange ? mode : currentMode,
      type: getShapeType(),
      locale: locale,
      renderHeadLeft: renderHeadLeft,
      renderHeadRight: renderHeadRight,
      onPickerShow: function onPickerShow(show) {
        setYearPickerShow(show);
      },
      onModeChange: function onModeChange(v) {
        if (_onModeChange) {
          _onModeChange(v);

          return;
        }

        changeCurrentMode(v);
      },
      onDateChange: function onDateChange(date, isAdd, changeMode) {
        if (changeMode === 'picker') {
          var d = (0, _dayjs.default)(date);
          var y = d.year();
          var m = d.month();
          var firstDayOfMonth = (0, _dayjs.default)(y + "-" + (m + 1) + "-01");
          var day = (0, _date.isValidDate)(selectedDate) ? (0, _dayjs.default)(selectedDate).date() : 1;

          if (firstDayOfMonth.daysInMonth() < day) {
            day = firstDayOfMonth.daysInMonth();
          }

          if (shape !== 'range' && shape !== 'multi') {
            onSelect((0, _dayjs.default)(y + "-" + (m + 1) + "-" + day).toDate());
          }

          changeVisibleDate(date);
          return;
        }

        if (fixSliderNumber) {
          var sliderIndex = currentPage;

          if (isAdd) {
            sliderIndex = sliderIndex + 1;
          } else {
            sliderIndex = sliderIndex - 1;
          }

          if (sliderIndex >= 0 && sliderIndex <= totalPageDates.length - 1) {
            sliderRef.current.slideTo(sliderIndex);
          }

          return;
        }

        changeVisibleDate(date);
        var newPre;
        var newCurrent;
        var newNext;

        if (isAdd) {
          newPre = (0, _utils.getTargetDate)(changeMode, preVisibleDate, 'next', maxDate, minDate);
          newCurrent = (0, _utils.getTargetDate)(changeMode, currentVisibleDate, 'next', maxDate, minDate);
          newNext = (0, _utils.getTargetDate)(changeMode, nextVisibleDate, 'next', maxDate, minDate);
        } else {
          newPre = (0, _utils.getTargetDate)(changeMode, preVisibleDate, 'pre', maxDate, minDate);
          newCurrent = (0, _utils.getTargetDate)(changeMode, currentVisibleDate, 'pre', maxDate, minDate);
          newNext = (0, _utils.getTargetDate)(changeMode, nextVisibleDate, 'pre', maxDate, minDate);
        }

        changeCurrentVisibleDate(newCurrent);
        changePreVisibleDate(newPre);
        changeNextVisibleDate(newNext);
      }
    });
  }() : null, !showYearPicker && !showTimePicker ? function renderCalendar() {
    var s = getShapeType();

    if (needSlider && s === 'normal') {
      return renderSliderContent();
    }

    return renderContent();
  }() : null, showTimePickerNode && !showYearPicker && /*#__PURE__*/(0, _react.createElement)(_timePicker.default, {
    value: selectedDate,
    format: timeFormat,
    label: locale.timePickerLabel,
    onPickerToggle: function handleTimePickerToggle(show) {
      setTimePickerShow(show);
    },
    onChange: function onChange(date) {
      if (onSelect) {
        onSelect(date);
      }
    }
  }));
};

Calendar.displayName = 'Calendar';

var _default = /*#__PURE__*/(0, _react.forwardRef)(Calendar);

exports.default = _default;