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 index from "../../../../plus/productSelect/index.js";
import { Toast } from "../../utils.js";
import { useAppointmentBookingContext } from "../../context.js";
import { useAppointmentBooking, useAppointmentBookingProduct, useAppointmentBookingSetting, useAppointmentBookingStep, useConfig } from "../../hooks.js";
import dayjs from "dayjs";
import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from "react";
import { locales } from "@pisell/utils";
import "./index.less";
//#region src/components/appointmentBooking/components/Services/index.tsx
const Services = forwardRef((props, ref) => {
	const context = useEngineContext();
	const { utils } = context.appHelper || {};
	const appointmentBooking = useAppointmentBooking();
	const { isDateSelectedFirst, isRetailTemplate } = useAppointmentBookingSetting();
	const { getProducts, checkProductType } = useAppointmentBookingProduct();
	const { removeStep, nextStep } = useAppointmentBookingStep();
	const { currentStep, setLoading, carts } = useAppointmentBookingContext();
	const [products, setProducts] = useState(null);
	const [productLoading, setProductLoading] = useState(false);
	const { isMobile } = useConfig();
	useImperativeHandle(ref, () => ({ next: () => {
		setLoading(true);
		setTimeout(() => {
			nextStep();
			setLoading(false);
		}, 500);
	} }));
	useEffect(() => {
		setProductLoading(true);
		getProducts().then((res) => {
			setProducts(res || []);
			setProductLoading(false);
		}).catch(() => {
			setProducts([]);
			setProductLoading(false);
		});
	}, [isDateSelectedFirst]);
	/**
	* @description: 是否显示商品详情页面的步进器
	* @param {*} useMemo
	* @return {*}
	*/
	const isShowProductDetailStepper = useMemo(() => {
		const { productModuleParams } = (appointmentBooking === null || appointmentBooking === void 0 ? void 0 : appointmentBooking.otherParams) || {};
		return productModuleParams === null || productModuleParams === void 0 ? void 0 : productModuleParams.isShowProductDetailStepper;
	}, [appointmentBooking === null || appointmentBooking === void 0 ? void 0 : appointmentBooking.otherParams]);
	const handleSelectProduct = function() {
		var _ref2 = _asyncToGenerator(function* (item, clickType) {
			let type = "";
			if (!isRetailTemplate) {
				type = yield checkProductType(item === null || item === void 0 ? void 0 : item.id);
				appointmentBooking.openProductDetail(item.id);
			}
			utils === null || utils === void 0 || utils.action({
				type: "pisell1.productDetail",
				data: {
					detail: _objectSpread2(_objectSpread2({}, item), {}, { open_deposit: 1 }),
					setting: {
						can_input: true,
						item_max_length: isShowProductDetailStepper,
						is_detail_open: clickType === "cover"
					}
				},
				callback: function() {
					var _ref = _asyncToGenerator(function* (data) {
						if (data.isCancel) {
							appointmentBooking.closeProductDetail();
							return;
						}
						const product = _objectSpread2(_objectSpread2({}, data), {}, { options: (data === null || data === void 0 ? void 0 : data.option) || [] });
						delete product.option;
						if (isRetailTemplate) {
							if (data === null || data === void 0 ? void 0 : data.isCancel) return;
							const res = appointmentBooking.storeProduct(product);
							if (!res.success && res.errorCode === "not_enough_stock") return Toast(locales.getText("pisell2.appointment.unuse.stock"));
							return;
						}
						const session = data === null || data === void 0 ? void 0 : data.session;
						if (session) {
							const startDate = dayjs(session === null || session === void 0 ? void 0 : session.start_at).format("YYYY-MM-DD");
							const endDate = dayjs(session === null || session === void 0 ? void 0 : session.end_at).format("YYYY-MM-DD");
							const res = appointmentBooking.addProductToCart({
								product: _objectSpread2({}, product),
								date: {
									startTime: `${startDate} ${session === null || session === void 0 ? void 0 : session.start_time}`,
									endTime: `${endDate} ${session === null || session === void 0 ? void 0 : session.end_time}`
								}
							});
							if (!res.success && res.errorCode === "not_enough_stock") return Toast(locales.getText("pisell2.appointment.unuse.stock"));
							appointmentBooking.closeProductDetail();
							yield appointmentBooking.getAvailableDate({
								startDate,
								endDate
							});
						} else {
							var _data$origin;
							if (!((data === null || data === void 0 || (_data$origin = data.origin) === null || _data$origin === void 0 || (_data$origin = _data$origin.product_resource) === null || _data$origin === void 0 ? void 0 : _data$origin.resources) || []).find((item) => item.status === 1) && !appointmentBooking.isTargetNormalProduct(data === null || data === void 0 ? void 0 : data.origin)) return Toast(locales.getText("pisell2.appointment.no.available.service"));
							const res = appointmentBooking.storeProduct(product);
							if (!res.success && res.errorCode === "not_enough_stock") return Toast(locales.getText("pisell2.appointment.unuse.stock"));
							if (type === "duration") yield appointmentBooking.getAvailableDate();
						}
						appointmentBooking.closeProductDetail();
						if (isDateSelectedFirst) {
							const index = (currentStep === null || currentStep === void 0 ? void 0 : currentStep.index) + 2;
							if (type === "duration" || appointmentBooking.isCartHasDurationProduct()) {
								const stepList = appointmentBooking.getStepList();
								if (stepList === null || stepList === void 0 ? void 0 : stepList.find((item) => (item === null || item === void 0 ? void 0 : item.key) === "select-resource")) {
									const description = locales.getText("pisell2.appointment.select.time");
									appointmentBooking.addStep({
										index,
										key: "select-time",
										description
									}, "select-resource");
								}
							} else removeStep("select-time");
						} else if (type === "session") {
							removeStep("select-date");
							removeStep("select-time");
						}
					});
					return function callback(_x) {
						return _ref.apply(this, arguments);
					};
				}()
			});
		});
		return function handleSelectProduct(_x2, _x3) {
			return _ref2.apply(this, arguments);
		};
	}();
	const productListSetting = useMemo(() => {
		var _context$engine;
		const { customPageData } = ((_context$engine = context.engine) === null || _context$engine === void 0 ? void 0 : _context$engine.props) || {};
		let productListBlock;
		if (Array.isArray(customPageData === null || customPageData === void 0 ? void 0 : customPageData.block)) productListBlock = customPageData.block.find((b) => "product_list" === b.type);
		return (productListBlock === null || productListBlock === void 0 ? void 0 : productListBlock.setting) || {};
	}, [context]);
	const _isMobile = useMemo(() => {
		if (typeof isMobile === "function") return isMobile();
		return isMobile;
	}, [isMobile]);
	return /* @__PURE__ */ React.createElement("div", { className: "appointment-service-wrap" }, /* @__PURE__ */ React.createElement(index, {
		dataSource: products,
		onChange: handleSelectProduct,
		scrollDom: _isMobile ? ".parallel-content-wrap" : ".parallel-booking-wrap",
		offsetDom: _isMobile ? "" : ".pisell-section-headers",
		loading: productLoading,
		emptyDescription: locales.getText("pisell2.appointment.booking.empty.service"),
		token: {
			colorPrimary: "var(--theme-color)",
			containerBg: "#FFFFFF",
			tabItemBg: "#F2F4F7",
			tabItemHoverBg: "#F2F4F7",
			tabItemActiveBg: "var(--theme-color)",
			categoryTextColor: "#1B1B1B",
			cardSelectedBg: "var(--theme-color)"
		},
		productListSetting,
		selectedItems: carts,
		hideCategoryWhenOne: true
	}));
});
//#endregion
export { Services as default };
