<template>
  <svg :width="width" :height="height" :viewBox="'0 0 ' + viewBoxWidth + ' ' + viewBoxHeight" class="pin-component">
    <g :transform="`translate(${viewBoxWidth / 2}, ${viewBoxHeight / 2})`">
      <g>
        <g transform="translate(-12.5, -12.5)">
          <!-- 添加一个透明的更大区域来增强点击能力，但比原来小一点 -->
          <circle cx="12.5" cy="12.5" r="5" fill="transparent" class="interactive" @click.stop="handlePinClick"
            @mousedown.stop @touchstart.stop :data-pin-element="`${props.pinId}`"
            :data-component-id="props.componentId" />
          <!-- 实际可见的引脚圆点 -->
          <circle :style="{ fill: pinColor }" cx="12.5" cy="12.5" r="3.75" pointer-events="none"
            :data-pin-visual="`${props.pinId}`" />
        </g>
      </g>
    </g>
  </svg>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from "vue";
import { useConstraintsStore } from "../../stores/constraints";
const { getConstraintColor, onConstraintStateChange } = useConstraintsStore();

interface Props {
  size?: number;
  label?: string;
  constraint?: string;
  direction?: "input" | "output" | "inout";
  type?: "digital" | "analog";
  pinId?: string; // 添加引脚ID属性，用于唯一标识
  componentId?: string; // 添加组件ID属性，关联到父组件
}

const props = withDefaults(defineProps<Props>(), {
  size: 1,
  label: "PIN",
  constraint: "",
  direction: "input",
  type: "digital",
  pinId: "pin-default", // 默认ID
  componentId: "", // 默认空字符串
});

const emit = defineEmits([
  "value-change",
  "pin-click", // 新增Pin点击事件
]);

// 内部状态
const analogValue = ref(0);

// 处理针脚点击
function handlePinClick(event: MouseEvent) {
  // 获取针脚在SVG中的位置
  const target = event.target as SVGElement;
  const rect = target.getBoundingClientRect();
  const pinCenter = {
    x: rect.left + rect.width / 2,
    y: rect.top + rect.height / 2,
  };
  emit("pin-click", {
    label: props.label,
    constraint: props.constraint,
    type: props.type,
    direction: props.direction,
    position: pinCenter,
    originalEvent: event,
  });
}

const width = computed(() => 15 * props.size);
const height = computed(() => 15 * props.size);
const viewBoxWidth = computed(() => 15);
const viewBoxHeight = computed(() => 15);

const getColorByType = computed(() => {
  return props.type === "analog" ? "#2a6099" : "#444";
});

// 根据约束电平状态计算引脚颜色
const pinColor = computed(() => {
  return getConstraintColor(props.constraint) || getColorByType.value;
});

// 监听约束状态变化
let unsubscribe: (() => void) | null = null;

onMounted(() => {
  // 监听约束状态变化
  if (props.constraint) {
    unsubscribe = onConstraintStateChange((constraint, level) => {
      if (constraint === props.constraint) {
        emit("value-change", { constraint, level });
      }
    });
  }
});

onUnmounted(() => {
  if (unsubscribe) {
    unsubscribe();
  }
});

watch(
  () => props.constraint,
  (newConstraint, oldConstraint) => {
    if (unsubscribe) {
      unsubscribe();
      unsubscribe = null;
    }
    if (newConstraint) {
      unsubscribe = onConstraintStateChange((constraint, level) => {
        if (constraint === newConstraint) {
          emit("value-change", { constraint, level });
        }
      });
    }
  },
);

function updateAnalogValue(value: number) {
  if (props.type !== "analog") return;
  analogValue.value = Math.max(0, Math.min(1, value));
  emit("value-change", {
    label: props.label,
    constraint: props.constraint,
    value: analogValue.value,
  });
}

defineExpose({
  setAnalogValue: updateAnalogValue,
  getAnalogValue: () => analogValue.value,
  getInfo: () => ({
    label: props.label,
    constraint: props.constraint,
    direction: props.direction,
    type: props.type,
    pinId: props.pinId,
  }),
  getPinPosition: () => {
    // Pin组件自身的getPinPosition应该返回相对于父组件的位置
    // 在MechanicalButton等组件中已经明确传递了position，所以这里实际上可能不会被使用
    return {
      x: viewBoxWidth.value / 2,
      y: viewBoxHeight.value / 2,
    };
  },
});
</script>

<script lang="ts">
// 添加一个静态方法来获取默认props
export function getDefaultProps() {
  return {
    size: 1,
    label: "PIN",
    constraint: "",
    direction: "input",
    type: "digital",
    pinId: "pin-default",
    componentId: "",
    pins: [
      {
        pinId: "PIN",
        constraint: "",
        x: 0,
        y: 0,
      },
    ],
  };
}
</script>

<style scoped>
.pin-component {
  display: block;
  user-select: none;
  position: relative;
  z-index: 5;
  /* 提高引脚组件的z-index */
  pointer-events: auto;
  /* 确保可以接收点击事件 */
  overflow: visible;
  /* 确保可以看到引脚 */
}

.interactive {
  cursor: pointer;
  transition: filter 0.2s;
  pointer-events: auto;
  /* 确保可以接收点击事件 */
}

.interactive:hover {
  filter: brightness(1.2);
  stroke: rgba(255, 255, 255, 0.3);
  /* 添加边框以便更容易看到点击区域 */
  stroke-width: 1;
}
</style>
