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 = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { DatePicker, Popover, Tabs, Button, message } from 'antd';
import moment from 'moment';
import locale from 'antd/es/date-picker/locale/zh_CN';
var AntdRangePicker = DatePicker.RangePicker;
var CustomRangePicker = function CustomRangePicker(props) {
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    open = _useState2[0],
    setOpen = _useState2[1];
  var _useState3 = useState('fixed'),
    _useState4 = _slicedToArray(_useState3, 2),
    activeTab = _useState4[0],
    setActiveTab = _useState4[1];
  var _useState5 = useState([null, null]),
    _useState6 = _slicedToArray(_useState5, 2),
    dates = _useState6[0],
    setDates = _useState6[1];
  var _useState7 = useState(null),
    _useState8 = _slicedToArray(_useState7, 2),
    selectedDate = _useState8[0],
    setSelectedDate = _useState8[1];
  // const getMinDate = useCallback(() => {
  //   // 优先使用传入的 eventStartTime详情获取的时间
  //   if (props.eventStartTime) return moment(props.eventStartTime);
  //   if (props.resEventStartTime) return moment(props.resEventStartTime);
  //   // 否则使用默认的 365 天前
  //   return moment().subtract(365, 'days').startOf('day');
  // }, [props.eventStartTime, props.resEventStartTime]);
  var getMinDate = useCallback(function () {
    var date;
    if (props.eventStartTime) {
      date = moment(props.eventStartTime).startOf('day');
    } else if (props.resEventStartTime) {
      date = moment(props.resEventStartTime).startOf('day');
    } else {
      date = moment().subtract(365, 'days').startOf('day');
    }
    return date;
  }, [props.eventStartTime, props.resEventStartTime]);
  var disabledDate = function disabledDate(current) {
    if (!current) return false;
    var yesterday = moment().subtract(1, 'days').startOf('day');
    var minDate;
    if (activeTab === 'dynamic') {
      // 动态模式允许的最大跨度为365天（包含结束日）
      var minAllowedStartDate = yesterday.clone().subtract(364, 'days').startOf('day');
      minDate = moment.max(getMinDate(), minAllowedStartDate);
    } else {
      minDate = getMinDate();
    }
    return current.isAfter(yesterday, 'day') || current.isBefore(minDate, 'day');
  };
  // 改进的初始化逻辑
  useEffect(function () {
    if (props.value && !Array.isArray(props.value)) {
      var _props$value = props.value,
        start = _props$value.start,
        end = _props$value.end,
        mode = _props$value.mode;
      var yesterday = moment().subtract(1, 'days');
      if (mode === 'dynamic') {
        // 确保选择的日期在有效范围内
        var minDate = getMinDate();
        var startMoment = moment(start);
        // 确保开始日期不小于 minDate 且不晚于昨天
        var validStart = moment.max(minDate, startMoment.isBefore(yesterday) ? startMoment : yesterday);
        validStart.startOf('day');
        setSelectedDate(validStart);
        setDates([validStart, yesterday]);
        setActiveTab('dynamic');
      } else {
        // 固定模式需要同时校验开始和结束时间
        var _validStart = start ? moment.max(getMinDate(), moment(start)) : null;
        var validEnd = end ? moment.min(yesterday, moment(end)) : null;
        setDates([_validStart, validEnd]);
        setActiveTab('fixed');
      }
    }
  }, [props.value, getMinDate]);
  var handleConfirm = function handleConfirm() {
    var _dates$, _dates$2, _props$onChange;
    var yesterday = moment().subtract(1, 'days');
    var payload = {
      mode: activeTab,
      start: activeTab === 'dynamic' ? selectedDate === null || selectedDate === void 0 ? void 0 : selectedDate.format('YYYY-MM-DD') : (_dates$ = dates[0]) === null || _dates$ === void 0 ? void 0 : _dates$.format('YYYY-MM-DD'),
      end: activeTab === 'dynamic' ? yesterday.format('YYYY-MM-DD') : (_dates$2 = dates[1]) === null || _dates$2 === void 0 ? void 0 : _dates$2.format('YYYY-MM-DD')
    };
    var isValid = true;
    // 新增校验：时间跨度不超过365天
    if (activeTab === 'dynamic') {
      if (!selectedDate) {
        isValid = false;
        message.error('请选择开始日期');
      } else {
        var diffDays = yesterday.diff(selectedDate, 'days') + 1; // 包含结束日
        if (diffDays > 365) {
          isValid = false;
          message.error('时间跨度不能超过365天');
          setSelectedDate(null);
        }
      }
    } else {
      if (!dates[0] || !dates[1]) {
        isValid = false;
        message.error('请选择完整时间范围');
      } else {
        var _diffDays = dates[1].diff(dates[0], 'days') + 1;
        if (_diffDays > 365) {
          isValid = false;
          message.error('时间跨度不能超过365天');
          setDates([null, null]);
        }
      }
    }
    (_props$onChange = props.onChange) === null || _props$onChange === void 0 ? void 0 : _props$onChange.call(props, payload);
    if (!isValid) return;
    setOpen(false);
  };
  var handleTabChange = useCallback(function (key) {
    setActiveTab(key);
  }, [props.ranges]);
  var tabItems = [{
    key: 'fixed',
    label: '固定时段',
    children: /*#__PURE__*/React.createElement("div", {
      style: {
        padding: 8
      }
    }, /*#__PURE__*/React.createElement(AntdRangePicker, {
      open: activeTab === 'fixed',
      separator: "\u81F3",
      getPopupContainer: function getPopupContainer(trigger) {
        return trigger.parentNode;
      },
      disabledDate: disabledDate,
      value: dates,
      allowClear: false,
      locale: locale,
      onChange: function onChange(val) {
        return val && setDates(val);
      },
      onCalendarChange: function onCalendarChange(val) {
        return val && setDates(val);
      }
    }))
  }, {
    key: 'dynamic',
    label: '动态时段',
    children: /*#__PURE__*/React.createElement("div", {
      style: {
        padding: 8
      }
    }, /*#__PURE__*/React.createElement(DatePicker, {
      value: selectedDate,
      onChange: function onChange(value) {
        setSelectedDate(value);
        setDates([value, null]);
      },
      disabledDate: disabledDate,
      locale: locale,
      allowClear: false,
      open: activeTab === 'dynamic' && open,
      onOk: function onOk(v) {
        console.log(v, 'vv');
      }
    }))
  }];
  var displayText = useMemo(function () {
    if (activeTab === 'dynamic') {
      if (!selectedDate) return '请选择时间范围';
      var endDate = moment().subtract(1, 'days');
      return "".concat(selectedDate.format('YYYY-MM-DD'), " \u81F3 ").concat(endDate.format('YYYY-MM-DD'), "\uFF08\u52A8\u6001\u65F6\u6BB5\uFF09");
    }
    if (!dates[0] || !dates[1]) return '请选择时间范围';
    return "".concat(dates[0].format('YYYY-MM-DD'), " \u81F3 ").concat(dates[1].format('YYYY-MM-DD'), "\uFF08\u56FA\u5B9A\u65F6\u6BB5\uFF09");
  }, [dates, selectedDate, activeTab]);
  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Popover, {
    open: open,
    onOpenChange: setOpen,
    content: /*#__PURE__*/React.createElement("div", {
      style: {
        width: 520,
        height: 420
      }
    }, /*#__PURE__*/React.createElement(Tabs, {
      activeKey: activeTab,
      items: tabItems,
      onChange: handleTabChange,
      tabBarStyle: {
        marginBottom: 16
      }
    }), /*#__PURE__*/React.createElement("div", {
      style: {
        textAlign: 'right',
        marginTop: 280
      }
    }, /*#__PURE__*/React.createElement(Button, {
      onClick: function onClick() {
        return setOpen(false);
      }
    }, "\u53D6\u6D88"), /*#__PURE__*/React.createElement(Button, {
      type: "primary",
      onClick: handleConfirm,
      style: {
        marginLeft: 8
      }
    }, "\u786E\u5B9A"))),
    trigger: "click",
    placement: "bottomLeft",
    overlayStyle: {
      width: 600
    }
  }, /*#__PURE__*/React.createElement(Button, {
    style: {
      width: 460
    }
  }, displayText)));
};
export default CustomRangePicker;