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 _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 React, { useCallback, useEffect, useMemo, useState } from 'react';
import { CalendarPicker, ConfigProvider as AntMobileConfigProvider } from 'antd-mobile';
import dayjs from 'dayjs';
import classNames from 'classnames';
import Calendar from '@pisell/icon/es/Calendar';
import antdMobileZhCN from 'antd-mobile/es/locales/zh-CN';
import antdMobileZhTW from 'antd-mobile/es/locales/zh-TW';
import antdMobileZhHK from 'antd-mobile/es/locales/zh-HK';
import antdMobileEnUS from 'antd-mobile/es/locales/en-US';
import antdMobileJaJP from 'antd-mobile/es/locales/ja-JP';
import antdMobilePtBR from 'antd-mobile/es/locales/pt-BR';
import { getText } from "../../locales";
import { getCurrentLocale } from "../../utils/locale";
import { PISELL_MOBILE_DATE_RANGE_PICKER_FILTER_POPUP_CLASS } from "./types";
import 'antd-mobile/es/global/global.css';
import "./PisellMobileDateRangePicker.less";

/**
 * 项目语言 → antd-mobile 内置 locale 包映射。
 * 对齐 packages/materials/src/locales/index.ts 的 langMap。
 * 未匹配时回落 en-US。
 */
var ANTD_MOBILE_LOCALE_MAP = {
  'zh-CN': antdMobileZhCN,
  'zh-TW': antdMobileZhTW,
  'zh-HK': antdMobileZhHK,
  'en-US': antdMobileEnUS,
  en: antdMobileEnUS,
  original: antdMobileEnUS,
  ja: antdMobileJaJP,
  pt: antdMobilePtBR
};

/** 高于 antd Popover 默认 1030，避免嵌套在齿轮/Filter 弹层下被遮挡 */
var FILTER_POPUP_Z_INDEX = 1100;

/**
 * 默认日期范围：当前月起往前 1 年。
 * - antd-mobile `CalendarPickerView` 默认窗口仅「打开月 +6 个月」，业务上预约/筛选场景
 *   常需要至少能往前查 1 年。
 * - 该组件 `renderBody` 是「一次性把 min..max 之间所有月份都渲染」，无虚拟滚动；
 *   ±1 年（约 13 个月）DOM 量在 ≈400 cells，开销可接受。
 * - 业务方仍可用 `min` / `max` props 显式覆盖。
 */
function getDefaultMin() {
  return dayjs().subtract(1, 'year').startOf('month').toDate();
}
function getDefaultMax() {
  return dayjs().endOf('month').toDate();
}

/** 与 FilterItem `toRangePickerValue` 一致：兼容 form 中的 dayjs[] / string[] / Date[] */
function toDayjsRange(val) {
  if (val == null) return null;
  if (!Array.isArray(val) || val.length < 2) return null;
  var start = val[0] ? dayjs.isDayjs(val[0]) ? val[0] : dayjs(val[0]) : null;
  var end = val[1] ? dayjs.isDayjs(val[1]) ? val[1] : dayjs(val[1]) : null;
  if (!(start !== null && start !== void 0 && start.isValid()) || !(end !== null && end !== void 0 && end.isValid())) return null;
  return [start, end];
}
function toDateRange(val) {
  var normalized = toDayjsRange(val);
  if (!normalized) return null;
  return [normalized[0].toDate(), normalized[1].toDate()];
}
function formatRangeLabel(range, format, placeholder) {
  if (!range) return placeholder;
  return "".concat(range[0].format(format), " - ").concat(range[1].format(format));
}
function resolveFilterGetContainer() {
  if (typeof document === 'undefined') return null;
  return document.body;
}

/**
 * antd-mobile CalendarPicker（range）薄封装：受控 value/onChange 与 RecordBoard 快筛 dayjs[] 对齐。
 */
export var PisellMobileDateRangePicker = function PisellMobileDateRangePicker(_ref) {
  var _ANTD_MOBILE_LOCALE_M, _popupStyle$zIndex;
  var value = _ref.value,
    onChange = _ref.onChange,
    _ref$format = _ref.format,
    format = _ref$format === void 0 ? 'DD/MM/YYYY' : _ref$format,
    placeholder = _ref.placeholder,
    className = _ref.className,
    style = _ref.style,
    title = _ref.title,
    confirmText = _ref.confirmText,
    _ref$allowClear = _ref.allowClear,
    allowClear = _ref$allowClear === void 0 ? true : _ref$allowClear,
    min = _ref.min,
    max = _ref.max,
    _ref$variant = _ref.variant,
    variant = _ref$variant === void 0 ? 'toolbar' : _ref$variant,
    getContainer = _ref.getContainer,
    popupClassName = _ref.popupClassName,
    popupStyle = _ref.popupStyle,
    onOpen = _ref.onOpen,
    onClose = _ref.onClose;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    visible = _useState2[0],
    setVisible = _useState2[1];
  var dayjsRange = useMemo(function () {
    return toDayjsRange(value);
  }, [value]);
  var pickerValue = useMemo(function () {
    return toDateRange(value);
  }, [value]);

  /**
   * 弹层「内部受控」缓冲：
   * - antd-mobile `CalendarPickerView` 内部 `usePropsValue` 每次渲染都执行
   *   `if (value !== undefined) stateRef.current = value`，因此一旦透传非空 `value`，
   *   单格点选触发的 `setDateRange + onChange` 不写回外层 form 时，下一次重渲染会立刻把
   *   内部累计选择覆盖回 prop 原值，表现为「点格子完全无反应」。
   * - 解决：始终把 `value` 接到本地 `innerValue`，并把 `onChange` 写回 `innerValue`，
   *   形成真正的「弹层内部受控」。打开弹层时再用外部 form 值同步一次初值。
   *   `onConfirm` 时把 `innerValue` 写回外部 form。
   */
  var _useState3 = useState(pickerValue),
    _useState4 = _slicedToArray(_useState3, 2),
    innerValue = _useState4[0],
    setInnerValue = _useState4[1];
  useEffect(function () {
    if (visible) {
      setInnerValue(pickerValue);
    }
    // 故意不把 pickerValue 放进依赖：弹层打开后外部 form 临时变化不应打断点选。
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);
  var resolvedPlaceholder = placeholder !== null && placeholder !== void 0 ? placeholder : getText('pisell-mobile-date-range-picker-placeholder');
  var resolvedTitle = title !== null && title !== void 0 ? title : getText('pisell-mobile-date-range-picker-title');
  var resolvedConfirmText = confirmText !== null && confirmText !== void 0 ? confirmText : getText('pisell-mobile-date-range-picker-confirm');
  // 每次渲染读取最新语言（getCurrentLocale 内部读取全局配置/localStorage，开销可忽略）。
  var antMobileLocale = (_ANTD_MOBILE_LOCALE_M = ANTD_MOBILE_LOCALE_MAP[getCurrentLocale()]) !== null && _ANTD_MOBILE_LOCALE_M !== void 0 ? _ANTD_MOBILE_LOCALE_M : antdMobileEnUS;
  var isFilterVariant = variant === 'filter';
  var openPicker = useCallback(function () {
    setVisible(true);
    onOpen === null || onOpen === void 0 || onOpen();
  }, [onOpen]);
  var closePicker = useCallback(function () {
    setVisible(false);
    onClose === null || onClose === void 0 || onClose();
  }, [onClose]);
  var handleConfirm = useCallback(function (next) {
    if (!next) {
      onChange === null || onChange === void 0 || onChange(undefined);
      closePicker();
      return;
    }
    onChange === null || onChange === void 0 || onChange([dayjs(next[0]).startOf('day'), dayjs(next[1]).startOf('day')]);
    closePicker();
  }, [onChange, closePicker]);
  var resolvedGetContainer = getContainer !== null && getContainer !== void 0 ? getContainer : isFilterVariant ? resolveFilterGetContainer : undefined;
  var resolvedPopupClassName = classNames(isFilterVariant ? PISELL_MOBILE_DATE_RANGE_PICKER_FILTER_POPUP_CLASS : null, popupClassName);
  var resolvedPopupStyle = isFilterVariant ? _objectSpread(_objectSpread({}, popupStyle), {}, {
    zIndex: (_popupStyle$zIndex = popupStyle === null || popupStyle === void 0 ? void 0 : popupStyle.zIndex) !== null && _popupStyle$zIndex !== void 0 ? _popupStyle$zIndex : FILTER_POPUP_Z_INDEX
  }) : popupStyle;
  return /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-mobile-date-range-picker', {
      'pisell-mobile-date-range-picker--filter': isFilterVariant
    }, className),
    style: style
  }, /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: classNames('pisell-mobile-date-range-picker__trigger', {
      'pisell-mobile-date-range-picker__trigger--placeholder': !dayjsRange
    }),
    onClick: openPicker
  }, /*#__PURE__*/React.createElement("span", {
    className: "pisell-mobile-date-range-picker__trigger-text"
  }, formatRangeLabel(dayjsRange, format, resolvedPlaceholder)), isFilterVariant ? /*#__PURE__*/React.createElement(Calendar, {
    className: "pisell-mobile-date-range-picker__trigger-icon",
    "aria-hidden": true
  }) : null), /*#__PURE__*/React.createElement(AntMobileConfigProvider, {
    locale: antMobileLocale
  }, /*#__PURE__*/React.createElement(CalendarPicker, {
    visible: visible,
    selectionMode: "range",
    value: innerValue !== null && innerValue !== void 0 ? innerValue : undefined,
    onChange: function onChange(v) {
      return setInnerValue(v);
    },
    onClose: closePicker,
    onMaskClick: closePicker,
    closeOnMaskClick: true,
    onConfirm: handleConfirm,
    title: resolvedTitle,
    confirmText: resolvedConfirmText,
    allowClear: allowClear,
    min: min !== null && min !== void 0 ? min : getDefaultMin(),
    max: max !== null && max !== void 0 ? max : getDefaultMax(),
    getContainer: resolvedGetContainer,
    popupClassName: resolvedPopupClassName || undefined,
    popupStyle: resolvedPopupStyle
  })));
};