<template>
  <div class="editable-furniture" :style="containerStyle" @mousedown.stop="startDrag">
    <div class="furniture-rotated-container" :style="rotatedContainerStyle">
      <div class="furniture-wrapper">
        <furnitureIcon :icon="localItem.type" :width="localItem.width" :height="localItem.length" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, watch, computed, onMounted, nextTick, type CSSProperties } from 'vue'
import type { FurnitureItem, FurnitureType, LocalFurnitureItem } from '@/api/room/types'
import { convert_furniture_r2c, rotateRect } from '@/utils/coordTransform'

defineOptions({ name: 'EditableFurniture' })

interface Props {
  item: FurnitureItem
  angle: number
  coordinates: [number, number, number, number]
  canvasSize?: number
  initialAtOrigin?: boolean
  disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  canvasSize: 500,
  initialAtOrigin: false,
  disabled: false,
})

const emit = defineEmits<{
  (e: 'update', item: LocalFurnitureItem): void
  (e: 'delete', nanoid: string): void
}>()

// 坐标转换函数
const geoToPixel = (geoX: number, geoY: number): { x: number; y: number } => {
  return {
    x: props.canvasSize / 2 + geoX,
    y: props.canvasSize / 2 - geoY,
  }
}

const pixelToGeo = (pixelX: number, pixelY: number): { x: number; y: number } => {
  return {
    x: pixelX - props.canvasSize / 2,
    y: props.canvasSize / 2 - pixelY,
  }
}

// 计算旋转后的边界框（基于左上角基准）
const calculateBoundingBox = () => {
  const { width, length, rotate } = localItem
  const rad = (rotate * Math.PI) / 180

  if (rotate === 0) {
    // 未旋转时，边界框就是家具本身
    return {
      left: 0,
      right: width,
      top: 0,
      bottom: length,
      width: width,
      height: length,
    }
  }

  // 计算旋转后的四个角点（相对于左上角）
  const corners = [
    { x: 0, y: 0 }, // 左上
    { x: width, y: 0 }, // 右上
    { x: width, y: length }, // 右下
    { x: 0, y: length }, // 左下
  ]

  // 旋转角点（围绕左上角旋转）
  const rotatedCorners = corners.map((corner) => ({
    x: corner.x * Math.cos(rad) - corner.y * Math.sin(rad),
    y: corner.x * Math.sin(rad) + corner.y * Math.cos(rad),
  }))

  // 计算边界框
  const xs = rotatedCorners.map((c) => c.x)
  const ys = rotatedCorners.map((c) => c.y)

  const minX = Math.min(...xs)
  const maxX = Math.max(...xs)
  const minY = Math.min(...ys)
  const maxY = Math.max(...ys)

  return {
    left: minX,
    right: maxX,
    top: minY,
    bottom: maxY,
    width: maxX - minX,
    height: maxY - minY,
  }
}

// 本地家具数据
const localItem = reactive<FurnitureItem>({
  ...props.item,
  x: props.item.x ?? 0,
  y: props.item.y ?? 0,
  width: props.item.width ?? 100,
  length: props.item.length ?? 100,
  rotate: props.item.rotate ?? 0,
  type: props.item.type as FurnitureType,
})

// 像素位置和边界框
const pixelPosition = reactive({ left: props.item.left ?? 0, top: props.item.top ?? 0 })

// 计算属性
const boundingBox = computed(() => calculateBoundingBox())

// 容器样式 - 基于边界框
const containerStyle = computed(
  () =>
    ({
      position: 'absolute',
      left: `${pixelPosition.left}px`,
      top: `${pixelPosition.top}px`,
      width: `${boundingBox.value.width}px`,
      height: `${boundingBox.value.height}px`,
      pointerEvents: props.disabled ? 'none' : 'auto',
      zIndex: 100,
      cursor: 'move',
    }) as CSSProperties
)

// 旋转容器样式 - 调整位置使左上角对齐
const rotatedContainerStyle = computed(
  () =>
    ({
      position: 'absolute',
      left: `${-boundingBox.value.left}px`,
      top: `${-boundingBox.value.top}px`,
      width: `${localItem.width}px`,
      height: `${localItem.length}px`,
      transform: `rotate(${localItem.rotate}deg)`,
      transformOrigin: '0 0',
    }) as CSSProperties
)

// 监听props变化
watch(
  () => props.item,
  (newItem) => {
    if (!newItem) return
    Object.assign(localItem, {
      ...newItem,
      x: newItem.x ?? 0,
      y: newItem.y ?? 0,
      width: newItem.width ?? 100,
      length: newItem.length ?? 100,
      rotate: newItem.rotate ?? 0,
    })
    updatePixelPosition()
  },
  { deep: true }
)

// 监听坐标和角度变化
watch(
  () => [props.coordinates, props.angle],
  () => {
    nextTick(() => {
      updatePixelPosition()
    })
  },
  { deep: true }
)

// 更新像素位置（从地理坐标转换）- 左上角基准
const updatePixelPosition = () => {
  const pixelPos = geoToPixel(localItem.x, localItem.y)

  // 直接使用左上角位置
  pixelPosition.left = pixelPos.x
  pixelPosition.top = pixelPos.y

  console.log('Update pixel position (top-left):', {
    geo: { x: localItem.x, y: localItem.y },
    pixelPosition: { ...pixelPosition },
    boundingBox: boundingBox.value,
    canvasCenter: { x: 200, y: 200 },
  })
}

const initPixelPosition = () => {
  const { x, y, width, length } = props.item
  // === 1️⃣ 将房间坐标转换为画布坐标 ===
  const itemConvert = convert_furniture_r2c(
    {
      x: x,
      y: y,
      width: width,
      height: length,
    },
    {
      x_radar: 250,
      y_radar: 250,
    }
  )

  // === 2️⃣ 再根据雷达朝向旋转 ===
  const rotatedRect = rotateRect(
    {
      left: itemConvert.left,
      top: itemConvert.top,
      width: width,
      height: length,
    },
    { x: 250, y: 250 },
    props.angle
  )

  // === 3️⃣ 应用最终位置 ===
  /* 90度和270度需要特殊处理，因为旋转后家具的中心位置会改变 */
  pixelPosition.left = props.angle === 90 ? rotatedRect.left + length / 2 : rotatedRect.left
  pixelPosition.top = props.angle === 270 ? rotatedRect.top - length / 2 : rotatedRect.top

  // 同步像素位置到 localItem（方便 emit）
  // localItem.left = rotatedRect.left
  // localItem.top = rotatedRect.top
  localItem.left = pixelPosition.left
  localItem.top = pixelPosition.top

  console.log('✅ Init pixel position (after convert & rotate):', {
    angle: props.angle,
    geo: { x: localItem.x, y: localItem.y },
    itemConvert,
    rotatedRect,
    final: { left: pixelPosition.left, top: pixelPosition.top },
  })
}

// 更新地理坐标（从像素位置转换）- 左上角基准
const updateGeoPosition = () => {
  // 直接转换左上角坐标
  const geoPos = pixelToGeo(pixelPosition.left, pixelPosition.top)
  localItem.x = geoPos.x
  localItem.y = geoPos.y

  const pixelPos = geoToPixel(geoPos.x, geoPos.y)
  localItem.left = pixelPos.x
  localItem.top = pixelPos.y

  console.log('Update geo position (top-left):', {
    pixel: { left: pixelPosition.left, top: pixelPosition.top },
    geo: { x: localItem.x, y: localItem.y },
  })
}

// 组件挂载
onMounted(() => {
  console.log('EditableFurniture mounted (top-left基准):', {
    item: props.item,
    coordinates: props.coordinates,
    angle: props.angle,
    canvasSize: props.canvasSize,
  })

  if (props.initialAtOrigin) {
    localItem.x = 0
    localItem.y = 0
  }

  nextTick(() => {
    initPixelPosition()
  })
})

// 拖拽家具
const startDrag = (e: MouseEvent) => {
  e.preventDefault()
  e.stopPropagation()

  const startX = e.clientX
  const startY = e.clientY
  const initLeft = pixelPosition.left
  const initTop = pixelPosition.top

  const onMove = (ev: MouseEvent) => {
    pixelPosition.left = initLeft + (ev.clientX - startX)
    pixelPosition.top = initTop + (ev.clientY - startY)
    updateGeoPosition()
    emit('update', { ...localItem })
  }

  const onUp = () => {
    window.removeEventListener('mousemove', onMove)
    window.removeEventListener('mouseup', onUp)
    document.body.style.userSelect = ''
    console.log('End drag furniture')
  }

  window.addEventListener('mousemove', onMove)
  window.addEventListener('mouseup', onUp)
  document.body.style.userSelect = 'none'
}
</script>

<style scoped lang="less">
.editable-furniture {
  position: absolute;
  pointer-events: auto;
  z-index: 100;
  cursor: move;

  &:hover {
    outline: 2px dashed #1890ff;
    outline-offset: 1px;
  }

  .furniture-rotated-container {
    position: absolute;

    .furniture-wrapper {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;

      :deep(*) {
        pointer-events: none;
      }
    }
  }

  .property-panel {
    position: absolute;
    top: 0;
    left: 0;
    background: #fff;
    border-radius: 8px;
    border: 1px solid #ddd;
    padding: 5px 12px 12px;
    font-size: 12px;
    z-index: 1000;
    width: 260px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    user-select: none;

    .panel-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      margin-bottom: 8px;
      position: relative;
      user-select: none;

      .capsule {
        cursor: move;
        position: absolute;
        top: -5px;
        left: 50%;
        transform: translateX(-50%);
        border-radius: 10px;
        width: 100px;
        height: 8px;
        background: rgba(230, 230, 230, 0.8);
        backdrop-filter: blur(10px);
      }

      &:hover {
        cursor: move;
      }

      .title {
        font-size: 13px;
      }

      .close {
        font-size: 22px;
        color: #999;
        cursor: pointer;
        transition: color 0.2s;

        &:hover {
          color: #333;
        }
      }
    }

    .panel-item {
      display: flex;
      align-items: center;
      margin-bottom: 6px;

      label {
        flex: 0 0 80px;
        color: #666;
      }

      :deep(.ant-input-number),
      :deep(.ant-select),
      :deep(.ant-input) {
        flex: 1;
        width: 100%;
      }

      :deep(.ant-space) {
        flex: 1;
        display: flex;
        gap: 4px;
      }

      :deep(.anticon) {
        font-size: 16px;
        color: #333;
        cursor: pointer;
        transition: color 0.2s;

        &:hover {
          color: #1890ff;
        }
      }
    }
  }
}
</style>
