"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof = require("@babel/runtime/helpers/typeof");

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

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _newArrowCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/newArrowCheck"));

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

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

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

var _useUncontrolled5 = _interopRequireDefault(require("../../hooks/useUncontrolled"));

var _useLocale = _interopRequireDefault(require("../../components/LocaleProvider/useLocale"));

var _ControllerContext = _interopRequireDefault(require("../../components/Form/ControllerContext"));

var _useDidMount = _interopRequireDefault(require("../../hooks/useDidMount"));

var _isArray = _interopRequireDefault(require("../../utils/isArray"));

var _isNumber = _interopRequireDefault(require("../../utils/isNumber"));

var _pick = _interopRequireDefault(require("../../utils/pick"));

var _RangePicker = _interopRequireDefault(require("./RangePicker"));

var _zh_CN = _interopRequireDefault(require("./locale/zh_CN"));

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

var _style = require("./style");

var _excluded = ["options", "option", "defaultOption", "onOptionChange", "hideOptions", "value", "defaultValue", "onChange", "onInitialChange", "nullable", "size", "display", "format", "rules", "type", "disabled", "zIndex", "locale", "selectProps", "popoverProps", "rangeTip", "status", "placeholder", "shortcuts", "customRender"],
    _excluded2 = ["range"];

var _this = void 0;

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; }

var formatValue = function formatValue(v) {
  var nullable = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  var defaultV = arguments.length > 2 ? arguments[2] : undefined;
  return v == null ? nullable ? null : (0, _moment.default)(+defaultV) : (0, _moment.default)(+v);
};

var formatRangeValue = function formatRangeValue(value) {
  var nullable = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var d = arguments.length > 2 ? arguments[2] : undefined;
  return [formatValue(value[0], nullable[0], d), formatValue(value[1], nullable[1], d)];
};

var getDateFromOption = function getDateFromOption(option) {
  (0, _newArrowCheck2.default)(this, _this);
  if (option === null) return null;

  if (_moment.default.isDate(option) || _moment.default.isMoment(option) || (0, _isNumber.default)(option)) {
    return (0, _moment.default)(option);
  } else {
    return (0, _moment.default)().add(option);
  }
}.bind(void 0);

var getValueFromOption = function getValueFromOption() {
  var _this2 = this;

  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var optionValue = arguments.length > 1 ? arguments[1] : undefined;
  var option = options.find(function (option) {
    (0, _newArrowCheck2.default)(this, _this2);
    return option.value === optionValue;
  }.bind(this));

  var _ref = option || {},
      _ref$range = _ref.range,
      range = _ref$range === void 0 ? {} : _ref$range;

  var s = getDateFromOption(range.start);
  var e = getDateFromOption(range.end);
  return [s, e];
};

var Range = function Range(_ref2) {
  var _this3 = this;

  (0, _newArrowCheck2.default)(this, _this);
  var _options = _ref2.options,
      _option = _ref2.option,
      defaultOption = _ref2.defaultOption,
      _onOptionChange = _ref2.onOptionChange,
      hideOptions = _ref2.hideOptions,
      _value = _ref2.value,
      defaultValue = _ref2.defaultValue,
      _onChange = _ref2.onChange,
      onInitialChange = _ref2.onInitialChange,
      nullable = _ref2.nullable,
      _ref2$size = _ref2.size,
      size = _ref2$size === void 0 ? 'md' : _ref2$size,
      _ref2$display = _ref2.display,
      display = _ref2$display === void 0 ? {} : _ref2$display,
      format = _ref2.format,
      _ref2$rules = _ref2.rules,
      rules = _ref2$rules === void 0 ? {} : _ref2$rules,
      type = _ref2.type,
      disabled = _ref2.disabled,
      zIndex = _ref2.zIndex,
      _locale = _ref2.locale,
      selectProps = _ref2.selectProps,
      popoverProps = _ref2.popoverProps,
      rangeTip = _ref2.rangeTip,
      status = _ref2.status,
      placeholder = _ref2.placeholder,
      shortcuts = _ref2.shortcuts,
      customRender = _ref2.customRender,
      rest = (0, _objectWithoutProperties2.default)(_ref2, _excluded);
  var d = (0, _react.useMemo)(function () {
    (0, _newArrowCheck2.default)(this, _this3);
    return new Date();
  }.bind(this), []);

  var _useState = (0, _react.useState)(false),
      _useState2 = (0, _slicedToArray2.default)(_useState, 2),
      activeS = _useState2[0],
      setActiveS = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
      activeE = _useState4[0],
      setActiveE = _useState4[1];

  var locale = (0, _useLocale.default)(_zh_CN.default, 'DatePicker', _locale);

  var _useUncontrolled = (0, _useUncontrolled5.default)(_option, defaultOption || 'custom', _onOptionChange),
      _useUncontrolled2 = (0, _slicedToArray2.default)(_useUncontrolled, 2),
      option = _useUncontrolled2[0],
      onOptionChange = _useUncontrolled2[1];

  var options = (0, _react.useMemo)(function () {
    (0, _newArrowCheck2.default)(this, _this3);
    return _options ? _options.concat({
      label: locale.custom,
      value: 'custom'
    }) : [];
  }.bind(this), [_options, locale.custom]);

  var _useUncontrolled3 = (0, _useUncontrolled5.default)(_value, defaultValue || [null, null], _onChange),
      _useUncontrolled4 = (0, _slicedToArray2.default)(_useUncontrolled3, 3),
      value = _useUncontrolled4[0],
      onChange = _useUncontrolled4[1],
      updateValueWithoutCallOnChange = _useUncontrolled4[2];

  var _useState5 = (0, _react.useState)(function () {
    (0, _newArrowCheck2.default)(this, _this3);
    return formatRangeValue(value, nullable, d);
  }.bind(this)),
      _useState6 = (0, _slicedToArray2.default)(_useState5, 2),
      cacheValue = _useState6[0],
      setCacheValue = _useState6[1];

  var _useState7 = (0, _react.useState)(),
      _useState8 = (0, _slicedToArray2.default)(_useState7, 2),
      rangeError = _useState8[0],
      setRangeError = _useState8[1];

  var inputRefS = (0, _react.useRef)();
  var inputRefE = (0, _react.useRef)();

  var _useContext = (0, _react.useContext)(_ControllerContext.default),
      contextStatus = _useContext.status;

  var readonly = option !== 'custom';

  var _ref3 = (0, _isArray.default)(nullable) ? nullable : [],
      _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
      nullableS = _ref4[0],
      nullableE = _ref4[1];

  var precision = type === 'month' ? 'month' : null; // eslint-disable-next-line @typescript-eslint/no-unused-vars

  var rangeDisplay = display.range,
      pickerDisplay = (0, _objectWithoutProperties2.default)(display, _excluded2);

  var _ref5 = (0, _isArray.default)(shortcuts) ? shortcuts : [],
      _ref6 = (0, _slicedToArray2.default)(_ref5, 2),
      shortcutsS = _ref6[0],
      shortcutsE = _ref6[1];

  (0, _useDidMount.default)(function () {
    (0, _newArrowCheck2.default)(this, _this3);

    var _ref7 = (0, _isArray.default)(value) ? value : [null, null],
        _ref8 = (0, _slicedToArray2.default)(_ref7, 2),
        valueS = _ref8[0],
        valueE = _ref8[1];

    var initialValue;

    if (option !== 'custom') {
      initialValue = getValueFromOption(options, option);
    } else {
      initialValue = [formatValue(valueS, nullableS, d), formatValue(valueE, nullableE, d)];
    }

    onInitialChange && onInitialChange(initialValue);
    updateValueWithoutCallOnChange(initialValue);
  }.bind(this));
  var handleStartChange = (0, _react.useCallback)(function (value) {
    (0, _newArrowCheck2.default)(this, _this3);

    var _cacheValue = (0, _slicedToArray2.default)(cacheValue, 2),
        valueE = _cacheValue[1];

    var newValue = [value, valueE];
    var rangeDateValidResult = (0, _utils.isRangeDateValid)(newValue, rules, precision);

    if (rangeDateValidResult !== true) {
      setRangeError(rangeDateValidResult);
      inputRefE.current && inputRefE.current.focus();
    } else {
      setRangeError(undefined);
      onChange(newValue);
    }

    setCacheValue(newValue);
  }.bind(this), [onChange, precision, rules, cacheValue]);
  var handleEndChange = (0, _react.useCallback)(function (value) {
    (0, _newArrowCheck2.default)(this, _this3);

    var _cacheValue2 = (0, _slicedToArray2.default)(cacheValue, 1),
        valueS = _cacheValue2[0];

    var newValue = [valueS, value];
    var rangeDateValidResult = (0, _utils.isRangeDateValid)(newValue, rules, precision);

    if (rangeDateValidResult !== true) {
      setRangeError(rangeDateValidResult);
      inputRefS.current && inputRefS.current.focus();
    } else {
      setRangeError(undefined);
      onChange(newValue);
    }

    setCacheValue(newValue);
  }.bind(this), [onChange, precision, rules, cacheValue]);
  var handleOptionChange = (0, _react.useCallback)(function (value) {
    (0, _newArrowCheck2.default)(this, _this3);
    if (value !== 'custom') onChange(getValueFromOption(options, value));
    onOptionChange(value);
  }.bind(this), [onChange, onOptionChange, options]);
  var handleStartActiveChange = (0, _react.useCallback)(function (active) {
    (0, _newArrowCheck2.default)(this, _this3);
    return setActiveS(active);
  }.bind(this), []);
  var handleEndActiveChange = (0, _react.useCallback)(function (active) {
    (0, _newArrowCheck2.default)(this, _this3);
    return setActiveE(active);
  }.bind(this), []);
  var handleInputMouseDown = (0, _react.useCallback)(function (e) {
    (0, _newArrowCheck2.default)(this, _this3);
    if (e.target === e.currentTarget) e.preventDefault();
  }.bind(this), []);
  (0, _react.useEffect)(function () {
    (0, _newArrowCheck2.default)(this, _this3);
    if (activeS || activeE) return;
    setCacheValue(formatRangeValue(value, nullable, d));
  }.bind(this), [activeE, activeS, d, nullable, value]);
  var rangeErrorTip = locale["".concat(rangeError, "Tip")];
  var sharedPickerProps = {
    size: size,
    format: format,
    display: pickerDisplay,
    disabled: disabled,
    popoverProps: popoverProps,
    zIndex: zIndex,
    type: type,
    readonly: readonly,
    tip: rangeTip,
    error: rangeErrorTip,
    rules: rules
  };

  var _cacheValue3 = (0, _slicedToArray2.default)(cacheValue, 2),
      valueS = _cacheValue3[0],
      valueE = _cacheValue3[1];

  var _ref9 = (0, _isArray.default)(placeholder) ? placeholder : [],
      _ref10 = (0, _slicedToArray2.default)(_ref9, 2),
      _ref10$ = _ref10[0],
      placeholderS = _ref10$ === void 0 ? locale.placeholderRangeStart : _ref10$,
      _ref10$2 = _ref10[1],
      placeholderE = _ref10$2 === void 0 ? locale.placeholderRangeEnd : _ref10$2;

  return /*#__PURE__*/_react.default.createElement(_style.RangeContainer, (0, _extends2.default)({}, rest, {
    disabled: disabled
  }), !!options.length && /*#__PURE__*/_react.default.createElement(_style.RangeSelect, (0, _extends2.default)({}, selectProps, {
    options: options.map(function (option) {
      (0, _newArrowCheck2.default)(this, _this3);
      return (0, _pick.default)(option, ['label', 'value', 'disabled']);
    }.bind(this)),
    size: size,
    value: option,
    disabled: disabled,
    onChange: handleOptionChange
  })), readonly && customRender !== null && customRender !== void 0 && customRender.readonlyDisplay ? customRender.readonlyDisplay(cacheValue) : /*#__PURE__*/_react.default.createElement(_style.SRangeInputWrap, {
    size: size,
    disabled: disabled,
    focused: activeS || activeE,
    readonly: readonly,
    onMouseDown: handleInputMouseDown,
    status: status || contextStatus
  }, /*#__PURE__*/_react.default.createElement(_RangePicker.default, (0, _extends2.default)({
    value: valueS,
    onChange: handleStartChange,
    nullable: nullableS,
    prefix: true,
    ref: inputRefS,
    onActiveChange: handleStartActiveChange,
    placeholder: placeholderS,
    shortcuts: shortcutsS,
    footerTip: locale.chooseTipRangeStart
  }, sharedPickerProps)), /*#__PURE__*/_react.default.createElement(_style.RangeDateSeparator, null), /*#__PURE__*/_react.default.createElement(_RangePicker.default, (0, _extends2.default)({
    value: valueE,
    onChange: handleEndChange,
    nullable: nullableE,
    ref: inputRefE,
    onActiveChange: handleEndActiveChange,
    placeholder: placeholderE,
    shortcuts: shortcutsE,
    footerTip: locale.chooseTipRangeEnd
  }, sharedPickerProps))));
}.bind(void 0);

Range.propTypes = {
  onChange: _propTypes.default.func,
  onInitialChange: _propTypes.default.func,
  options: _propTypes.default.arrayOf(_propTypes.default.shape({
    label: _propTypes.default.node.isRequired,
    value: _propTypes.default.string.isRequired,
    disabled: _propTypes.default.bool,
    range: _propTypes.default.shape({})
  })),
  option: _propTypes.default.string,
  defaultOption: _propTypes.default.string,
  onOptionChange: _propTypes.default.func,
  hideOptions: _propTypes.default.bool,
  format: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.arrayOf(_propTypes.default.string)]),
  display: _propTypes.default.shape({
    date: _propTypes.default.shape({
      format: _propTypes.default.string,
      show: _propTypes.default.bool
    }),
    hour: _propTypes.default.bool,
    minute: _propTypes.default.bool,
    second: _propTypes.default.bool,
    range: _propTypes.default.shape({
      format: _propTypes.default.string
    })
  }),
  rules: _propTypes.default.shape({
    maxRange: _propTypes.default.any,
    minRange: _propTypes.default.any
  }),
  status: _propTypes.default.oneOf(['default', 'error']),
  type: _propTypes.default.oneOf(['date', 'month']),
  size: _propTypes.default.oneOf(['sm', 'md', 'lg']),
  disabled: _propTypes.default.bool,
  zIndex: _propTypes.default.number,
  selectProps: _propTypes.default.any,
  popoverProps: _propTypes.default.any,
  customRender: _propTypes.default.shape({
    readonlyDisplay: _propTypes.default.func
  }),
  rangeTip: _propTypes.default.node,
  locale: _propTypes.default.any
};

var _default = /*#__PURE__*/(0, _react.memo)(Range);

exports.default = _default;