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/ticketBooking/components/addServiceVariant/addService.tsx
var addService_exports = {};
__export(addService_exports, {
  default: () => addService_default
});
module.exports = __toCommonJS(addService_exports);
var import_utils = require("@pisell/utils");
var import_react = __toESM(require("react"));
var import_ahooks = require("ahooks");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_utils2 = require("../../../booking/utils");
var import_utils3 = require("../../../booking/info2/service/addService/utils");
var import_utils4 = require("../../../booking/info/service2/utils");
var import_utils5 = require("../../../booking/info/utils");
var import_serviceManager = require("../../../booking/info/service/serviceManager");
var import_productSelect = __toESM(require("../../../../plus/productSelect"));
var import_index = require("./index.less");
var import_utils6 = require("../../utils");
var import_notAvailable = __toESM(require("../notAvailable"));
var import_dayjs = __toESM(require("dayjs"));
var import_pisellos = require("../../hooks/pisellos");
var import_utils7 = require("./utils");
var import_materials = require("@pisell/materials");
var productListLayout = {
  grid: true,
  config: "12:12"
};
var productListSetting = {
  isProductCover: 1,
  isTitle: 1,
  isSubtitle: 1,
  isPrice: 1,
  isOriginPrice: 0,
  isStock: 0
};
var AddSerivce = (props) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
  const { onEdit, state, dispatch, renderMode = "current" } = props;
  const context = (0, import_useEngineContext.default)();
  const notAvailableRef = (0, import_react.useRef)(null);
  const isLoadedServiceRef = (0, import_react.useRef)(false);
  import_utils2.request.setRequest(context.appHelper.utils.request);
  const Toast = (0, import_materials.useToast)();
  const { createBookingData, createBooking } = (0, import_serviceManager.useService)({
    renderMode,
    onEdit,
    state,
    dispatch
  });
  const isBooking4 = (0, import_utils5.isBooking4Shop)(
    ((_c = (_b = (_a = context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.getData) == null ? void 0 : _c.call(_b, "shop_id")) || ((_h = (_g = (_f = (_e = (_d = context.appHelper.utils.store) == null ? void 0 : _d.getState) == null ? void 0 : _e.call(_d)) == null ? void 0 : _f.global) == null ? void 0 : _g.globalConfig) == null ? void 0 : _h.id),
    state == null ? void 0 : state.renderType,
    (_i = context.appHelper.utils) == null ? void 0 : _i.businessUtils
  );
  const [currentProduct, setCurrentProduct] = (0, import_react.useState)(null);
  const stateRef = (0, import_react.useRef)(state);
  stateRef.current = state;
  const { getProducts, products, loading } = (0, import_pisellos.useProducts)();
  (0, import_react.useEffect)(() => {
    return () => {
      Object.values(debounceTimersRef.current).forEach((timer) => {
        if (timer) clearTimeout(timer);
      });
      debounceTimersRef.current = {};
    };
  }, []);
  (0, import_react.useEffect)(() => {
    const handler = (event) => {
      var _a2;
      const cacheItem = (_a2 = event == null ? void 0 : event.detail) == null ? void 0 : _a2.cacheItem;
      console.log("Modal closed with result:", event.detail.cacheItem);
      if (!(cacheItem == null ? void 0 : cacheItem.id)) return;
      (0, import_utils6.addServiceScroll)(String(cacheItem.id), cacheItem);
    };
    window.addEventListener("onAddNewService", handler);
    return () => {
      window.removeEventListener("onAddNewService", handler);
    };
  }, []);
  const pendingCacheValuesRef = (0, import_react.useRef)({});
  const clickCountRef = (0, import_react.useRef)({});
  const debounceTimersRef = (0, import_react.useRef)({});
  const menuList = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    return ((_c2 = (_b2 = (_a2 = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.menu_list_tab) == null ? void 0 : _c2.menu_list) || [];
  }, [(_j = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _j.config]);
  const customerId = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    return ((_b2 = (_a2 = state.client) == null ? void 0 : _a2.value) == null ? void 0 : _b2.id) || void 0;
  }, [(_l = (_k = state.client) == null ? void 0 : _k.value) == null ? void 0 : _l.id]);
  const scanAddService = (0, import_ahooks.useMemoizedFn)((list, code) => {
    let newService = [...state.service.value];
    list.forEach((item) => {
      if ((0, import_utils7.isBundle)(item) || (0, import_utils7.isOption)(item)) {
        handleSelectProduct(item);
        return;
      }
      const values = (0, import_utils7.genValues)(item, code);
      let cacheItem = (0, import_utils7.createCacheItem)(item, values, state);
      cacheItem._serviceKey = (0, import_utils6.genServiceKey)(cacheItem);
      cacheItem.autoClose = false;
      let { list: _list, quantity } = (0, import_utils6.addService)(
        [...newService],
        cacheItem,
        state
      );
      handleAddToast(cacheItem.title, quantity);
      newService = _list;
    });
    dispatch({
      type: "setService",
      payload: {
        value: newService,
        edit: true
      }
    });
  });
  (0, import_react.useMemo)(() => {
    (0, import_utils7.setHandleSetService)(scanAddService);
  }, []);
  const handleAddToast = (title, quantity) => {
    var _a2;
    (_a2 = Toast == null ? void 0 : Toast.success) == null ? void 0 : _a2.call(
      Toast,
      /* @__PURE__ */ import_react.default.createElement("div", { className: "add-toast-wrap" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "add-toast-title" }, title), /* @__PURE__ */ import_react.default.createElement("div", { className: "add-toast-quantity" }, import_utils.locales.getText("pisell2.ticket-booking.in-cart")(quantity || 1)))
    );
  };
  const executeCacheValues = (0, import_ahooks.useMemoizedFn)(
    (productId, originalCacheValues, item, originalCallback) => {
      const clickCount = clickCountRef.current[productId] || 1;
      const finalCacheValues = {
        ...originalCacheValues,
        quantity: clickCount
      };
      delete pendingCacheValuesRef.current[productId];
      delete clickCountRef.current[productId];
      delete debounceTimersRef.current[productId];
      originalCallback(finalCacheValues, "", item, true);
    }
  );
  const debouncedExecuteCacheValues = (0, import_ahooks.useMemoizedFn)(
    (productId, cacheValues, item, callback) => {
      if (debounceTimersRef.current[productId]) {
        clearTimeout(debounceTimersRef.current[productId]);
      }
      debounceTimersRef.current[productId] = setTimeout(() => {
        executeCacheValues(productId, cacheValues, item, callback);
      }, 0);
    }
  );
  const handleSelectProduct = (0, import_ahooks.useMemoizedFn)(
    (item, type = "select") => {
      var _a2, _b2, _c2, _d2;
      console.log("handleSelectProduct");
      if (!(0, import_utils4.isNormalProductByDurationSchedule)(item)) {
        if (!Array.isArray((_a2 = state.service) == null ? void 0 : _a2.resourcesOrigin) || !state.service.resourcesOrigin.length) {
          dispatch({
            type: "setService",
            payload: {
              ...stateRef.current.service,
              reloadResourceModal: true
            }
          });
          return;
        }
      }
      const isSession = (0, import_utils2.isSessionProduct)(item);
      const isEject = (0, import_utils2.getIsEject)(item, type);
      const isOnlySession = (0, import_utils2.getIsOnlySession)(item);
      let lock = false;
      let cacheValues = null;
      if (isEject) {
        setCurrentProduct(item);
      } else {
        setCurrentProduct(null);
        if ((item == null ? void 0 : item.extension_type) === "normal") {
          cacheValues = {
            bundle: [],
            key: item.id,
            option: [],
            product_id: item.id,
            product_variant_id: 0,
            quantity: 1,
            rowKey: item.id,
            session: null,
            unique: "08974625397",
            _originalItem: item
            // 保存原始商品信息
          };
        }
      }
      const callback = async (e, extension_type, detail, notShowToast) => {
        var _a3, _b3, _c3, _d3, _e2, _f2, _g2;
        setCurrentProduct(null);
        if (lock) {
          return;
        }
        lock = true;
        setTimeout(() => {
          lock = false;
        }, 2e3);
        if (!isBooking4) {
          const data = await createBookingData({
            product: { ...detail || item, _params: e }
          });
          createBooking({ booking: data });
          return;
        }
        const _detail = detail || item;
        const other = JSON.parse(JSON.stringify(e));
        other.session = e.session;
        let cacheItem = {
          ..._detail,
          product_id: item.id,
          _id: (0, import_utils.getUniqueId)(),
          _key: e.key,
          _extend: {
            start_date: state.date.value,
            quantity: (e == null ? void 0 : e.quantity) || 1,
            price: _detail.price,
            product_name: item.title,
            other
          },
          new: 1
        };
        let _total = (0, import_utils2.getProductTotalPrice)(cacheItem);
        cacheItem._extend.total = _total;
        cacheItem._extend.origin_total = _total;
        const _isEdit = !!state.service.cacheItem;
        if (_isEdit) {
          cacheItem._id = (_a3 = state.service.cacheItem) == null ? void 0 : _a3._id;
          cacheItem.new = 0;
        }
        if (renderMode === "current") {
          cacheItem.currentDefaultTime = state.date.value.format("HH:mm");
        }
        cacheItem = (0, import_utils3.getProductExtend)({
          cacheItem,
          state,
          isDisabledTime: true
        });
        if (state.renderType === "eventBooking") {
          cacheItem.autoClose = false;
        }
        if (cacheItem.autoClose) {
          cacheItem.autoClose = false;
          cacheItem._serviceKey = (0, import_utils6.genServiceKey)(cacheItem);
          let { list: _list, quantity } = (0, import_utils6.addService)(
            [...state.service.value],
            cacheItem,
            state
          );
          if (!notShowToast) {
            handleAddToast(cacheItem.title, quantity || 1);
          }
          window.dispatchEvent(
            new CustomEvent("onAddNewService", {
              detail: {
                cacheItem
              }
            })
          );
          try {
            if (((_f2 = (_e2 = (_d3 = (_c3 = (_b3 = context.appHelper.utils.store) == null ? void 0 : _b3.getState) == null ? void 0 : _c3.call(_b3)) == null ? void 0 : _d3.global) == null ? void 0 : _e2.globalConfig) == null ? void 0 : _f2.id) === 2155) {
              const val = _list == null ? void 0 : _list.map((s) => {
                return {
                  product_id: s == null ? void 0 : s.product_id,
                  detailId: s == null ? void 0 : s.id,
                  detailProductId: s == null ? void 0 : s.product_id,
                  product_name: s == null ? void 0 : s.title,
                  price: s == null ? void 0 : s.price,
                  _id: s == null ? void 0 : s._id,
                  _key: s == null ? void 0 : s._key,
                  _serviceKey: s == null ? void 0 : s._serviceKey
                };
              });
              const sendData = {
                product_id: item == null ? void 0 : item.id,
                detailId: _detail == null ? void 0 : _detail.id,
                detailProductId: _detail == null ? void 0 : _detail.product_id,
                product_name: item == null ? void 0 : item.title,
                price: _detail == null ? void 0 : _detail.price,
                serviceVal: val
              };
              (0, import_utils.sendWarningLog)({
                title: "addService",
                content: [
                  { key: "添加数据", value: JSON.stringify(sendData) },
                  {
                    key: "日期",
                    value: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
                  }
                ]
              });
            }
          } catch (error) {
          }
          dispatch({
            type: "setService",
            payload: {
              addModal: false,
              value: _list,
              edit: true,
              changeService: false
            }
          });
        } else {
          (_g2 = window.openBookingEditModal) == null ? void 0 : _g2.call(window);
          dispatch({
            type: "setService",
            payload: {
              editModal: true,
              cacheItem,
              addModal: !cacheItem.autoClose,
              changeService: false
            }
          });
          onEdit == null ? void 0 : onEdit(cacheItem);
        }
      };
      if (cacheValues) {
        const productId = item.id.toString();
        if (pendingCacheValuesRef.current[productId]) {
          clickCountRef.current[productId] = (clickCountRef.current[productId] || 1) + 1;
        } else {
          pendingCacheValuesRef.current[productId] = cacheValues;
          clickCountRef.current[productId] = 1;
        }
        const cacheItem = (0, import_utils6.createSimpleCacheItem)(item, cacheValues, state);
        const detail = (_b2 = state.service.value) == null ? void 0 : _b2.find(
          (val) => (0, import_utils6.isSameProduct)(val, cacheItem)
        );
        const originalQuantity = ((_c2 = detail == null ? void 0 : detail._extend) == null ? void 0 : _c2.quantity) || 0;
        (_d2 = Toast == null ? void 0 : Toast.success) == null ? void 0 : _d2.call(
          Toast,
          /* @__PURE__ */ import_react.default.createElement("div", { className: "add-toast-wrap" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "add-toast-title" }, item.title), /* @__PURE__ */ import_react.default.createElement("div", { className: "add-toast-quantity" }, import_utils.locales.getText("pisell2.ticket-booking.in-cart")(
            (clickCountRef.current[productId] || 1) + originalQuantity
          )))
        );
        debouncedExecuteCacheValues(productId, cacheValues, item, callback);
        return;
      }
      state.action({
        type: "pisell1.handleOpenProductModal",
        data: {
          id: item.id,
          date: state.date.value.format("YYYY-MM-DD"),
          showConfig: {
            option: true,
            session: isSession,
            variant: true,
            package: true,
            number: (0, import_utils6.getIsShowNumber)(item, state)
          },
          isOnlySession,
          is_eject: isEject ? 1 : 0,
          customer_id: customerId,
          isOS: isSession
        },
        onCancel: () => {
          setCurrentProduct(null);
        },
        callback
      });
    }
  );
  const renderList = (0, import_react.useMemo)(() => {
    let _list = products || [];
    if ((0, import_utils4.isDaysBooking)(state)) {
      if (!(0, import_utils4.holderId)(state)) {
        _list = _list.filter(
          (item) => (0, import_utils4.isNormalProductByDurationSchedule)(item)
        );
      }
    }
    return _list;
  }, [products, state == null ? void 0 : state.activeCartId]);
  const currentDate = (0, import_react.useMemo)(() => {
    return state.date.value.format("YYYY-MM-DD");
  }, [state.date.value]);
  const currentDatetime = (0, import_react.useMemo)(() => {
    return state.date.value.format("YYYY-MM-DD HH:mm:ss");
  }, [state.date.value]);
  (0, import_react.useEffect)(() => {
    if (renderMode === "current" && state.bookingConfig) {
      getProducts({
        schedule_date: currentDate,
        customer_id: customerId,
        menu_list_ids: menuList,
        schedule_datetime: currentDatetime
      });
    }
  }, [renderMode, currentDate, customerId, menuList, currentDatetime]);
  return (0, import_react.useMemo)(() => {
    if (renderMode === "current") {
      return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
        import_productSelect.default,
        {
          dataSource: renderList,
          layout: productListLayout,
          onChange: handleSelectProduct,
          value: currentProduct == null ? void 0 : currentProduct.id,
          loading: !renderList.length && loading,
          productListSetting
        }
      ), /* @__PURE__ */ import_react.default.createElement(import_notAvailable.default, { ref: notAvailableRef }));
    }
    return null;
  }, [
    state.service.addModal,
    import_utils.locales,
    renderList,
    state.amountSymbol,
    state.renderType,
    state == null ? void 0 : state.activeCartId,
    (0, import_utils4.holderId)(state),
    loading,
    currentProduct,
    isBooking4
  ]);
};
var addService_default = AddSerivce;
