import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import { Toast } from "../../utils.js";
import { useAppointmentBookingContext } from "../../context.js";
import { useAppointmentBookingSetting, useAppointmentBookingStep, useConfig } from "../../hooks.js";
import { localeTypes } from "./state.js";
import dayjs from "dayjs";
import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { Skeleton } from "antd";
import { locales } from "@pisell/utils";
import classNames from "classnames";
import { CaretLeftOutlined, CaretRightOutlined } from "@ant-design/icons";
import isSameOrBefore from "dayjs/plugin/isSameOrBefore";
import "./index.less";
//#region src/components/appointmentBooking/components/Date/index.tsx
dayjs.extend(isSameOrBefore);
const Date = forwardRef((props, ref) => {
	var _context$engine2, _Dayjs$locale;
	const isFetchingDates = useRef(false);
	const [loading, setLoading] = useState(false);
	const [currentDate, setCurrentDate] = useState();
	const [dateMonthList, setDateMonthList] = useState([]);
	const [currentMonth, setCurrentMonth] = useState();
	const { appointmentBooking } = useAppointmentBookingContext();
	const { isDateSelectedFirst, customPageId, channel } = useAppointmentBookingSetting();
	const { nextStep } = useAppointmentBookingStep();
	const context = useEngineContext();
	const { isMobile } = useConfig();
	useImperativeHandle(ref, () => ({ next: handleNext }));
	/**
	* @title: 处理进入下一步的逻辑
	* @description:
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-05-13 15:36
	*/
	const handleNext = function() {
		var _ref = _asyncToGenerator(function* () {
			const data = yield appointmentBooking.getDateRange();
			if (!(data === null || data === void 0 ? void 0 : data.length)) return Toast(locales.getText("pisell2.appointment.unselect.date"));
			nextStep();
		});
		return function handleNext() {
			return _ref.apply(this, arguments);
		};
	}();
	const weekListText = [
		locales.getText("pisell2.appointment.sunday"),
		locales.getText("pisell2.appointment.monday"),
		locales.getText("pisell2.appointment.tuesday"),
		locales.getText("pisell2.appointment.wednesday"),
		locales.getText("pisell2.appointment.thursday"),
		locales.getText("pisell2.appointment.friday"),
		locales.getText("pisell2.appointment.saturday")
	];
	const startingColumn = 0;
	const columns = Array.from({ length: 7 }, (_, index) => (index + 7 - startingColumn) % 7);
	useEffect(() => {
		(function() {
			var _ref2 = _asyncToGenerator(function* () {
				var _data$;
				const data = yield appointmentBooking.getDateRange();
				setCurrentMonth(dayjs(data === null || data === void 0 || (_data$ = data[0]) === null || _data$ === void 0 ? void 0 : _data$.date) || dayjs());
			});
			return function getCurrentMonthData() {
				return _ref2.apply(this, arguments);
			};
		})()();
	}, []);
	const locale = useMemo(() => {
		var _context$engine;
		return localeTypes[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";
	}, [context === null || context === void 0 || (_context$engine2 = context.engine) === null || _context$engine2 === void 0 || (_context$engine2 = _context$engine2.props) === null || _context$engine2 === void 0 ? void 0 : _context$engine2.locale]);
	/**
	* @title: 获取当前月日期
	* @description:
	* @param {*}
	* @return {*}
	* @Author: 严文强
	* @Date: 2024-02-01 20:30
	*/
	const getMonthData = (date) => {
		const firstDay = dayjs(`${date}-01`);
		const startDay = firstDay.day();
		const daysInMonth = firstDay.daysInMonth();
		const monthData = [];
		for (let i = 0; i < startDay; i++) monthData.push({
			day: -1,
			date: dayjs(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;
	};
	/**
	* @title: 计算是否已经切换到当前月，如果是则禁止继续点击上一个月
	* @description:
	* @param {*}
	* @return {*}
	* @Author: 严文强
	* @Date: 2024-02-01 19:27
	*/
	const lastMonthDisable = () => {
		return dayjs(currentMonth === null || currentMonth === void 0 ? void 0 : currentMonth.format("YYYY-MM")).subtract(1, "month").isBefore(dayjs(), "month");
	};
	/**
	* @title: 获取日期数据
	* @description:
	* @param {*} params
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-04-24 18:31
	*/
	const getDateData = function() {
		var _ref3 = _asyncToGenerator(function* (params) {
			console.log(isDateSelectedFirst, customPageId, params, channel, "wh7868");
			if (isDateSelectedFirst) return appointmentBooking.loadScheduleAvailableDate(_objectSpread2(_objectSpread2({}, params), {}, {
				custom_page_id: customPageId,
				channel
			}));
			return yield appointmentBooking.getAvailableDate(params);
		});
		return function getDateData(_x) {
			return _ref3.apply(this, arguments);
		};
	}();
	const getDates = function() {
		var _ref4 = _asyncToGenerator(function* (date) {
			try {
				const data = yield getDateData({
					startDate: dayjs(date).startOf("month").format("YYYY-MM-DD"),
					endDate: dayjs(date).endOf("month").format("YYYY-MM-DD")
				});
				const firstAvailableDate = (data || []).find((d) => d.status === "available");
				if (!firstAvailableDate && !isFetchingDates.current) {
					isFetchingDates.current = true;
					setCurrentMonth(dayjs(date).add(1, "month"));
					setLoading(true);
					return;
				}
				const selected = yield appointmentBooking.getDateRange();
				console.log(data, selected, customPageId, "getDates");
				if ((selected === null || selected === void 0 ? void 0 : selected.length) > 0) {
					var _selected$;
					setCurrentDate(selected === null || selected === void 0 || (_selected$ = selected[0]) === null || _selected$ === void 0 ? void 0 : _selected$.date);
				} else if (!isDateSelectedFirst) {
					if (date.format("YYYY-MM") === dayjs().format("YYYY-MM") || isFetchingDates.current) {
						if (firstAvailableDate) {
							setCurrentDate(firstAvailableDate === null || firstAvailableDate === void 0 ? void 0 : firstAvailableDate.date);
							appointmentBooking.setDateRange([firstAvailableDate]);
						}
					}
				}
				const updatedDates = getMonthData(date.format("YYYY-MM")).map((day) => {
					const matchedDay = data.find((d) => d.date === day.date);
					if (matchedDay) return _objectSpread2(_objectSpread2(_objectSpread2({}, day), matchedDay), {}, { disabled: matchedDay.status === "unavailable" });
					return day;
				});
				setLoading(false);
				setDateMonthList(updatedDates);
			} catch (error) {
				setLoading(false);
				setDateMonthList([]);
			}
		});
		return function getDates(_x2) {
			return _ref4.apply(this, arguments);
		};
	}();
	useEffect(() => {
		if (!currentMonth) return;
		getDates(currentMonth);
	}, [currentMonth]);
	/**
	* @title: 切换上个月
	* @description:
	* @param {*}
	* @return {*}
	* @Author: 严文强
	* @Date: 2024-02-01 19:15
	*/
	const lastMonth = () => {
		setCurrentMonth(dayjs(currentMonth === null || currentMonth === void 0 ? void 0 : currentMonth.format("YYYY-MM")).subtract(1, "month"));
	};
	/**
	* @title: 切换下个月
	* @description:
	* @param {*}
	* @return {*}
	* @Author: 严文强
	* @Date: 2024-02-01 19:15
	*/
	const nextMonth = () => {
		setCurrentMonth(dayjs(currentMonth === null || currentMonth === void 0 ? void 0 : currentMonth.format("YYYY-MM")).add(1, "month"));
		setLoading(true);
	};
	/**
	* @title: 点击某一天日期
	* @description:
	* @param {any} day
	* @param {any} date
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-04-24 18:36
	*/
	const handleClick = (day, date) => {
		if (day === null || day === void 0 ? void 0 : day.disabled) return;
		setCurrentDate(date);
		appointmentBooking.setDateRange([day]);
		if (isDateSelectedFirst) handleNext();
	};
	return /* @__PURE__ */ React.createElement("div", { className: `calendar-date-box ${isMobile ? "calendar-date-mobile-box" : ""}` }, !dateMonthList.length || !currentMonth ? /* @__PURE__ */ React.createElement(Skeleton, {
		loading: true,
		active: true,
		style: { paddingTop: "16px" }
	}) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "calendar-header" }, /* @__PURE__ */ React.createElement("div", {
		className: classNames("calendar-last-month", { ["last-month-disabled"]: lastMonthDisable() }),
		onClick: () => {
			if (lastMonthDisable()) return;
			lastMonth();
		}
	}, /* @__PURE__ */ React.createElement(CaretLeftOutlined, null)), /* @__PURE__ */ React.createElement("div", { className: "calendar-current-month" }, (_Dayjs$locale = dayjs(currentMonth).locale(locale)) === null || _Dayjs$locale === void 0 ? void 0 : _Dayjs$locale.format("MMMM YYYY")), /* @__PURE__ */ React.createElement("div", {
		className: "calendar-next-month",
		onClick: nextMonth
	}, /* @__PURE__ */ React.createElement(CaretRightOutlined, null))), /* @__PURE__ */ React.createElement("div", { className: "calendar-content" }, /* @__PURE__ */ React.createElement("div", { className: "calendar-weeks" }, columns.map((col) => /* @__PURE__ */ React.createElement("div", {
		key: col,
		className: "calendar-weeks-items"
	}, weekListText[Number(col)]))), /* @__PURE__ */ React.createElement("div", { className: "calendar-days" }, dateMonthList.map((day, index) => {
		const date = dayjs(day.date).format("YYYY-MM-DD");
		const isCurrentMonth = dayjs(day.date).isSame(currentMonth, "month");
		return /* @__PURE__ */ React.createElement("div", {
			key: index,
			className: classNames("calendar-days-items", {
				["disabledDate"]: day === null || day === void 0 ? void 0 : day.disabled,
				["selectDate"]: currentDate === date,
				["other-month-days"]: !isCurrentMonth,
				["loading-item"]: loading
			}),
			onClick: () => handleClick(day, date)
		}, isCurrentMonth && /* @__PURE__ */ React.createElement("div", { className: classNames("day-text") }, dayjs(day.date).format("D")));
	})))));
});
//#endregion
export { Date as default };
