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 _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 _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; }
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; }
/**
 * EdgeLayer - 拓扑连线 SVG 层（正交折线 + 端口标签）
 */
import React, { useMemo } from 'react';
import classNames from 'classnames';
import { getPortLabelPosition, resolveEdgeCenterLabelPositions } from "../utils/edgeRouting";
import "./EdgeLayer.less";
var PREFIX = 'pisell-floor-map-layout';

/** 中段手柄基础视觉尺寸（px），实际渲染会按 viewportScale 反向缩放 */
var SEGMENT_HANDLE_BASE_SIZE = 12;
/** 段长 < 该值（px）时不渲染手柄，避免极短段误触 */
var SEGMENT_HANDLE_MIN_LENGTH = 16;
function resolveEdgeStroke(edge, appearance, selected) {
  var _edge$status, _edge$strokeWidth3;
  if (selected) {
    var _edge$strokeWidth;
    return {
      stroke: appearance.edgeSelectedStroke,
      strokeWidth: ((_edge$strokeWidth = edge.strokeWidth) !== null && _edge$strokeWidth !== void 0 ? _edge$strokeWidth : 1.5) + 1
    };
  }
  if (edge.color) {
    var _edge$strokeWidth2;
    return {
      stroke: edge.color,
      strokeWidth: (_edge$strokeWidth2 = edge.strokeWidth) !== null && _edge$strokeWidth2 !== void 0 ? _edge$strokeWidth2 : 1.5,
      strokeDasharray: edge.dashed ? '6 4' : undefined
    };
  }
  var status = (_edge$status = edge.status) !== null && _edge$status !== void 0 ? _edge$status : 'unknown';
  var style = appearance.edgeStatusStyles[status];
  return {
    stroke: style.stroke,
    strokeWidth: (_edge$strokeWidth3 = edge.strokeWidth) !== null && _edge$strokeWidth3 !== void 0 ? _edge$strokeWidth3 : 1.5,
    strokeDasharray: edge.dashed || style.dashed ? '6 4' : undefined
  };
}
function PortLabel(props) {
  var x = props.x,
    y = props.y,
    text = props.text,
    appearance = props.appearance;
  var padX = 6;
  var padY = 3;
  var estW = Math.max(32, text.length * 6.5 + padX * 2);
  var h = 18;
  return /*#__PURE__*/React.createElement("g", {
    className: "".concat(PREFIX, "-edge-port-label")
  }, /*#__PURE__*/React.createElement("rect", {
    x: x - estW / 2,
    y: y - h / 2,
    width: estW,
    height: h,
    rx: 4,
    fill: appearance.edgePortLabelBackground,
    stroke: appearance.edgePortLabelBorder,
    strokeWidth: 1
  }), /*#__PURE__*/React.createElement("text", {
    x: x,
    y: y + 4,
    textAnchor: "middle",
    fontSize: 11,
    fill: appearance.edgePortLabelText
  }, text));
}
export function EdgeLayer(props) {
  var width = props.width,
    height = props.height,
    _props$contentOffsetX = props.contentOffsetX,
    contentOffsetX = _props$contentOffsetX === void 0 ? 0 : _props$contentOffsetX,
    _props$contentOffsetY = props.contentOffsetY,
    contentOffsetY = _props$contentOffsetY === void 0 ? 0 : _props$contentOffsetY,
    edges = props.edges,
    routes = props.routes,
    rectsById = props.rectsById,
    appearance = props.appearance,
    mode = props.mode,
    selectedEdgeId = props.selectedEdgeId,
    ghostPathD = props.ghostPathD,
    onEdgeClick = props.onEdgeClick,
    _props$viewportScale = props.viewportScale,
    viewportScale = _props$viewportScale === void 0 ? 1 : _props$viewportScale,
    onSegmentDragStart = props.onSegmentDragStart,
    className = props.className;
  var safeScale = Math.max(viewportScale, 0.01);
  var handleSize = SEGMENT_HANDLE_BASE_SIZE / safeScale;
  var handleHalf = handleSize / 2;
  var edgeById = useMemo(function () {
    var m = new Map();
    var _iterator = _createForOfIteratorHelper(edges),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var e = _step.value;
        m.set(e.id, e);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    return m;
  }, [edges]);
  var routeById = useMemo(function () {
    var m = new Map();
    var _iterator2 = _createForOfIteratorHelper(routes),
      _step2;
    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var r = _step2.value;
        m.set(r.edgeId, r);
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }
    return m;
  }, [routes]);

  /** 同目标多边时错开 connection_type 标签，避免叠在一起 */
  var centerLabelByEdgeId = useMemo(function () {
    return resolveEdgeCenterLabelPositions(routes.map(function (route) {
      var edge = edgeById.get(route.edgeId);
      if (!edge) return null;
      return {
        edgeId: route.edgeId,
        sourceId: edge.sourceId,
        targetId: edge.targetId,
        points: route.points,
        label: edge.label
      };
    }).filter(function (row) {
      return row != null;
    }), {
      placement: 'target-tail',
      rectsById: rectsById
    });
  }, [routes, edgeById, rectsById]);
  return /*#__PURE__*/React.createElement("svg", {
    className: classNames("".concat(PREFIX, "-edge-layer"), className),
    width: width,
    height: height,
    style: {
      position: 'absolute',
      left: contentOffsetX,
      top: contentOffsetY,
      pointerEvents: 'none',
      overflow: 'visible'
    },
    "aria-hidden": mode === 'read'
  }, /*#__PURE__*/React.createElement("g", {
    className: "".concat(PREFIX, "-edge-layer-inner")
  }, routes.map(function (route) {
    var edge = edgeById.get(route.edgeId);
    if (!edge) return null;
    var selected = selectedEdgeId === edge.id;
    var stroke = resolveEdgeStroke(edge, appearance, selected);
    return /*#__PURE__*/React.createElement("g", {
      key: edge.id,
      className: "".concat(PREFIX, "-edge-group")
    }, /*#__PURE__*/React.createElement("path", {
      d: route.pathD,
      fill: "none",
      stroke: stroke.stroke,
      strokeWidth: stroke.strokeWidth,
      strokeDasharray: stroke.strokeDasharray,
      strokeLinecap: "round",
      strokeLinejoin: "round",
      className: classNames("".concat(PREFIX, "-edge-path"), _defineProperty(_defineProperty({}, "".concat(PREFIX, "-edge-path--selected"), selected), "".concat(PREFIX, "-edge-path--interactive"), mode === 'edit')),
      style: {
        pointerEvents: mode === 'edit' ? 'stroke' : 'none',
        cursor: mode === 'edit' ? 'pointer' : undefined
      },
      onClick: mode === 'edit' && onEdgeClick ? function (ev) {
        ev.stopPropagation();
        onEdgeClick(edge.id, ev);
      } : undefined
    }), edge.label && route.points.length >= 2 ? function () {
      var labelPos = centerLabelByEdgeId.get(edge.id);
      if (!labelPos) return null;
      return /*#__PURE__*/React.createElement(PortLabel, {
        x: labelPos.x,
        y: labelPos.y,
        text: edge.label,
        appearance: appearance
      });
    }() : null);
  }), edges.map(function (edge) {
    var _edge$sourceAnchor, _edge$targetAnchor;
    var route = routeById.get(edge.id);
    var srcRect = rectsById.get(edge.sourceId);
    var tgtRect = rectsById.get(edge.targetId);
    if (!route || !srcRect || !tgtRect) return null;
    var sourceAnchor = (_edge$sourceAnchor = edge.sourceAnchor) !== null && _edge$sourceAnchor !== void 0 ? _edge$sourceAnchor : 'right';
    var targetAnchor = (_edge$targetAnchor = edge.targetAnchor) !== null && _edge$targetAnchor !== void 0 ? _edge$targetAnchor : 'left';
    var spLabel = getPortLabelPosition(srcRect, sourceAnchor);
    var tpLabel = getPortLabelPosition(tgtRect, targetAnchor);
    return /*#__PURE__*/React.createElement("g", {
      key: "".concat(edge.id, "-labels")
    }, edge.sourceLabel ? /*#__PURE__*/React.createElement(PortLabel, {
      x: spLabel.x,
      y: spLabel.y,
      text: edge.sourceLabel,
      appearance: appearance
    }) : null, edge.targetLabel ? /*#__PURE__*/React.createElement(PortLabel, {
      x: tpLabel.x,
      y: tpLabel.y,
      text: edge.targetLabel,
      appearance: appearance
    }) : null);
  }), mode === 'edit' && selectedEdgeId && onSegmentDragStart ? function () {
    var route = routeById.get(selectedEdgeId);
    if (!route) return null;
    var pts = route.points;
    if (pts.length < 2) return null;
    var lastSegIdx = pts.length - 2;
    var handles = [];
    for (var i = 0; i <= lastSegIdx; i++) {
      var role = i === 0 ? 'first' : i === lastSegIdx ? 'last' : 'inner';
      var _pts$i = _slicedToArray(pts[i], 2),
        x1 = _pts$i[0],
        y1 = _pts$i[1];
      var _pts = _slicedToArray(pts[i + 1], 2),
        x2 = _pts[0],
        y2 = _pts[1];
      var axis = void 0;
      var position = void 0;
      var length = void 0;
      var midX = void 0;
      var midY = void 0;
      if (y1 === y2 && x1 !== x2) {
        axis = 'h';
        position = y1;
        length = Math.abs(x2 - x1);
        midX = (x1 + x2) / 2;
        midY = y1;
      } else if (x1 === x2 && y1 !== y2) {
        axis = 'v';
        position = x1;
        length = Math.abs(y2 - y1);
        midX = x1;
        midY = (y1 + y2) / 2;
      } else {
        continue;
      }
      if (length < SEGMENT_HANDLE_MIN_LENGTH) continue;
      handles.push({
        key: "".concat(role, "-").concat(i),
        role: role,
        /** inner 时传 path segment index（拖动逻辑直接消费） */
        segmentIndex: i,
        axis: axis,
        position: position,
        length: length,
        midX: midX,
        midY: midY
      });
    }
    if (handles.length === 0) return null;
    return /*#__PURE__*/React.createElement("g", {
      className: "".concat(PREFIX, "-edge-segment-handles"),
      pointerEvents: "auto"
    }, handles.map(function (h) {
      return /*#__PURE__*/React.createElement("rect", {
        key: h.key,
        x: h.midX - handleHalf,
        y: h.midY - handleHalf,
        width: handleSize,
        height: handleSize,
        rx: handleHalf,
        ry: handleHalf,
        className: classNames("".concat(PREFIX, "-edge-segment-handle"), "".concat(PREFIX, "-edge-segment-handle--").concat(h.axis), "".concat(PREFIX, "-edge-segment-handle--").concat(h.role)),
        fill: appearance.edgeSelectedStroke,
        stroke: "#fff",
        strokeWidth: 1.5 / safeScale,
        style: {
          cursor: h.axis === 'h' ? 'ns-resize' : 'ew-resize',
          touchAction: 'none'
        },
        onPointerDown: function onPointerDown(ev) {
          ev.stopPropagation();
          ev.preventDefault();
          onSegmentDragStart({
            edgeId: selectedEdgeId,
            role: h.role,
            segmentIndex: h.segmentIndex,
            axis: h.axis,
            startPosition: h.position,
            clientX: ev.clientX,
            clientY: ev.clientY,
            segmentLength: h.length
          });
        }
      });
    }));
  }() : null, ghostPathD ? /*#__PURE__*/React.createElement("path", {
    d: ghostPathD,
    fill: "none",
    stroke: appearance.edgeGhostStroke,
    strokeWidth: 1.5,
    strokeDasharray: "4 4",
    strokeLinecap: "round",
    pointerEvents: "none"
  }) : null));
}