function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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 _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 _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; }
/**
 * 平面图侧栏 palette「查看全部」弹窗（私有物料）
 * - 复用 `PisellProResourcePickerModal` 的 UI 与 Selector 数量选择能力
 * - Selector 使用 valueType="object" 以启用数量选择器（max>1）
 */
import React, { useEffect, useMemo } from 'react';
import { locales } from '@pisell/utils';
import { PisellTabbarTemplate1, floorMapLayoutLocales } from '@pisell/materials';
import useEngineContext from "../../hooks/useEngineContext";
import { PisellProResourcePickerModal } from "./PisellProResourcePickerModal";
/**
 * 模块加载时即用安全的默认 locale（zh-CN）初始化 floor map 文案字典，
 * 让首次 render 的 `useMemo`（如 tabbarDataSource 读「图片 / 图标」）就能拿到值，
 * 避免 React render 期 side-effect。引擎语言变化由组件内 `useEffect` 再次 init 切换。
 */
locales.init(floorMapLayoutLocales, 'zh-CN');

/** 与 materials 内 FloorMapElementKindConfig.value 对齐的「图片」kind 值 */
var IMAGE_KIND_VALUE = 'floorMapImage';
/** View All 顶部 Tabbar 的两个分类标识，写入 record.__category 与 Tabbar dataSource.id */
var CATEGORY_IMAGE = 'image';
var CATEGORY_ICON = 'icon';
var I18N_VA = 'pisell-floor-map-layout.toolbar';

/** 与 materials 内 FloorMapToolbarPaletteEntry 兼容的最小字段集合 */

function expandEntriesByQuantity(entries, quantities) {
  var out = [];
  var _iterator = _createForOfIteratorHelper(entries),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _quantities$e$key;
      var e = _step.value;
      var n = Math.max(0, Math.floor((_quantities$e$key = quantities[e.key]) !== null && _quantities$e$key !== void 0 ? _quantities$e$key : 0));
      for (var i = 0; i < n; i += 1) {
        out.push(_objectSpread({
          elementKind: e.kind.value
        }, e.builtinShapeKey ? {
          builtinShapeKey: e.builtinShapeKey
        } : {}));
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return out;
}
export function PisellFloorMapPaletteViewAllModal(props) {
  var _ref, _engine$props;
  var open = props.open,
    categoryLabel = props.categoryLabel,
    entries = props.entries,
    onClose = props.onClose,
    _onConfirm = props.onConfirm,
    renderEntryPreview = props.renderEntryPreview,
    platform = props.platform;
  var _useEngineContext = useEngineContext(),
    engine = _useEngineContext.engine;
  var engineLocale = (_ref = engine === null || engine === void 0 || (_engine$props = engine.props) === null || _engine$props === void 0 ? void 0 : _engine$props.locale) !== null && _ref !== void 0 ? _ref : 'zh-CN';

  /**
   * 切换引擎语言或弹窗打开时同步语言字典；首次 render 用的是模块顶层 init 的
   * 默认 locale，因此这里只负责追随后续语言变化，不在 render 期产生副作用。
   */
  useEffect(function () {
    if (open) {
      locales.init(floorMapLayoutLocales, engineLocale);
    }
  }, [open, engineLocale]);

  /**
   * 给每个 record 打上一级分类标签：
   * - image：图元 kind 为 `floorMapImage`（如「Image (background)」）
   * - icon：其它装饰（多为 builtin shape 如 Toilet / Divider / Sofa…）
   */
  var records = useMemo(function () {
    return entries.map(function (e) {
      return {
        id: e.key,
        title: e.label,
        __category: e.kind.value === IMAGE_KIND_VALUE ? CATEGORY_IMAGE : CATEGORY_ICON,
        __entry: e
      };
    });
  }, [entries]);

  /**
   * View All 顶部 Tabbar 固定两类：图片 / 图标。只有在 entries 中确有该类时才展示对应按钮。
   * Tabbar 自带内置 search + all，业务方无需自己注入。
   */
  var tabbarDataSource = useMemo(function () {
    var hasImage = entries.some(function (e) {
      return e.kind.value === IMAGE_KIND_VALUE;
    });
    var hasIcon = entries.some(function (e) {
      return e.kind.value !== IMAGE_KIND_VALUE;
    });
    var out = [];
    if (hasImage) {
      out.push({
        id: CATEGORY_IMAGE,
        name: locales.getText("".concat(I18N_VA, ".view-all-modal-category-image"))
      });
    }
    if (hasIcon) {
      out.push({
        id: CATEGORY_ICON,
        name: locales.getText("".concat(I18N_VA, ".view-all-modal-category-icon"))
      });
    }
    return out;
  }, [entries, engineLocale]);
  var title = categoryLabel;
  return /*#__PURE__*/React.createElement(PisellProResourcePickerModal, {
    open: open,
    title: title,
    onClose: onClose,
    platform: platform,
    onConfirm: function onConfirm(selected) {
      var quantities = {};
      var _iterator2 = _createForOfIteratorHelper(selected),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var v = _step2.value;
          var key = v.value.trim();
          if (!key) continue;
          quantities[key] = Math.max(0, Math.floor(v.quantity));
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      _onConfirm(expandEntriesByQuantity(entries, quantities));
    },
    records: records,
    mode: "multiple",
    value: []
    /** View all：必须开启 object 返回，才能展示并读取数量 */,
    selectorValueType: "object",
    selectorShowStepper: true,
    getOptionRuleConfig: function getOptionRuleConfig() {
      return {
        max: 99
      };
    },
    getSearchText: function getSearchText(r) {
      var _title;
      return String((_title = r.title) !== null && _title !== void 0 ? _title : '').toLowerCase();
    }
    /**
     * 用 record.__category（'image' / 'icon'）作为一级分类字段；点击 Tabbar
     * 某项时列表过滤到对应一类；点 All 显示全部。
     */,
    categoryConfig: {
      levels: [{
        field: '__category'
      }]
    }
    /**
     * 顶部筛选区与资源选择 modal 保持一致：使用 PisellTabbarTemplate1。
     * dataSource 走外部构造的 entry 列表（name 用 entry.label），
     * Tabbar 会自动在前面注入「search + all」内置按钮。
     */,
    renderFilterBar: function renderFilterBar(ctx) {
      return /*#__PURE__*/React.createElement(PisellTabbarTemplate1, {
        className: "pisell-pro-resource-picker-tabbar",
        style: {
          position: 'sticky',
          top: 0,
          zIndex: 10,
          padding: 6,
          background: 'rgb(250, 250, 250)'
        },
        dataSource: tabbarDataSource
        /**
         * useActiveKey 内部 `value || default` 的判空中 `[]` 是 truthy
         * 会被当作有效值，导致 initialActiveKey=[]、All 项无法高亮。
         * 这里把空数组归一化为 `['0']`（PisellTabbarTemplate1 注入的 All 项 id），
         * 确保打开 modal 时 All 默认选中；用户后续切到真实分类时仍走正常流程。
         */,
        value: Array.isArray(ctx.tabbarValue) && ctx.tabbarValue.length ? ctx.tabbarValue : ['0'],
        onChange: ctx.onTabbarValueChange,
        onSearch: ctx.onKeywordChange,
        maxLevel: 1
      });
    }
    /**
     * View All 走内置卡片渲染：把 palette preview 作为 image 节点回填到 meta，
     * 与资源选择卡片复用同一套 image+title+actions 结构。
     */,
    getCardMeta: function getCardMeta(r) {
      var _title2;
      var e = r.__entry;
      return {
        title: String((_title2 = r.title) !== null && _title2 !== void 0 ? _title2 : ''),
        subtitles: [],
        image: e ? renderEntryPreview(e) : undefined
      };
    }
  });
}
export default PisellFloorMapPaletteViewAllModal;