var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/date-picker/datePickerCpt.tsx
var datePickerCpt_exports = {};
__export(datePickerCpt_exports, {
  default: () => datePickerCpt_default
});
module.exports = __toCommonJS(datePickerCpt_exports);
var import_react = __toESM(require("react"));
var import_dayjs = __toESM(require("dayjs"));
var import_classnames = __toESM(require("classnames"));
var import_antd = require("antd");
var import_browserSelect = __toESM(require("../browserSelect"));
var import_utils = require("@pisell/utils");
var import_constants = require("./constants");
var import_locales = require("../../locales");
var import_useResponsive = __toESM(require("../../hooks/useResponsive"));
var import_index = require("./index.less");
var isValidDate = (dateString, format) => {
  const date = window.dayjs(dateString, format, true);
  return date.isValid();
};
(0, import_useResponsive.configResponsive)({
  phone: 0,
  ipad: 768,
  pc: 1080
});
var DatePickerCpt = (props) => {
  const {
    picker,
    onChange,
    value,
    format: propsFormat,
    defaultValue,
    showTime,
    ...others
  } = props;
  const { locale } = (0, import_react.useContext)(import_antd.ConfigProvider.ConfigContext);
  const [currentShortcut, setCurrentShortcut] = (0, import_react.useState)("");
  const [open, setOpen] = (0, import_react.useState)(false);
  const [popupOpen, setPopupOpen] = (0, import_react.useState)(false);
  const [_value, setValue] = (0, import_react.useState)(value);
  const [valueStr, setValueStr] = (0, import_react.useState)("");
  const [error, setError] = (0, import_react.useState)(false);
  const ref = (0, import_react.useRef)(null);
  const panelRef = (0, import_react.useRef)(null);
  const canClose = (0, import_react.useRef)(true);
  const [panelTimeWidth, setPanelTimeWidth] = (0, import_react.useState)(0);
  const responsive = (0, import_useResponsive.default)();
  const isDesktop = !("ontouchstart" in window || navigator.maxTouchPoints);
  (0, import_react.useEffect)(() => {
    document.body.id = "body";
  }, []);
  (0, import_react.useEffect)(() => {
    setValue(value);
  }, [value]);
  (0, import_react.useEffect)(() => {
    var _a;
    setValueStr(((_a = _value == null ? void 0 : _value.format) == null ? void 0 : _a.call(_value, format || "YYYY-MM-DD")) || "");
  }, [_value]);
  const customPresetItems = (0, import_react.useMemo)(() => {
    const preset = [
      {
        label: import_constants.presetDetailMap["today"].label(),
        value: "today"
      },
      {
        label: import_constants.presetDetailMap["yesterday"].label(),
        value: "yesterday"
      },
      {
        label: import_constants.presetDetailMap["tomorrow"].label(),
        value: "tomorrow"
      },
      {
        label: import_constants.presetDetailMap["next_monday"].label(),
        value: "next_monday"
      },
      {
        label: import_constants.presetDetailMap["last_friday"].label(),
        value: "last_friday"
      },
      {
        label: import_constants.presetDetailMap["first_day_of_this_month"].label(),
        value: "first_day_of_this_month"
      },
      {
        label: import_constants.presetDetailMap["last_day_of_this_month"].label(),
        value: "last_day_of_this_month"
      },
      {
        label: import_constants.presetDetailMap["first_day_of_next_month"].label(),
        value: "first_day_of_next_month"
      },
      {
        label: import_constants.presetDetailMap["last_day_of_last_month"].label(),
        value: "last_day_of_last_month"
      }
    ];
    if (!currentShortcut) {
      preset.push({
        label: (0, import_locales.getText)("date-picker-shortcut-custom"),
        value: "custom"
      });
    }
    return preset;
  }, [currentShortcut]);
  const format = (0, import_react.useMemo)(() => {
    if (propsFormat) {
      if ((0, import_utils.isFunction)(propsFormat)) {
        return propsFormat(value);
      }
      return propsFormat + ((showTime == null ? void 0 : showTime.format) ? ` ${showTime == null ? void 0 : showTime.format}` : "");
    }
    let localeValue = locale == null ? void 0 : locale.locale;
    return localeValue === "en" || localeValue === "en-US" ? "DD/MM/YYYY" : "YYYY/MM/DD";
  }, [propsFormat, locale]);
  const handleSelectChange = (e) => {
    var _a;
    canClose.current = true;
    const shortcut = e.target.value;
    setCurrentShortcut(shortcut);
    const date = (_a = import_constants.presetDetailMap[shortcut]) == null ? void 0 : _a.getValue();
    setValue(date);
    handleOk(date);
  };
  const handleTodayClick = () => {
    const val = (0, import_dayjs.default)().startOf("day");
    handleChange(val);
    handleOpenChange(false);
  };
  const handleOpenChange = (visible) => {
    if (!visible) {
      setOpen(visible);
      setTimeout(() => {
        var _a;
        setPopupOpen(visible);
        (_a = ref.current) == null ? void 0 : _a.blur();
      });
      return;
    }
    setOpen(visible);
    setPopupOpen(visible);
  };
  const handleOk = (val) => {
    let returnValue = val;
    if (returnValue !== null) {
      returnValue = returnValue || _value;
    }
    onChange == null ? void 0 : onChange(returnValue, returnValue == null ? void 0 : returnValue.format("YYYY-MM-DD"));
    handleOpenChange(false);
  };
  const handleChange = (val, valStr, isNotChange) => {
    if (!showTime) {
      canClose.current = true;
    }
    setError(false);
    setCurrentShortcut("");
    setValue(val);
    if (!isNotChange) {
      handleOk(val);
    }
  };
  const handleApply = () => {
    if (error)
      return;
    handleOk();
  };
  const handleDataStrChange = (e) => {
    const val = e.target.value;
    setValueStr(val);
    if (isValidDate(val, format)) {
      setError(false);
      const valDate = (0, import_dayjs.default)(val, format);
      setValue(valDate);
    } else {
      setError(true);
    }
  };
  (0, import_react.useEffect)(() => {
    var _a;
    let width = 0;
    const childElements = ((_a = panelRef.current) == null ? void 0 : _a.getElementsByClassName(
      "pisell-lowcode-picker-time-panel"
    )) || [];
    if (childElements.length > 0) {
      const childElement = childElements[0];
      width = childElement.offsetWidth;
    }
    if (width > 0) {
      setPanelTimeWidth(width);
    }
  }, [open]);
  const handleSelect = (val) => {
    canClose.current = !showTime;
    setValue(val);
  };
  const handleTimeChange = (val) => {
    setValue(
      (preVal) => {
        var _a, _b;
        return ((_b = (_a = preVal == null ? void 0 : preVal.set("hour", (val == null ? void 0 : val.get("hour")) || 0)) == null ? void 0 : _a.set("minute", (val == null ? void 0 : val.get("minute")) || 0)) == null ? void 0 : _b.set("second", (val == null ? void 0 : val.get("second")) || 0)) || null;
      }
    );
  };
  const timeInputProps = (0, import_react.useMemo)(() => {
    var _a;
    let step = 1;
    let _format = "";
    if ((showTime == null ? void 0 : showTime.format) === "HH:mm") {
      step = void 0;
      _format = "HH:mm";
    } else if ((showTime == null ? void 0 : showTime.format) === "HH:mm:ss" || showTime) {
      step = 1;
      _format = "HH:mm:ss";
    }
    return {
      step,
      onChange: (e) => {
        const val = e.target.value;
        handleTimeChange(window.dayjs(val, _format));
      },
      value: (_a = _value == null ? void 0 : _value.format) == null ? void 0 : _a.call(_value, _format)
    };
  }, [showTime, _value]);
  if (!picker || picker === "date") {
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
      import_antd.DatePicker,
      {
        ...others,
        ref,
        onSelect: handleSelect,
        showTime: isDesktop ? showTime : false,
        defaultValue,
        showNow: false,
        onChange: (val, valStr) => handleChange(val, valStr, !isDesktop && showTime),
        open: popupOpen,
        renderExtraFooter: !(!showTime || isDesktop) ? () => {
          return /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              onMouseDown: (e) => {
                canClose.current = false;
                e.stopPropagation();
              }
            },
            /* @__PURE__ */ import_react.default.createElement("div", { className: "date-picker-time-label" }, "Time"),
            /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement(
              "input",
              {
                type: "time",
                className: "date-picker-input-time",
                ...timeInputProps
              }
            ))
          );
        } : void 0,
        className: (0, import_classnames.default)(
          "pisell-lowcode-mode-date-picker",
          others.className
        ),
        value: _value,
        onOpenChange: (o) => {
          if (!o && (!canClose.current || showTime)) {
            return;
          }
          handleOpenChange(o);
        },
        mode: "date",
        picker: "date",
        popupClassName: "date-picker-popup-wrap",
        format: currentShortcut ? () => import_constants.presetDetailMap[currentShortcut].label() : format,
        panelRender: (panelNode) => {
          const dom = /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              className: (0, import_classnames.default)(
                "pisell-lowcode-date-picker-custom-wrap",
                {
                  ["pisell-lowcode-date-picker-custom-wrap-show-time"]: showTime
                }
              ),
              ref: panelRef
            },
            !showTime && /* @__PURE__ */ import_react.default.createElement(
              "div",
              {
                className: "pisell-lowcode-date-picker-custom-action",
                onMouseDown: (e) => {
                  canClose.current = false;
                  e.stopPropagation();
                },
                style: {
                  width: `calc(100% - 48px - ${panelTimeWidth}px)`
                }
              },
              /* @__PURE__ */ import_react.default.createElement("div", { style: { width: "50%" } }, /* @__PURE__ */ import_react.default.createElement(
                import_antd.Input,
                {
                  size: "large",
                  placeholder: (0, import_dayjs.default)().format(
                    format || "YYYY-MM-DD"
                  ),
                  value: valueStr,
                  onChange: handleDataStrChange
                }
              ), error && /* @__PURE__ */ import_react.default.createElement("span", { className: "date-picker-error" }, (0, import_locales.getText)("date-picker-invalid-date"))),
              /* @__PURE__ */ import_react.default.createElement(
                import_browserSelect.default,
                {
                  value: currentShortcut || "custom",
                  className: "date-picker-toolbar-select",
                  options: customPresetItems,
                  size: "large",
                  onChange: handleSelectChange,
                  style: { width: "50%" }
                }
              )
            ),
            panelNode
          ), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode-custom-footer" }, /* @__PURE__ */ import_react.default.createElement(
            "span",
            {
              className: "pisell-lowcode-custom-footer-today",
              onClick: handleTodayClick
            },
            (0, import_locales.getText)("date-picker-today")
          ), /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { type: "primary", size: "large", onClick: handleApply }, (0, import_locales.getText)("date-picker-apply"))));
          if (isDesktop) {
            return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode-date-picker-custom-popup-wrap pisell-lowcode-date-picker-dropdown-mode" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode-date-picker-custom-wrap" }, dom));
          }
          if (responsive === "phone") {
            return /* @__PURE__ */ import_react.default.createElement(
              import_antd.Drawer,
              {
                placement: "bottom",
                open,
                height: "auto",
                closable: false,
                styles: {
                  content: {
                    borderRadius: "8px 8px 0 0"
                  }
                },
                bodyStyle: { padding: 0 },
                maskClosable: false
              },
              /* @__PURE__ */ import_react.default.createElement(
                "div",
                {
                  className: "pisell-lowcode-picker-custom-dropdown pisell-lowcode-date-picker-custom-popup-wrap",
                  onMouseDown: (e) => e.stopPropagation()
                },
                /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode-picker-panel-container pisell-lowcode-picker-date-panel-container" }, dom)
              )
            );
          }
          return /* @__PURE__ */ import_react.default.createElement(
            import_antd.Modal,
            {
              width: 458,
              open,
              footer: null,
              closable: false,
              wrapClassName: "pisell-lowcode-date-picker-modal"
            },
            /* @__PURE__ */ import_react.default.createElement(
              "div",
              {
                className: "pisell-lowcode-picker-custom-dropdown pisell-lowcode-date-picker-custom-popup-wrap",
                onMouseDown: (e) => e.stopPropagation()
              },
              /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode-picker-panel-container pisell-lowcode-picker-date-panel-container" }, dom)
            )
          );
        }
      }
    ));
  }
  return /* @__PURE__ */ import_react.default.createElement(import_antd.DatePicker, { ...props });
};
var datePickerCpt_default = DatePickerCpt;
