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/Sales/Cart/index.tsx
var Cart_exports = {};
__export(Cart_exports, {
  CartContext: () => CartContext,
  CartProvider: () => CartProvider,
  default: () => Cart_default,
  useCart: () => useCart
});
module.exports = __toCommonJS(Cart_exports);
var import_react = __toESM(require("react"));
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var import_SalesModel = require("../../../businessModel/SalesModel");
var import_serve = require("./serve");
var import_Customer = require("../Customer");
var import_ahooks = require("ahooks");
var import_utils2 = require("../Checkout/utils");
var import_utils3 = require("./utils");
var defaultState = {
  cartItems: [],
  currentCartItem: null
};
var CartContext = (0, import_react.createContext)(
  void 0
);
var CartProvider = ({ children }) => {
  const { appContext, appUtils, getUserInfo } = (0, import_Customer.useCustomer)();
  const { data, setData, hooks, getCurrentData } = (0, import_SalesModel.useSales)();
  const [openCart, setOpen] = (0, import_react.useState)(false);
  const checkRef = (0, import_react.useRef)(null);
  const cartData = (0, import_react.useMemo)(() => {
    return data.cartData || defaultState;
  }, [data]);
  const currentCartItem = (0, import_react.useMemo)(() => {
    return cartData.currentCartItem;
  }, [cartData]);
  const cartDataHolderList = (0, import_react.useMemo)(() => {
    var _a, _b;
    if (!((_a = cartData.cartItems) == null ? void 0 : _a.length)) {
      return [];
    }
    const selectedHolderItems = ((_b = getCurrentData().holderData) == null ? void 0 : _b.selectedHolderItems) || [];
    if (selectedHolderItems == null ? void 0 : selectedHolderItems.length) {
      const cartMap = getCurrentData().cartData.cartItems.reduce(
        (map, cartItem) => {
          if (!map.has(cartItem.holder_id)) {
            map.set(cartItem.holder_id, []);
          }
          map.get(cartItem.holder_id).push(cartItem);
          return map;
        },
        /* @__PURE__ */ new Map()
      );
      const result = selectedHolderItems.map((holderItem) => {
        return {
          ...holderItem,
          children: cartMap.get(holderItem.id) || []
        };
      });
      if (cartMap.get(void 0)) {
        result.push({ children: cartMap.get(void 0) });
      }
      return result;
    } else {
      return [{ children: cartData.cartItems }];
    }
  }, [data]);
  const onOpenCart = () => {
    setOpen(true);
  };
  const onCloseCart = () => {
    setOpen(false);
  };
  const setCartData = (newCartData) => {
    setData({
      cartData: {
        ...getCurrentData().cartData || {},
        ...newCartData
      }
    });
  };
  const createCartItemOriginData = () => {
    return {
      // 新增为0
      id: 0,
      // 数量 固定为1
      number: 1,
      // 客户端报名所有活动;
      registration_type: "all",
      // 暂时不用
      relation_products: [],
      // 商品相关
      product: null,
      // holder相关
      holder: null,
      // 资源相关
      // 资源状态 -固定
      like_status: "common",
      // 资源类型 - 固定
      relation_type: "form",
      // 日程id - 固定
      schedule_id: 0,
      // 资源id - event id
      relation_id: null,
      // 所选开始时间 - 从日程中取第一个
      start_date: null,
      // 所选开始时间 - 从日程中取第一个
      start_time: null,
      // 所选开始时间 - 从日程中取第一个
      select_date: null,
      // 所选结束时间 -固定
      end_time: null,
      // 所选结束时间 - 固定
      end_date: null,
      // 时长类型 - 固定 - 天
      sub_type: "days",
      // 时长 - 固定
      duration: 0,
      // 固定
      is_all: false
    };
  };
  const createCartItem = () => {
    const cartItem = {
      _id: (0, import_utils.getUniqueId)(),
      _originData: createCartItemOriginData()
    };
    setCurrentCartItem(cartItem);
    return cartItem;
  };
  const createCartItemFromEvent = (eventItem) => {
    console.log("eventItem>>>>>>", eventItem);
    const { resourceData, holderData } = getCurrentData();
    let cartItem = {
      _id: (0, import_utils.getUniqueId)(),
      _originData: createCartItemOriginData(),
      resourceItem: resourceData == null ? void 0 : resourceData.currentResourceItem,
      eventItem: { ...eventItem }
    };
    const currentHolderItem = getCurrentHolderItem();
    if (currentHolderItem) {
      cartItem = { ...cartItem, holderItem: currentHolderItem };
    }
    setCurrentCartItem(cartItem);
    return cartItem;
  };
  const createCartItemFromHolder = (holderItem) => {
    var _a;
    const cartItem = {
      _id: (0, import_utils.getUniqueId)(),
      _originData: createCartItemOriginData(),
      resourceItem: (_a = data.resourceData) == null ? void 0 : _a.currentResourceItem,
      holderItem
    };
    setCurrentCartItem(cartItem);
    return cartItem;
  };
  const checkBeforeAddToCartResquest = (0, import_ahooks.useRequest)(import_serve.checkBeforeAddToCartApi, {
    manual: true,
    onSuccess: (res) => {
      var _a, _b;
      if ((_a = res.data) == null ? void 0 : _a.length) {
        const isUnavailable = checkCartItemIsUnavailable(
          res.data,
          checkRef.current.cartItem
        );
        checkRef.current.callback({
          result: isUnavailable ? false : true,
          num: isUnavailable ? (_b = res.data) == null ? void 0 : _b.length : 0
        });
      } else {
        checkRef.current.callback({ result: true });
      }
    }
  });
  const checkBeforeAddToCart = () => {
    return new Promise((resolve) => {
      var _a, _b;
      const _cartData = getCurrentData().cartData;
      const newCartItem = createCartItemData() || {};
      const params = (0, import_utils2.formatValues)({
        state: {
          cartData: {
            cartItems: [..._cartData.cartItems || [], newCartItem]
          }
        },
        platform: (_b = (_a = appContext == null ? void 0 : appContext.appHelper) == null ? void 0 : _a.constants) == null ? void 0 : _b.platform
      });
      checkRef.current = {
        callback: (res) => {
          resolve(res);
          checkRef.current = null;
        },
        cartItem: newCartItem
      };
      checkBeforeAddToCartResquest.runAsync(params);
    });
  };
  const createCartItemData = () => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u;
    const _cartData = getCurrentData().cartData;
    if (_cartData.currentCartItem) {
      const {
        _id,
        eventItem = {},
        holderItem = {}
      } = _cartData.currentCartItem || {};
      const eventDetail = eventItem == null ? void 0 : eventItem.eventDetail;
      const bookingOptionData = (_a = eventDetail == null ? void 0 : eventDetail.bookingOptionItem) == null ? void 0 : _a._originData;
      console.log("eventDetail>>>>>>", eventDetail);
      const startDateInfo = (_c = (_b = eventItem == null ? void 0 : eventItem.eventDetail) == null ? void 0 : _b.selectDate) == null ? void 0 : _c.startDateInfo;
      const startTime = (_e = (_d = startDateInfo == null ? void 0 : startDateInfo.times) == null ? void 0 : _d[0]) == null ? void 0 : _e.start_at;
      const endDateInfo = (_g = (_f = eventItem == null ? void 0 : eventItem.eventDetail) == null ? void 0 : _f.selectDate) == null ? void 0 : _g.endDateInfo;
      const endTime = (_j = (_i = (_h = endDateInfo == null ? void 0 : endDateInfo.times) == null ? void 0 : _h.slice(-1)) == null ? void 0 : _i[0]) == null ? void 0 : _j.end_at;
      const num = 1;
      const { price, totalPrice, originTotal, is_charge_tax } = (0, import_utils3.handleProductInfo)(eventDetail, num);
      const transformProduct = (_temp) => {
        var _a2;
        if (!((_a2 = _temp == null ? void 0 : _temp.variant) == null ? void 0 : _a2.length)) {
          return { ..._temp || {}, variant: [] };
        }
        return _temp;
      };
      const newCartItem = {
        _id,
        id: eventItem.id,
        name: eventItem.title,
        price,
        // eventBooking中售价和总价保持一致，因为数量为1
        origin_price: price,
        total: totalPrice,
        // 排除原始价格为0的场景
        origin_total: isNaN(originTotal) || originTotal === 0 ? void 0 : originTotal,
        num,
        image: eventItem.image,
        isShowNote: true,
        note: "",
        holder_title: holderItem.name,
        holder_id: holderItem.id,
        symbol: appUtils == null ? void 0 : appUtils.getSymbolic(),
        start_date: (startDateInfo == null ? void 0 : startDateInfo.date) || "",
        start_time: startTime ? (0, import_dayjs.default)(startTime || "").format("HH:mm") : "",
        end_date: (endDateInfo == null ? void 0 : endDateInfo.date) || "",
        // 格式化日期显示的格式
        format: ["HH:mm DD/MM/YYYY", "YYYY-MM-DD HH:mm"],
        // 是否显示时间
        show_time: true,
        end_time: endTime ? (0, import_dayjs.default)(endTime || "").format("HH:mm") : "",
        custom_day_count: ((_m = (_l = (_k = eventItem == null ? void 0 : eventItem.eventDetail) == null ? void 0 : _k.selectDate) == null ? void 0 : _l.dates) == null ? void 0 : _m.length) || 0,
        is_charge_tax,
        selectedBundle: (_n = eventDetail == null ? void 0 : eventDetail.productDetail) == null ? void 0 : _n.bundle,
        selectedOptions: (_o = eventDetail == null ? void 0 : eventDetail.productDetail) == null ? void 0 : _o.options,
        isNormalProduct: true,
        // 是否是普通商品，eventBooking中接入的都是普通商品
        _originData: {
          ..._cartData.currentCartItem._originData,
          product: {
            num: 1,
            product_id: bookingOptionData == null ? void 0 : bookingOptionData.id,
            note: "",
            // eventdetail 获取
            product_bundle: [],
            product_option_item: [],
            product_variant_id: 0
          },
          relation_id: eventItem.id,
          start_date: (startDateInfo == null ? void 0 : startDateInfo.date) || null,
          start_time: startTime ? (0, import_dayjs.default)(startTime || "").format("HH:mm") : null,
          select_date: (startDateInfo == null ? void 0 : startDateInfo.date) || null,
          metadata: {
            end_date_text: (endDateInfo == null ? void 0 : endDateInfo.date) || null,
            end_time_text: endTime ? (0, import_dayjs.default)(endTime || "").format("HH:mm") : null
          },
          event_unique_identifier: _id
          // 传递给接口用于商品可用性检测的比对
        },
        _eventDetail: eventDetail,
        _productDetail: eventDetail.productDetail,
        _productOrigin: transformProduct(
          ((_p = eventDetail == null ? void 0 : eventDetail.productDetail) == null ? void 0 : _p.origin) || bookingOptionData
        ),
        _productInit: transformProduct(
          ((_q = eventDetail == null ? void 0 : eventDetail.productDetail) == null ? void 0 : _q.origin) || bookingOptionData
        )
      };
      newCartItem.deposit = (0, import_utils3.handleProductDeposit)(newCartItem, eventDetail, num);
      const originData = (0, import_utils3.handleCartItemOrigin)(newCartItem, eventDetail);
      newCartItem._originData = originData;
      if (holderItem == null ? void 0 : holderItem._originData) {
        newCartItem._originData.holder = {
          customer_id: (_r = getUserInfo()) == null ? void 0 : _r.id,
          form_id: (_s = holderItem == null ? void 0 : holderItem._originData) == null ? void 0 : _s.form_id,
          form_record: ((_t = holderItem == null ? void 0 : holderItem._originData) == null ? void 0 : _t.form_record_id) ? [(_u = holderItem == null ? void 0 : holderItem._originData) == null ? void 0 : _u.form_record_id] : null
        };
      }
      return newCartItem;
    }
    return null;
  };
  const addToCart = () => {
    const _cartData = getCurrentData().cartData;
    const newCartItem = createCartItemData();
    if (_cartData.currentCartItem && newCartItem) {
      setCartData({
        cartItems: [..._cartData.cartItems || [], newCartItem],
        currentCartItem: null
      });
    }
  };
  const updateCartItem = (cartItem, updateType) => {
    var _a, _b, _c;
    let newCartItems = (_c = (_b = (_a = getCurrentData()) == null ? void 0 : _a.cartData) == null ? void 0 : _b.cartItems) == null ? void 0 : _c.map(
      (item) => {
        if (item._id === cartItem._id) {
          const _tempCartItem = { ...cartItem || {} };
          if (updateType === "deposit") {
            const eventDetail = _tempCartItem == null ? void 0 : _tempCartItem._eventDetail;
            if (eventDetail) {
              const num = (_tempCartItem == null ? void 0 : _tempCartItem.num) || 1;
              const deposit = (0, import_utils3.handleProductDeposit)(_tempCartItem, eventDetail, num);
              _tempCartItem.deposit = deposit;
            }
          }
          return _tempCartItem;
        }
        return item;
      }
    );
    setCartData({
      cartItems: newCartItems
    });
    return cartItem;
  };
  const addHolderToCartItem = (holderItem) => {
    const newCartItems = getCurrentData().cartData.cartItems.map(
      (item) => {
        var _a, _b, _c, _d;
        if (!item.holder_id) {
          item = {
            ...item,
            holder_title: holderItem.name,
            holder_id: holderItem.id
          };
          item._originData.holder = {
            customer_id: (_a = getUserInfo()) == null ? void 0 : _a.id,
            form_id: (_b = holderItem == null ? void 0 : holderItem._originData) == null ? void 0 : _b.form_id,
            form_record: ((_c = holderItem == null ? void 0 : holderItem._originData) == null ? void 0 : _c.form_record_id) ? [(_d = holderItem == null ? void 0 : holderItem._originData) == null ? void 0 : _d.form_record_id] : null
          };
        }
        return item;
      }
    );
    setCartData({ cartItems: newCartItems });
  };
  const addNoteToCartItem = (cartItem) => {
    const newCartItems = getCurrentData().cartData.cartItems.map(
      (item) => {
        if (item._id === cartItem._id) {
          item = {
            ...item,
            note: cartItem.note
          };
          item._originData.product = {
            ...item._originData.product || {},
            note: cartItem.note
          };
        }
        return item;
      }
    );
    setCartData({ cartItems: newCartItems });
  };
  const deleteCartItem = (cartItem) => {
    const newCartItems = getCurrentData().cartData.cartItems.filter(
      (item) => item._id !== cartItem._id
    );
    setCartData({
      cartItems: newCartItems
    });
  };
  const deleteCartItemByHolder = (holder_id) => {
    const newCartItems = getCurrentData().cartData.cartItems.filter(
      (item) => item.holder_id !== holder_id
    );
    setCartData({
      cartItems: newCartItems
    });
  };
  const clickCartItem = (cartItem) => {
    setCurrentCartItem(cartItem);
  };
  const setCurrentCartItem = (cartItem) => {
    setCartData({
      currentCartItem: cartItem
    });
  };
  const updateCurrentCartItem = (cartItem) => {
    var _a;
    const item = (_a = getCurrentData().cartData) == null ? void 0 : _a.currentCartItem;
    if (item) {
      setCurrentCartItem({ ...item, ...cartItem });
    }
  };
  const clearCurrentCartItem = () => {
    setCartData({
      currentCartItem: null
    });
  };
  const checkHolder = () => {
    var _a;
    const currentCartItems = (_a = getCurrentData().cartData) == null ? void 0 : _a.cartItems;
    if (currentCartItems == null ? void 0 : currentCartItems.length) {
      const idx = currentCartItems.find((v) => !v.holder_id);
      if (idx === void 0) {
        return true;
      }
    }
    return false;
  };
  const getCurrentHolderItem = () => {
    const { selectedHolderItems, currentHolderItem } = getCurrentData().holderData || {};
    if (selectedHolderItems == null ? void 0 : selectedHolderItems.length) {
      let newCurrentHolderItem = currentHolderItem;
      const result = selectedHolderItems.find(
        (v) => v.id === (currentHolderItem == null ? void 0 : currentHolderItem.id)
      );
      if (result === void 0) {
        newCurrentHolderItem = selectedHolderItems[selectedHolderItems.length - 1];
      }
      return newCurrentHolderItem;
    }
    return null;
  };
  const checkCartItemIsUnavailable = (list, item) => {
    var _a, _b, _c, _d;
    const productId = (_b = (_a = item._originData) == null ? void 0 : _a.product) == null ? void 0 : _b.product_id;
    const relationId = (_c = item._originData) == null ? void 0 : _c.relation_id;
    const eventUniqueIdentifier = (_d = item._originData) == null ? void 0 : _d.event_unique_identifier;
    return list.find((res) => {
      var _a2;
      const checkType = ["available_capacity"];
      const isTypeIncludes = ((_a2 = res.details) == null ? void 0 : _a2.find((v) => {
        var _a3;
        return (_a3 = checkType.includes) == null ? void 0 : _a3.call(checkType, v.type || "");
      })) !== void 0;
      if (isTypeIncludes) {
        return res.product_id === productId && res.relation_id === relationId && res.event_unique_identifier === eventUniqueIdentifier;
      }
      return false;
    }) !== void 0;
  };
  const updateDisabledCartItem = (list) => {
    const currentCartItems = getCurrentData().cartData.cartItems || [];
    if ((list == null ? void 0 : list.length) && currentCartItems.length) {
      const newCartItems = currentCartItems.map((item) => {
        const isUnavailable = checkCartItemIsUnavailable(list, item);
        if (isUnavailable) {
          item.disabled = true;
        } else {
          item.disabled = false;
        }
        return item;
      });
      setCartData({ cartItems: newCartItems });
    }
  };
  const getWithoutCartItemsHolderNames = () => {
    var _a;
    const list = [];
    (_a = cartDataHolderList == null ? void 0 : cartDataHolderList.forEach) == null ? void 0 : _a.call(cartDataHolderList, (v) => {
      var _a2;
      if (!((_a2 = v == null ? void 0 : v.children) == null ? void 0 : _a2.length)) {
        list.push((v == null ? void 0 : v.name) || "");
      }
    });
    return list;
  };
  const contextValue = {
    createCartItem,
    createCartItemFromEvent,
    createCartItemFromHolder,
    addToCart,
    updateCartItem,
    deleteCartItem,
    clickCartItem,
    updateCurrentCartItem,
    clearCurrentCartItem,
    currentCartItem,
    cartData,
    checkHolder,
    openCart,
    onOpenCart,
    onCloseCart,
    deleteCartItemByHolder,
    addHolderToCartItem,
    cartDataHolderList,
    addNoteToCartItem,
    updateDisabledCartItem,
    getWithoutCartItemsHolderNames,
    checkBeforeAddToCartResquest,
    checkBeforeAddToCart
  };
  return /* @__PURE__ */ import_react.default.createElement(CartContext.Provider, { value: contextValue }, children);
};
var useCart = () => {
  const context = import_react.default.useContext(CartContext);
  if (!context) {
    throw new Error("useCart must be used within a CartProvider");
  }
  return context;
};
var Cart_default = {
  defaultState
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CartContext,
  CartProvider,
  useCart
});
