import { StickerItem } from '@ohos/common/src/main/ets/viewmodel/LocalBean';

@Component
export struct StickerView {
  @ObjectLink item: StickerItem;
  @Link selectedIndex: number; // 改用 @Link 关联父组件的索引，实现实时同步
  @Prop index: number;         // 传入当前在 ForEach 中的索引

  build() {
    Image(this.item.pixelMap)
      .width(200)
      .height(200)
      .objectFit(ImageFit.Contain)
      .translate({ x: this.item.posX, y: this.item.posY })
      .scale({ x: this.item.scaleValue, y: this.item.scaleValue })
      .rotate({ angle: this.item.rotateValue })
      .zIndex(this.item.zIndex)
      // Transparent 模式确保点到透明处会穿透，点到实体像素才拦截
      .hitTestBehavior(HitTestMode.Transparent)
      .visibility(this.item.isHidden ? Visibility.None : Visibility.Visible)
      .gesture(
        GestureGroup(GestureMode.Parallel,
          PanGesture()
            .onActionStart(() => {
              // 手指摸到的瞬间，立刻把选中的人设为自己
              this.selectedIndex = this.index;
              // 确保选中的在同类最前面
              this.promoteZIndex();
            })
            .onActionUpdate((event: GestureEvent) => {
              if (this.selectedIndex !== this.index) return;
              this.item.posX = this.item.lastX + event.offsetX;
              this.item.posY = this.item.lastY + event.offsetY;
            })
            .onActionEnd(() => {
              this.item.lastX = this.item.posX;
              this.item.lastY = this.item.posY;
            }),
          // 缩放和旋转手势同理在 onActionStart 加入选中逻辑
          PinchGesture()
            .onActionStart(() => { this.selectedIndex = this.index; })
            .onActionUpdate((event: GestureEvent) => {
              if (this.selectedIndex !== this.index) return;
              this.item.scaleValue = this.item.lastScale * event.scale;
            })
            .onActionEnd(() => { this.item.lastScale = this.item.scaleValue; }),

          RotationGesture()
            .onActionStart(() => { this.selectedIndex = this.index; })
            .onActionUpdate((event: GestureEvent) => {
              if (this.selectedIndex !== this.index) return;
              this.item.rotateValue = this.item.lastRotate + event.angle;
            })
            .onActionEnd(() => { this.item.lastRotate = this.item.rotateValue; })
        )
      )
  }

  private promoteZIndex() {
    const baseZ = (this.item.type + 1) * 10;
    this.item.zIndex = baseZ + 9; // 直接拉到该区间的最高位
  }
}


