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 _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 _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 _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 _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 { FLOOR_MAP_IMAGE_ELEMENT_KIND, FLOOR_MAP_STAGE_ELEMENT_KIND } from "../types";
import { locales } from '@pisell/utils';
import { STAGE_DECO_DEFAULT } from "./floorMapStageDefaults";

/** 与 RecordBoard Story 一致：`floorMapImage` */
export function isFloorMapImageElementKind(kind) {
  return kind === FLOOR_MAP_IMAGE_ELEMENT_KIND;
}

/** dataBindingPolicy 缺省视为 none */
export 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';
}
export function getElementKindConfig(config, elementKind) {
  var _config$elementKinds;
  if (!elementKind || !(config !== null && config !== void 0 && (_config$elementKinds = config.elementKinds) !== null && _config$elementKinds !== void 0 && _config$elementKinds.length)) return undefined;
  return config.elementKinds.find(function (k) {
    return k.value === elementKind;
  });
}

/**
 * 与调色板分组一致：取与当前图元 **同一 categoryId**（含未填 categoryId 时落到首个分类）下的可切换种类，
 * 排除舞台、底图。若仅有一种则编辑面板可不展示切换器。
 */
export 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 && _config$elementKinds2.length)) return [];
  var rawCats = (_config$elementKindCa = config.elementKindCategories) !== null && _config$elementKindCa !== void 0 ? _config$elementKindCa : [];
  var sorted = _toConsumableArray(rawCats).sort(function (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);
  });
  var fallbackId = (_sorted$0$id = (_sorted$ = sorted[0]) === null || _sorted$ === void 0 ? void 0 : _sorted$.id) !== null && _sorted$0$id !== void 0 ? _sorted$0$id : '_uncat';
  var self = config.elementKinds.find(function (k) {
    return k.value === elementKind;
  });
  if (!self) return [];
  var cid = (_self$categoryId = self.categoryId) !== null && _self$categoryId !== void 0 ? _self$categoryId : fallbackId;
  return config.elementKinds.filter(function (k) {
    var _k$categoryId;
    if (k.showInPalette === false) return false;
    if (k.value === FLOOR_MAP_STAGE_ELEMENT_KIND) return false;
    if (k.value === FLOOR_MAP_IMAGE_ELEMENT_KIND) return false;
    return ((_k$categoryId = k.categoryId) !== null && _k$categoryId !== void 0 ? _k$categoryId : fallbackId) === cid;
  });
}
var DEFAULT_PLACE_W = 180;
var DEFAULT_PLACE_H = 120;
var IMAGE_PLACE_W = 400;
var IMAGE_PLACE_H = 240;
var DECO_SIZE = 48;

/**
 * 在右侧编辑面板将图元改为同分类下的另一种 kind 时的草稿 patch（绑定不兼容则清空）
 */
export function patchSceneElementForKindSwitch(config, element, nextKindValue) {
  var _nextCfg$allowedDataS, _element$width, _element$width2, _element$height, _element$height2, _nextCfg$defaultPrese;
  var nextCfg = getElementKindConfig(config, nextKindValue);
  var nextPol = resolveDataBindingPolicy(nextCfg);
  var binding = element.dataBinding;
  var isNextImage = isFloorMapImageElementKind(nextKindValue);
  var isNextStage = nextKindValue === FLOOR_MAP_STAGE_ELEMENT_KIND;
  var clearBinding = false;
  if (nextPol === 'none') {
    clearBinding = true;
  } else if (binding && nextCfg !== null && nextCfg !== void 0 && (_nextCfg$allowedDataS = nextCfg.allowedDataSourceKeys) !== null && _nextCfg$allowedDataS !== void 0 && _nextCfg$allowedDataS.length) {
    if (!nextCfg.allowedDataSourceKeys.includes(binding.dataSourceKey)) {
      clearBinding = true;
    }
  }
  var nextW = isNextImage ? IMAGE_PLACE_W : isNextStage ? STAGE_DECO_DEFAULT.width : DEFAULT_PLACE_W;
  var nextH = isNextImage ? IMAGE_PLACE_H : isNextStage ? STAGE_DECO_DEFAULT.height : DEFAULT_PLACE_H;
  var useDecoSize = nextPol === 'none' && nextKindValue !== FLOOR_MAP_STAGE_ELEMENT_KIND && !isNextImage;
  var 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);
  var 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);
  var patch = {
    elementKind: nextKindValue,
    shape: isNextStage || isNextImage ? 'rect' : nextCfg === null || nextCfg === void 0 ? void 0 : nextCfg.defaultShape,
    width: width,
    height: 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 = undefined;
  }
  if (isNextImage) {
    var _element$imageUrl;
    patch.imageUrl = (_element$imageUrl = element.imageUrl) !== null && _element$imageUrl !== void 0 ? _element$imageUrl : '';
  } else {
    patch.imageUrl = undefined;
  }
  return patch;
}

/**
 * @returns 人类可读错误文案；无问题时返回 null
 */
export function getSceneElementRenderIssue(element, kind, dataSources) {
  var policy = resolveDataBindingPolicy(kind);
  var binding = element.dataBinding;
  if (policy === 'required' && !binding) {
    return locales.getText('pisell-floor-map-layout.binding-error.required-row');
  }
  if (!binding) return null;
  var keys = kind === null || kind === void 0 ? void 0 : kind.allowedDataSourceKeys;
  if (keys !== null && keys !== 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);
  }
  var rows = dataSources === null || dataSources === void 0 ? void 0 : dataSources[binding.dataSourceKey];
  var rid = binding.recordId != null ? String(binding.recordId).trim() : '';

  /**
   * 未选行、new_ 占位、或列表中已无该行：不在这里拦截，
   * 交给 renderItemByKind（方桌/圆桌/蘸料等）使用统一的浅底虚线占位，避免只有红字无卡片感。
   */
  if (rid === '' || rid.startsWith('new_')) {
    return null;
  }
  var row = rows === null || rows === void 0 ? void 0 : rows.find(function (r) {
    return r.id === rid;
  });
  if (!row) {
    return null;
  }
  var expected = kind === null || kind === void 0 ? void 0 : kind.expectedRecordFields;
  if (expected !== null && expected !== void 0 && expected.length) {
    var _iterator = _createForOfIteratorHelper(expected),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var f = _step.value;
        if (row[f] === undefined || row[f] === null || row[f] === '') {
          return locales.getText('pisell-floor-map-layout.binding-error.missing-field').replace(/\{field\}/g, f);
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  }
  return null;
}