<template>
  <div class="chip-container" :style="{
    width: width + 'px',
    height: height + 'px',
    position: 'relative',
  }">
    <svg xmlns="http://www.w3.org/2000/svg" :width="width" :height="height" viewBox="0 0 400 400" class="fbg676-chip">
      <!-- 芯片外边框 - 用多段path代替rect，这样可以实现缺角 -->
      <path d="M30,0 H390 Q400,0 400,10 V390 Q400,400 390,400 H10 Q0,400 0,390 V30 L30,0 Z" fill="#1C4E2D" />

      <!-- 芯片内层 - 增大尺寸 -->
      <rect width="280" height="280" x="60" y="60" fill="#0F1211" rx="2" ry="2" />
    </svg>
    <!-- 渲染芯片引脚 -->
    <div v-for="pin in computedPins" :key="pin.pinId" :style="{
      position: 'absolute',
      left: `${(pin.x || 0) * props.size * 0.37}px`,
      top: `${(pin.y || 0) * props.size * 0.37}px`,
      transform: 'translate(-50%, -50%)',
    }" :data-pin-wrapper="`${pin.pinId}`" :data-pin-x="`${(pin.x || 0) * props.size * 0.37}`"
      :data-pin-y="`${(pin.y || 0) * props.size * 0.37}`">
      <Pin :ref="(el) => {
          if (el) pinRefs[pin.pinId] = el;
        }
        " :label="pin.pinId" :constraint="pin.constraint" :pinId="pin.pinId" :size="0.35"
        @pin-click="$emit('pin-click', $event)" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import Pin from "./Pin.vue";

// 存储多个Pin引用
const pinRefs = ref<Record<string, any>>({});

// 芯片特有属性
interface ChipProps {
  size?: number;
  pins?: {
    pinId: string;
    constraint: string;
    x?: number; // x坐标现在是可选的
    y?: number; // y坐标现在是可选的
  }[];
}

const props = withDefaults(defineProps<ChipProps>(), {
  size: 1,
  pins: () => [],
});

// 计算尺寸
const width = computed(() => 400 * props.size * 0.37);
const height = computed(() => 400 * props.size * 0.37);

// 生成676个引脚（26x26）
const computedPins = computed(() => {
  // 设置BGA矩阵布局参数
  const pinRows = 26;
  const pinColumns = 26;
  const margin = 25; // 四周边距
  const xStart = margin;
  const yStart = margin;
  const xEnd = 400 - margin;
  const yEnd = 400 - margin;
  const xStep = (xEnd - xStart) / (pinColumns - 1);
  const yStep = (yEnd - yStart) / (pinRows - 1);

  // 如果提供了pins，则合并引脚信息和位置信息
  if (props.pins && props.pins.length > 0) {
    // 复制一份提供的pins
    const mergedPins = [...props.pins];

    // 对于不包含xy坐标的引脚，生成默认的xy坐标
    for (let i = 0; i < mergedPins.length; i++) {
      const pin = mergedPins[i];
      // 如果没有提供xy坐标，根据引脚索引计算位置
      if (pin.x === undefined || pin.y === undefined) {
        const row = Math.floor(i / pinColumns);
        const col = i % pinColumns;

        pin.x = xStart + col * xStep;
        pin.y = yStart + row * yStep;
      }
    }

    return mergedPins;
  }

  // 否则生成默认的676个引脚，按BGA格式矩阵排列
  const pins = [];
  let pinIndex = 0;
  // 生成BGA封装的矩阵引脚
  for (let row = 0; row < pinRows; row++) {
    for (let col = 0; col < pinColumns; col++) {
      pins.push({
        pinId: `pin_${pinIndex++}`,
        constraint: "",
        x: xStart + col * xStep,
        y: yStart + row * yStep,
      });
    }
  }

  return pins;
});

defineExpose({
  getInfo: () => ({
    chipType: "PG2L100H_FBG676",
    direction: "inout",
    type: "digital",
    pins: computedPins.value,
  }),
  getPinPosition: (pinId: string) => {
    // 返回指定引脚ID的位置
    if (computedPins.value && computedPins.value.length > 0) {
      const customPin = computedPins.value.find((p) => p.pinId === pinId);

      if (customPin && customPin.x !== undefined && customPin.y !== undefined) {
        // 考虑组件尺寸的缩放，应用0.37的系数确保居中对齐
        const scaledX = customPin.x * props.size * 0.37;
        const scaledY = customPin.y * props.size * 0.37;

        return {
          x: scaledX,
          y: scaledY,
        };
      }
      return null;
    }
    return null;
  },
});
</script>

<script lang="ts">
// 添加一个静态方法来获取默认props
export function getDefaultProps() {
  return {
    size: 1,
    pins: [], // 默认不提供引脚，由computedPins计算生成
  };
}
</script>

<style scoped>
.chip-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.fbg676-chip {
  display: block;
  padding: 0;
  margin: 0;
  line-height: 0;
  font-size: 0;
  box-sizing: content-box;
  overflow: visible;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}
</style>
