<template>
  <div class="photomap-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="photomap-loading">
      <div class="loading-spinner"></div>
      <p>正在加载照片位置信息...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="error && !loading" class="photomap-error">
      <div class="error-icon">⚠️</div>
      <p>{{ error }}</p>
      <button @click="retry" class="retry-btn">重试</button>
    </div>

    <!-- 地图容器 - 始终渲染，但在加载时隐藏 -->
    <div class="photomap-map-wrapper">
      <div
        ref="mapContainer"
        class="photomap-map"
        :class="{ 'photomap-hidden': loading }"
        :style="{ height: mapHeight }"
      ></div>
      
      <!-- 地图类型切换器 -->
      <div v-if="showStyleSwitcher && !loading" class="photomap-map-type-switcher">
        <div class="map-type-buttons">
          <button 
            v-for="(type, key) in mapTypes" 
            :key="key"
            :class="['map-type-btn', { 'active': currentMapType === key }]"
            @click="switchMapType(key)"
            :title="type.title"
          >
            <span class="map-type-icon">{{ type.icon }}</span>
            <span class="map-type-label">{{ type.label }}</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 照片列表（可选显示） -->
    <div v-if="showPhotoList && photos.length > 0" class="photomap-photos">
      <h4>照片列表</h4>
      <div class="photo-grid">
        <div
          v-for="(photo, index) in photos"
          :key="index"
          class="photo-thumbnail"
          :class="{ 'no-gps': !photo.hasGPS }"
          @click="handlePhotoClick(photo, index)"
        >
          <img
            :src="photo.src"
            :alt="photo.alt"
            loading="lazy"
          />
          <div class="photo-info">
            <span class="photo-alt">{{ photo.alt || `照片 ${index + 1}` }}</span>
            <span v-if="!photo.hasGPS" class="no-gps-label">无位置信息</span>
            <span v-else-if="photo.gps" class="gps-info">
              {{ photo.gps.latitude.toFixed(4) }}, {{ photo.gps.longitude.toFixed(4) }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { useExifReader, type PhotoData } from '../composables/useExifReader'
import { useMapLibre } from '../composables/useMapLibre'
import { usePhotoSwipe } from '../composables/usePhotoSwipe'

// 定义Props
interface ImageItem {
  src: string
  alt: string
}

interface Props {
  images?: ImageItem[]
  height?: string
  showPhotoList?: boolean
  mapStyle?: string
  defaultZoom?: number
  maxZoom?: number
  markerSize?: number
  enablePhotoSwipe?: boolean
  enableTerrain?: boolean
  enableSatelliteHybrid?: boolean
  terrainExaggeration?: number
  mapTilerApiKey?: string
  // 新增选项
  mapType?: 'satellite' | 'terrain' | 'simple' // 地图类型
  enableAtmosphere?: boolean // 是否启用大气效果（仅markdown设置）
  showStyleSwitcher?: boolean // 是否显示地图类型切换器
}

const props = withDefaults(defineProps<Props>(), {
  images: () => [],
  height: '400px',
  showPhotoList: false,
  mapStyle: '',
  defaultZoom: 10,
  maxZoom: 18,
  markerSize: 40,
  enablePhotoSwipe: true,
  enableTerrain: true,
  enableSatelliteHybrid: true,
  terrainExaggeration: 1,
  mapTilerApiKey: '', // 默认为空，从插件配置获取
  // 新增选项默认值
  mapType: 'satellite',
  enableAtmosphere: true,
  showStyleSwitcher: true
})

// 响应式数据
const mapContainer = ref<HTMLElement>()
const photos = ref<PhotoData[]>([])
const loading = ref(false)
const error = ref<string | null>(null)

// 地图类型切换器状态
const currentMapType = ref(props.mapType)

// 地图类型定义
const mapTypes = {
  satellite: {
    label: '卫星',
    icon: '🛰️',
    title: '卫星地图'
  },
  terrain: {
    label: '地形',
    icon: '🏔️', 
    title: '地形图'
  },
  simple: {
    label: '简约',
    icon: '🗺️',
    title: '简约地图'
  }
}

// 获取插件配置
const getPluginConfig = () => {
  // 尝试从全局配置获取 PhotoMap 插件配置
  if (typeof window !== 'undefined' && (window as any).__VUEPRESS_PHOTOMAP_CONFIG__) {
    return (window as any).__VUEPRESS_PHOTOMAP_CONFIG__
  }
  return {}
}

// 计算属性
const mapHeight = computed(() => props.height)

// 获取最终的 API key（优先使用 props，然后是全局配置）
const getApiKey = () => {
  if (props.mapTilerApiKey) {
    return props.mapTilerApiKey
  }
  const config = getPluginConfig()
  return config.mapTilerApiKey || 'get_your_own_OpIi9ZULNHzrESv6T2vL'
}

// 初始化composables
const { loadImagesExif } = useExifReader()
// 计算地图配置
const mapConfig = computed(() => ({
  style: props.mapStyle,
  defaultZoom: props.defaultZoom,
  maxZoom: props.maxZoom,
  markerSize: props.markerSize,
  enableTerrain: props.enableTerrain, // 由地形按钮控制
  enableSatelliteHybrid: currentMapType.value === 'satellite',
  enableAtmosphere: props.enableAtmosphere, // 仅通过markdown设置
  terrainExaggeration: props.terrainExaggeration,
  mapTilerApiKey: getApiKey(),
  mapType: currentMapType.value
}))

const { initMap, addPhotoMarkers, flyToPhoto, resizeMap, destroyMap, updateMapStyle } = useMapLibre(mapConfig.value)
const { openPhotoSwipe } = usePhotoSwipe({
  enablePhotoSwipe: props.enablePhotoSwipe
})

// 解析图片列表（从props获取）
const parseSlotImages = (): Array<{src: string, alt: string}> => {
  return props.images || []
}

// 处理照片点击事件
const handlePhotoClick = (photo: PhotoData, index: number) => {
  if (photo.hasGPS && photo.gps) {
    // 如果照片有GPS信息，先飞到该位置
    flyToPhoto(photo)
  }
  
  // 打开PhotoSwipe查看大图
  openPhotoSwipe(photos.value, index)
}

// 处理地图标记点击事件
const handleMarkerClick = (photo: PhotoData, index: number) => {
  openPhotoSwipe(photos.value, index)
}

// 地图类型切换处理函数
const switchMapType = async (mapType: string) => {
  console.log('PhotoMap: 切换地图类型到:', mapType)
  currentMapType.value = mapType as 'satellite' | 'terrain' | 'simple'
  if (updateMapStyle) {
    await updateMapStyle(mapConfig.value)
  }
}

// 重试加载
const retry = async () => {
  await loadPhotos()
}

// 加载照片数据
const loadPhotos = async () => {
  console.log('PhotoMap: 开始加载照片数据')
  loading.value = true
  error.value = null

  try {
    // 解析图片列表
    const imageList = parseSlotImages()
    console.log('PhotoMap: 解析到的图片列表:', imageList)
    
    if (imageList.length === 0) {
      error.value = '没有找到可处理的图片'
      console.log('PhotoMap: 没有找到图片')
      return
    }

    // 加载EXIF数据
    console.log('PhotoMap: 开始加载EXIF数据')
    const photoData = await loadImagesExif(imageList)
    console.log('PhotoMap: EXIF数据加载完成:', photoData)
    photos.value = photoData

    // 等待DOM元素完全渲染
    await nextTick()
    
    // 多次尝试等待mapContainer元素
    let retryCount = 0
    const maxRetries = 10
    
    while (!mapContainer.value && retryCount < maxRetries) {
      console.log(`PhotoMap: 等待mapContainer元素 (第${retryCount + 1}次尝试)`)
      await new Promise(resolve => setTimeout(resolve, 100))
      retryCount++
    }
    
    console.log('PhotoMap: 开始初始化地图', mapContainer.value)
    
    if (mapContainer.value) {
      await initMap(mapContainer.value)
      console.log('PhotoMap: 地图初始化完成')
      
      // 添加照片标记
      addPhotoMarkers(photoData, handleMarkerClick)
      console.log('PhotoMap: 照片标记添加完成')
    } else {
      console.error('PhotoMap: mapContainer.value 仍为 null，尝试了', retryCount, '次')
      error.value = '地图容器初始化失败'
    }

  } catch (err) {
    error.value = '加载失败，请稍后重试'
    console.error('PhotoMap加载错误:', err)
  } finally {
    loading.value = false
    console.log('PhotoMap: 加载流程结束，尝试初始化地图')
    
    // 加载完成后，mapContainer元素应该可用了，再次尝试初始化地图
    await nextTick()
    setTimeout(async () => {
      console.log('PhotoMap: 检查模板状态 - loading:', loading.value, 'error:', error.value, 'photos:', photos.value.length)
      console.log('PhotoMap: mapContainer.value:', mapContainer.value)
      
      if (mapContainer.value && photos.value.length > 0) {
        console.log('PhotoMap: 加载完成后初始化地图', mapContainer.value)
        try {
          await initMap(mapContainer.value)
          console.log('PhotoMap: 地图初始化完成')
          
          // 添加照片标记
          addPhotoMarkers(photos.value, handleMarkerClick)
          console.log('PhotoMap: 照片标记添加完成')
          
          // 清除错误状态
          error.value = null
        } catch (err) {
          console.error('PhotoMap: 加载完成后初始化地图失败:', err)
        }
      } else {
        console.log('PhotoMap: 加载完成后 mapContainer 仍不可用或无照片数据')
        console.log('PhotoMap: mapContainer:', !!mapContainer.value, 'photos length:', photos.value.length)
      }
    }, 100)
  }
}

// 响应式处理
const handleResize = () => {
  resizeMap()
}

// 生命周期
onMounted(async () => {
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
  
  // 等待DOM渲染完成后再加载照片数据
  await nextTick()
  setTimeout(async () => {
    await loadPhotos()
  }, 100) // 延迟100ms确保DOM完全渲染
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  destroyMap()
})

// 暴露给父组件的方法
defineExpose({
  retry,
  photos,
  flyToPhoto
})
</script>

<style scoped>
.photomap-container {
  width: 100%;
  margin: 1rem 0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.photomap-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  background: #f5f5f5;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.photomap-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  background: #fff5f5;
  color: #e74c3c;
  text-align: center;
  padding: 2rem;
}

.error-icon {
  font-size: 2rem;
  margin-bottom: 1rem;
}

.retry-btn {
  background: #3498db;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 1rem;
  transition: background 0.3s;
}

.retry-btn:hover {
  background: #2980b9;
}

.photomap-map {
  width: 100%;
  min-height: 300px;
  position: relative;
}

.photomap-hidden {
  display: none;
}

.photomap-photos {
  padding: 1rem;
  background: white;
  border-top: 1px solid #eee;
}

.photomap-photos h4 {
  margin: 0 0 1rem 0;
  font-size: 1.1rem;
  color: #333;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 1rem;
}

.photo-thumbnail {
  cursor: pointer;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s;
  background: white;
  border: 1px solid #eee;
}

.photo-thumbnail:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.photo-thumbnail.no-gps {
  opacity: 0.6;
}

.photo-thumbnail img {
  width: 100%;
  height: 80px;
  object-fit: cover;
  display: block;
}

.photo-info {
  padding: 0.5rem;
  font-size: 0.8rem;
}

.photo-alt {
  display: block;
  font-weight: 500;
  color: #333;
  margin-bottom: 0.25rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.gps-info {
  color: #666;
  font-family: monospace;
  font-size: 0.7rem;
}

.no-gps-label {
  color: #e74c3c;
  font-size: 0.7rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .photo-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 0.5rem;
  }
  
  .photomap-photos {
    padding: 0.5rem;
  }
  
  .photo-thumbnail img {
    height: 60px;
  }
}

/* 全局样式：地图标记 */
:global(.photo-marker) {
  transition: transform 0.2s;
}

:global(.photo-marker:hover) {
  transform: scale(1.1);
  z-index: 1000;
}
</style>
