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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
/**
 * 拉取拓扑 floor-plan：把远端 layout 解析成已保存的 sceneElements / edges。
 *
 * 设计点：
 * - 不再混入 mock shell，调用方直接拿到「已保存」的 sceneElements / edges 用于对账
 * - 区分「未加载」「已加载但为空」「已加载且有内容」三态：未加载时 savedSceneElements = undefined
 */
import { useCallback, useEffect, useRef, useState } from 'react';
import { parseLayoutFieldToViewConfigPatch, shopLayoutToSceneElements, useShopFloorPlanSubscription } from '@pisell/materials';
import { getUniqueId } from '@pisell/utils';
import { TOPOLOGY_DEVICE_KIND_PREFIX, TOPOLOGY_DEVICES_DATA_SOURCE_KEY, TOPOLOGY_MAIN_CANVAS_ID } from "../topologyFloorPlanConstants";
import { ensureShopFloorPlanByCode, toastFloorPlanLoadError, unsubscribeShopFloorPlanCodeQuery } from "./topologyFloorPlanApi";
var TOPOLOGY_UNKNOWN_KIND = "".concat(TOPOLOGY_DEVICE_KIND_PREFIX, "unknown");

/** 创建空的默认 floor-plan post body（首次创建时使用，不放任何 mock 节点） */
function buildEmptyTopologyFloorPlanPostBody(code) {
  var trimmed = code === null || code === void 0 ? void 0 : code.trim();
  if (!trimmed) throw new Error('floor plan code is required');
  return {
    code: trimmed,
    name: {
      'zh-CN': '拓扑'
    },
    layout: {
      canvases: [{
        id: 'main',
        name: 'Devices',
        order: 0,
        enabled: true
      }],
      canvasUi: {
        canCreate: false,
        canEdit: false
      },
      sceneElements: [],
      edges: []
    },
    canvas_width: 1920,
    canvas_height: 1080
  };
}
export function useTopologyFloorPlan(options) {
  var floorPlanCode = options.floorPlanCode,
    _options$enabled = options.enabled,
    enabled = _options$enabled === void 0 ? true : _options$enabled,
    _options$subscribeFlo = options.subscribeFloorPlanPush,
    subscribeFloorPlanPush = _options$subscribeFlo === void 0 ? false : _options$subscribeFlo;
  var _useState = useState(null),
    _useState2 = _slicedToArray(_useState, 2),
    floorPlanRemoteId = _useState2[0],
    setFloorPlanRemoteId = _useState2[1];
  var _useState3 = useState(undefined),
    _useState4 = _slicedToArray(_useState3, 2),
    savedSceneElements = _useState4[0],
    setSavedSceneElements = _useState4[1];
  var _useState5 = useState(undefined),
    _useState6 = _slicedToArray(_useState5, 2),
    savedEdges = _useState6[0],
    setSavedEdges = _useState6[1];
  var subscriberIdRef = useRef(getUniqueId('topology-floor-plan-code'));

  /**
   * 必须稳定引用：`useShopFloorPlanSubscription` 的 effect 依赖 ensureByCode，
   * 若每次 render 新建内联函数会反复 unsubscribe → 再订阅，形成 pisell_topology 与
   * unsubscribe 交替刷屏。
   */
  var ensureByCode = useCallback(function (code, opts) {
    return ensureShopFloorPlanByCode(code, _objectSpread(_objectSpread({}, opts), {}, {
      buildDefaultPostBody: buildEmptyTopologyFloorPlanPostBody
    }));
  }, []);
  var applyDetail = useCallback(function (detail) {
    if (typeof detail.id === 'number' && Number.isFinite(detail.id)) {
      setFloorPlanRemoteId(Math.trunc(detail.id));
    }
    var fromLayoutField = parseLayoutFieldToViewConfigPatch(detail.layout);
    if (fromLayoutField) {
      var _fromLayoutField$scen, _fromLayoutField$edge;
      setSavedSceneElements((_fromLayoutField$scen = fromLayoutField.sceneElements) !== null && _fromLayoutField$scen !== void 0 ? _fromLayoutField$scen : []);
      setSavedEdges((_fromLayoutField$edge = fromLayoutField.edges) !== null && _fromLayoutField$edge !== void 0 ? _fromLayoutField$edge : []);
      return;
    }
    /**
     * 兼容预约同款扁平 layout 数组（后端常存 ShopFloorPlanLayoutItem[]）。
     * 若按 ViewConfig 解析失败但 layout 是数组，则转成 sceneElements 再对账。
     */
    if (Array.isArray(detail.layout)) {
      setSavedSceneElements(detail.layout.length > 0 ? shopLayoutToSceneElements(detail.layout, {
        canvasId: TOPOLOGY_MAIN_CANVAS_ID,
        dataSourceKey: TOPOLOGY_DEVICES_DATA_SOURCE_KEY,
        rectElementKind: TOPOLOGY_UNKNOWN_KIND,
        circleElementKind: TOPOLOGY_UNKNOWN_KIND
      }) : []);
      setSavedEdges([]);
      return;
    }
    setSavedSceneElements([]);
    setSavedEdges([]);
  }, []);

  /**
   * 关闭时清空，否则切换 code 时旧数据会泄漏成新 code 的 saved 基线。
   */
  useEffect(function () {
    if (!enabled) {
      setFloorPlanRemoteId(null);
      setSavedSceneElements(undefined);
      setSavedEdges(undefined);
    }
  }, [enabled, floorPlanCode]);

  /** 非 WebPOS：单次 ensure（GET + 404/4004 自动创建），不注册推送订阅 */
  useEffect(function () {
    if (!enabled || !floorPlanCode || subscribeFloorPlanPush) return;
    var cancelled = false;
    void ensureByCode(floorPlanCode).then(function (detail) {
      if (cancelled || !detail) return;
      applyDetail(detail);
    }).catch(function (err) {
      if (!cancelled) toastFloorPlanLoadError(err);
    });
    return function () {
      cancelled = true;
    };
  }, [enabled, floorPlanCode, subscribeFloorPlanPush, ensureByCode, applyDetail]);
  useShopFloorPlanSubscription({
    enabled: enabled && !!floorPlanCode && subscribeFloorPlanPush,
    code: floorPlanCode,
    subscriberId: subscriberIdRef.current,
    ensureByCode: ensureByCode,
    unsubscribeQuery: unsubscribeShopFloorPlanCodeQuery,
    onDetail: applyDetail,
    onLoadError: toastFloorPlanLoadError
  });
  var applyLocalSave = useCallback(function (params) {
    setSavedSceneElements(params.sceneElements);
    setSavedEdges(params.edges);
  }, []);
  var setRemoteFloorPlanView = useCallback(function (patch) {
    if (patch == null) {
      setSavedSceneElements(undefined);
      setSavedEdges(undefined);
      return;
    }
    if (patch.sceneElements != null) {
      setSavedSceneElements(patch.sceneElements);
    }
    if (patch.edges != null) {
      setSavedEdges(patch.edges);
    }
  }, []);
  return {
    floorPlanRemoteId: floorPlanRemoteId,
    savedSceneElements: savedSceneElements,
    savedEdges: savedEdges,
    isLoaded: savedSceneElements !== undefined,
    applyLocalSave: applyLocalSave,
    setRemoteFloorPlanView: setRemoteFloorPlanView
  };
}