import { ref, reactive } from 'vue';

export interface WireItem {
  id: string;
  startX: number;
  startY: number;
  endX: number;
  endY: number;
  startComponentId: string;
  endComponentId?: string;
  color?: string;
  isActive?: boolean;
  constraint?: string;
  strokeWidth?: number;
  routingMode?: 'auto' | 'orthogonal' | 'direct';
  showLabel?: boolean;
}

// 全局wires状态
export const wires = ref<WireItem[]>([]);

// 添加新连线
export function addWire(wire: WireItem) {
  wires.value.push(wire);
}

// 删除连线
export function deleteWire(wireId: string) {
  const idx = wires.value.findIndex(w => w.id === wireId);
  if (idx !== -1) wires.value.splice(idx, 1);
}

// 批量更新与某个引脚相关的所有Wire的约束
export function updateWiresConstraintByPin(componentId: string, newConstraint: string) {
  wires.value.forEach(wire => {
    if (
      (wire.startComponentId === componentId) ||
      (wire.endComponentId === componentId)
    ) {
      wire.constraint = newConstraint;
    }
  });
}

// 查找与某个引脚相关的所有Wire
export function findWiresByPin(componentId: string) {
  return wires.value.filter(wire =>
    (wire.startComponentId === componentId) ||
    (wire.endComponentId === componentId)
  );
}

// 临时连线相关状态
export const isCreatingWire = ref(false);
export const creatingWireStart = reactive({ x: 0, y: 0 });
export const creatingWireStartInfo = reactive({
  componentId: '',
  pinLabel: '',
  constraint: ''
});
export const mousePosition = reactive({ x: 0, y: 0 });

export function resetWireCreation() {
  isCreatingWire.value = false;
  creatingWireStart.x = 0;
  creatingWireStart.y = 0;
  creatingWireStartInfo.componentId = '';
  creatingWireStartInfo.pinLabel = '';
  creatingWireStartInfo.constraint = '';
}

export function setWireCreationStart(x: number, y: number, componentId: string, pinLabel: string, constraint: string) {
  isCreatingWire.value = true;
  creatingWireStart.x = x;
  creatingWireStart.y = y;
  creatingWireStartInfo.componentId = componentId;
  creatingWireStartInfo.pinLabel = pinLabel;
  creatingWireStartInfo.constraint = constraint;
}

export function setMousePosition(x: number, y: number) {
  mousePosition.x = x;
  mousePosition.y = y;
}

