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/appointmentBooking/components/Date/index.tsx
var Date_exports = {};
__export(Date_exports, {
  default: () => Date_default
});
module.exports = __toCommonJS(Date_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_dayjs = __toESM(require("dayjs"));
var import_isSameOrBefore = __toESM(require("dayjs/plugin/isSameOrBefore"));
var import_classnames = __toESM(require("classnames"));
var import_utils = require("@pisell/utils");
var import_icons = require("@ant-design/icons");
var import_context = require("../../context");
var import_utils2 = require("../../utils");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_hooks = require("../../hooks");
var import_state = require("./state");
var import_index = require("./index.less");
import_dayjs.default.extend(import_isSameOrBefore.default);
var Date = (0, import_react.forwardRef)((props, ref) => {
  var _a, _b, _c;
  const isFetchingDates = (0, import_react.useRef)(false);
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [currentDate, setCurrentDate] = (0, import_react.useState)();
  const [dateMonthList, setDateMonthList] = (0, import_react.useState)([]);
  const [currentMonth, setCurrentMonth] = (0, import_react.useState)();
  const { appointmentBooking } = (0, import_context.useAppointmentBookingContext)();
  const { isDateSelectedFirst, customPageId, channel } = (0, import_hooks.useAppointmentBookingSetting)();
  const { nextStep } = (0, import_hooks.useAppointmentBookingStep)();
  const context = (0, import_useEngineContext.default)();
  (0, import_react.useImperativeHandle)(ref, () => ({
    next: handleNext
  }));
  const handleNext = async () => {
    const data = await appointmentBooking.getDateRange();
    if (!(data == null ? void 0 : data.length)) {
      return (0, import_utils2.Toast)(import_utils.locales.getText("pisell2.appointment.unselect.date"));
    }
    nextStep();
  };
  const weekListText = [
    import_utils.locales.getText("pisell2.appointment.sunday"),
    import_utils.locales.getText("pisell2.appointment.monday"),
    import_utils.locales.getText("pisell2.appointment.tuesday"),
    import_utils.locales.getText("pisell2.appointment.wednesday"),
    import_utils.locales.getText("pisell2.appointment.thursday"),
    import_utils.locales.getText("pisell2.appointment.friday"),
    import_utils.locales.getText("pisell2.appointment.saturday")
  ];
  const startingColumn = 0 % 7;
  const columns = Array.from(
    { length: 7 },
    (_, index) => (index + 7 - startingColumn) % 7
  );
  (0, import_react.useEffect)(() => {
    const getCurrentMonthData = async () => {
      var _a2;
      const data = await appointmentBooking.getDateRange();
      setCurrentMonth((0, import_dayjs.default)((_a2 = data == null ? void 0 : data[0]) == null ? void 0 : _a2.date) || (0, import_dayjs.default)());
    };
    getCurrentMonthData();
  }, []);
  const locale = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    const currentLocale = (_b2 = (_a2 = context == null ? void 0 : context.engine) == null ? void 0 : _a2.props) == null ? void 0 : _b2.locale;
    return import_state.localeTypes[currentLocale] || "en";
  }, [(_b = (_a = context == null ? void 0 : context.engine) == null ? void 0 : _a.props) == null ? void 0 : _b.locale]);
  const getMonthData = (date) => {
    const firstDay = (0, import_dayjs.default)(`${date}-01`);
    const startDay = firstDay.day();
    const daysInMonth = firstDay.daysInMonth();
    const monthData = [];
    for (let i = 0; i < startDay; i++) {
      monthData.push({
        day: -1,
        // 表示前一个月的日期
        date: (0, import_dayjs.default)(firstDay).subtract(startDay - i, "day").toDate()
      });
    }
    for (let i = 1; i <= daysInMonth; i++) {
      monthData.push({
        day: i,
        date: firstDay.date(i).format("YYYY-MM-DD")
      });
    }
    return monthData;
  };
  const lastMonthDisable = () => {
    let newCurrentMonth = currentMonth == null ? void 0 : currentMonth.format("YYYY-MM");
    let lastDate = (0, import_dayjs.default)(newCurrentMonth).subtract(1, "month");
    return lastDate.isBefore((0, import_dayjs.default)(), "month");
  };
  const getDateData = async (params) => {
    console.log(isDateSelectedFirst, customPageId, params, channel, "wh7868");
    if (isDateSelectedFirst) {
      return appointmentBooking.loadScheduleAvailableDate({
        ...params,
        custom_page_id: customPageId,
        channel
      });
    }
    return await appointmentBooking.getAvailableDate(params);
  };
  const getDates = async (date) => {
    var _a2;
    try {
      const startDate = (0, import_dayjs.default)(date).startOf("month").format("YYYY-MM-DD");
      const endDate = (0, import_dayjs.default)(date).endOf("month").format("YYYY-MM-DD");
      const params = {
        startDate,
        endDate
      };
      const data = await getDateData(params);
      const firstAvailableDate = (data || []).find(
        (d) => d.status === "available"
      );
      if (!firstAvailableDate && !isFetchingDates.current) {
        isFetchingDates.current = true;
        const nextMonthDate = (0, import_dayjs.default)(date).add(1, "month");
        setCurrentMonth(nextMonthDate);
        setLoading(true);
        return;
      }
      const selected = await appointmentBooking.getDateRange();
      console.log(data, selected, customPageId, "getDates");
      if ((selected == null ? void 0 : selected.length) > 0) {
        setCurrentDate((_a2 = selected == null ? void 0 : selected[0]) == null ? void 0 : _a2.date);
      } else if (!isDateSelectedFirst) {
        if (date.format("YYYY-MM") === (0, import_dayjs.default)().format("YYYY-MM") || isFetchingDates.current) {
          if (firstAvailableDate) {
            setCurrentDate(firstAvailableDate == null ? void 0 : firstAvailableDate.date);
            appointmentBooking.setDateRange([firstAvailableDate]);
          }
        }
      }
      const baseMonthData = getMonthData(date.format("YYYY-MM"));
      const updatedDates = baseMonthData.map((day) => {
        const matchedDay = data.find((d) => d.date === day.date);
        if (matchedDay) {
          return {
            ...day,
            ...matchedDay,
            disabled: matchedDay.status === "unavailable"
          };
        }
        return day;
      });
      setLoading(false);
      setDateMonthList(updatedDates);
    } catch (error) {
      setLoading(false);
      setDateMonthList([]);
    }
  };
  (0, import_react.useEffect)(() => {
    if (!currentMonth) return;
    getDates(currentMonth);
  }, [currentMonth]);
  const lastMonth = () => {
    let currentLastText = currentMonth == null ? void 0 : currentMonth.format("YYYY-MM");
    let newLastMonth = (0, import_dayjs.default)(currentLastText).subtract(1, "month");
    setCurrentMonth(newLastMonth);
  };
  const nextMonth = () => {
    let currentMonthText = currentMonth == null ? void 0 : currentMonth.format("YYYY-MM");
    let newNextMonth = (0, import_dayjs.default)(currentMonthText).add(1, "month");
    setCurrentMonth(newNextMonth);
    setLoading(true);
  };
  const handleClick = (day, date) => {
    if (day == null ? void 0 : day.disabled) return;
    setCurrentDate(date);
    appointmentBooking.setDateRange([day]);
    if (isDateSelectedFirst) {
      handleNext();
    }
  };
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: `calendar-date-box ${(0, import_utils.isMobile)() ? "calendar-date-mobile-box" : ""}`
    },
    !dateMonthList.length || !currentMonth ? /* @__PURE__ */ import_react.default.createElement(import_antd.Skeleton, { loading: true, active: true, style: { paddingTop: "16px" } }) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "calendar-header" }, /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: (0, import_classnames.default)("calendar-last-month", {
          ["last-month-disabled"]: lastMonthDisable()
        }),
        onClick: () => {
          if (lastMonthDisable()) return;
          lastMonth();
        }
      },
      /* @__PURE__ */ import_react.default.createElement(import_icons.CaretLeftOutlined, null)
    ), /* @__PURE__ */ import_react.default.createElement("div", { className: "calendar-current-month" }, (_c = (0, import_dayjs.default)(currentMonth).locale(locale)) == null ? void 0 : _c.format("MMMM YYYY")), /* @__PURE__ */ import_react.default.createElement("div", { className: "calendar-next-month", onClick: nextMonth }, /* @__PURE__ */ import_react.default.createElement(import_icons.CaretRightOutlined, null))), /* @__PURE__ */ import_react.default.createElement("div", { className: "calendar-content" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "calendar-weeks" }, columns.map((col) => /* @__PURE__ */ import_react.default.createElement("div", { key: col, className: "calendar-weeks-items" }, weekListText[Number(col)]))), /* @__PURE__ */ import_react.default.createElement("div", { className: "calendar-days" }, dateMonthList.map((day, index) => {
      const date = (0, import_dayjs.default)(day.date).format("YYYY-MM-DD");
      const isCurrentMonth = (0, import_dayjs.default)(day.date).isSame(
        currentMonth,
        "month"
      );
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          key: index,
          className: (0, import_classnames.default)("calendar-days-items", {
            ["disabledDate"]: day == null ? void 0 : day.disabled,
            ["selectDate"]: currentDate === date,
            ["other-month-days"]: !isCurrentMonth,
            ["loading-item"]: loading
          }),
          onClick: () => handleClick(day, date)
        },
        isCurrentMonth && /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)("day-text") }, (0, import_dayjs.default)(day.date).format("D"))
      );
    }))))
  );
});
var Date_default = Date;
