"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

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

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

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

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

var _timerPickerInput = _interopRequireDefault(require("./timer-picker-input"));

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

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

require("./index.css");

var _excluded = ["disabled", "enableKeyBoard", "timeFormat", "hourStep", "minuteStep", "onChange", "value"];

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

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

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) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_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; }

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

var TimePicker = function TimePicker(props) {
  var disabled = props.disabled,
      _props$enableKeyBoard = props.enableKeyBoard,
      enableKeyBoard = _props$enableKeyBoard === void 0 ? true : _props$enableKeyBoard,
      _props$timeFormat = props.timeFormat,
      timeFormat = _props$timeFormat === void 0 ? 'hh:mm' : _props$timeFormat,
      _props$hourStep = props.hourStep,
      hourStep = _props$hourStep === void 0 ? 1 : _props$hourStep,
      _props$minuteStep = props.minuteStep,
      minuteStep = _props$minuteStep === void 0 ? 1 : _props$minuteStep,
      onChange = props.onChange,
      _props$value = props.value,
      value = _props$value === void 0 ? '00:00' : _props$value,
      restProps = _objectWithoutProperties(props, _excluded);

  var _useState = (0, _react.useState)(''),
      _useState2 = _slicedToArray(_useState, 2),
      timeSetingtType = _useState2[0],
      setTimeSettingType = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      visible = _useState4[0],
      setVisible = _useState4[1];

  var hourRef = (0, _react.useRef)((0, _moment["default"])(value || '00:00', timeFormat).format('HH'));
  var hInputRef = (0, _react.useRef)();
  var mInputRef = (0, _react.useRef)();
  var minuteRef = (0, _react.useRef)((0, _moment["default"])(value || '00:00', timeFormat).format('mm'));
  var triggerRef = (0, _react.useRef)();
  var hours = (0, _utils.getHours)(hourStep);
  var minutes = (0, _utils.getMinutes)(minuteStep);

  var onTimeChange = function onTimeChange() {
    return onChange === null || onChange === void 0 ? void 0 : onChange("".concat(hourRef.current, ":").concat(minuteRef.current));
  };

  var onInputClickHandler = function onInputClickHandler(type) {
    return setTimeSettingType(function () {
      return type;
    });
  };

  var onKeyDownHandler = function onKeyDownHandler(e) {
    var keyCode = e.keyCode;

    if ([_utils.KEYCODE.directionLeft, _utils.KEYCODE.directionRight].includes(keyCode)) {
      setTimeSettingType(_utils.TargetMapByKeyCode[keyCode]);
    }

    if ([_utils.KEYCODE.directionUp, _utils.KEYCODE.directionDown].includes(keyCode)) {
      switch (timeSetingtType) {
        case 'hour':
          hourRef.current = setTimeOnKeyboardDirectionChange(keyCode, 'hour', hourRef.current);
          break;

        case 'minute':
          minuteRef.current = setTimeOnKeyboardDirectionChange(keyCode, 'minute', minuteRef.current);
          break;

        default:
          break;
      }

      onTimeChange();
    }
  };

  var onHourInputChange = function onHourInputChange(e) {
    var v = e.target.value;

    if (!Number.isNaN(Number(v))) {
      // setHour(v);
      hourRef.current = v;
      setTimeout(function () {
        if (hInputRef.current) {
          hInputRef.current.blur();
        }
      }, 1000);
      onTimeChange();
    }
  };

  var onMinuteInputChange = function onMinuteInputChange(e) {
    var v = e.target.value;

    if (!Number.isNaN(Number(v))) {
      // setMinute(v);
      minuteRef.current = v;
      setTimeout(function () {
        if (mInputRef.current) {
          mInputRef.current.blur();
        }
      }, 1000);
      onTimeChange();
    }
  };

  var setTimeOnKeyboardDirectionChange = function setTimeOnKeyboardDirectionChange(keyCode, type, currTime) {
    var datas = JSON.parse(JSON.stringify(type === 'hour' ? hours : minutes));
    var currentTimeIndex;
    datas.forEach(function (item, index) {
      if (item === currTime) {
        currentTimeIndex = index;
      } else if (item < currTime) {
        var nextIndex = index + 1;
        var nextData = datas[nextIndex];

        if (!nextData || nextData && nextData > currTime) {
          currentTimeIndex = keyCode === _utils.KEYCODE.directionUp || !nextData ? index : nextIndex;
        }
      }
    });

    if (keyCode === _utils.KEYCODE.directionUp) {
      // 方向键：↑
      var nextIndex = currentTimeIndex + 1 === datas.length ? 0 : currentTimeIndex + 1;
      var nextValue = datas[nextIndex];

      if (currentTimeIndex > -1 && !!nextValue) {
        if (type === 'minute' && nextValue === datas[0]) {
          hourRef.current = setTimeOnKeyboardDirectionChange(keyCode, 'hour', hourRef.current);
        }

        return nextValue;
      }
    } else if (keyCode === _utils.KEYCODE.directionDown) {
      // 方向键：↓
      var prevIndex = currentTimeIndex - 1 < 0 ? datas.length - 1 : currentTimeIndex - 1;
      var prevValue = datas[prevIndex];

      if (currentTimeIndex > -1 && !!prevValue) {
        if (type === 'minute' && prevValue === datas[datas.length - 1]) {
          hourRef.current = setTimeOnKeyboardDirectionChange(keyCode, 'hour', hourRef.current);
        }

        return prevValue;
      }
    }

    return currTime;
  };

  var showSelectorPop = function showSelectorPop() {
    return setVisible(true);
  };

  return /*#__PURE__*/_react["default"].createElement("div", {
    className: _utils.TimePickerClass
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(_utils.TimePickerClass, "-trigger"), _defineProperty({}, "".concat(_utils.TimePickerClass, "-trigger--disabled"), disabled)),
    ref: triggerRef
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(_utils.TimePickerClass, "-inputs"), _defineProperty({}, "".concat(_utils.TimePickerClass, "-inputs--placeholder"), !value)),
    onClick: function onClick() {
      return !enableKeyBoard && showSelectorPop();
    }
  }, /*#__PURE__*/_react["default"].createElement(_timerPickerInput["default"], _extends({
    className: (0, _classnames["default"])("".concat(_utils.TimePickerClass, "-input"), {
      active: enableKeyBoard && timeSetingtType === 'hour'
    }),
    disabled: disabled,
    maxLength: 2,
    onChange: onHourInputChange,
    onClick: function onClick() {
      return onInputClickHandler('hour');
    },
    onKeyDown: onKeyDownHandler,
    ref: hInputRef,
    value: hourRef.current
  }, restProps)), /*#__PURE__*/_react["default"].createElement("span", null, ":"), /*#__PURE__*/_react["default"].createElement(_timerPickerInput["default"], {
    className: (0, _classnames["default"])("".concat(_utils.TimePickerClass, "-input"), {
      active: enableKeyBoard && timeSetingtType === 'minute'
    }),
    disabled: disabled,
    maxLength: 2,
    onChange: onMinuteInputChange,
    onClick: function onClick() {
      return onInputClickHandler('minute');
    },
    onKeyDown: onKeyDownHandler,
    ref: mInputRef,
    value: minuteRef.current
  })), !disabled && /*#__PURE__*/_react["default"].createElement(_timePickerSelector["default"], _extends({
    popupAlign: {
      offset: [12, 8],
      overflow: {
        adjustX: true,
        adjustY: true
      },
      targetOffset: [0, 0]
    },
    timeData: {
      hours: hours,
      minutes: minutes
    },
    timeSetting: {
      hour: hourRef.current,
      minute: minuteRef.current,
      setTime: function setTime(time) {
        hourRef.current = (0, _moment["default"])(time, 'HH:mm').format('HH');
        minuteRef.current = (0, _moment["default"])(time, 'HH:mm').format('mm');
        onChange(time);
      }
    },
    visibleSetting: {
      visible: visible,
      setVisible: setVisible
    }
  }, restProps), /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(_utils.TimePickerClass, "-icon tu-icon-caret-down"),
    onClick: showSelectorPop
  }))));
};

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