<template>
  <el-dialog
    :model-value="visible"
    title="选择摄像头"
    width="500px"
    :close-on-click-modal="false"
    @update:model-value="$emit('update:visible', $event)"
  >
    <!-- 搜索框 -->
    <div class="selector-search">
      <el-input v-model="searchText" placeholder="搜索摄像头..." clearable :prefix-icon="Search" />
    </div>

    <!-- 摄像头列表 -->
    <div class="selector-list">
      <el-scrollbar height="300px">
        <div
          v-for="camera in filteredCameras"
          :key="camera.id"
          class="selector-item"
          :class="{ 'selector-item--selected': selectedCamera?.id === camera.id }"
          @click="selectedCamera = camera"
        >
          <div class="selector-item__radio">
            <el-icon v-if="selectedCamera?.id === camera.id" color="var(--color-primary)">
              <CircleCheckFilled />
            </el-icon>
            <el-icon v-else color="var(--text-placeholder)">
              <CircleCheck />
            </el-icon>
          </div>
          <div class="selector-item__info">
            <div class="selector-item__name">{{ camera.name }}</div>
            <div class="selector-item__meta">
              <el-tag size="small" :type="camera.streamType === 'webrtc' ? 'success' : 'primary'">
                {{ camera.streamType === 'webrtc' ? 'WebRTC' : 'Cloudflare' }}
              </el-tag>
              <el-tag size="small" :type="camera.online ? 'success' : 'danger'">
                {{ camera.online ? '在线' : '离线' }}
              </el-tag>
            </div>
          </div>
        </div>

        <div v-if="filteredCameras.length === 0" class="selector-empty">
          <el-empty description="没有找到摄像头" :image-size="80" />
        </div>
      </el-scrollbar>
    </div>

    <template #footer>
      <el-button @click="$emit('update:visible', false)">取消</el-button>
      <el-button type="primary" :disabled="!selectedCamera" @click="handleConfirm">确定选择</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Search, CircleCheck, CircleCheckFilled } from '@element-plus/icons-vue'
import { adminListCameras } from '@/api/camera'
import type { CameraVendor } from '@/composables/useMonitorStore'

interface CameraItem {
  id: string
  name: string
  streamType: 'webrtc' | 'cloudflare'
  streamUrl: string
  online: boolean
  // PTZ 配置
  vendor?: CameraVendor
  ptzHost?: string
  ptzUsername?: string
  ptzPassword?: string
}

interface Props {
  visible: boolean
  currentPosition?: number
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
  select: [
    camera: {
      id: string
      name: string
      streamType: 'webrtc' | 'cloudflare'
      streamUrl: string
      vendor?: CameraVendor
      ptzHost?: string
      ptzUsername?: string
      ptzPassword?: string
    }
  ]
}>()

const searchText = ref('')
const cameras = ref<CameraItem[]>([])
const selectedCamera = ref<CameraItem | null>(null)
const loading = ref(false)

const filteredCameras = computed(() => {
  if (!searchText.value) return cameras.value
  const keyword = searchText.value.toLowerCase()
  return cameras.value.filter((camera) => camera.name.toLowerCase().includes(keyword))
})

// 预设的 WebRTC 摄像头流列表 (包含 PTZ 配置，统一使用 viewer 账号)
const presetWebrtcCameras: CameraItem[] = [
  // ANPVIZ - 带 PTZ 配置
  {
    id: 'anpviz',
    name: 'ANPVIZ 主码流',
    streamType: 'webrtc',
    streamUrl: 'anpviz',
    online: true,
    vendor: 'ANPVIZ',
    ptzHost: '192.168.0.96',
    ptzUsername: 'viewer',
    ptzPassword: 'Wxc767718929'
  },
  {
    id: 'anpviz_raw',
    name: 'ANPVIZ 原始流',
    streamType: 'webrtc',
    streamUrl: 'anpviz_raw',
    online: true,
    vendor: 'ANPVIZ',
    ptzHost: '192.168.0.96',
    ptzUsername: 'viewer',
    ptzPassword: 'Wxc767718929'
  },
  {
    id: 'anpviz_sub',
    name: 'ANPVIZ 子码流',
    streamType: 'webrtc',
    streamUrl: 'anpviz_sub',
    online: true,
    vendor: 'ANPVIZ',
    ptzHost: '192.168.0.96',
    ptzUsername: 'viewer',
    ptzPassword: 'Wxc767718929'
  },
  // CT-IP500
  {
    id: 'ct-ip500',
    name: 'CT-IP500 主码流',
    streamType: 'webrtc',
    streamUrl: 'ct-ip500',
    online: true,
    vendor: 'CT-IP500'
  },
  {
    id: 'ct-ip500_sub',
    name: 'CT-IP500 子码流',
    streamType: 'webrtc',
    streamUrl: 'ct-ip500_sub',
    online: true,
    vendor: 'CT-IP500'
  },
  // HIKVISION 海康威视 - 带 PTZ 配置
  {
    id: 'hikvision',
    name: '海康威视 主码流',
    streamType: 'webrtc',
    streamUrl: 'hikvision',
    online: true,
    vendor: 'HIKVISION',
    ptzHost: '192.168.0.64',
    ptzUsername: 'viewer',
    ptzPassword: 'Wxc767718929'
  },
  {
    id: 'hikvision_sub',
    name: '海康威视 子码流',
    streamType: 'webrtc',
    streamUrl: 'hikvision_sub',
    online: true,
    vendor: 'HIKVISION',
    ptzHost: '192.168.0.64',
    ptzUsername: 'viewer',
    ptzPassword: 'Wxc767718929'
  },
  // SVBC
  { id: 'svbc', name: 'SVBC 主码流', streamType: 'webrtc', streamUrl: 'svbc', online: true, vendor: 'SVBC' },
  { id: 'svbc_raw', name: 'SVBC 原始流', streamType: 'webrtc', streamUrl: 'svbc_raw', online: true, vendor: 'SVBC' },
  { id: 'svbc_sub', name: 'SVBC 子码流', streamType: 'webrtc', streamUrl: 'svbc_sub', online: true, vendor: 'SVBC' }
]

// 加载摄像头列表
async function loadCameras() {
  loading.value = true
  try {
    const res = await adminListCameras()
    if (res.success && res.data.list && res.data.list.length > 0) {
      // 从 API 加载的摄像头
      const apiCameras = res.data.list.map((item) => ({
        id: String(item.id),
        name: item.name || `摄像头 ${item.id}`,
        streamType: (item as any).streamType || 'webrtc',
        streamUrl: (item as any).streamUrl || (item as any).rtspUrl || '',
        online: (item as any).online !== false
      })) as CameraItem[]
      // 合并 API 摄像头和预设 WebRTC 摄像头
      cameras.value = [...presetWebrtcCameras, ...apiCameras]
    } else {
      // 使用预设 WebRTC 摄像头
      cameras.value = presetWebrtcCameras
    }
  } catch (error) {
    console.error('Failed to load cameras:', error)
    // 使用预设 WebRTC 摄像头
    cameras.value = presetWebrtcCameras
  } finally {
    loading.value = false
  }
}

function handleConfirm() {
  if (!selectedCamera.value) return

  emit('select', {
    id: selectedCamera.value.id,
    name: selectedCamera.value.name,
    streamType: selectedCamera.value.streamType,
    streamUrl: selectedCamera.value.streamUrl,
    vendor: selectedCamera.value.vendor,
    ptzHost: selectedCamera.value.ptzHost,
    ptzUsername: selectedCamera.value.ptzUsername,
    ptzPassword: selectedCamera.value.ptzPassword
  })
}

// 监听 visible 变化，打开时加载数据
watch(
  () => props.visible,
  (val) => {
    if (val) {
      selectedCamera.value = null
      searchText.value = ''
      loadCameras()
    }
  }
)
</script>

<style lang="scss" scoped>
.selector-search {
  margin-bottom: 16px;
}

.selector-list {
  border: 1px solid var(--border-color);
  border-radius: var(--radius-base);
}

.selector-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  border-bottom: 1px solid var(--border-color-light);

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background-color: var(--bg-hover);
  }

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

  &__radio {
    font-size: 20px;
  }

  &__info {
    flex: 1;
  }

  &__name {
    font-size: 14px;
    font-weight: 500;
    color: var(--text-primary);
    margin-bottom: 4px;
  }

  &__meta {
    display: flex;
    gap: 8px;
  }
}

.selector-empty {
  padding: 40px 0;
}
</style>
