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/Services/index.tsx
var Services_exports = {};
__export(Services_exports, {
  default: () => Services_default
});
module.exports = __toCommonJS(Services_exports);
var import_react = __toESM(require("react"));
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var import_productSelect = __toESM(require("../../../../plus/productSelect"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_context = require("../../context");
var import_hooks = require("../../hooks");
var import_index = require("./index.less");
var import_utils2 = require("../../utils");
var Services = (0, import_react.forwardRef)((props, ref) => {
  const context = (0, import_useEngineContext.default)();
  const { utils } = context.appHelper || {};
  const appointmentBooking = (0, import_hooks.useAppointmentBooking)();
  const { isDateSelectedFirst, isRetailTemplate } = (0, import_hooks.useAppointmentBookingSetting)();
  const { getProducts, checkProductType } = (0, import_hooks.useAppointmentBookingProduct)();
  const { removeStep, nextStep } = (0, import_hooks.useAppointmentBookingStep)();
  const { currentStep, setLoading, carts } = (0, import_context.useAppointmentBookingContext)();
  const [products, setProducts] = (0, import_react.useState)(null);
  const [productLoading, setProductLoading] = (0, import_react.useState)(false);
  (0, import_react.useImperativeHandle)(ref, () => ({
    next: () => {
      setLoading(true);
      setTimeout(() => {
        nextStep();
        setLoading(false);
      }, 500);
    }
  }));
  (0, import_react.useEffect)(() => {
    setProductLoading(true);
    getProducts().then((res) => {
      setProducts(res || []);
      setProductLoading(false);
    }).catch(() => {
      setProducts([]);
      setProductLoading(false);
    });
  }, [isDateSelectedFirst]);
  const isShowProductDetailStepper = (0, import_react.useMemo)(() => {
    const { productModuleParams } = (appointmentBooking == null ? void 0 : appointmentBooking.otherParams) || {};
    return productModuleParams == null ? void 0 : productModuleParams.isShowProductDetailStepper;
  }, [appointmentBooking == null ? void 0 : appointmentBooking.otherParams]);
  const handleSelectProduct = async (item, clickType) => {
    let type = "";
    if (!isRetailTemplate) {
      type = await checkProductType(item == null ? void 0 : item.id);
      appointmentBooking.openProductDetail(item.id);
    }
    utils == null ? void 0 : utils.action({
      type: "pisell1.productDetail",
      data: {
        detail: { ...item, open_deposit: 1 },
        setting: { can_input: true, item_max_length: isShowProductDetailStepper, is_detail_open: clickType === "cover" }
      },
      callback: async (data) => {
        var _a, _b;
        if (data.isCancel) {
          appointmentBooking.closeProductDetail();
          return;
        }
        const product = {
          ...data,
          options: (data == null ? void 0 : data.option) || []
        };
        delete product.option;
        if (isRetailTemplate) {
          if (data == null ? void 0 : data.isCancel) return;
          const res = appointmentBooking.storeProduct(product);
          if (!res.success && res.errorCode === "not_enough_stock") {
            return (0, import_utils2.Toast)(import_utils.locales.getText("pisell2.appointment.unuse.stock"));
          }
          return;
        }
        const session = data == null ? void 0 : data.session;
        if (session) {
          const startDate = (0, import_dayjs.default)(session == null ? void 0 : session.start_at).format("YYYY-MM-DD");
          const endDate = (0, import_dayjs.default)(session == null ? void 0 : session.end_at).format("YYYY-MM-DD");
          const res = appointmentBooking.addProductToCart({
            product: { ...product },
            date: {
              startTime: `${startDate} ${session == null ? void 0 : session.start_time}`,
              endTime: `${endDate} ${session == null ? void 0 : session.end_time}`
            }
          });
          if (!res.success && res.errorCode === "not_enough_stock") {
            return (0, import_utils2.Toast)(import_utils.locales.getText("pisell2.appointment.unuse.stock"));
          }
          appointmentBooking.closeProductDetail();
          await appointmentBooking.getAvailableDate({
            startDate,
            endDate
          });
        } else {
          const resources = ((_b = (_a = data == null ? void 0 : data.origin) == null ? void 0 : _a.product_resource) == null ? void 0 : _b.resources) || [];
          const activeStatus = resources.find((item2) => item2.status === 1);
          if (!activeStatus && !appointmentBooking.isTargetNormalProduct(data == null ? void 0 : data.origin)) {
            return (0, import_utils2.Toast)(
              import_utils.locales.getText("pisell2.appointment.no.available.service")
            );
          }
          const res = appointmentBooking.storeProduct(product);
          if (!res.success && res.errorCode === "not_enough_stock") {
            return (0, import_utils2.Toast)(import_utils.locales.getText("pisell2.appointment.unuse.stock"));
          }
          if (type === "duration") {
            await appointmentBooking.getAvailableDate();
          }
        }
        appointmentBooking.closeProductDetail();
        if (isDateSelectedFirst) {
          const index = (currentStep == null ? void 0 : currentStep.index) + 2;
          if (type === "duration" || appointmentBooking.isCartHasDurationProduct()) {
            const stepList = appointmentBooking.getStepList();
            const hasResourceStep = stepList == null ? void 0 : stepList.find(
              (item2) => (item2 == null ? void 0 : item2.key) === "select-resource"
            );
            if (hasResourceStep) {
              const description = import_utils.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");
          }
        }
      }
    });
  };
  const productListSetting = (0, import_react.useMemo)(() => {
    var _a;
    const { customPageData } = ((_a = context.engine) == null ? void 0 : _a.props) || {};
    let productListBlock;
    if (Array.isArray(customPageData == null ? void 0 : customPageData.block)) {
      productListBlock = customPageData.block.find(
        (b) => "product_list" === b.type
      );
    }
    return (productListBlock == null ? void 0 : productListBlock.setting) || {};
  }, [context]);
  const _isMobile = (0, import_react.useMemo)(() => {
    if (typeof import_utils.isMobile === "function") return (0, import_utils.isMobile)();
    return import_utils.isMobile;
  }, [import_utils.isMobile]);
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "appointment-service-wrap" }, /* @__PURE__ */ import_react.default.createElement(
    import_productSelect.default,
    {
      dataSource: products,
      onChange: handleSelectProduct,
      scrollDom: _isMobile ? ".parallel-content-wrap" : ".parallel-booking-wrap",
      offsetDom: _isMobile ? "" : ".pisell-section-headers",
      loading: productLoading,
      emptyDescription: import_utils.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
    }
  ));
});
var Services_default = Services;
