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); }
import React from 'react';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/en';
import { useCurrentTime } from "./hooks";
import { getRefreshInterval, isChinese as checkIsChinese, getRelativeDay, getRelativeDayLabel, getDayjsLocale } from "./utils";
import { TimeDisplay, DateDisplay, WeekdayDisplay } from "./components";
import { DATETIME_DISPLAY_FORMATS } from "./formats/dateTimeDisplayFormats";
import useEngineContext from "../../hooks/useEngineContext";
import "./PisellDateTimeDisplay.less";

/**
 * PisellDateTimeDisplay 组件
 *
 * @description
 * 专注于展示当前时间的组件，支持：
 * - 当前日期、时间、星期展示
 * - 多种布局方式（水平、垂直、单行）
 * - 丰富的格式化配置
 * - 自动刷新
 * - 国际化支持
 *
 * @example
 * // 基础用法
 * <PisellDateTimeDisplay />
 *
 * // 自定义格式
 * <PisellDateTimeDisplay
 *   layout="vertical"
 *   timeFormat={{ use12Hour: true, showSeconds: true }}
 *   dateFormat={{ showYear: true, showChineseUnit: true }}
 * />
 *
 * // 自定义格式化字符串
 * <PisellDateTimeDisplay
 *   customFormat="YYYY-MM-DD HH:mm:ss"
 * />
 */
export var PisellDateTimeDisplay = function PisellDateTimeDisplay(props) {
  var _context$engine, _ref, _presetSource$localeK;
  var valueProp = props.value,
    _props$layout = props.layout,
    layout = _props$layout === void 0 ? 'horizontal' : _props$layout,
    _props$textAlign = props.textAlign,
    textAlign = _props$textAlign === void 0 ? 'center' : _props$textAlign,
    fields = props.fields,
    formatByLocale = props.formatByLocale,
    timeFormat = props.timeFormat,
    dateFormat = props.dateFormat,
    weekdayFormat = props.weekdayFormat,
    customFormat = props.customFormat,
    _props$inlineSeparato = props.inlineSeparator,
    inlineSeparator = _props$inlineSeparato === void 0 ? ' · ' : _props$inlineSeparato,
    containerStyle = props.containerStyle,
    timeStyle = props.timeStyle,
    dateStyle = props.dateStyle,
    weekdayStyle = props.weekdayStyle,
    refreshInterval = props.refreshInterval,
    _props$disableAutoRef = props.disableAutoRefresh,
    disableAutoRefresh = _props$disableAutoRef === void 0 ? false : _props$disableAutoRef,
    locale = props.locale,
    onTimeUpdate = props.onTimeUpdate,
    onClick = props.onClick,
    className = props.className,
    style = props.style;
  var context = useEngineContext();
  var resolvedLocale = locale || (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || 'en';
  // 多语言格式：formatByLocale 优先，否则用内置 DATETIME_DISPLAY_FORMATS；再与单项 props 合并（单项优先）
  var localeKey = getDayjsLocale(resolvedLocale);
  var baseLocale = localeKey.split('-')[0];
  var presetSource = formatByLocale !== null && formatByLocale !== void 0 ? formatByLocale : DATETIME_DISPLAY_FORMATS;
  var preset = (_ref = (_presetSource$localeK = presetSource[localeKey]) !== null && _presetSource$localeK !== void 0 ? _presetSource$localeK : presetSource[baseLocale]) !== null && _ref !== void 0 ? _ref : {};
  var effectiveFields = _objectSpread(_objectSpread({}, preset.fields), fields);
  var effectiveDateFormat = _objectSpread(_objectSpread({}, preset.dateFormat), dateFormat);
  var effectiveTimeFormat = _objectSpread(_objectSpread({}, preset.timeFormat), timeFormat);
  var effectiveWeekdayFormat = _objectSpread(_objectSpread({}, preset.weekdayFormat), weekdayFormat);

  // 计算刷新间隔
  var computedRefreshInterval = refreshInterval !== null && refreshInterval !== void 0 ? refreshInterval : getRefreshInterval(effectiveTimeFormat);

  // 使用自定义 hook 管理当前时间（仅在没有 value 时用于展示）
  var currentTime = useCurrentTime({
    refreshInterval: computedRefreshInterval,
    disabled: disableAutoRefresh || valueProp !== undefined,
    locale: resolvedLocale,
    onUpdate: onTimeUpdate
  });

  // 展示时间：传入 value 时用 value 并应用当前 locale，否则用已带 locale 的 currentTime
  var displayTime = valueProp !== undefined && valueProp !== null ? dayjs(valueProp).locale(localeKey) : currentTime;

  // 如果有自定义格式化，直接使用
  if (customFormat) {
    var formattedTime = displayTime.format(customFormat);
    var _containerInlineStyle = _objectSpread({
      background: containerStyle === null || containerStyle === void 0 ? void 0 : containerStyle.background,
      borderRadius: containerStyle === null || containerStyle === void 0 ? void 0 : containerStyle.borderRadius,
      border: containerStyle === null || containerStyle === void 0 ? void 0 : containerStyle.border,
      boxShadow: containerStyle === null || containerStyle === void 0 ? void 0 : containerStyle.boxShadow,
      padding: containerStyle === null || containerStyle === void 0 ? void 0 : containerStyle.padding,
      textAlign: textAlign
    }, style);
    return /*#__PURE__*/React.createElement("div", {
      className: "pisell-datetime-display pisell-datetime-display-custom ".concat(className || '').trim(),
      style: _containerInlineStyle,
      onClick: onClick
    }, /*#__PURE__*/React.createElement("span", null, formattedTime));
  }

  // 获取字段配置（已含多语言预设合并）
  var _ref2 = effectiveFields || {},
    _ref2$showTime = _ref2.showTime,
    showTime = _ref2$showTime === void 0 ? true : _ref2$showTime,
    _ref2$showDate = _ref2.showDate,
    showDate = _ref2$showDate === void 0 ? true : _ref2$showDate,
    _ref2$showWeekday = _ref2.showWeekday,
    showWeekday = _ref2$showWeekday === void 0 ? true : _ref2$showWeekday,
    _ref2$fieldOrder = _ref2.fieldOrder,
    fieldOrder = _ref2$fieldOrder === void 0 ? ['time', 'date', 'weekday'] : _ref2$fieldOrder;

  // 日期与星期一体：若日期以相对日（今天/昨天/明天）展示，则不展示星期
  var referenceDate = dayjs();
  var relativeDay = effectiveDateFormat !== null && effectiveDateFormat !== void 0 && effectiveDateFormat.showRelativeDay ? getRelativeDay(displayTime, referenceDate) : null;
  var hideWeekdayWhenDateRelative = showDate && relativeDay !== null;

  // 构建容器样式
  var containerInlineStyle = _objectSpread({
    background: containerStyle === null || containerStyle === void 0 ? void 0 : containerStyle.background,
    borderRadius: containerStyle === null || containerStyle === void 0 ? void 0 : containerStyle.borderRadius,
    border: containerStyle === null || containerStyle === void 0 ? void 0 : containerStyle.border,
    boxShadow: containerStyle === null || containerStyle === void 0 ? void 0 : containerStyle.boxShadow,
    padding: containerStyle === null || containerStyle === void 0 ? void 0 : containerStyle.padding,
    gap: containerStyle === null || containerStyle === void 0 ? void 0 : containerStyle.gap,
    textAlign: textAlign
  }, style);

  // 渲染单个字段
  var renderField = function renderField(fieldType) {
    switch (fieldType) {
      case 'time':
        return showTime ? /*#__PURE__*/React.createElement(TimeDisplay, {
          key: "time",
          time: displayTime,
          format: effectiveTimeFormat,
          style: timeStyle
        }) : null;
      case 'date':
        return showDate ? /*#__PURE__*/React.createElement(DateDisplay, {
          key: "date",
          date: displayTime,
          format: effectiveDateFormat,
          referenceDate: dayjs(),
          style: dateStyle
        }) : null;
      case 'weekday':
        return showWeekday && !hideWeekdayWhenDateRelative ? /*#__PURE__*/React.createElement(WeekdayDisplay, {
          key: "weekday",
          weekday: displayTime,
          format: effectiveWeekdayFormat,
          style: weekdayStyle
        }) : null;
      default:
        return null;
    }
  };

  // 单行布局：使用分隔符连接，支持每段不同分隔符（如 2025-12-31 - 2:00 周四）
  if (layout === 'inline') {
    var inlineSeparators = effectiveFields === null || effectiveFields === void 0 ? void 0 : effectiveFields.inlineSeparators;
    var _renderedFields = fieldOrder.map(renderField).filter(function (field) {
      return field !== null;
    });
    if (_renderedFields.length === 0) {
      return null;
    }
    return /*#__PURE__*/React.createElement("div", {
      className: "pisell-datetime-display pisell-datetime-display-inline ".concat(className || '').trim(),
      style: containerInlineStyle,
      onClick: onClick
    }, _renderedFields.map(function (field, index) {
      var _inlineSeparators$ind;
      return /*#__PURE__*/React.createElement(React.Fragment, {
        key: index
      }, field, index < _renderedFields.length - 1 && /*#__PURE__*/React.createElement("span", {
        className: "pisell-datetime-display-separator"
      }, (_inlineSeparators$ind = inlineSeparators === null || inlineSeparators === void 0 ? void 0 : inlineSeparators[index]) !== null && _inlineSeparators$ind !== void 0 ? _inlineSeparators$ind : inlineSeparator));
    }));
  }

  // 水平或垂直布局：直接渲染字段
  var renderedFields = fieldOrder.map(renderField).filter(function (field) {
    return field !== null;
  });

  // 如果没有要显示的字段，返回 null
  if (renderedFields.length === 0) {
    return null;
  }

  // 水平布局特殊处理：将日期和星期放在同一行
  if (layout === 'horizontal') {
    // 提取时间字段
    var timeField = showTime ? renderField('time') : null;

    // 判断是否为中文环境
    var currentLocale = displayTime.locale();
    var isChinese = checkIsChinese(currentLocale);

    // 当同时显示日期和星期时，使用合并格式；有相对日时只展示相对日，不展示具体日期与星期
    if (showDate && showWeekday) {
      var _labels$relativeDay;
      var labels = effectiveDateFormat === null || effectiveDateFormat === void 0 ? void 0 : effectiveDateFormat.relativeDayLabels;
      var dateStr = relativeDay ? (_labels$relativeDay = labels === null || labels === void 0 ? void 0 : labels[relativeDay]) !== null && _labels$relativeDay !== void 0 ? _labels$relativeDay : getRelativeDayLabel(relativeDay, displayTime.locale()) : isChinese ? displayTime.format('M月D日') : displayTime.format('D MMM');
      var weekdayStr = displayTime.format('ddd');
      // 相对日替换掉原日期展示：有今天/昨天/明天时只显示相对日，不拼接具体日期或星期
      var combinedStr = relativeDay ? dateStr : isChinese ? "".concat(weekdayStr, " ").concat(dateStr) : "".concat(weekdayStr, ", ").concat(dateStr);

      // 构建日期样式
      var dateInlineStyle = {
        fontSize: dateStyle === null || dateStyle === void 0 ? void 0 : dateStyle.fontSize,
        fontWeight: dateStyle === null || dateStyle === void 0 ? void 0 : dateStyle.fontWeight,
        color: dateStyle === null || dateStyle === void 0 ? void 0 : dateStyle.color,
        lineHeight: dateStyle === null || dateStyle === void 0 ? void 0 : dateStyle.lineHeight
      };
      return /*#__PURE__*/React.createElement("div", {
        className: "pisell-datetime-display pisell-datetime-display-".concat(layout, " ").concat(className || '').trim(),
        style: containerInlineStyle,
        onClick: onClick
      }, timeField, /*#__PURE__*/React.createElement("span", {
        className: "pisell-datetime-display-date pisell-datetime-display-combined",
        style: dateInlineStyle
      }, combinedStr));
    }

    // 只显示日期或只显示星期：分别渲染
    var dateField = showDate ? renderField('date') : null;
    var weekdayField = showWeekday ? renderField('weekday') : null;
    return /*#__PURE__*/React.createElement("div", {
      className: "pisell-datetime-display pisell-datetime-display-".concat(layout, " ").concat(className || '').trim(),
      style: containerInlineStyle,
      onClick: onClick
    }, timeField, (dateField || weekdayField) && /*#__PURE__*/React.createElement("div", {
      className: "pisell-datetime-display-date-weekday-row"
    }, dateField, weekdayField));
  }
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-datetime-display pisell-datetime-display-".concat(layout, " ").concat(className || '').trim(),
    style: containerInlineStyle,
    onClick: onClick
  }, renderedFields);
};

// 性能优化：使用 React.memo
export default /*#__PURE__*/React.memo(PisellDateTimeDisplay);