import { FLOOR_MAP_BUILTIN_SHAPE_ELEMENT_KIND, FLOOR_MAP_IMAGE_ELEMENT_KIND, FLOOR_MAP_STAGE_ELEMENT_KIND } from "../types.js";
import { STAGE_DECO_DEFAULT } from "./floorMapStageDefaults.js";
import { FLOOR_MAP_BUILTIN_SHAPES, getFloorMapBuiltinShapeDef } from "./floorMapBuiltinShapes.js";
import { locales } from "@pisell/utils";
//#region src/components/pisellFloorMapLayout/utils/floorMapElementKindUtils.ts
/** 与 RecordBoard Story 一致：`floorMapImage` */
function isFloorMapImageElementKind(kind) {
	return kind === FLOOR_MAP_IMAGE_ELEMENT_KIND;
}
/** 内置图形图元：与 image 类似的「无数据源 + 视觉填充」单体 kind */
function isFloorMapBuiltinShapeElementKind(kind) {
	return kind === FLOOR_MAP_BUILTIN_SHAPE_ELEMENT_KIND;
}
/** dataBindingPolicy 缺省视为 none */
function resolveDataBindingPolicy(kind) {
	var _kind$dataBindingPoli;
	return (_kind$dataBindingPoli = kind === null || kind === void 0 ? void 0 : kind.dataBindingPolicy) !== null && _kind$dataBindingPoli !== void 0 ? _kind$dataBindingPoli : "none";
}
/**
* 侧栏调色板：点击即可落点，无需数据源 / 数据行等二次选择。
* 含预约「装饰」下的内置图形（厕所/分隔/柱子等）、底图图片等（`dataBindingPolicy: none`）。
* 不含舞台；内置图形须带 `builtinShapeKey` 由 {@link isDirectPlacePaletteEntry} 判断。
*/
function isDirectPlacePaletteKind(kind) {
	if (!kind) return false;
	if (kind.value === "stage") return false;
	/** 内置图形在调色板按预设展开为多张卡，不单靠 kind 落点 */
	if (kind.value === "floorMapBuiltinShape") return false;
	return resolveDataBindingPolicy(kind) === "none";
}
function getElementKindConfig(config, elementKind) {
	var _config$elementKinds;
	if (!elementKind || !(config === null || config === void 0 || (_config$elementKinds = config.elementKinds) === null || _config$elementKinds === void 0 ? void 0 : _config$elementKinds.length)) return void 0;
	return config.elementKinds.find((k) => k.value === elementKind);
}
/**
* 与调色板分组一致：取与当前图元 **同一 categoryId**（含未填 categoryId 时落到首个分类）下的可切换种类，
* 排除舞台、底图。若仅有一种则编辑面板可不展示切换器。
*/
function getSwappableElementKindsInSameCategory(config, elementKind) {
	var _config$elementKinds2, _config$elementKindCa, _sorted$0$id, _sorted$, _self$categoryId;
	if (!elementKind || !((_config$elementKinds2 = config.elementKinds) === null || _config$elementKinds2 === void 0 ? void 0 : _config$elementKinds2.length)) return [];
	const fallbackId = (_sorted$0$id = (_sorted$ = [...(_config$elementKindCa = config.elementKindCategories) !== null && _config$elementKindCa !== void 0 ? _config$elementKindCa : []].sort((a, b) => {
		var _a$order, _b$order;
		return ((_a$order = a.order) !== null && _a$order !== void 0 ? _a$order : 0) - ((_b$order = b.order) !== null && _b$order !== void 0 ? _b$order : 0);
	})[0]) === null || _sorted$ === void 0 ? void 0 : _sorted$.id) !== null && _sorted$0$id !== void 0 ? _sorted$0$id : "_uncat";
	const self = config.elementKinds.find((k) => k.value === elementKind);
	if (!self) return [];
	const cid = (_self$categoryId = self.categoryId) !== null && _self$categoryId !== void 0 ? _self$categoryId : fallbackId;
	return config.elementKinds.filter((k) => {
		var _k$categoryId;
		if (k.showInPalette === false) return false;
		if (k.value === "stage") return false;
		if (k.value === "floorMapImage") return false;
		/** 内置图形与图片图元同属「视觉单体」，不参与同分类的 kind 切换下拉 */
		if (k.value === "floorMapBuiltinShape") return false;
		return ((_k$categoryId = k.categoryId) !== null && _k$categoryId !== void 0 ? _k$categoryId : fallbackId) === cid;
	});
}
/** 绑定资源类图元（dataBindingPolicy 为 required/optional）新建默认尺寸 */
const FLOOR_MAP_RESOURCE_PLACE_DEFAULT = {
	width: 300,
	height: 200
};
const DEFAULT_PLACE_W = FLOOR_MAP_RESOURCE_PLACE_DEFAULT.width;
const DEFAULT_PLACE_H = FLOOR_MAP_RESOURCE_PLACE_DEFAULT.height;
const IMAGE_PLACE_W = 400;
const IMAGE_PLACE_H = 240;
const DECO_SIZE = 48;
/** 内置图形落点默认尺寸（未选 key 时用），具体 key 选定后会按 def.defaultSize 取代 */
const BUILTIN_SHAPE_PLACE_W = 96;
const BUILTIN_SHAPE_PLACE_H = 96;
/**
* 在右侧编辑面板将图元改为同分类下的另一种 kind 时的草稿 patch（绑定不兼容则清空）
*/
function patchSceneElementForKindSwitch(config, element, nextKindValue) {
	var _nextCfg$allowedDataS, _builtinDef$defaultSi, _builtinDef$defaultSi2, _element$width, _element$width2, _element$height, _element$height2, _nextCfg$defaultPrese;
	const nextCfg = getElementKindConfig(config, nextKindValue);
	const nextPol = resolveDataBindingPolicy(nextCfg);
	const binding = element.dataBinding;
	const isNextImage = isFloorMapImageElementKind(nextKindValue);
	const isNextStage = nextKindValue === FLOOR_MAP_STAGE_ELEMENT_KIND;
	const isNextBuiltinShape = isFloorMapBuiltinShapeElementKind(nextKindValue);
	let clearBinding = false;
	if (nextPol === "none") clearBinding = true;
	else if (binding && (nextCfg === null || nextCfg === void 0 || (_nextCfg$allowedDataS = nextCfg.allowedDataSourceKeys) === null || _nextCfg$allowedDataS === void 0 ? void 0 : _nextCfg$allowedDataS.length)) {
		if (!nextCfg.allowedDataSourceKeys.includes(binding.dataSourceKey)) clearBinding = true;
	}
	/** 切到内置图形：尺寸用「当前 key 的 defaultSize」，无 key 时给一个保底正方形 */
	const builtinDef = isNextBuiltinShape ? getFloorMapBuiltinShapeDef(element.builtinShapeKey) : void 0;
	const builtinW = (_builtinDef$defaultSi = builtinDef === null || builtinDef === void 0 ? void 0 : builtinDef.defaultSize.width) !== null && _builtinDef$defaultSi !== void 0 ? _builtinDef$defaultSi : BUILTIN_SHAPE_PLACE_W;
	const builtinH = (_builtinDef$defaultSi2 = builtinDef === null || builtinDef === void 0 ? void 0 : builtinDef.defaultSize.height) !== null && _builtinDef$defaultSi2 !== void 0 ? _builtinDef$defaultSi2 : BUILTIN_SHAPE_PLACE_H;
	const nextW = isNextImage ? IMAGE_PLACE_W : isNextStage ? STAGE_DECO_DEFAULT.width : isNextBuiltinShape ? builtinW : DEFAULT_PLACE_W;
	const nextH = isNextImage ? IMAGE_PLACE_H : isNextStage ? STAGE_DECO_DEFAULT.height : isNextBuiltinShape ? builtinH : DEFAULT_PLACE_H;
	const useDecoSize = nextPol === "none" && nextKindValue !== "stage" && !isNextImage && !isNextBuiltinShape;
	const width = useDecoSize ? Math.max((_element$width = element.width) !== null && _element$width !== void 0 ? _element$width : DECO_SIZE, DECO_SIZE) : Math.max((_element$width2 = element.width) !== null && _element$width2 !== void 0 ? _element$width2 : nextW, nextW);
	const height = useDecoSize ? Math.max((_element$height = element.height) !== null && _element$height !== void 0 ? _element$height : DECO_SIZE, DECO_SIZE) : Math.max((_element$height2 = element.height) !== null && _element$height2 !== void 0 ? _element$height2 : nextH, nextH);
	const patch = {
		elementKind: nextKindValue,
		shape: isNextStage || isNextImage || isNextBuiltinShape ? "rect" : nextCfg === null || nextCfg === void 0 ? void 0 : nextCfg.defaultShape,
		width,
		height,
		name: (nextCfg === null || nextCfg === void 0 || (_nextCfg$defaultPrese = nextCfg.defaultPresentation) === null || _nextCfg$defaultPrese === void 0 ? void 0 : _nextCfg$defaultPrese.title) != null && String(nextCfg.defaultPresentation.title).trim() !== "" ? String(nextCfg.defaultPresentation.title) : element.name
	};
	if (clearBinding) patch.dataBinding = void 0;
	if (isNextImage) {
		var _element$imageUrl;
		patch.imageUrl = (_element$imageUrl = element.imageUrl) !== null && _element$imageUrl !== void 0 ? _element$imageUrl : "";
	} else patch.imageUrl = void 0;
	if (isNextBuiltinShape) {
		var _ref, _keep$key, _FLOOR_MAP_BUILTIN_SH;
		/**
		* 切到内置图形：保留已有 key（若有效），否则用预设里的第一项作为缺省。
		* 这样调色板拖入 / 同分类切换都能立刻看到图形，而不是占位文案。
		*/
		const keep = getFloorMapBuiltinShapeDef(element.builtinShapeKey);
		patch.builtinShapeKey = (_ref = (_keep$key = keep === null || keep === void 0 ? void 0 : keep.key) !== null && _keep$key !== void 0 ? _keep$key : (_FLOOR_MAP_BUILTIN_SH = FLOOR_MAP_BUILTIN_SHAPES[0]) === null || _FLOOR_MAP_BUILTIN_SH === void 0 ? void 0 : _FLOOR_MAP_BUILTIN_SH.key) !== null && _ref !== void 0 ? _ref : void 0;
	} else patch.builtinShapeKey = void 0;
	return patch;
}
/**
* @returns 人类可读错误文案；无问题时返回 null
*/
function getSceneElementRenderIssue(element, kind, dataSources) {
	const policy = resolveDataBindingPolicy(kind);
	const binding = element.dataBinding;
	if (policy === "required" && !binding) return locales.getText("pisell-floor-map-layout.binding-error.required-row");
	if (!binding) return null;
	const keys = kind === null || kind === void 0 ? void 0 : kind.allowedDataSourceKeys;
	if ((keys === null || keys === void 0 ? void 0 : keys.length) && !keys.includes(binding.dataSourceKey)) return locales.getText("pisell-floor-map-layout.binding-error.ds-not-allowed").replace(/\{key\}/g, binding.dataSourceKey);
	const rows = dataSources === null || dataSources === void 0 ? void 0 : dataSources[binding.dataSourceKey];
	const rid = binding.recordId != null ? String(binding.recordId).trim() : "";
	/**
	* 未选行、new_ 占位、或列表中已无该行：不在这里拦截，
	* 交给 renderItemByKind（方桌/圆桌/蘸料等）使用统一的浅底虚线占位，避免只有红字无卡片感。
	*/
	if (rid === "" || rid.startsWith("new_")) return null;
	const row = rows === null || rows === void 0 ? void 0 : rows.find((r) => r.id === rid);
	if (!row) return null;
	const expected = kind === null || kind === void 0 ? void 0 : kind.expectedRecordFields;
	if (expected === null || expected === void 0 ? void 0 : expected.length) {
		for (const f of expected) if (row[f] === void 0 || row[f] === null || row[f] === "") return locales.getText("pisell-floor-map-layout.binding-error.missing-field").replace(/\{field\}/g, f);
	}
	return null;
}
//#endregion
export { FLOOR_MAP_RESOURCE_PLACE_DEFAULT, getElementKindConfig, getSceneElementRenderIssue, getSwappableElementKindsInSameCategory, isDirectPlacePaletteKind, isFloorMapBuiltinShapeElementKind, isFloorMapImageElementKind, patchSceneElementForKindSwitch, resolveDataBindingPolicy };
