function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { createContext, useMemo, useRef, useState } from 'react';
import dayjs from 'dayjs';
import { getUniqueId } from '@pisell/utils';
import { useSales } from "../../../businessModel/SalesModel";
import { checkBeforeAddToCartApi } from "./serve";
import { useCustomer } from "../Customer";
import { useRequest } from 'ahooks';
import { formatValues } from "../Checkout/utils";
import { handleCartItemOrigin, handleProductDeposit, handleProductInfo } from "./utils";
var defaultState = {
  cartItems: [],
  currentCartItem: null
};
export var CartContext = /*#__PURE__*/createContext(undefined);
export var CartProvider = function CartProvider(_ref) {
  var children = _ref.children;
  var _useCustomer = useCustomer(),
    appContext = _useCustomer.appContext,
    appUtils = _useCustomer.appUtils,
    getUserInfo = _useCustomer.getUserInfo;
  var _useSales = useSales(),
    data = _useSales.data,
    setData = _useSales.setData,
    hooks = _useSales.hooks,
    getCurrentData = _useSales.getCurrentData;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    openCart = _useState2[0],
    setOpen = _useState2[1];
  var checkRef = useRef(null);
  var cartData = useMemo(function () {
    return data.cartData || defaultState;
  }, [data]);
  var currentCartItem = useMemo(function () {
    return cartData.currentCartItem;
  }, [cartData]);

  /**
   * @title: 通过holder对购物车中商品进行分类展示
   * @Author: xiangfeng.xue
   */
  var cartDataHolderList = useMemo(function () {
    var _cartData$cartItems, _getCurrentData$holde;
    if (!((_cartData$cartItems = cartData.cartItems) !== null && _cartData$cartItems !== void 0 && _cartData$cartItems.length)) {
      return [];
    }
    var selectedHolderItems = ((_getCurrentData$holde = getCurrentData().holderData) === null || _getCurrentData$holde === void 0 ? void 0 : _getCurrentData$holde.selectedHolderItems) || [];
    if (selectedHolderItems !== null && selectedHolderItems !== void 0 && selectedHolderItems.length) {
      var cartMap = getCurrentData().cartData.cartItems.reduce(function (map, cartItem) {
        if (!map.has(cartItem.holder_id)) {
          map.set(cartItem.holder_id, []);
        }
        map.get(cartItem.holder_id).push(cartItem);
        return map;
      }, new Map());
      var result = selectedHolderItems.map(function (holderItem) {
        return _objectSpread(_objectSpread({}, holderItem), {}, {
          children: cartMap.get(holderItem.id) || []
        });
      });
      if (cartMap.get(undefined)) {
        result.push({
          children: cartMap.get(undefined)
        });
      }
      return result;
    } else {
      return [{
        children: cartData.cartItems
      }];
    }
  }, [data]);
  var onOpenCart = function onOpenCart() {
    setOpen(true);
  };
  var onCloseCart = function onCloseCart() {
    setOpen(false);
  };
  var setCartData = function setCartData(newCartData) {
    setData({
      cartData: _objectSpread(_objectSpread({}, getCurrentData().cartData || {}), newCartData)
    });
  };
  var createCartItemOriginData = function 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
    };
  };
  var createCartItem = function createCartItem() {
    var cartItem = {
      _id: getUniqueId(),
      _originData: createCartItemOriginData()
    };
    // 创建购物车数据模型后将current指向该模型
    setCurrentCartItem(cartItem);
    return cartItem;
  };

  /**
   * 从event列表直接创建购物车
   */
  /**
   * @title:
   * @description: 从event列表直接创建购物车，没有holder时选择最后一次操作的holder信息
   * @param {any} eventItem
   * @return {void}
   * @Author: xiangfeng.xue
   * @Date: 2025-01-20 13:00
   */
  var createCartItemFromEvent = function createCartItemFromEvent(eventItem) {
    console.log('eventItem>>>>>>', eventItem);
    var _getCurrentData = getCurrentData(),
      resourceData = _getCurrentData.resourceData,
      holderData = _getCurrentData.holderData;
    var cartItem = {
      _id: getUniqueId(),
      _originData: createCartItemOriginData(),
      resourceItem: resourceData === null || resourceData === void 0 ? void 0 : resourceData.currentResourceItem,
      eventItem: _objectSpread({}, eventItem)
    };
    var currentHolderItem = getCurrentHolderItem();
    if (currentHolderItem) {
      cartItem = _objectSpread(_objectSpread({}, cartItem), {}, {
        holderItem: currentHolderItem
      });
    }
    // 创建购物车数据模型后将current指向该模型
    setCurrentCartItem(cartItem);
    return cartItem;
  };

  /**
   * 使用holder直接创建购物车
   */
  /**
   * @description: 使用holder直接创建购物车
   * @param {any} holderItem holder信息
   * @return {*}
   * @Author: xiangfeng.xue
   */
  var createCartItemFromHolder = function createCartItemFromHolder(holderItem) {
    var _data$resourceData;
    var cartItem = {
      _id: getUniqueId(),
      _originData: createCartItemOriginData(),
      resourceItem: (_data$resourceData = data.resourceData) === null || _data$resourceData === void 0 ? void 0 : _data$resourceData.currentResourceItem,
      holderItem: holderItem
    };
    // 创建购物车数据模型后将current指向该模型
    setCurrentCartItem(cartItem);
    return cartItem;
  };
  var checkBeforeAddToCartResquest = useRequest(checkBeforeAddToCartApi, {
    manual: true,
    onSuccess: function onSuccess(res) {
      var _res$data;
      if ((_res$data = res.data) !== null && _res$data !== void 0 && _res$data.length) {
        var _res$data2;
        var isUnavailable = checkCartItemIsUnavailable(res.data, checkRef.current.cartItem);
        // 检测当前商品是否不可用
        checkRef.current.callback({
          result: isUnavailable ? false : true,
          num: isUnavailable ? (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.length : 0
        });
      } else {
        checkRef.current.callback({
          result: true
        });
      }
    }
  });

  /**
   * @title: 商品加入购物车前进行校验
   * @description:
   * @Author: xiangfeng.xue
   */
  var checkBeforeAddToCart = function checkBeforeAddToCart() {
    return new Promise(function (resolve) {
      var _appContext$appHelper;
      var _cartData = getCurrentData().cartData;
      var newCartItem = createCartItemData() || {};
      var params = formatValues({
        state: {
          cartData: {
            cartItems: [].concat(_toConsumableArray(_cartData.cartItems || []), [newCartItem])
          }
        },
        platform: appContext === null || appContext === void 0 || (_appContext$appHelper = appContext.appHelper) === null || _appContext$appHelper === void 0 || (_appContext$appHelper = _appContext$appHelper.constants) === null || _appContext$appHelper === void 0 ? void 0 : _appContext$appHelper.platform
      });
      checkRef.current = {
        callback: function callback(res) {
          resolve(res);
          checkRef.current = null;
        },
        cartItem: newCartItem
      };
      checkBeforeAddToCartResquest.runAsync(params);
    });
  };

  /**
   * @title: 构建当前商品的完整购物车数据
   * @description:
   * @return {*} Object | null
   * @Author: xiangfeng.xue
   */
  var createCartItemData = function createCartItemData() {
    var _cartData = getCurrentData().cartData;
    if (_cartData.currentCartItem) {
      var _eventDetail$bookingO, _eventItem$eventDetai, _startDateInfo$times, _eventItem$eventDetai2, _endDateInfo$times, _eventItem$eventDetai3, _eventDetail$productD, _eventDetail$productD2, _eventDetail$productD3, _eventDetail$productD4;
      var _ref2 = _cartData.currentCartItem || {},
        _id = _ref2._id,
        _ref2$eventItem = _ref2.eventItem,
        _eventItem = _ref2$eventItem === void 0 ? {} : _ref2$eventItem,
        _ref2$holderItem = _ref2.holderItem,
        _holderItem = _ref2$holderItem === void 0 ? {} : _ref2$holderItem;
      var eventDetail = _eventItem === null || _eventItem === void 0 ? void 0 : _eventItem.eventDetail;
      var bookingOptionData = eventDetail === null || eventDetail === void 0 || (_eventDetail$bookingO = eventDetail.bookingOptionItem) === null || _eventDetail$bookingO === void 0 ? void 0 : _eventDetail$bookingO._originData;
      console.log('eventDetail>>>>>>', eventDetail);

      // 活动开始日期相关信息
      var startDateInfo = _eventItem === null || _eventItem === void 0 || (_eventItem$eventDetai = _eventItem.eventDetail) === null || _eventItem$eventDetai === void 0 || (_eventItem$eventDetai = _eventItem$eventDetai.selectDate) === null || _eventItem$eventDetai === void 0 ? void 0 : _eventItem$eventDetai.startDateInfo;
      var startTime = startDateInfo === null || startDateInfo === void 0 || (_startDateInfo$times = startDateInfo.times) === null || _startDateInfo$times === void 0 || (_startDateInfo$times = _startDateInfo$times[0]) === null || _startDateInfo$times === void 0 ? void 0 : _startDateInfo$times.start_at;
      var endDateInfo = _eventItem === null || _eventItem === void 0 || (_eventItem$eventDetai2 = _eventItem.eventDetail) === null || _eventItem$eventDetai2 === void 0 || (_eventItem$eventDetai2 = _eventItem$eventDetai2.selectDate) === null || _eventItem$eventDetai2 === void 0 ? void 0 : _eventItem$eventDetai2.endDateInfo;
      var endTime = endDateInfo === null || endDateInfo === void 0 || (_endDateInfo$times = endDateInfo.times) === null || _endDateInfo$times === void 0 || (_endDateInfo$times = _endDateInfo$times.slice(-1)) === null || _endDateInfo$times === void 0 || (_endDateInfo$times = _endDateInfo$times[0]) === null || _endDateInfo$times === void 0 ? void 0 : _endDateInfo$times.end_at;
      var num = 1;
      var _handleProductInfo = handleProductInfo(eventDetail, num),
        price = _handleProductInfo.price,
        totalPrice = _handleProductInfo.totalPrice,
        originTotal = _handleProductInfo.originTotal,
        is_charge_tax = _handleProductInfo.is_charge_tax;
      var transformProduct = function transformProduct(_temp) {
        var _temp$variant;
        if (!(_temp !== null && _temp !== void 0 && (_temp$variant = _temp.variant) !== null && _temp$variant !== void 0 && _temp$variant.length)) {
          return _objectSpread(_objectSpread({}, _temp || {}), {}, {
            variant: []
          });
        }
        return _temp;
      };
      var newCartItem = {
        _id: _id,
        id: _eventItem.id,
        name: _eventItem.title,
        price: price,
        // eventBooking中售价和总价保持一致，因为数量为1
        origin_price: price,
        total: totalPrice,
        // 排除原始价格为0的场景
        origin_total: isNaN(originTotal) || originTotal === 0 ? undefined : originTotal,
        num: num,
        image: _eventItem.image,
        isShowNote: true,
        note: '',
        holder_title: _holderItem.name,
        holder_id: _holderItem.id,
        symbol: appUtils === null || appUtils === void 0 ? void 0 : appUtils.getSymbolic(),
        start_date: (startDateInfo === null || startDateInfo === void 0 ? void 0 : startDateInfo.date) || '',
        start_time: startTime ? dayjs(startTime || '').format('HH:mm') : '',
        end_date: (endDateInfo === null || endDateInfo === void 0 ? void 0 : endDateInfo.date) || '',
        // 格式化日期显示的格式
        format: ['HH:mm DD/MM/YYYY', 'YYYY-MM-DD HH:mm'],
        // 是否显示时间
        show_time: true,
        end_time: endTime ? dayjs(endTime || '').format('HH:mm') : '',
        custom_day_count: (_eventItem === null || _eventItem === void 0 || (_eventItem$eventDetai3 = _eventItem.eventDetail) === null || _eventItem$eventDetai3 === void 0 || (_eventItem$eventDetai3 = _eventItem$eventDetai3.selectDate) === null || _eventItem$eventDetai3 === void 0 || (_eventItem$eventDetai3 = _eventItem$eventDetai3.dates) === null || _eventItem$eventDetai3 === void 0 ? void 0 : _eventItem$eventDetai3.length) || 0,
        is_charge_tax: is_charge_tax,
        selectedBundle: eventDetail === null || eventDetail === void 0 || (_eventDetail$productD = eventDetail.productDetail) === null || _eventDetail$productD === void 0 ? void 0 : _eventDetail$productD.bundle,
        selectedOptions: eventDetail === null || eventDetail === void 0 || (_eventDetail$productD2 = eventDetail.productDetail) === null || _eventDetail$productD2 === void 0 ? void 0 : _eventDetail$productD2.options,
        isNormalProduct: true,
        // 是否是普通商品，eventBooking中接入的都是普通商品
        _originData: _objectSpread(_objectSpread({}, _cartData.currentCartItem._originData), {}, {
          product: {
            num: 1,
            product_id: bookingOptionData === null || bookingOptionData === void 0 ? void 0 : bookingOptionData.id,
            note: '',
            // eventdetail 获取
            product_bundle: [],
            product_option_item: [],
            product_variant_id: 0
          },
          relation_id: _eventItem.id,
          start_date: (startDateInfo === null || startDateInfo === void 0 ? void 0 : startDateInfo.date) || null,
          start_time: startTime ? dayjs(startTime || '').format('HH:mm') : null,
          select_date: (startDateInfo === null || startDateInfo === void 0 ? void 0 : startDateInfo.date) || null,
          metadata: {
            end_date_text: (endDateInfo === null || endDateInfo === void 0 ? void 0 : endDateInfo.date) || null,
            end_time_text: endTime ? dayjs(endTime || '').format('HH:mm') : null
          },
          event_unique_identifier: _id // 传递给接口用于商品可用性检测的比对
        }),
        _eventDetail: eventDetail,
        _productDetail: eventDetail.productDetail,
        _productOrigin: transformProduct((eventDetail === null || eventDetail === void 0 || (_eventDetail$productD3 = eventDetail.productDetail) === null || _eventDetail$productD3 === void 0 ? void 0 : _eventDetail$productD3.origin) || bookingOptionData),
        _productInit: transformProduct((eventDetail === null || eventDetail === void 0 || (_eventDetail$productD4 = eventDetail.productDetail) === null || _eventDetail$productD4 === void 0 ? void 0 : _eventDetail$productD4.origin) || bookingOptionData)
      };

      // 处理定金
      newCartItem.deposit = handleProductDeposit(newCartItem, eventDetail, num);
      // 处理提交给接口的数据
      var originData = handleCartItemOrigin(newCartItem, eventDetail);
      newCartItem._originData = originData;
      if (_holderItem !== null && _holderItem !== void 0 && _holderItem._originData) {
        var _getUserInfo, _holderItem$_originDa, _holderItem$_originDa2, _holderItem$_originDa3;
        newCartItem._originData.holder = {
          customer_id: (_getUserInfo = getUserInfo()) === null || _getUserInfo === void 0 ? void 0 : _getUserInfo.id,
          form_id: _holderItem === null || _holderItem === void 0 || (_holderItem$_originDa = _holderItem._originData) === null || _holderItem$_originDa === void 0 ? void 0 : _holderItem$_originDa.form_id,
          form_record: _holderItem !== null && _holderItem !== void 0 && (_holderItem$_originDa2 = _holderItem._originData) !== null && _holderItem$_originDa2 !== void 0 && _holderItem$_originDa2.form_record_id ? [_holderItem === null || _holderItem === void 0 || (_holderItem$_originDa3 = _holderItem._originData) === null || _holderItem$_originDa3 === void 0 ? void 0 : _holderItem$_originDa3.form_record_id] : null
        };
      }
      return newCartItem;
    }
    return null;
  };

  /**
   * 将商品加入购物车
   */
  var addToCart = function addToCart() {
    var _cartData = getCurrentData().cartData;
    var newCartItem = createCartItemData();
    if (_cartData.currentCartItem && newCartItem) {
      setCartData({
        cartItems: [].concat(_toConsumableArray(_cartData.cartItems || []), [newCartItem]),
        currentCartItem: null
      });
    }
  };
  var updateCartItem = function updateCartItem(cartItem, updateType) {
    var _getCurrentData2;
    var newCartItems = (_getCurrentData2 = getCurrentData()) === null || _getCurrentData2 === void 0 || (_getCurrentData2 = _getCurrentData2.cartData) === null || _getCurrentData2 === void 0 || (_getCurrentData2 = _getCurrentData2.cartItems) === null || _getCurrentData2 === void 0 ? void 0 : _getCurrentData2.map(function (item) {
      if (item._id === cartItem._id) {
        var _tempCartItem = _objectSpread({}, cartItem || {});
        // 更新定金信息
        if (updateType === 'deposit') {
          var eventDetail = _tempCartItem === null || _tempCartItem === void 0 ? void 0 : _tempCartItem._eventDetail;
          if (eventDetail) {
            var num = (_tempCartItem === null || _tempCartItem === void 0 ? void 0 : _tempCartItem.num) || 1;
            var deposit = handleProductDeposit(_tempCartItem, eventDetail, num);
            _tempCartItem.deposit = deposit;
          }
        }
        return _tempCartItem;
      }
      return item;
    });
    setCartData({
      cartItems: newCartItems
    });
    return cartItem;
  };

  /**
   * 将holder添加到所有没有holder信息的商品中
   * @param holderItem any
   */
  var addHolderToCartItem = function addHolderToCartItem(holderItem) {
    var newCartItems = getCurrentData().cartData.cartItems.map(function (item) {
      if (!item.holder_id) {
        var _getUserInfo2, _holderItem$_originDa4, _holderItem$_originDa5, _holderItem$_originDa6;
        item = _objectSpread(_objectSpread({}, item), {}, {
          holder_title: holderItem.name,
          holder_id: holderItem.id
        });
        item._originData.holder = {
          customer_id: (_getUserInfo2 = getUserInfo()) === null || _getUserInfo2 === void 0 ? void 0 : _getUserInfo2.id,
          form_id: holderItem === null || holderItem === void 0 || (_holderItem$_originDa4 = holderItem._originData) === null || _holderItem$_originDa4 === void 0 ? void 0 : _holderItem$_originDa4.form_id,
          form_record: holderItem !== null && holderItem !== void 0 && (_holderItem$_originDa5 = holderItem._originData) !== null && _holderItem$_originDa5 !== void 0 && _holderItem$_originDa5.form_record_id ? [holderItem === null || holderItem === void 0 || (_holderItem$_originDa6 = holderItem._originData) === null || _holderItem$_originDa6 === void 0 ? void 0 : _holderItem$_originDa6.form_record_id] : null
        };
      }
      return item;
    });
    setCartData({
      cartItems: newCartItems
    });
  };

  /**
   * @description: 给购物车中商品增加备注
   * @param {CartItem} cartItem
   * @Author: xiangfeng.xue
   */
  var addNoteToCartItem = function addNoteToCartItem(cartItem) {
    var newCartItems = getCurrentData().cartData.cartItems.map(function (item) {
      if (item._id === cartItem._id) {
        item = _objectSpread(_objectSpread({}, item), {}, {
          note: cartItem.note
        });
        item._originData.product = _objectSpread(_objectSpread({}, item._originData.product || {}), {}, {
          note: cartItem.note
        });
      }
      return item;
    });
    setCartData({
      cartItems: newCartItems
    });
  };

  // 通过cartId进行删除
  var deleteCartItem = function deleteCartItem(cartItem) {
    var newCartItems = getCurrentData().cartData.cartItems.filter(function (item) {
      return item._id !== cartItem._id;
    });
    setCartData({
      cartItems: newCartItems
    });
  };

  // 通过holder进行删除
  var deleteCartItemByHolder = function deleteCartItemByHolder(holder_id) {
    var newCartItems = getCurrentData().cartData.cartItems.filter(function (item) {
      return item.holder_id !== holder_id;
    });
    setCartData({
      cartItems: newCartItems
    });
  };
  var clickCartItem = function clickCartItem(cartItem) {
    setCurrentCartItem(cartItem);
  };
  var setCurrentCartItem = function setCurrentCartItem(cartItem) {
    setCartData({
      currentCartItem: cartItem
    });
  };
  var updateCurrentCartItem = function updateCurrentCartItem(cartItem) {
    var _getCurrentData$cartD;
    var item = (_getCurrentData$cartD = getCurrentData().cartData) === null || _getCurrentData$cartD === void 0 ? void 0 : _getCurrentData$cartD.currentCartItem;
    if (item) {
      setCurrentCartItem(_objectSpread(_objectSpread({}, item), cartItem));
    }
  };
  var clearCurrentCartItem = function clearCurrentCartItem() {
    setCartData({
      currentCartItem: null
    });
  };
  var checkHolder = function checkHolder() {
    var _getCurrentData$cartD2;
    var currentCartItems = (_getCurrentData$cartD2 = getCurrentData().cartData) === null || _getCurrentData$cartD2 === void 0 ? void 0 : _getCurrentData$cartD2.cartItems;
    if (currentCartItems !== null && currentCartItems !== void 0 && currentCartItems.length) {
      var idx = currentCartItems.find(function (v) {
        return !v.holder_id;
      });
      if (idx === undefined) {
        return true;
      }
    }
    return false;
  };

  /**
   * @description: 获取当前操作中的holder信息
   * 如果currentHolderItem在selectedHolderItems中找不到，说明该holder已经被删除
   * 这时取selectedHolderItems中的最后一个，
   * @return {*}
   * @Author: xiangfeng.xue
   */
  var getCurrentHolderItem = function getCurrentHolderItem() {
    var _ref3 = getCurrentData().holderData || {},
      selectedHolderItems = _ref3.selectedHolderItems,
      currentHolderItem = _ref3.currentHolderItem;
    if (selectedHolderItems !== null && selectedHolderItems !== void 0 && selectedHolderItems.length) {
      var newCurrentHolderItem = currentHolderItem;
      var result = selectedHolderItems.find(function (v) {
        return v.id === (currentHolderItem === null || currentHolderItem === void 0 ? void 0 : currentHolderItem.id);
      });
      if (result === undefined) {
        newCurrentHolderItem = selectedHolderItems[selectedHolderItems.length - 1];
      }
      return newCurrentHolderItem;
    }
    return null;
  };

  /**
   * @title: 检测购物车中商品是否是不可用状态
   * @description: 250210：本期只关注库存的检测结果
   * @param {any} list
   * @param {CartItem} item
   * @return {*} boolean
   * @Author: xiangfeng.xue
   */
  var checkCartItemIsUnavailable = function checkCartItemIsUnavailable(list, item) {
    var _item$_originData, _item$_originData2, _item$_originData3;
    var productId = (_item$_originData = item._originData) === null || _item$_originData === void 0 || (_item$_originData = _item$_originData.product) === null || _item$_originData === void 0 ? void 0 : _item$_originData.product_id;
    var relationId = (_item$_originData2 = item._originData) === null || _item$_originData2 === void 0 ? void 0 : _item$_originData2.relation_id;
    var eventUniqueIdentifier = (_item$_originData3 = item._originData) === null || _item$_originData3 === void 0 ? void 0 : _item$_originData3.event_unique_identifier;
    // 根据检测项过滤检测结果
    return list.find(function (res) {
      var _res$details;
      var checkType = ['available_capacity'];
      var isTypeIncludes = ((_res$details = res.details) === null || _res$details === void 0 ? void 0 : _res$details.find(function (v) {
        var _checkType$includes;
        return (_checkType$includes = checkType.includes) === null || _checkType$includes === void 0 ? void 0 : _checkType$includes.call(checkType, v.type || '');
      })) !== undefined;
      if (isTypeIncludes) {
        return res.product_id === productId && res.relation_id === relationId && res.event_unique_identifier === eventUniqueIdentifier;
      }
      return false;
    }) !== undefined;
  };

  /**
   * @title: 更新购物车中不可用的商品
   * @discription
   * @return {void}
   * @Author: xiangfeng.xue
   */
  var updateDisabledCartItem = function updateDisabledCartItem(list) {
    var currentCartItems = getCurrentData().cartData.cartItems || [];
    if (list !== null && list !== void 0 && list.length && currentCartItems.length) {
      var newCartItems = currentCartItems.map(function (item) {
        var isUnavailable = checkCartItemIsUnavailable(list, item);
        // 需要判定活动id和商品id是否都匹配
        if (isUnavailable) {
          item.disabled = true;
          // item.show_delete = true;
        } else {
          item.disabled = false;
        }
        return item;
      });
      setCartData({
        cartItems: newCartItems
      });
    }
  };

  /**
   * @description: 获取没有商品信息的holder名称
   * @return {Array<string>}
   * @Author: xiangfeng.xue
   */
  var getWithoutCartItemsHolderNames = function getWithoutCartItemsHolderNames() {
    var _cartDataHolderList$f;
    var list = [];
    cartDataHolderList === null || cartDataHolderList === void 0 || (_cartDataHolderList$f = cartDataHolderList.forEach) === null || _cartDataHolderList$f === void 0 || _cartDataHolderList$f.call(cartDataHolderList, function (v) {
      var _v$children;
      if (!(v !== null && v !== void 0 && (_v$children = v.children) !== null && _v$children !== void 0 && _v$children.length)) {
        list.push((v === null || v === void 0 ? void 0 : v.name) || '');
      }
    });
    return list;
  };
  var contextValue = {
    createCartItem: createCartItem,
    createCartItemFromEvent: createCartItemFromEvent,
    createCartItemFromHolder: createCartItemFromHolder,
    addToCart: addToCart,
    updateCartItem: updateCartItem,
    deleteCartItem: deleteCartItem,
    clickCartItem: clickCartItem,
    updateCurrentCartItem: updateCurrentCartItem,
    clearCurrentCartItem: clearCurrentCartItem,
    currentCartItem: currentCartItem,
    cartData: cartData,
    checkHolder: checkHolder,
    openCart: openCart,
    onOpenCart: onOpenCart,
    onCloseCart: onCloseCart,
    deleteCartItemByHolder: deleteCartItemByHolder,
    addHolderToCartItem: addHolderToCartItem,
    cartDataHolderList: cartDataHolderList,
    addNoteToCartItem: addNoteToCartItem,
    updateDisabledCartItem: updateDisabledCartItem,
    getWithoutCartItemsHolderNames: getWithoutCartItemsHolderNames,
    checkBeforeAddToCartResquest: checkBeforeAddToCartResquest,
    checkBeforeAddToCart: checkBeforeAddToCart
  };
  return /*#__PURE__*/React.createElement(CartContext.Provider, {
    value: contextValue
  }, children);
};

/**
 * 使用步骤管理的Hook
 * @throws {Error} 如果在StepProvider外部使用会抛出错误
 * @returns {StepContextType} 步骤管理上下文
 */
export var useCart = function useCart() {
  var context = React.useContext(CartContext);
  if (!context) {
    throw new Error('useCart must be used within a CartProvider');
  }
  return context;
};
export default {
  defaultState: defaultState
};