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 _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; }
/**
 * 根据 edges + 图元矩形计算连线路由
 */
import { useMemo } from 'react';
import { buildEdgeRoute, getEdgeChannelOffset, getItemPixelRect } from "../utils/edgeRouting";

/**
 * 路径轴线对齐 segment：用于检测两条 route 是否共享同一通道。
 * 水平段：orientation='h', key=y, [a, b] 表示 x 范围
 * 竖直段：orientation='v', key=x, [a, b] 表示 y 范围
 */

function extractRouteSegments(points) {
  var segs = [];
  for (var i = 0; i < points.length - 1; i++) {
    var _points$i = _slicedToArray(points[i], 2),
      x1 = _points$i[0],
      y1 = _points$i[1];
    var _points = _slicedToArray(points[i + 1], 2),
      x2 = _points[0],
      y2 = _points[1];
    if (y1 === y2 && x1 !== x2) {
      segs.push({
        orientation: 'h',
        key: y1,
        a: Math.min(x1, x2),
        b: Math.max(x1, x2)
      });
    } else if (x1 === x2 && y1 !== y2) {
      segs.push({
        orientation: 'v',
        key: x1,
        a: Math.min(y1, y2),
        b: Math.max(y1, y2)
      });
    }
  }
  return segs;
}
function segmentsOverlap(a, b) {
  if (a.orientation !== b.orientation) return false;
  if (a.key !== b.key) return false;
  return Math.max(a.a, b.a) < Math.min(a.b, b.b);
}
function routesShareChannel(a, b) {
  var segsA = extractRouteSegments(a);
  var segsB = extractRouteSegments(b);
  var _iterator = _createForOfIteratorHelper(segsA),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var sa = _step.value;
      var _iterator2 = _createForOfIteratorHelper(segsB),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var sb = _step2.value;
          if (segmentsOverlap(sa, sb)) return true;
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return false;
}

/** 同一目标的多条边在末段竖线处必然共线，需主动分配通道错位 */
function edgesShareTarget(a, b) {
  return a.targetId === b.targetId || a.sourceId === b.sourceId;
}
export function useFloorMapEdgeViewModel(params) {
  var _params$edges = params.edges,
    edges = _params$edges === void 0 ? [] : _params$edges,
    items = params.items,
    cellSize = params.cellSize,
    itemUnit = params.itemUnit,
    itemGap = params.itemGap,
    pendingRectsById = params.pendingRectsById,
    pendingRoutingByEdge = params.pendingRoutingByEdge;
  return useMemo(function () {
    var rectsById = new Map();
    var _iterator3 = _createForOfIteratorHelper(items),
      _step3;
    try {
      for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
        var item = _step3.value;
        rectsById.set(item.id, getItemPixelRect(item, {
          cellSize: cellSize,
          itemUnit: itemUnit,
          itemGap: itemGap,
          override: pendingRectsById === null || pendingRectsById === void 0 ? void 0 : pendingRectsById[item.id]
        }));
      }
      /** Pass 1：所有 edge 用默认通道（offset = 0）计算一次 */
    } catch (err) {
      _iterator3.e(err);
    } finally {
      _iterator3.f();
    }
    var naive = edges.map(function (edge) {
      return {
        edge: edge,
        route: buildEdgeRoute(edge, rectsById, {
          routingOverride: pendingRoutingByEdge === null || pendingRoutingByEdge === void 0 ? void 0 : pendingRoutingByEdge[edge.id]
        })
      };
    });

    /**
     * Pass 2：对共享通道的 edges 分配错位 offset。
     * 用 union-find 风格：按 edges 出现顺序遍历，与已选 routes 比对，若冲突则用下一个 offset。
     */
    var routes = [];
    var accepted = [];
    var acceptedEdges = [];
    var _loop = function _loop() {
      var _naive$i = naive[i],
        edge = _naive$i.edge,
        route = _naive$i.route;
      if (!route) return 1; // continue
      var chosen = route;
      var attempt = 0;
      var maxAttempts = 10;
      while (attempt < maxAttempts) {
        var conflicts = accepted.some(function (r, idx) {
          var other = acceptedEdges[idx];
          return routesShareChannel(chosen.points, r.points) || other != null && edgesShareTarget(edge, other);
        });
        if (!conflicts) break;
        attempt += 1;
        var offset = getEdgeChannelOffset(attempt);
        var re = buildEdgeRoute(edge, rectsById, {
          channelOffset: offset,
          routingOverride: pendingRoutingByEdge === null || pendingRoutingByEdge === void 0 ? void 0 : pendingRoutingByEdge[edge.id]
        });
        if (!re) break;
        chosen = re;
      }
      accepted.push(chosen);
      acceptedEdges.push(edge);
      routes.push(chosen);
    };
    for (var i = 0; i < naive.length; i++) {
      if (_loop()) continue;
    }
    return {
      routes: routes,
      rectsById: rectsById
    };
  }, [edges, items, cellSize, itemUnit, itemGap, pendingRectsById, pendingRoutingByEdge]);
}