const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
let _pisell_utils = require("@pisell/utils");
let decimal_js = require("decimal.js");
decimal_js = require_runtime.__toESM(decimal_js);
//#region src/components/ticketBooking/components/ProductDisplayAdapter/utils.ts
/**
* 生成简单的 Tab 列表（非树形结构）
* 遍历商品直接关联的分类，扁平化输出为 CategoryTreeNode[]
* 
* @param products 产品列表
* @returns CategoryTreeNode[] 扁平化的分类列表，children 为空数组
*/
const 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 || catB === void 0 ? void 0 : catB.sort) || 0) - ((catA === null || catA === void 0 ? void 0 : catA.sort) || 0);
	});
	return result;
};
/**
* 根据产品数据生成分类 Tabs（Switch 模式）
* 参考 TestResponsiveWrapper 的 generateSimpleTabItems 函数
* 
* @param products 产品列表
* @param tabStyle tab 样式类型
* @returns Switch 模式返回 CategoryTreeNode[]，Anchor 模式返回 TabItem[]
*/
const generateProductTabs = (products, tabStyle = "switch", isTreeTab = true) => {
	if (!products || products.length === 0) {
		if (tabStyle === "switch") return [];
		return [{
			key: "all",
			label: _pisell_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: `${_pisell_utils.locales.getText("pisell2.ticket-booking.all")} (${products.length})`
		}];
		Object.entries(categoryCount).sort(([, a], [, b]) => (b.category.sort || 0) - (a.category.sort || 0)).forEach(([key, { count, category }]) => {
			tabs.push({
				key,
				label: `${category.name} (${count})`,
				group: key
			});
		});
		return tabs;
	}
};
/**
* 递归收集分类及其所有父级分类
* 通过 parent_category 字段向上追溯，确保所有层级的分类都被收集
* 
* @param category 当前分类（带 parent_category 字段）
* @param categoryMap 分类信息 Map
*/
const collectCategoryWithParents = (category, categoryMap) => {
	if (!categoryMap.has(category.id)) {
		var _ref, _category$parent_id, _category$parent_cate;
		categoryMap.set(category.id, {
			id: category.id,
			name: category.name,
			icon: category.icon,
			slug: category.slug,
			sort: category.sort,
			parent_id: (_ref = (_category$parent_id = category.parent_id) !== null && _category$parent_id !== void 0 ? _category$parent_id : (_category$parent_cate = category.parent_category) === null || _category$parent_cate === void 0 ? void 0 : _category$parent_cate.id) !== null && _ref !== void 0 ? _ref : null
		});
	}
	if (category.parent_category) collectCategoryWithParents(category.parent_category, categoryMap);
};
/**
* 构建分类树形结构（Switch 模式专用）
* 
* @param products 产品列表
* @returns CategoryTreeNode[] 树形分类结构
*/
const 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 || catB === void 0 ? void 0 : catB.sort) || 0) - ((catA === null || catA === void 0 ? void 0 : catA.sort) || 0);
		});
	};
	/**
	* 递归构建分类节点
	* 
	* @param categoryId 分类 ID
	* @param parentPath 父级路径（用于生成 pid）
	* @returns CategoryTreeNode 分类节点
	*/
	const buildNode = (categoryId, parentPath) => {
		const category = categoryMap.get(categoryId);
		const sortedChildIds = sortBySort([...childrenMap.get(categoryId) || []]);
		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
		};
		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);
			}, []);
			node.productIds = Array.from(new Set([...directProductIds, ...allChildProductIds]));
			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 rootNodes = sortBySort([...rootCategories]).map((rootId) => buildNode(rootId, ""));
	if (rootNodes.length > 0) {
		Array.from(new Set(rootNodes.flatMap((node) => node.productIds)));
		return [...rootNodes];
	}
	return rootNodes;
};
/**
* 按 tabData 分类顺序对商品列表排序，同分类内按商品 sort 降序
* 仅在 isTreeTab 为 false 时使用
*
* @param data 商品列表（category 已转为 string[] 格式）
* @param tabData 分类 tab 列表（CategoryTreeNode[]）
* @returns 排序后的商品列表（原地排序）
*/
const 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$category, _b$category, _categoryOrderMap$get, _categoryOrderMap$get2;
		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$category = a.category) === null || _a$category === void 0 ? void 0 : _a$category[aIndex];
		const bCategoryId = (_b$category = b.category) === null || _b$category === void 0 ? void 0 : _b$category[bIndex];
		const aOrder = aCategoryId !== void 0 ? (_categoryOrderMap$get = categoryOrderMap.get(String(aCategoryId))) !== null && _categoryOrderMap$get !== void 0 ? _categoryOrderMap$get : Infinity : Infinity;
		const bOrder = bCategoryId !== void 0 ? (_categoryOrderMap$get2 = categoryOrderMap.get(String(bCategoryId))) !== null && _categoryOrderMap$get2 !== void 0 ? _categoryOrderMap$get2 : Infinity : Infinity;
		if (aOrder !== bOrder) return aOrder - bOrder;
		return (b.sort || 0) - (a.sort || 0);
	});
};
//#endregion
exports.generateProductTabs = generateProductTabs;
exports.sortProductsByTabOrder = sortProductsByTabOrder;
