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 _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; }
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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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; }
import dayjs from 'dayjs';

/**
 * @title: 基于选择的商品格式化容量
 * @description:
 * @param {any} param1
 * @return {*}
 * @Author: zhiwei.Wang
 */
export var formatDefaultCapacitys = function formatDefaultCapacitys(_ref) {
  var capacity = _ref.capacity,
    product_bundle = _ref.product_bundle;
  if ((capacity === null || capacity === void 0 ? void 0 : capacity.type) === 'package') {
    return (product_bundle || []).map(function (d) {
      var id = d.bundle_product_id;
      var variantId = d.bundle_variant_id;
      var item = ((capacity === null || capacity === void 0 ? void 0 : capacity.package) || []).find(function (item) {
        return item.product_id === id || item.product_id === variantId;
      });
      return {
        id: id,
        value: item ? d.num || 0 : 0,
        name: (item === null || item === void 0 ? void 0 : item.name) || (d === null || d === void 0 ? void 0 : d.title)
      };
    });
  }
  if ((capacity === null || capacity === void 0 ? void 0 : capacity.type) === 'custom') {
    return ((capacity === null || capacity === void 0 ? void 0 : capacity.custom) || []).map(function (d) {
      return {
        id: d.id,
        value: d.min,
        name: d.name
      };
    });
  }

  // 默认为1
  return [{
    id: 0,
    value: 1,
    name: ''
  }];
};

/**
 * @title: 获取总容量
 * @description:
 * @param {object} capacity 为 formatDefaultCapacitys()的结果
 * @return {*}
 * @Author: zhiwei.Wang
 */
export var getSumCapacity = function getSumCapacity(_ref2) {
  var capacity = _ref2.capacity,
    _ref2$num = _ref2.num,
    num = _ref2$num === void 0 ? 1 : _ref2$num;
  var sum = 0;
  var _iterator = _createForOfIteratorHelper(capacity || []),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var item = _step.value;
      sum += item.value;
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return sum * num;
};

/**
 * 给定购物车数据，返回对应的 capacity 信息和套餐 capacity
 *
 * @export
 * @param {CartItem} targetCartItem
 * @return {*} 
 */
export function getCapacityInfoByCartItem(targetCartItem) {
  var _targetCartItem$_prod;
  var formatCapacity = formatDefaultCapacitys({
    capacity: (_targetCartItem$_prod = targetCartItem._productOrigin) === null || _targetCartItem$_prod === void 0 ? void 0 : _targetCartItem$_prod.capacity,
    product_bundle: targetCartItem._origin.product.product_bundle
  });
  var currentCapacity = getSumCapacity({
    capacity: formatCapacity,
    num: (targetCartItem === null || targetCartItem === void 0 ? void 0 : targetCartItem.num) || 1
  });
  return {
    formatCapacity: formatCapacity,
    currentCapacity: currentCapacity
  };
}

/**
 * @title: 传入资源，如果有子资源，会根据组合资源的 capacity 计算修改子资源的 capacity
 * @description:
 * @param {object} resource
 * @return {*}
 * @Author: jinglin.tan
 */
export var checkSubResourcesCapacity = function checkSubResourcesCapacity(resource) {
  if (resource.children && resource.children.length) {
    var countCapacity = resource.capacity; // 100
    resource.children.forEach(function (child, index) {
      if (index === resource.children.length - 1) {
        // 如果是最后一个资源，直接拿剩余未分配完的容量去占用
        // 哪怕这个东西会超过资源本身的 capacity也得让他占，PRD 里有写
        child.capacity = countCapacity;
        return;
      }
      if (child.capacity <= countCapacity) {
        countCapacity -= child.capacity; // 100 -  = 90
      } else {
        child.capacity = countCapacity; // 10
        countCapacity = 0; // 0
      }
    });
  }
};

/**
 * 检查资源是否有足够的容量供额外使用
 * @param currentCapacity - 当前已使用的容量
 * @param requiredCapacity - 需要的额外容量
 * @param maxCapacity - 最大允许容量
 * @returns 如果资源可以容纳额外的容量则返回 true
 */
export var checkResourceCanUseByCapacity = function checkResourceCanUseByCapacity(currentCapacity, requiredCapacity, maxCapacity) {
  // Handle edge cases early
  if (currentCapacity < 0 || requiredCapacity < 0 || maxCapacity <= 0) {
    return false;
  }
  return currentCapacity + requiredCapacity <= maxCapacity;
};

/**
 * 计算按资源类型分组的容量占用情况
 * 
 * @param {CartItem[]} cartItems 购物车商品列表
 * @param {string} timeSlotStart 时间段开始时间
 * @param {string} timeSlotEnd 时间段结束时间
 * @param {ResourceItem[]} allProductResources 当前商品的所有资源列表
 * @return {Record<string, number>} 返回每种资源类型(form_id)的容量占用
 */
export function calculateCartItemsCapacityUsageByResourceType(_ref3) {
  var cartItems = _ref3.cartItems,
    timeSlotStart = _ref3.timeSlotStart,
    timeSlotEnd = _ref3.timeSlotEnd,
    allProductResources = _ref3.allProductResources;
  // 按 form_id 分组当前商品的资源
  var resourceTypeMap = {};
  allProductResources.forEach(function (resource) {
    var _resource$form_id;
    var formId = ((_resource$form_id = resource.form_id) === null || _resource$form_id === void 0 ? void 0 : _resource$form_id.toString()) || 'default';
    if (!resourceTypeMap[formId]) {
      resourceTypeMap[formId] = [];
    }
    resourceTypeMap[formId].push(resource);
  });

  // 计算每种资源类型的容量占用
  var capacityUsageByType = {};
  Object.keys(resourceTypeMap).forEach(function (formId) {
    var totalUsage = 0;
    var resourcesInThisType = resourceTypeMap[formId];
    var resourceIdsInThisType = resourcesInThisType.map(function (r) {
      return r.id;
    });
    cartItems.forEach(function (cartItem) {
      // 检查该商品是否已经选定了时间
      if (!cartItem.start_time || !cartItem.end_time) return;

      // 构建该商品的时间段
      var itemStart = "".concat(cartItem.start_date, " ").concat(cartItem.start_time);
      var itemEnd = "".concat(cartItem.end_date || cartItem.start_date, " ").concat(cartItem.end_time);

      // 检查时间段是否有重叠
      var hasTimeOverlap = !(dayjs(itemEnd).isBefore(dayjs(timeSlotStart)) || dayjs(itemStart).isAfter(dayjs(timeSlotEnd)));
      if (!hasTimeOverlap) return;

      // 检查该商品的资源配置中是否需要这种类型的资源
      // 由于购物车商品只选定了时间，没有选定具体资源，我们需要看商品的资源配置
      var productResourceIds = getResourcesIdsByProduct(cartItem._productOrigin);
      var hasResourceTypeOverlap = productResourceIds.some(function (id) {
        return resourceIdsInThisType.includes(id);
      });
      if (!hasResourceTypeOverlap) return;

      // 计算该商品的容量占用
      var _getCapacityInfoByCar = getCapacityInfoByCartItem(cartItem),
        currentCapacity = _getCapacityInfoByCar.currentCapacity;
      totalUsage += currentCapacity;
    });
    capacityUsageByType[formId] = totalUsage;
  });
  return capacityUsageByType;
}

/**
 * 获取商品的资源ID列表
 */
export function getResourcesIdsByProduct(product) {
  var _product$product_reso, _product$product_reso2;
  var tempResourceIds = [];
  product === null || product === void 0 || (_product$product_reso = product.product_resource) === null || _product$product_reso === void 0 || (_product$product_reso = _product$product_reso.resources) === null || _product$product_reso === void 0 || (_product$product_reso2 = _product$product_reso.forEach) === null || _product$product_reso2 === void 0 || _product$product_reso2.call(_product$product_reso, function (resource) {
    if ((resource === null || resource === void 0 ? void 0 : resource.status) == 1) {
      var _resource$default_res, _resource$optional_re;
      if (resource !== null && resource !== void 0 && (_resource$default_res = resource.default_resource) !== null && _resource$default_res !== void 0 && _resource$default_res.length) {
        tempResourceIds.push.apply(tempResourceIds, _toConsumableArray(resource === null || resource === void 0 ? void 0 : resource.default_resource));
      } else if (resource !== null && resource !== void 0 && (_resource$optional_re = resource.optional_resource) !== null && _resource$optional_re !== void 0 && _resource$optional_re.length) {
        tempResourceIds.push.apply(tempResourceIds, _toConsumableArray(resource === null || resource === void 0 ? void 0 : resource.optional_resource));
      }
    }
  });
  return tempResourceIds;
}

/**
 * 检查特定时间段的容量是否足够
 */
export function checkTimeSlotCapacity(timeSlotStart, timeSlotEnd, cartItems, allResources) {
  // 按资源类型分组
  var resourceTypeMap = {};
  allResources.forEach(function (resource) {
    var _resource$form_id2;
    var formId = ((_resource$form_id2 = resource.form_id) === null || _resource$form_id2 === void 0 ? void 0 : _resource$form_id2.toString()) || 'default';
    if (!resourceTypeMap[formId]) {
      resourceTypeMap[formId] = [];
    }
    resourceTypeMap[formId].push(resource);
  });

  // 计算每种资源类型需要的总容量
  var requiredCapacityByType = {};
  cartItems.forEach(function (cartItem) {
    var productResourceIds = getResourcesIdsByProduct(cartItem._productOrigin);
    var _getCapacityInfoByCar2 = getCapacityInfoByCartItem(cartItem),
      currentCapacity = _getCapacityInfoByCar2.currentCapacity;
    Object.keys(resourceTypeMap).forEach(function (formId) {
      var _cartItem$_productOri;
      var resourcesInType = resourceTypeMap[formId];
      var resourceIdsInType = resourcesInType.map(function (r) {
        return r.id;
      });
      var selectType = (_cartItem$_productOri = cartItem._productOrigin) === null || _cartItem$_productOri === void 0 || (_cartItem$_productOri = _cartItem$_productOri.product_resource) === null || _cartItem$_productOri === void 0 || (_cartItem$_productOri = _cartItem$_productOri.resources) === null || _cartItem$_productOri === void 0 || (_cartItem$_productOri = _cartItem$_productOri.find(function (r) {
        var _r$id;
        return ((_r$id = r.id) === null || _r$id === void 0 ? void 0 : _r$id.toString()) === formId;
      })) === null || _cartItem$_productOri === void 0 ? void 0 : _cartItem$_productOri.type;

      // 检查该商品是否需要这种类型的资源
      var needsThisResourceType = productResourceIds.some(function (id) {
        return resourceIdsInType.includes(id);
      });
      if (needsThisResourceType) {
        // 需要判断是单个预约还是多个预约，如果是单个预约，不用加 capacity，只用+1
        if (selectType === 'single') {
          requiredCapacityByType[formId] = (requiredCapacityByType[formId] || 0) + ((cartItem === null || cartItem === void 0 ? void 0 : cartItem.num) || 1);
        } else {
          requiredCapacityByType[formId] = (requiredCapacityByType[formId] || 0) + currentCapacity;
        }
        // requiredCapacityByType[formId] = (requiredCapacityByType[formId] || 0) + currentCapacity;
      }
    });
  });

  // 检查每种资源类型是否有足够的容量
  var _loop = function _loop() {
      var _resourceTypeConfig, _resourceTypeConfig2;
      var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
        formId = _Object$entries$_i[0],
        requiredCapacity = _Object$entries$_i[1];
      var resourcesInType = resourceTypeMap[formId];
      if (resourcesInType.length === 0) return 0; // continue

      // 从购物车商品中获取正确的资源类型配置
      var resourceTypeConfig = null;
      var _iterator2 = _createForOfIteratorHelper(cartItems),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var _cartItem$_productOri2;
          var cartItem = _step2.value;
          if ((_cartItem$_productOri2 = cartItem._productOrigin) !== null && _cartItem$_productOri2 !== void 0 && (_cartItem$_productOri2 = _cartItem$_productOri2.product_resource) !== null && _cartItem$_productOri2 !== void 0 && _cartItem$_productOri2.resources) {
            resourceTypeConfig = cartItem._productOrigin.product_resource.resources.find(function (r) {
              var _r$id2;
              return ((_r$id2 = r.id) === null || _r$id2 === void 0 ? void 0 : _r$id2.toString()) === formId && r.status === 1;
            });
            if (resourceTypeConfig) break;
          }
        }

        // 确定这种资源类型的预约类型
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      var isMultipleBooking = ((_resourceTypeConfig = resourceTypeConfig) === null || _resourceTypeConfig === void 0 ? void 0 : _resourceTypeConfig.type) === 'multiple';
      console.log("capacity.ts - \u8D44\u6E90\u7C7B\u578B ".concat(formId, " \u914D\u7F6E:"), {
        resourceTypeConfig: resourceTypeConfig,
        type: (_resourceTypeConfig2 = resourceTypeConfig) === null || _resourceTypeConfig2 === void 0 ? void 0 : _resourceTypeConfig2.type,
        isMultipleBooking: isMultipleBooking,
        requiredCapacity: requiredCapacity
      });
      if (isMultipleBooking) {
        // 多个预约：计算总可用容量
        var totalAvailableCapacity = 0;
        resourcesInType.forEach(function (resource) {
          // 过滤出在时间段内的资源时间片
          var availableTimes = resource.times.filter(function (time) {
            return !dayjs(time.start_at).isAfter(dayjs(timeSlotStart), 'minute') && !dayjs(time.end_at).isBefore(dayjs(timeSlotEnd), 'minute') || resource.onlyComputed && dayjs(time.start_at).isBefore(dayjs(timeSlotEnd), 'minute') && dayjs(time.end_at).isAfter(dayjs(timeSlotStart), 'minute');
          });
          if (availableTimes.length > 0) {
            // 简化逻辑：如果资源在时间段内有可用时间，就计算其容量
            totalAvailableCapacity += resource.capacity || 0;
          }
        });
        console.log("capacity.ts - \u8D44\u6E90\u7C7B\u578B ".concat(formId, " \u591A\u4E2A\u9884\u7EA6\u68C0\u67E5: \u603B\u5BB9\u91CF ").concat(totalAvailableCapacity, ", \u9700\u6C42 ").concat(requiredCapacity));
        if (totalAvailableCapacity < requiredCapacity) {
          console.log("\u8D44\u6E90\u7C7B\u578B ".concat(formId, " \u5BB9\u91CF\u4E0D\u8DB3: \u9700\u8981 ").concat(requiredCapacity, ", \u53EF\u7528 ").concat(totalAvailableCapacity));
          return {
            v: {
              success: false,
              required: requiredCapacity,
              available: totalAvailableCapacity
            }
          };
        }
      } else {
        // 单个预约：计算可用资源数量
        var availableResourceCount = 0;
        resourcesInType.forEach(function (resource) {
          // 过滤出在时间段内的资源时间片
          var availableTimes = resource.times.filter(function (time) {
            return !dayjs(time.start_at).isAfter(dayjs(timeSlotStart), 'minute') && !dayjs(time.end_at).isBefore(dayjs(timeSlotEnd), 'minute') || dayjs(time.start_at).isBefore(dayjs(timeSlotEnd), 'minute') && dayjs(time.end_at).isAfter(dayjs(timeSlotStart), 'minute');
          });
          if (availableTimes.length > 0) {
            availableResourceCount++;
          }
        });
        console.log("capacity.ts - \u8D44\u6E90\u7C7B\u578B ".concat(formId, " \u5355\u4E2A\u9884\u7EA6\u68C0\u67E5: \u53EF\u7528\u8D44\u6E90\u6570 ").concat(availableResourceCount, ", \u9700\u6C42 ").concat(requiredCapacity));
        if (availableResourceCount < requiredCapacity) {
          console.log("\u8D44\u6E90\u7C7B\u578B ".concat(formId, " \u6570\u91CF\u4E0D\u8DB3: \u9700\u8981 ").concat(requiredCapacity, ", \u53EF\u7528 ").concat(availableResourceCount));
          return {
            v: {
              success: false,
              required: requiredCapacity,
              available: availableResourceCount
            }
          };
        }
      }
    },
    _ret;
  for (var _i = 0, _Object$entries = Object.entries(requiredCapacityByType); _i < _Object$entries.length; _i++) {
    _ret = _loop();
    if (_ret === 0) continue;
    if (_ret) return _ret.v;
  }
  return {
    success: true,
    required: 0,
    available: 0
  };
}