function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { CalendarOutlined, CloseOutlined } from '@ant-design/icons';
import { Button, ConfigProvider, DatePicker, Input, Popover, Radio, Slider, Switch } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import moment from 'moment';
import RangeCalendar from 'rc-calendar/lib/RangeCalendar';
import enUS from 'rc-calendar/lib/locale/en_US';
import zhCN from 'rc-calendar/lib/locale/zh_CN';
import zhHK from 'rc-calendar/lib/locale/zh_TW';
import TimePickerPanel from 'rc-time-picker/lib/Panel';
import React, { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import 'rc-calendar/assets/index.css';
import 'rc-time-picker/assets/index.css';
import "./index.less";
dayjs.extend(customParseFormat);
var RangePicker = DatePicker.RangePicker;
var DEFAULT_DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
var DEFAULT_QUICK_TIME_OPTIONS = [{
  id: 1,
  value: 1,
  label: '5分钟',
  diff: 5 * 60 * 1000,
  interval: 1,
  timeUnitId: 1
}, {
  id: 2,
  value: 2,
  label: '1小时',
  diff: 60 * 60 * 1000,
  interval: 2,
  timeUnitId: 2
}, {
  id: 3,
  value: 3,
  label: '6小时',
  diff: 6 * 60 * 60 * 1000,
  interval: 4,
  timeUnitId: 2
}, {
  id: 4,
  value: 4,
  label: '12小时',
  diff: 12 * 60 * 60 * 1000,
  interval: 5,
  timeUnitId: 4
}, {
  id: 5,
  value: 5,
  label: '1天',
  diff: 24 * 60 * 60 * 1000,
  interval: 6,
  timeUnitId: 5
}, {
  id: 6,
  value: 6,
  label: '7天',
  diff: 7 * 24 * 60 * 60 * 1000,
  interval: 5,
  timeUnitId: 5
}];
var LOCALE_TEXT = {
  'zh-CN': {
    recent: '最近',
    custom: '指定时间',
    confirm: '确定'
  },
  'zh-HK': {
    recent: '最近',
    custom: '指定時間',
    confirm: '確定'
  },
  'en-US': {
    recent: 'Recent',
    custom: 'Custom',
    confirm: 'Confirm'
  }
};
var CALENDAR_LOCALE_MAP = {
  'zh-CN': zhCN,
  'zh-HK': zhHK,
  'en-US': enUS
};
var PRIMARY = 'var(--ant-color-primary, #1677ff)';
var TEXT_SECONDARY = 'rgba(0, 0, 0, 0.65)';
var DateRangePicker = function DateRangePicker(props) {
  var _quickTimeOptions$2;
  var onChange = props.onChange,
    value = props.value,
    _props$format = props.format,
    format = _props$format === void 0 ? DEFAULT_DATE_TIME_FORMAT : _props$format,
    _props$placement = props.placement,
    placement = _props$placement === void 0 ? 'bottomLeft' : _props$placement,
    _props$quickTimeOptio = props.quickTimeOptions,
    quickTimeOptions = _props$quickTimeOptio === void 0 ? DEFAULT_QUICK_TIME_OPTIONS : _props$quickTimeOptio,
    disabledDate = props.disabledDate,
    width = props.width,
    disabled = props.disabled,
    _props$flat = props.flat,
    flat = _props$flat === void 0 ? false : _props$flat;
  var _useContext = useContext(ConfigProvider.ConfigContext),
    antdLocale = _useContext.locale;
  var currentLocale = useMemo(function () {
    var localeName = antdLocale === null || antdLocale === void 0 ? void 0 : antdLocale.locale;
    if (localeName === 'zh-cn' || localeName === 'zh_CN') {
      return 'zh-CN';
    }
    if (localeName === 'zh-hk' || localeName === 'zh_HK' || localeName === 'zh-tw' || localeName === 'zh_TW') {
      return 'zh-HK';
    }
    if (localeName === 'en' || localeName === 'en-us' || localeName === 'en_US') {
      return 'en-US';
    }
    return 'zh-CN';
  }, [antdLocale]);
  var i18n = useMemo(function () {
    return LOCALE_TEXT[currentLocale];
  }, [currentLocale]);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    visible = _useState2[0],
    setVisible = _useState2[1];
  var _useState3 = useState(true),
    _useState4 = _slicedToArray(_useState3, 2),
    isRecent = _useState4[0],
    setIsRecent = _useState4[1];
  var _useState5 = useState(function () {
      var _quickTimeOptions$0$v, _quickTimeOptions$;
      return (_quickTimeOptions$0$v = (_quickTimeOptions$ = quickTimeOptions[0]) === null || _quickTimeOptions$ === void 0 ? void 0 : _quickTimeOptions$.value) !== null && _quickTimeOptions$0$v !== void 0 ? _quickTimeOptions$0$v : DEFAULT_QUICK_TIME_OPTIONS[0].value;
    }),
    _useState6 = _slicedToArray(_useState5, 2),
    sliderValue = _useState6[0],
    setSliderValue = _useState6[1];
  var _useState7 = useState([dayjs().subtract(1, 'day'), dayjs()]),
    _useState8 = _slicedToArray(_useState7, 2),
    selectTimeRange = _useState8[0],
    setSelectTimeRange = _useState8[1];
  var _useState9 = useState([moment().subtract(1, 'days'), moment()]),
    _useState10 = _slicedToArray(_useState9, 2),
    customTimeRange = _useState10[0],
    setCustomTimeRange = _useState10[1];
  var _useState11 = useState(''),
    _useState12 = _slicedToArray(_useState11, 2),
    displayValue = _useState12[0],
    setDisplayValue = _useState12[1];
  var _useState13 = useState((_quickTimeOptions$2 = quickTimeOptions[0]) === null || _quickTimeOptions$2 === void 0 ? void 0 : _quickTimeOptions$2.id),
    _useState14 = _slicedToArray(_useState13, 2),
    flatRadioValue = _useState14[0],
    setFlatRadioValue = _useState14[1];
  var marks = useMemo(function () {
    var marksObj = {};
    quickTimeOptions.forEach(function (option) {
      marksObj[option.value] = option.label;
    });
    return marksObj;
  }, [quickTimeOptions]);
  var sliderRange = useMemo(function () {
    var values = quickTimeOptions.map(function (opt) {
      return opt.value;
    });
    return {
      min: Math.min.apply(Math, _toConsumableArray(values)),
      max: Math.max.apply(Math, _toConsumableArray(values))
    };
  }, [quickTimeOptions]);
  var setRangeByDate = useCallback(function (from, to) {
    setSelectTimeRange([from, to]);
    setCustomTimeRange([moment(from.valueOf()), moment(to.valueOf())]);
  }, []);
  var calculateInterval = useCallback(function (fromTime, toTime) {
    var diff = dayjs(toTime).valueOf() - dayjs(fromTime).valueOf();
    var hours = diff / (60 * 60 * 1000);
    if (hours <= 1) {
      return {
        interval: 1,
        timeUnitId: 1
      };
    }
    if (hours <= 6) {
      return {
        interval: 2,
        timeUnitId: 2
      };
    }
    if (hours <= 24) {
      return {
        interval: 5,
        timeUnitId: 4
      };
    }
    if (hours <= 72) {
      return {
        interval: 15,
        timeUnitId: 4
      };
    }
    return {
      interval: 30,
      timeUnitId: 4
    };
  }, []);
  useEffect(function () {
    if (value) {
      var sValue = value.sliderValue,
        from = value.from,
        to = value.to;
      var fromD = dayjs(from, format, true);
      var toD = dayjs(to, format, true);
      var safeFrom = fromD.isValid() ? fromD : dayjs(from);
      var safeTo = toD.isValid() ? toD : dayjs(to);
      setRangeByDate(safeFrom, safeTo);
      if (sValue !== null && sValue !== undefined) {
        setIsRecent(true);
        setSliderValue(sValue);
        var option = quickTimeOptions.find(function (opt) {
          return opt.id === value.id || opt.value === sValue;
        });
        if (option) {
          setDisplayValue(option.label);
          if (flat) {
            setFlatRadioValue(option.id);
          }
        }
      } else {
        setIsRecent(false);
        setDisplayValue("".concat(from, " - ").concat(to));
        if (flat) {
          setFlatRadioValue(undefined);
        }
      }
    } else if (quickTimeOptions.length > 0) {
      var defaultOption = quickTimeOptions[0];
      var _to = dayjs();
      var _from = dayjs().subtract(defaultOption.diff, 'millisecond');
      setSliderValue(defaultOption.value);
      setDisplayValue(defaultOption.label);
      setRangeByDate(_from, _to);
      if (flat) {
        setFlatRadioValue(defaultOption.id);
      }
    }
  }, [value, quickTimeOptions, flat, format, setRangeByDate]);
  var handleRecentSave = useCallback(function () {
    var option = quickTimeOptions.find(function (opt) {
      return opt.value === sliderValue;
    });
    if (!option) {
      return;
    }
    var to = Date.now();
    var from = to - option.diff;
    var fromDay = dayjs(from);
    var toDay = dayjs(to);
    setRangeByDate(fromDay, toDay);
    var timeInfo = {
      inputValue: option.label,
      from: fromDay.format(format),
      to: toDay.format(format),
      diff: option.diff,
      sliderValue: sliderValue,
      interval: option.interval,
      timeUnitId: option.timeUnitId,
      id: option.id
    };
    setDisplayValue(timeInfo.inputValue);
    setVisible(false);
    onChange === null || onChange === void 0 || onChange(timeInfo);
  }, [sliderValue, format, onChange, quickTimeOptions, setRangeByDate]);
  var handleCustomRangeChange = useCallback(function (dates) {
    if ((dates === null || dates === void 0 ? void 0 : dates.length) === 2) {
      setCustomTimeRange(dates);
    }
  }, []);
  var commitCustomRange = useCallback(function () {
    var from = customTimeRange[0].format(format);
    var to = customTimeRange[1].format(format);
    var diff = customTimeRange[1].valueOf() - customTimeRange[0].valueOf();
    var interval = calculateInterval(from, to);
    var inputValue = "".concat(from, " - ").concat(to);
    setSelectTimeRange([dayjs(customTimeRange[0].valueOf()), dayjs(customTimeRange[1].valueOf())]);
    var timeInfo = _objectSpread({
      inputValue: inputValue,
      from: from,
      to: to,
      diff: diff,
      sliderValue: null
    }, interval);
    setDisplayValue(inputValue);
    setVisible(false);
    onChange === null || onChange === void 0 || onChange(timeInfo);
  }, [customTimeRange, format, calculateInterval, onChange]);
  var wrappedDisabledDateForCalendar = useCallback(function (current, options) {
    var _options$from$map, _options$from;
    if (!disabledDate) {
      return false;
    }
    var fromArr = (_options$from$map = options === null || options === void 0 || (_options$from = options.from) === null || _options$from === void 0 ? void 0 : _options$from.map(function (item) {
      return dayjs(item.valueOf());
    })) !== null && _options$from$map !== void 0 ? _options$from$map : [];
    var currentDayjs = current ? dayjs(current.valueOf()) : null;
    return disabledDate(currentDayjs, {
      from: fromArr
    });
  }, [disabledDate]);
  var wrappedDisabledDateForAntd = useCallback(function (current, info) {
    if (!disabledDate) {
      return false;
    }
    var fromArr = info.from ? [info.from] : [];
    return disabledDate(current, {
      from: fromArr
    });
  }, [disabledDate]);
  var handleFlatRadioChange = useCallback(function (e) {
    var selectedId = e.target.value;
    setFlatRadioValue(selectedId);
    var option = quickTimeOptions.find(function (opt) {
      return opt.id === selectedId;
    });
    if (!option) {
      return;
    }
    var to = dayjs();
    var from = dayjs().subtract(option.diff, 'millisecond');
    setRangeByDate(from, to);
    var timeInfo = {
      inputValue: option.label,
      from: from.format(format),
      to: to.format(format),
      diff: option.diff,
      sliderValue: option.value,
      interval: option.interval,
      timeUnitId: option.timeUnitId,
      id: option.id
    };
    onChange === null || onChange === void 0 || onChange(timeInfo);
  }, [quickTimeOptions, format, onChange, setRangeByDate]);
  var handleFlatRangeChange = useCallback(function (dates) {
    if (!(dates !== null && dates !== void 0 && dates[0]) || !(dates !== null && dates !== void 0 && dates[1])) {
      return;
    }
    var _dates = _slicedToArray(dates, 2),
      from = _dates[0],
      to = _dates[1];
    setRangeByDate(from, to);
    setFlatRadioValue(undefined);
    var diff = to.valueOf() - from.valueOf();
    var interval = calculateInterval(from.format(format), to.format(format));
    var timeInfo = _objectSpread({
      inputValue: "".concat(from.format(format), " - ").concat(to.format(format)),
      from: from.format(format),
      to: to.format(format),
      diff: diff,
      sliderValue: null
    }, interval);
    onChange === null || onChange === void 0 || onChange(timeInfo);
  }, [format, calculateInterval, onChange, setRangeByDate]);
  var popoverContent = /*#__PURE__*/React.createElement("div", {
    className: "hc-date-range-picker-content"
  }, /*#__PURE__*/React.createElement("div", {
    className: "hc-date-range-picker-header",
    style: isRecent ? undefined : {
      borderBottom: 'none'
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: "hc-date-range-picker-switch"
  }, /*#__PURE__*/React.createElement("span", {
    style: {
      color: isRecent ? PRIMARY : TEXT_SECONDARY
    }
  }, i18n.recent), /*#__PURE__*/React.createElement(Switch, {
    checked: !isRecent,
    onChange: function onChange(checked) {
      return setIsRecent(!checked);
    },
    size: "small",
    style: {
      margin: '0 8px'
    }
  }), /*#__PURE__*/React.createElement("span", {
    style: {
      color: isRecent ? TEXT_SECONDARY : PRIMARY
    }
  }, i18n.custom)), /*#__PURE__*/React.createElement(CloseOutlined, {
    className: "hc-date-range-picker-close",
    onClick: function onClick() {
      return setVisible(false);
    }
  })), /*#__PURE__*/React.createElement("div", {
    className: "hc-date-range-picker-body"
  }, isRecent ? /*#__PURE__*/React.createElement("div", {
    className: "hc-date-range-picker-recent"
  }, /*#__PURE__*/React.createElement(Slider, {
    marks: marks,
    max: sliderRange.max,
    min: sliderRange.min,
    step: null,
    value: sliderValue,
    onChange: setSliderValue,
    tooltip: {
      open: false
    }
  }), /*#__PURE__*/React.createElement("div", {
    className: "hc-date-range-picker-footer"
  }, /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    size: "small",
    onClick: handleRecentSave
  }, i18n.confirm))) : /*#__PURE__*/React.createElement("div", {
    className: "hc-date-range-picker-custom"
  }, /*#__PURE__*/React.createElement(RangeCalendar, {
    showToday: false,
    showWeekNumber: false,
    disabledDate: disabledDate ? wrappedDisabledDateForCalendar : undefined,
    selectedValue: customTimeRange,
    onOk: commitCustomRange,
    locale: CALENDAR_LOCALE_MAP[currentLocale],
    showOk: true,
    onChange: handleCustomRangeChange,
    format: format,
    timePicker: /*#__PURE__*/React.createElement(TimePickerPanel, null)
  }))));
  return /*#__PURE__*/React.createElement("div", {
    className: "hc-date-range-picker-wrapper ".concat(flat ? 'hc-date-range-picker-flat' : '')
  }, flat ? /*#__PURE__*/React.createElement("div", {
    className: "hc-date-range-picker-flat-content"
  }, /*#__PURE__*/React.createElement(Radio.Group, {
    className: "hc-date-range-picker-flat-radio-group",
    buttonStyle: "solid",
    value: flatRadioValue,
    onChange: handleFlatRadioChange
  }, quickTimeOptions.map(function (item) {
    return /*#__PURE__*/React.createElement(Radio.Button, {
      key: item.id,
      value: item.id
    }, item.label);
  })), /*#__PURE__*/React.createElement(RangePicker, {
    allowClear: false,
    disabledDate: disabledDate ? wrappedDisabledDateForAntd : undefined,
    format: format,
    showTime: true,
    style: {
      minWidth: 320
    },
    value: selectTimeRange,
    onChange: handleFlatRangeChange
  })) : /*#__PURE__*/React.createElement(Popover, {
    content: popoverContent,
    trigger: "click",
    open: visible && !disabled,
    onOpenChange: function onOpenChange(open) {
      return !disabled && setVisible(open);
    },
    placement: placement,
    overlayClassName: "hc-date-range-picker-popover"
  }, /*#__PURE__*/React.createElement(Input, {
    value: displayValue,
    readOnly: true,
    suffix: /*#__PURE__*/React.createElement(CalendarOutlined, null),
    className: "hc-date-range-picker-input",
    style: {
      width: width,
      cursor: disabled ? 'not-allowed' : 'pointer'
    },
    disabled: disabled
  })));
};
export default DateRangePicker;