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/ProductDisplayAdapter/utils.ts
var utils_exports = {};
__export(utils_exports, {
  formatSkuDataSource: () => formatSkuDataSource,
  generateProductTabs: () => generateProductTabs,
  sortProductsByTabOrder: () => sortProductsByTabOrder
});
module.exports = __toCommonJS(utils_exports);
var import_utils = require("@pisell/utils");
var import_decimal = __toESM(require("decimal.js"));
var formatSkuDataSource = (dataSource) => {
  const {
    price: _price,
    original_price: _original_price,
    is_bundle,
    minimum_markup_price
  } = dataSource;
  let price = _price;
  let original_price = _original_price;
  if (is_bundle) {
    price = new import_decimal.default(price || 0).plus(new import_decimal.default(minimum_markup_price || 0)).toFixed(2);
    original_price = new import_decimal.default(original_price || 0).plus(new import_decimal.default(minimum_markup_price || 0)).toFixed(2);
  }
  return {
    id: dataSource.id,
    title: dataSource.title,
    subtitle: dataSource.subtitle,
    cover: dataSource.cover,
    price,
    original_price,
    stock: dataSource.stock_quantity,
    sortKeys: ["title", "subtitle", "price"],
    isMini: is_bundle
  };
};
var generateSimpleTabItems = (products) => {
  const categoryMap = /* @__PURE__ */ new Map();
  const categoryProductMap = /* @__PURE__ */ new Map();
  products.forEach((product) => {
    if (product.category && Array.isArray(product.category)) {
      product.category.forEach((cat) => {
        if (!categoryMap.has(cat.id)) {
          categoryMap.set(cat.id, {
            id: cat.id,
            name: cat.name,
            icon: cat.icon,
            slug: cat.slug,
            sort: cat.sort
          });
        }
        if (!categoryProductMap.has(cat.id)) {
          categoryProductMap.set(cat.id, /* @__PURE__ */ new Set());
        }
        categoryProductMap.get(cat.id).add(product.id);
      });
    }
  });
  const result = [];
  categoryMap.forEach((category, id) => {
    const productIds = Array.from(categoryProductMap.get(id) || []);
    result.push({
      id,
      key: id,
      group: id,
      label: category.name,
      name: category.name,
      icon: category.icon,
      productIds,
      children: [],
      childrenMaxLevel: 0
    });
  });
  result.sort((a, b) => {
    const catA = categoryMap.get(a.id);
    const catB = categoryMap.get(b.id);
    return ((catB == null ? void 0 : catB.sort) || 0) - ((catA == null ? void 0 : catA.sort) || 0);
  });
  return result;
};
var generateProductTabs = (products, tabStyle = "switch", isTreeTab = true) => {
  if (!products || products.length === 0) {
    if (tabStyle === "switch") {
      return [];
    }
    return [{ key: "all", label: import_utils.locales.getText("pisell2.ticket-booking.all") }];
  }
  if (tabStyle === "switch") {
    return isTreeTab ? buildCategoryTree(products) : generateSimpleTabItems(products);
  } else {
    const categoryCount = products.reduce((acc, product) => {
      if (product.category && Array.isArray(product.category)) {
        product.category.forEach((cat) => {
          const key = String(cat.id);
          if (!acc[key]) {
            acc[key] = { count: 0, category: cat };
          }
          acc[key].count += 1;
        });
      }
      return acc;
    }, {});
    const tabs = [
      { key: "all", label: `${import_utils.locales.getText("pisell2.ticket-booking.all")} (${products.length})` }
    ];
    const sortedEntries = Object.entries(categoryCount).sort(
      ([, a], [, b]) => (b.category.sort || 0) - (a.category.sort || 0)
    );
    sortedEntries.forEach(([key, { count, category }]) => {
      tabs.push({
        key,
        label: `${category.name} (${count})`,
        group: key
      });
    });
    return tabs;
  }
};
var collectCategoryWithParents = (category, categoryMap) => {
  var _a;
  if (!categoryMap.has(category.id)) {
    categoryMap.set(category.id, {
      id: category.id,
      name: category.name,
      icon: category.icon,
      slug: category.slug,
      sort: category.sort,
      parent_id: category.parent_id ?? ((_a = category.parent_category) == null ? void 0 : _a.id) ?? null
    });
  }
  if (category.parent_category) {
    collectCategoryWithParents(category.parent_category, categoryMap);
  }
};
var buildCategoryTree = (products) => {
  const categoryMap = /* @__PURE__ */ new Map();
  const categoryProductMap = /* @__PURE__ */ new Map();
  products.forEach((product) => {
    if (product.category && Array.isArray(product.category)) {
      product.category.forEach((cat) => {
        collectCategoryWithParents(cat, categoryMap);
        if (!categoryProductMap.has(cat.id)) {
          categoryProductMap.set(cat.id, /* @__PURE__ */ new Set());
        }
        categoryProductMap.get(cat.id).add(product.id);
      });
    }
  });
  const childrenMap = /* @__PURE__ */ new Map();
  const rootCategories = [];
  categoryMap.forEach((category, id) => {
    const parentId = category.parent_id;
    if (!parentId || parentId === 0) {
      rootCategories.push(id);
    } else {
      if (!childrenMap.has(parentId)) {
        childrenMap.set(parentId, []);
      }
      childrenMap.get(parentId).push(id);
    }
  });
  const sortBySort = (ids) => {
    return ids.sort((a, b) => {
      const catA = categoryMap.get(a);
      const catB = categoryMap.get(b);
      return ((catB == null ? void 0 : catB.sort) || 0) - ((catA == null ? void 0 : catA.sort) || 0);
    });
  };
  const buildNode = (categoryId, parentPath) => {
    const category = categoryMap.get(categoryId);
    const childIds = childrenMap.get(categoryId) || [];
    const sortedChildIds = sortBySort([...childIds]);
    const directProductIds = Array.from(categoryProductMap.get(categoryId) || []);
    const currentPath = parentPath ? `${parentPath}_${categoryId}` : String(categoryId);
    const pid = parentPath || void 0;
    const node = {
      id: categoryId,
      key: categoryId,
      group: categoryId,
      label: category.name,
      name: category.name,
      icon: category.icon,
      productIds: directProductIds,
      childrenMaxLevel: 0
      // 默认无子分类时为 0
    };
    if (pid) {
      node.pid = pid;
    }
    if (sortedChildIds.length > 0) {
      const childNodes = sortedChildIds.map(
        (childId) => buildNode(childId, currentPath)
      );
      const allChildProductIds = childNodes.reduce((acc, child) => {
        return acc.concat(child.productIds);
      }, []);
      const mergedProductIds = Array.from(
        /* @__PURE__ */ new Set([...directProductIds, ...allChildProductIds])
      );
      node.productIds = mergedProductIds;
      node.children = [...childNodes];
      let maxChildLevel = 0;
      for (let i = 0; i < childNodes.length; i++) {
        if (childNodes[i].childrenMaxLevel > maxChildLevel) {
          maxChildLevel = childNodes[i].childrenMaxLevel;
        }
      }
      node.childrenMaxLevel = maxChildLevel + 1;
    }
    return node;
  };
  const sortedRootIds = sortBySort([...rootCategories]);
  const rootNodes = sortedRootIds.map((rootId) => buildNode(rootId, ""));
  if (rootNodes.length > 0) {
    const allProductIds = Array.from(
      new Set(rootNodes.flatMap((node) => node.productIds))
    );
    return [...rootNodes];
  }
  return rootNodes;
};
var sortProductsByTabOrder = (data, tabData) => {
  const categoryOrderMap = /* @__PURE__ */ new Map();
  tabData.forEach((tab, index) => {
    categoryOrderMap.set(String(tab.id), index);
  });
  return data.sort((a, b) => {
    var _a, _b;
    const aIndex = Math.max(Array.isArray(a.category) ? a.category.length - 1 : 0, 0);
    const bIndex = Math.max(Array.isArray(b.category) ? b.category.length - 1 : 0, 0);
    const aCategoryId = (_a = a.category) == null ? void 0 : _a[aIndex];
    const bCategoryId = (_b = b.category) == null ? void 0 : _b[bIndex];
    const aOrder = aCategoryId !== void 0 ? categoryOrderMap.get(String(aCategoryId)) ?? Infinity : Infinity;
    const bOrder = bCategoryId !== void 0 ? categoryOrderMap.get(String(bCategoryId)) ?? Infinity : Infinity;
    if (aOrder !== bOrder) {
      return aOrder - bOrder;
    }
    return (b.sort || 0) - (a.sort || 0);
  });
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  formatSkuDataSource,
  generateProductTabs,
  sortProductsByTabOrder
});
