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/solution/BookingByStep/utils/capacity.ts
var capacity_exports = {};
__export(capacity_exports, {
  calculateCartItemsCapacityUsageByResourceType: () => calculateCartItemsCapacityUsageByResourceType,
  checkResourceCanUseByCapacity: () => checkResourceCanUseByCapacity,
  checkSubResourcesCapacity: () => checkSubResourcesCapacity,
  checkTimeSlotCapacity: () => checkTimeSlotCapacity,
  formatDefaultCapacitys: () => formatDefaultCapacitys,
  getCapacityInfoByCartItem: () => getCapacityInfoByCartItem,
  getResourcesIdsByProduct: () => getResourcesIdsByProduct,
  getSumCapacity: () => getSumCapacity
});
module.exports = __toCommonJS(capacity_exports);
var import_dayjs = __toESM(require("dayjs"));
var formatDefaultCapacitys = ({
  capacity,
  product_bundle
}) => {
  if ((capacity == null ? void 0 : capacity.type) === "package") {
    return (product_bundle || []).map((d) => {
      const id = d.bundle_product_id;
      const variantId = d.bundle_variant_id;
      const item = ((capacity == null ? void 0 : capacity.package) || []).find(
        (item2) => item2.product_id === id || item2.product_id === variantId
      );
      return {
        id,
        value: item ? d.num || 0 : 0,
        name: (item == null ? void 0 : item.name) || (d == null ? void 0 : d.title)
      };
    });
  }
  if ((capacity == null ? void 0 : capacity.type) === "custom") {
    return ((capacity == null ? void 0 : capacity.custom) || []).map((d) => {
      return {
        id: d.id,
        value: d.min,
        name: d.name
      };
    });
  }
  return [{ id: 0, value: 1, name: "" }];
};
var getSumCapacity = ({ capacity, num = 1 }) => {
  let sum = 0;
  for (let item of capacity || []) {
    sum += item.value;
  }
  return sum * num;
};
function getCapacityInfoByCartItem(targetCartItem) {
  var _a;
  const formatCapacity = formatDefaultCapacitys({
    capacity: (_a = targetCartItem._productOrigin) == null ? void 0 : _a.capacity,
    product_bundle: targetCartItem._origin.product.product_bundle
  });
  const currentCapacity = getSumCapacity({ capacity: formatCapacity, num: (targetCartItem == null ? void 0 : targetCartItem.num) || 1 });
  return {
    formatCapacity,
    currentCapacity
  };
}
var checkSubResourcesCapacity = (resource) => {
  if (resource.children && resource.children.length) {
    let countCapacity = resource.capacity;
    resource.children.forEach((child, index) => {
      if (index === resource.children.length - 1) {
        child.capacity = countCapacity;
        return;
      }
      if (child.capacity <= countCapacity) {
        countCapacity -= child.capacity;
      } else {
        child.capacity = countCapacity;
        countCapacity = 0;
      }
    });
  }
};
var checkResourceCanUseByCapacity = (currentCapacity, requiredCapacity, maxCapacity) => {
  if (currentCapacity < 0 || requiredCapacity < 0 || maxCapacity <= 0) {
    return false;
  }
  return currentCapacity + requiredCapacity <= maxCapacity;
};
function calculateCartItemsCapacityUsageByResourceType({
  cartItems,
  timeSlotStart,
  timeSlotEnd,
  allProductResources
}) {
  const resourceTypeMap = {};
  allProductResources.forEach((resource) => {
    var _a;
    const formId = ((_a = resource.form_id) == null ? void 0 : _a.toString()) || "default";
    if (!resourceTypeMap[formId]) {
      resourceTypeMap[formId] = [];
    }
    resourceTypeMap[formId].push(resource);
  });
  const capacityUsageByType = {};
  Object.keys(resourceTypeMap).forEach((formId) => {
    let totalUsage = 0;
    const resourcesInThisType = resourceTypeMap[formId];
    const resourceIdsInThisType = resourcesInThisType.map((r) => r.id);
    cartItems.forEach((cartItem) => {
      if (!cartItem.start_time || !cartItem.end_time)
        return;
      const itemStart = `${cartItem.start_date} ${cartItem.start_time}`;
      const itemEnd = `${cartItem.end_date || cartItem.start_date} ${cartItem.end_time}`;
      const hasTimeOverlap = !((0, import_dayjs.default)(itemEnd).isBefore((0, import_dayjs.default)(timeSlotStart)) || (0, import_dayjs.default)(itemStart).isAfter((0, import_dayjs.default)(timeSlotEnd)));
      if (!hasTimeOverlap)
        return;
      const productResourceIds = getResourcesIdsByProduct(cartItem._productOrigin);
      const hasResourceTypeOverlap = productResourceIds.some(
        (id) => resourceIdsInThisType.includes(id)
      );
      if (!hasResourceTypeOverlap)
        return;
      const { currentCapacity } = getCapacityInfoByCartItem(cartItem);
      totalUsage += currentCapacity;
    });
    capacityUsageByType[formId] = totalUsage;
  });
  return capacityUsageByType;
}
function getResourcesIdsByProduct(product) {
  var _a, _b, _c;
  const tempResourceIds = [];
  (_c = (_b = (_a = product == null ? void 0 : product.product_resource) == null ? void 0 : _a.resources) == null ? void 0 : _b.forEach) == null ? void 0 : _c.call(_b, (resource) => {
    var _a2, _b2;
    if ((resource == null ? void 0 : resource.status) == 1) {
      if ((_a2 = resource == null ? void 0 : resource.default_resource) == null ? void 0 : _a2.length) {
        tempResourceIds.push(...resource == null ? void 0 : resource.default_resource);
      } else if ((_b2 = resource == null ? void 0 : resource.optional_resource) == null ? void 0 : _b2.length) {
        tempResourceIds.push(...resource == null ? void 0 : resource.optional_resource);
      }
    }
  });
  return tempResourceIds;
}
function checkTimeSlotCapacity(timeSlotStart, timeSlotEnd, cartItems, allResources) {
  var _a, _b;
  const resourceTypeMap = {};
  allResources.forEach((resource) => {
    var _a2;
    const formId = ((_a2 = resource.form_id) == null ? void 0 : _a2.toString()) || "default";
    if (!resourceTypeMap[formId]) {
      resourceTypeMap[formId] = [];
    }
    resourceTypeMap[formId].push(resource);
  });
  const requiredCapacityByType = {};
  cartItems.forEach((cartItem) => {
    const productResourceIds = getResourcesIdsByProduct(cartItem._productOrigin);
    const { currentCapacity } = getCapacityInfoByCartItem(cartItem);
    Object.keys(resourceTypeMap).forEach((formId) => {
      var _a2, _b2, _c, _d;
      const resourcesInType = resourceTypeMap[formId];
      const resourceIdsInType = resourcesInType.map((r) => r.id);
      const selectType = (_d = (_c = (_b2 = (_a2 = cartItem._productOrigin) == null ? void 0 : _a2.product_resource) == null ? void 0 : _b2.resources) == null ? void 0 : _c.find((r) => {
        var _a3;
        return ((_a3 = r.id) == null ? void 0 : _a3.toString()) === formId;
      })) == null ? void 0 : _d.type;
      const needsThisResourceType = productResourceIds.some(
        (id) => resourceIdsInType.includes(id)
      );
      if (needsThisResourceType) {
        if (selectType === "single") {
          requiredCapacityByType[formId] = (requiredCapacityByType[formId] || 0) + ((cartItem == null ? void 0 : cartItem.num) || 1);
        } else {
          requiredCapacityByType[formId] = (requiredCapacityByType[formId] || 0) + currentCapacity;
        }
      }
    });
  });
  for (const [formId, requiredCapacity] of Object.entries(requiredCapacityByType)) {
    const resourcesInType = resourceTypeMap[formId];
    if (resourcesInType.length === 0)
      continue;
    let resourceTypeConfig = null;
    for (const cartItem of cartItems) {
      if ((_b = (_a = cartItem._productOrigin) == null ? void 0 : _a.product_resource) == null ? void 0 : _b.resources) {
        resourceTypeConfig = cartItem._productOrigin.product_resource.resources.find(
          (r) => {
            var _a2;
            return ((_a2 = r.id) == null ? void 0 : _a2.toString()) === formId && r.status === 1;
          }
        );
        if (resourceTypeConfig)
          break;
      }
    }
    const isMultipleBooking = (resourceTypeConfig == null ? void 0 : resourceTypeConfig.type) === "multiple";
    console.log(`capacity.ts - 资源类型 ${formId} 配置:`, {
      resourceTypeConfig,
      type: resourceTypeConfig == null ? void 0 : resourceTypeConfig.type,
      isMultipleBooking,
      requiredCapacity
    });
    if (isMultipleBooking) {
      let totalAvailableCapacity = 0;
      resourcesInType.forEach((resource) => {
        const availableTimes = resource.times.filter((time) => {
          return !(0, import_dayjs.default)(time.start_at).isAfter((0, import_dayjs.default)(timeSlotStart), "minute") && !(0, import_dayjs.default)(time.end_at).isBefore((0, import_dayjs.default)(timeSlotEnd), "minute") || resource.onlyComputed && (0, import_dayjs.default)(time.start_at).isBefore((0, import_dayjs.default)(timeSlotEnd), "minute") && (0, import_dayjs.default)(time.end_at).isAfter((0, import_dayjs.default)(timeSlotStart), "minute");
        });
        if (availableTimes.length > 0) {
          totalAvailableCapacity += resource.capacity || 0;
        }
      });
      console.log(`capacity.ts - 资源类型 ${formId} 多个预约检查: 总容量 ${totalAvailableCapacity}, 需求 ${requiredCapacity}`);
      if (totalAvailableCapacity < requiredCapacity) {
        console.log(`资源类型 ${formId} 容量不足: 需要 ${requiredCapacity}, 可用 ${totalAvailableCapacity}`);
        return {
          success: false,
          required: requiredCapacity,
          available: totalAvailableCapacity
        };
      }
    } else {
      let availableResourceCount = 0;
      resourcesInType.forEach((resource) => {
        const availableTimes = resource.times.filter((time) => {
          return !(0, import_dayjs.default)(time.start_at).isAfter((0, import_dayjs.default)(timeSlotStart), "minute") && !(0, import_dayjs.default)(time.end_at).isBefore((0, import_dayjs.default)(timeSlotEnd), "minute") || (0, import_dayjs.default)(time.start_at).isBefore((0, import_dayjs.default)(timeSlotEnd), "minute") && (0, import_dayjs.default)(time.end_at).isAfter((0, import_dayjs.default)(timeSlotStart), "minute");
        });
        if (availableTimes.length > 0) {
          availableResourceCount++;
        }
      });
      console.log(`capacity.ts - 资源类型 ${formId} 单个预约检查: 可用资源数 ${availableResourceCount}, 需求 ${requiredCapacity}`);
      if (availableResourceCount < requiredCapacity) {
        console.log(`资源类型 ${formId} 数量不足: 需要 ${requiredCapacity}, 可用 ${availableResourceCount}`);
        return {
          success: false,
          required: requiredCapacity,
          available: availableResourceCount
        };
      }
    }
  }
  return {
    success: true,
    required: 0,
    available: 0
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  calculateCartItemsCapacityUsageByResourceType,
  checkResourceCanUseByCapacity,
  checkSubResourcesCapacity,
  checkTimeSlotCapacity,
  formatDefaultCapacitys,
  getCapacityInfoByCartItem,
  getResourcesIdsByProduct,
  getSumCapacity
});
