<template>
  <div
    class="video-cell"
    :class="{ 'video-cell--empty': !slotData, 'video-cell--hover': isHovering }"
    @mouseenter="isHovering = true"
    @mouseleave="isHovering = false"
    @dblclick="handleDoubleClick"
  >
    <!-- 空格子状态 -->
    <div v-if="!slotData" class="video-cell__empty" @click="$emit('select-camera')">
      <el-icon :size="40"><Plus /></el-icon>
      <span>选择摄像头</span>
    </div>

    <!-- 有视频时 -->
    <template v-else>
      <!-- 视频播放器 -->
      <div ref="videoContainerRef" class="video-cell__player">
        <VideoPlayer
          ref="playerRef"
          :player-type="slotData.streamType === 'webrtc' ? 'webrtc' : 'cloudflare'"
          :video-id="slotData.streamType === 'cloudflare' ? slotData.streamUrl : undefined"
          :customer-domain="
            slotData.streamType === 'cloudflare' ? getCloudflareCustomerDomain(slotData.streamUrl) : undefined
          "
          :go2rtc-url="slotData.streamType === 'webrtc' ? getGo2rtcUrl(slotData.streamUrl) : undefined"
          :stream-name="slotData.streamType === 'webrtc' ? getStreamName(slotData.streamUrl) : undefined"
          :use-iframe="slotData.streamType === 'cloudflare'"
          :autoplay="true"
          :muted="true"
          :controls="false"
        />
      </div>

      <!-- 悬停时显示的控制层 -->
      <transition name="fade">
        <div v-show="isHovering" class="video-cell__overlay">
          <!-- 顶部信息栏 -->
          <div class="video-cell__header">
            <span class="video-cell__name">{{ slotData.cameraName }}</span>
            <div class="video-cell__actions">
              <el-button size="small" circle @click.stop="handleFullscreen">
                <el-icon><FullScreen /></el-icon>
              </el-button>
              <el-button size="small" circle type="danger" @click.stop="handleRemove">
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </transition>

      <!-- 右下角 PTZ 控制面板 -->
      <transition name="fade">
        <div v-show="isHovering" class="video-cell__ptz">
          <PtzOverlay
            :camera-id="slotData.cameraId"
            :vendor="slotData.vendor"
            :host="slotData.ptzHost"
            :username="slotData.ptzUsername"
            :password="slotData.ptzPassword"
            @ptz-action="handlePtzAction"
          />
        </div>
      </transition>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Plus, FullScreen, Close } from '@element-plus/icons-vue'
import VideoPlayer from '@/components/VideoPlayer.vue'
import PtzOverlay from './PtzOverlay.vue'
import type { GridSlot } from '@/composables/useMonitorStore'

interface Props {
  position: number
  slotData?: GridSlot
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'select-camera': []
  'update-slot': [slot: Partial<GridSlot> | null]
}>()

const isHovering = ref(false)
const playerRef = ref<InstanceType<typeof VideoPlayer>>()
const videoContainerRef = ref<HTMLElement>()

// 解析 Cloudflare 的 customer domain
function getCloudflareCustomerDomain(url?: string): string {
  if (!url) return ''
  // 如果是完整 URL，提取 domain
  if (url.includes('cloudflarestream.com')) {
    const match = url.match(/https?:\/\/([^/]+)/)
    return match ? match[1] : 'customer-pj89kn2ke2tcuh19.cloudflarestream.com'
  }
  // 如果只是 videoId，返回默认 domain
  return 'customer-pj89kn2ke2tcuh19.cloudflarestream.com'
}

// 解析 go2rtc URL
function getGo2rtcUrl(url?: string): string {
  if (!url) return 'http://localhost:1984'
  // 如果包含完整 URL
  if (url.includes('://')) {
    const match = url.match(/(https?:\/\/[^/]+)/)
    return match ? match[1] : 'http://localhost:1984'
  }
  return 'http://localhost:1984'
}

// 解析 stream name
function getStreamName(url?: string): string {
  if (!url) return ''
  // 如果是完整 URL，提取 stream name
  if (url.includes('src=')) {
    const match = url.match(/src=([^&]+)/)
    return match ? match[1] : url
  }
  return url
}

function handleDoubleClick() {
  if (props.slotData) {
    handleFullscreen()
  }
}

function handleFullscreen() {
  if (videoContainerRef.value) {
    videoContainerRef.value.requestFullscreen?.()
  }
}

function handleRemove() {
  emit('update-slot', null)
}

function handlePtzAction(action: string, params?: any) {
  console.log('PTZ action:', action, params)
  // PTZ 控制由 PtzOverlay 组件内部处理
}
</script>

<style lang="scss" scoped>
.video-cell {
  position: relative;
  background-color: #1a1a1a;
  border-radius: var(--radius-base);
  overflow: hidden;
  cursor: pointer;
  aspect-ratio: 16 / 9;

  &--empty {
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px dashed var(--border-color);
    background-color: var(--bg-hover);

    &:hover {
      border-color: var(--color-primary);
      background-color: var(--color-primary-light-9);
    }
  }

  &__empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    color: var(--text-secondary);
    width: 100%;
    height: 100%;
    justify-content: center;

    .el-icon {
      color: var(--text-placeholder);
    }

    span {
      font-size: 14px;
    }
  }

  &__player {
    width: 100%;
    height: 100%;
  }

  &__overlay {
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    background: linear-gradient(
      to bottom,
      rgba(0, 0, 0, 0.7) 0%,
      transparent 30%,
      transparent 70%,
      rgba(0, 0, 0, 0.7) 100%
    );
    pointer-events: none;

    > * {
      pointer-events: auto;
    }
  }

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
  }

  &__name {
    color: #fff;
    font-size: 14px;
    font-weight: 500;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
  }

  &__actions {
    display: flex;
    gap: 4px;
  }

  &__ptz {
    position: absolute;
    right: 8px;
    bottom: 8px;
    background: rgba(0, 0, 0, 0.75);
    border-radius: var(--radius-base);
    backdrop-filter: blur(4px);
    z-index: 10;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
