Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

81.8 KB
Raw Blame
<script lang="ts" setup>
import { photoLibraryPresentation } from '../../utils/photoLibraryPresentation'
import { useUploadQueue } from '../../composables/useUploadQueue'
const consoleApi = useConsoleApi()

import type { FormSubmitEvent, TableColumn, DropdownMenuItem } from '@nuxt/ui'
import type { UploadPreparationResponse } from '@chronoframe/contracts/upload'
import type { Album, Photo } from '@chronoframe/contracts/resources'
import {
  MAX_ALBUM_PHOTOS_PER_REQUEST,
  type AddPhotosToAlbumResult,
} from '@chronoframe/gallery/shared/utils/album'
import { QueueWarningCode } from '@chronoframe/gallery/shared/utils/queue-warning'
import {
  UploadQueueStatus,
  UploadTransportStatus,
  isAbortableUploadStatus,
  isClearableUploadStatus,
  isInFlightTransportStatus,
} from '@chronoframe/gallery/shared/utils/upload-status'
import { h, resolveComponent } from 'vue'
import { Icon } from '#components'

const UCheckbox = resolveComponent('UCheckbox')
const route = useRoute()
const router = useRouter()

// 列名显示映射
const columnNameMap = computed<Record<string, string>>(() => ({
  thumbnailUrl: $t('dashboard.photos.table.columns.thumbnail.title'),
  id: $t('dashboard.photos.table.columns.id'),
  title: $t('dashboard.photos.table.columns.title'),
  tags: $t('dashboard.photos.table.columns.tags'),
  rating: $t('dashboard.photos.table.columns.rating'),
  isLivePhoto: $t('dashboard.photos.table.columns.isLivePhoto'),
  location: $t('dashboard.photos.table.columns.location'),
  dateTaken: $t('dashboard.photos.table.columns.dateTaken'),
  lastModified: $t('dashboard.photos.table.columns.lastModified'),
  fileSize: $t('dashboard.photos.table.columns.fileSize'),
  colorSpace: $t('dashboard.photos.table.columns.colorSpace'),
  reactions: $t('dashboard.photos.table.columns.reactions'),
  actions: $t('dashboard.photos.table.columns.actions'),
}))

definePageMeta({
  layout: 'dashboard',
})

useHead({
  title: () => $t('title.photos'),
})

const maxFileSizeMB = computed(() => {
  const val = getSetting('system:upload.maxFileSize')
  return typeof val === 'number' ? val : 256
})

const systemUploadEraseLocationDefault = computed(() => {
  const val = getSetting('privacy:upload.autoEraseLocation')
  return typeof val === 'boolean' ? val : false
})

const { photos, status, refresh } = usePhotos()
const { filteredPhotos, selectedCounts, hasActiveFilters } = usePhotoFilters()
const { currentSortIcon, currentSortOption } = usePhotoSort()

const totalSelectedFilters = computed(() => {
  return Object.values(selectedCounts.value).reduce(
    (total, count) => total + count,
    0,
  )
})

const reverseGeocodeLoading = ref<Record<string, boolean>>({})
const eraseLocationLoading = ref<Record<string, boolean>>({})

const setReverseGeocodeLoading = (photoId: string, loading: boolean) => {
  if (loading) {
    reverseGeocodeLoading.value = {
      ...reverseGeocodeLoading.value,
      [photoId]: true,
    }
  } else {
    const { [photoId]: _removed, ...rest } = reverseGeocodeLoading.value
    reverseGeocodeLoading.value = rest
  }
}

const setEraseLocationLoading = (photoId: string, loading: boolean) => {
  if (loading) {
    eraseLocationLoading.value = {
      ...eraseLocationLoading.value,
      [photoId]: true,
    }
  } else {
    const { [photoId]: _removed, ...rest } = eraseLocationLoading.value
    eraseLocationLoading.value = rest
  }
}

// 表态数据
const reactionsData = ref<Record<string, Record<string, number>>>({})
const reactionsLoading = ref(false)

// 获取表态数据
const fetchReactions = async (photoIds: string[]) => {
  if (photoIds.length === 0) return

  reactionsLoading.value = true
  try {
    const data = await consoleApi('/api/photos/reactions', {
      query: { ids: photoIds },
    })
    reactionsData.value = data as Record<string, Record<string, number>>
  } catch (error) {
    console.error('获取表态数据失败:', error)
  } finally {
    reactionsLoading.value = false
  }
}

const uploadQueue = useUploadQueue()
const { uploadingFiles } = uploadQueue

interface EditFormState {
  title: string
  description: string
  tags: string[]
  rating: number | null
}

const editingPhoto = ref<Photo | null>(null)
const isEditModalOpen = ref(false)
const isSavingMetadata = ref(false)

const editFormState = reactive<EditFormState>({
  title: '',
  description: '',
  tags: [],
  rating: null,
})

const originalMetadata = ref<{
  title: string
  description: string
  tags: string[]
  location: { latitude: number; longitude: number } | null
  rating: number | null
}>({
  title: '',
  description: '',
  tags: [],
  location: null,
  rating: null,
})

const locationSelection = ref<{ latitude: number; longitude: number } | null>(
  null,
)
const locationTouched = ref(false)

const normalizeTagList = (tags: string[]): string[] => {
  const seen = new Set<string>()
  const normalized: string[] = []
  for (const tag of tags) {
    const trimmed = tag.trim()
    if (!trimmed) continue
    const key = trimmed.toLowerCase()
    if (seen.has(key)) continue
    seen.add(key)
    normalized.push(trimmed)
  }
  return normalized
}

const areTagListsEqual = (a: string[], b: string[]): boolean => {
  if (a.length !== b.length) {
    return false
  }
  return a.every((tag, index) => tag === b[index])
}

const tagsModel = computed<string[]>({
  get: () => editFormState.tags,
  set: (value) => {
    const next = Array.isArray(value) ? normalizeTagList(value) : []
    if (!areTagListsEqual(editFormState.tags, next)) {
      editFormState.tags = next
    }
  },
})

const normalizedTitle = computed(() => editFormState.title.trim())
const normalizedDescription = computed(() => editFormState.description.trim())

const tagsChanged = computed(() => {
  const current = editFormState.tags
  const original = originalMetadata.value.tags
  return !areTagListsEqual(current, original)
})

const titleChanged = computed(
  () => normalizedTitle.value !== originalMetadata.value.title,
)
const descriptionChanged = computed(
  () => normalizedDescription.value !== originalMetadata.value.description,
)

const locationChanged = computed(() => {
  if (!locationTouched.value) {
    return false
  }
  const current = locationSelection.value
  const original = originalMetadata.value.location
  if (!current && !original) {
    return false
  }
  if (!current || !original) {
    return true
  }
  return (
    Math.abs(current.latitude - original.latitude) > 1e-6 ||
    Math.abs(current.longitude - original.longitude) > 1e-6
  )
})

const ratingChanged = computed(
  () => editFormState.rating !== originalMetadata.value.rating,
)

const isMetadataDirty = computed(
  () =>
    titleChanged.value ||
    descriptionChanged.value ||
    tagsChanged.value ||
    locationChanged.value ||
    ratingChanged.value,
)

const formattedCoordinates = computed(() => {
  if (!locationSelection.value) {
    return null
  }
  return {
    latitude: locationSelection.value.latitude.toFixed(6),
    longitude: locationSelection.value.longitude.toFixed(6),
  }
})

const uploadImage = async (
  file: File,
  existingFileId?: string,
  eraseLocationOnUpload?: boolean,
  albumId?: number,
  signal?: AbortSignal,
) => {
  const fileName = file.name
  const fileId = existingFileId || `${Date.now()}-${fileName}`
  const isVideoFile =
    file.type === 'video/quicktime' ||
    file.type === 'video/mp4' ||
    fileName.toLowerCase().endsWith('.mov')

  const uploadManager = useUpload({
    timeout: 60 * 1000, // 单个分片一分钟超时,避免请求长时间卡住
  })
  const abort = () => uploadManager.abortUpload()
  signal?.addEventListener('abort', abort)

  // 获取或创建 uploadingFile
  let uploadingFile = uploadingFiles.value.get(fileId)
  if (!uploadingFile) {
    uploadingFile = {
      file,
      fileName,
      fileId,
      status: UploadQueueStatus.Preparing,
      canAbort: false,
      abortUpload: () => uploadManager.abortUpload(),
    }
    uploadingFiles.value.set(fileId, uploadingFile)
  } else {
    // 更新现有条目的状态和回调
    uploadingFile.status = UploadQueueStatus.Preparing
    uploadingFile.canAbort = false
    uploadingFile.warning = undefined
    uploadingFiles.value = new Map(uploadingFiles.value)
  }

  try {
    signal?.throwIfAborted()
    // 第一步:获取预签名 URL
    uploadingFile.status = UploadQueueStatus.Preparing
    const signedUrlResponse = await consoleApi<UploadPreparationResponse>(
      '/api/photos',
      {
        method: 'POST',
        body: {
          fileName: file.name,
          contentType: file.type,
          fileSize: file.size,
          chunked: true,
        },
      },
    )

    uploadingFile.signedUrlResponse = signedUrlResponse
    signal?.throwIfAborted()

    // 检查是否为跳过模式(重复文件)
    if (signedUrlResponse.skipped) {
      uploadingFile.progress = 100
      uploadingFile.canAbort = false
      if (albumId !== undefined && !isVideoFile) {
        try {
          const existingPhotoId = signedUrlResponse.existingPhoto?.id
          if (!existingPhotoId) throw new Error('Skipped photo has no ID')
          const result = await consoleApi<AddPhotosToAlbumResult>(
            `/api/albums/${albumId}/photos`,
            {
              method: 'POST',
              body: { photoIds: [existingPhotoId] },
            },
          )
          const added = result.added > 0
          uploadingFile.status = UploadQueueStatus.Skipped
          uploadingFile.error = $t(
            added
              ? 'upload.duplicate.skip.addedToAlbum'
              : 'upload.duplicate.skip.alreadyInAlbum',
          )
          toast.add({
            title: added
              ? $t('dashboard.photos.addToAlbum.success')
              : $t('upload.duplicate.skip.title'),
            description: uploadingFile.error,
            color: added ? 'success' : 'neutral',
          })
        } catch (error) {
          console.error('Failed to add skipped photo to album:', error)
          uploadingFile.status = UploadQueueStatus.Error
          uploadingFile.error = $t('upload.duplicate.skip.albumAddFailed')
          toast.add({
            title: $t('dashboard.photos.addToAlbum.error'),
            description: uploadingFile.error,
            color: 'error',
          })
        }
      } else {
        uploadingFile.status = UploadQueueStatus.Skipped
        uploadingFile.error =
          signedUrlResponse.message ||
          $t('upload.duplicate.skip.message', { fileName })
        toast.add({
          title: signedUrlResponse.title || $t('upload.duplicate.skip.title'),
          description: uploadingFile.error,
          color: 'warning',
        })
      }

      uploadingFiles.value = new Map(uploadingFiles.value)
      return
    }

    if (signedUrlResponse.warningInfo) {
      uploadingFile.error = undefined
      uploadingFile.warning =
        signedUrlResponse.warningInfo.warning ||
        signedUrlResponse.warningInfo.message

      uploadingFiles.value = new Map(uploadingFiles.value)
    }

    uploadingFile.status = UploadQueueStatus.Uploading
    uploadingFile.canAbort = true
    uploadingFile.progress = 0
    uploadingFiles.value = new Map(uploadingFiles.value)

    // 第二步:使用 composable 上传文件到存储
    await uploadManager.uploadFile(
      file,
      signedUrlResponse.upload || signedUrlResponse.signedUrl,
      {
        onProgress: (progress: UploadProgress) => {
          uploadingFile.progress = progress.percentage
          uploadingFile.uploadProgress = {
            loaded: progress.loaded,
            total: progress.total,
            percentage: progress.percentage,
            speed: progress.speed,
            timeRemaining: progress.timeRemaining,
            speedText: progress.speed ? `${formatBytes(progress.speed)}/s` : '',
            timeRemainingText:
              progress.timeRemaining !== undefined
                ? uploadManager.formatTime(progress.timeRemaining)
                : '',
          }
          uploadingFiles.value = new Map(uploadingFiles.value)
        },
        onStatusChange: (status: UploadTransportStatus) => {
          uploadingFile.canAbort = isInFlightTransportStatus(status)
          if (status === UploadTransportStatus.Finalizing)
            uploadingFile.status = UploadQueueStatus.Finalizing
          uploadingFiles.value = new Map(uploadingFiles.value)
        },
        onSuccess: async (_xhr: XMLHttpRequest) => {
          if (signal?.aborted) return
          // 第三步:上传完成,提交到队列任务
          uploadingFile.status = UploadQueueStatus.Processing
          uploadingFile.progress = 100
          uploadingFile.canAbort = false
          uploadingFile.stage = null // 重置 stage,准备显示任务状态
          uploadingFiles.value = new Map(uploadingFiles.value)

          try {
            // 检查是否为MOV视频文件(通过MIME类型或文件扩展名)
            const enqueueTask = (targetAlbumId?: number) =>
              consoleApi('/api/queue/add-task', {
                method: 'POST',
                body: {
                  payload: {
                    type: isVideoFile ? 'live-photo-video' : 'photo',
                    storageKey: signedUrlResponse.fileKey,
                    ...(isVideoFile
                      ? {}
                      : {
                          eraseLocation:
                            eraseLocationOnUpload ??
                            systemUploadEraseLocationDefault.value,
                          ...(targetAlbumId !== undefined
                            ? { albumId: targetAlbumId }
                            : {}),
                        }),
                  },
                  priority: isVideoFile ? 0 : 1, // Live Photo 视频优先级更低,确保图片优先处理
                  maxAttempts: 3,
                },
              })

            let resp
            let albumAssignmentUnavailable = false
            try {
              resp = await enqueueTask(albumId)
            } catch (error: any) {
              const statusCode = error.statusCode ?? error.response?.status
              if (isVideoFile || albumId === undefined || statusCode !== 404) {
                throw error
              }

              // The image is already stored, so still process it if its album was deleted.
              resp = await enqueueTask()
              albumAssignmentUnavailable = true
            }

            if (resp.success) {
              if (albumAssignmentUnavailable) {
                const warning = $t('common.albumAssignment.missing')
                uploadingFile.warning = uploadingFile.warning
                  ? `${uploadingFile.warning} ${warning}`
                  : warning
              }
              uploadingFile.taskId = resp.taskId
              uploadingFile.status = UploadQueueStatus.Processing
              uploadingFiles.value = new Map(uploadingFiles.value)

              // 开始任务状态检查
              if (!signal?.aborted) startTaskStatusCheck(resp.taskId, fileId)
            } else {
              uploadingFile.status = UploadQueueStatus.Error
              uploadingFile.error = $t(
                'dashboard.photos.messages.taskSubmitFailed',
              )
              uploadingFiles.value = new Map(uploadingFiles.value)
            }
          } catch (processError: any) {
            uploadingFile.status = UploadQueueStatus.Error
            uploadingFile.error = `${$t('dashboard.photos.messages.taskSubmitFailed')}: ${processError.message}`
            uploadingFile.canAbort = false
            uploadingFiles.value = new Map(uploadingFiles.value)
          }
        },
        onError: (error: string) => {
          const isConflict = /\b409\b|Conflict/i.test(error)

          if (isConflict) {
            uploadingFile.status = UploadQueueStatus.Blocked
            uploadingFile.error = $t('upload.duplicate.block.message', {
              fileName,
            })
          } else {
            uploadingFile.status = UploadQueueStatus.Error
            uploadingFile.error = error
          }

          uploadingFile.canAbort = false
          uploadingFiles.value = new Map(uploadingFiles.value)
        },
      },
    )
  } catch (error: any) {
    uploadingFile.status = UploadQueueStatus.Error
    uploadingFile.canAbort = false

    // 处理重复文件阻止模式的错误
    const isDuplicateConflict =
      (error.statusCode === 409 ||
        error.status === 409 ||
        error.response?.status === 409) &&
      (error.data?.duplicate || /Conflict|409/i.test(error.message || ''))

    if (isDuplicateConflict) {
      uploadingFile.status = UploadQueueStatus.Blocked
      uploadingFile.error =
        error.data.message || $t('upload.duplicate.block.message', { fileName })

      toast.add({
        title: error.data?.title || $t('upload.duplicate.block.title'),
        description:
          error.data?.message ||
          $t('upload.duplicate.block.message', { fileName }),
        color: 'error',
      })
    } else {
      // 其他错误
      uploadingFile.error =
        error.message || $t('dashboard.photos.messages.uploadFailed')
    }

    uploadingFiles.value = new Map(uploadingFiles.value)

    // 提供更详细的错误信息
    if (error.response?.status === 401) {
      uploadingFile.error = $t('dashboard.photos.errors.uploadUnauthorized')
    } else if (error.message?.includes('CORS')) {
      uploadingFile.error = $t('dashboard.photos.errors.uploadCorsError')
    } else if (
      error.message?.includes('NetworkError') ||
      error.name === 'TypeError'
    ) {
      uploadingFile.error = $t('dashboard.photos.errors.uploadNetworkError')
    } else if (error.message?.includes('上传到存储失败')) {
      uploadingFile.error = $t('dashboard.photos.messages.uploadFailed')
    }

    uploadingFiles.value = new Map(uploadingFiles.value)
  } finally {
    signal?.removeEventListener('abort', abort)
  }
}

const toast = useToast()
const selectedFiles = ref<File[]>([])
const isUploadSlideoverOpen = ref(false)
const uploadEraseLocationEnabled = ref(systemUploadEraseLocationDefault.value)
type UploadAlbumOption = Pick<Album, 'id' | 'title' | 'isHidden'> & {
  photoCount: number
  hasPassword: boolean
}

const uploadAlbums = ref<UploadAlbumOption[]>([])
const selectedUploadAlbumId = ref(0)
const requestedUploadAlbumId = ref<number | null>(null)
const isLoadingUploadAlbums = ref(false)
const uploadAlbumsLoadFailed = ref(false)
let uploadAlbumsRequestId = 0

const selectedUploadAlbumUnavailable = computed(
  () =>
    selectedUploadAlbumId.value !== 0 &&
    !isLoadingUploadAlbums.value &&
    !uploadAlbumsLoadFailed.value &&
    !uploadAlbums.value.some(
      (album) => album.id === selectedUploadAlbumId.value,
    ),
)
const canUseSelectedUploadAlbum = computed(
  () =>
    selectedUploadAlbumId.value === 0 ||
    (!isLoadingUploadAlbums.value &&
      !uploadAlbumsLoadFailed.value &&
      !selectedUploadAlbumUnavailable.value),
)

const uploadAlbumItems = computed(() => [
  {
    label: $t('dashboard.photos.slideover.album.none'),
    icon: 'tabler:album-off',
    value: 0,
  },
  ...uploadAlbums.value.map((album) => ({
    label: album.title,
    description: [
      $t('plural.photo', { count: album.photoCount }, album.photoCount),
      album.isHidden
        ? $t('dashboard.photos.slideover.album.hidden')
        : undefined,
      album.hasPassword
        ? $t('dashboard.photos.slideover.album.passwordProtected')
        : undefined,
    ]
      .filter(Boolean)
      .join(' · '),
    icon: album.hasPassword
      ? 'tabler:lock'
      : album.isHidden
        ? 'tabler:eye-off'
        : 'tabler:album',
    value: album.id,
  })),
])
const bulkAlbumItems = computed(() => uploadAlbumItems.value.slice(1))

const loadUploadAlbums = async () => {
  const requestId = ++uploadAlbumsRequestId
  isLoadingUploadAlbums.value = true
  uploadAlbumsLoadFailed.value = false
  try {
    const albums = await consoleApi('/api/albums/upload-options')
    if (requestId === uploadAlbumsRequestId) uploadAlbums.value = albums
  } catch (error) {
    if (requestId !== uploadAlbumsRequestId) return
    console.error('Failed to load upload albums:', error)
    uploadAlbums.value = []
    uploadAlbumsLoadFailed.value = true
  } finally {
    if (requestId === uploadAlbumsRequestId) {
      isLoadingUploadAlbums.value = false
    }
  }
}

const clearSelectedFiles = () => {
  selectedFiles.value = []
}

watch(isUploadSlideoverOpen, (open) => {
  if (!open) {
    clearSelectedFiles()
    uploadEraseLocationEnabled.value = systemUploadEraseLocationDefault.value
    selectedUploadAlbumId.value = 0
    requestedUploadAlbumId.value = null
  }
})

const openUploadSlideover = (albumId?: number) => {
  uploadEraseLocationEnabled.value = systemUploadEraseLocationDefault.value
  requestedUploadAlbumId.value = albumId ?? null
  selectedUploadAlbumId.value = albumId ?? 0
  isUploadSlideoverOpen.value = true
  void loadUploadAlbums()
}

const openRequestedAlbumUpload = () => {
  const value = route.query.uploadAlbumId
  if (typeof value !== 'string') return
  const albumId = Number(value)
  if (/^[1-9]\d*$/.test(value) && Number.isSafeInteger(albumId)) {
    openUploadSlideover(albumId)
  }
  void router.replace({ query: { ...route.query, uploadAlbumId: undefined } })
}

onMounted(openRequestedAlbumUpload)
watch(() => route.query.uploadAlbumId, openRequestedAlbumUpload)

watch(isEditModalOpen, (open) => {
  if (!open) {
    editingPhoto.value = null
    editFormState.title = ''
    editFormState.description = ''
    editFormState.tags = []
    editFormState.rating = null
    originalMetadata.value = {
      title: '',
      description: '',
      tags: [],
      location: null,
      rating: null,
    }
    locationSelection.value = null
    locationTouched.value = false
  }
})

// 表格多选状态
const rowSelection = ref<Record<string, boolean>>({})
const layout = useLocalStorage<'list' | 'masonry'>(
  'dashboard-photos-layout',
  'masonry',
  { initOnMounted: true },
)
const table: any = useTemplateRef('table')
const getPhotoRowId = (photo: Photo) => photo.id
const rowRangeSelection = useShiftRangeSelection()
const isAddToAlbumOpen = ref(false)
const selectedBulkPhotoIds = ref<string[]>([])
const selectedBulkAlbumId = ref<number | null>(null)
const isAddingToAlbum = ref(false)

const selectedBulkPhotoCountLabel = computed(() =>
  $t(
    'plural.selectedPhoto',
    { count: selectedBulkPhotoIds.value.length },
    selectedBulkPhotoIds.value.length,
  ),
)

const formatAddToAlbumResult = (
  added: number,
  alreadyPresent: number,
  missing: number,
) => {
  const result = $t('dashboard.photos.addToAlbum.result', {
    added,
    alreadyPresent,
  })
  return missing > 0
    ? `${result} · ${$t('dashboard.photos.addToAlbum.missing', { count: missing })}`
    : result
}

const openAddToAlbum = () => {
  if (isAddingToAlbum.value) return

  const selectedRows = selectedPhotoRows.value
  selectedBulkPhotoIds.value = selectedRows.map(
    (row: { original: Photo }) => row.original.id,
  )
  if (selectedBulkPhotoIds.value.length === 0) return
  selectedBulkAlbumId.value = null
  isAddToAlbumOpen.value = true
  void loadUploadAlbums()
}

const addSelectedPhotosToAlbum = async () => {
  const albumId = selectedBulkAlbumId.value
  if (
    isAddingToAlbum.value ||
    albumId === null ||
    !uploadAlbums.value.some((album) => album.id === albumId)
  ) {
    return
  }

  isAddingToAlbum.value = true
  let added = 0
  let alreadyPresent = 0
  let missing = 0
  let completedRequests = 0
  try {
    const photoIds = [...selectedBulkPhotoIds.value]
    for (
      let index = 0;
      index < photoIds.length;
      index += MAX_ALBUM_PHOTOS_PER_REQUEST
    ) {
      const result = await consoleApi<AddPhotosToAlbumResult>(
        `/api/albums/${albumId}/photos`,
        {
          method: 'POST',
          body: {
            photoIds: photoIds.slice(
              index,
              index + MAX_ALBUM_PHOTOS_PER_REQUEST,
            ),
          },
        },
      )
      added += result.added
      alreadyPresent += result.alreadyPresent
      missing += result.missing
      completedRequests++
    }
    const noChanges = added === 0 && missing === 0
    toast.add({
      title: $t(
        added > 0
          ? 'dashboard.photos.addToAlbum.success'
          : 'dashboard.photos.addToAlbum.noChanges',
      ),
      description: noChanges
        ? $t('dashboard.photos.addToAlbum.allAlreadyPresent')
        : formatAddToAlbumResult(added, alreadyPresent, missing),
      color: added > 0 ? 'success' : 'neutral',
    })
    rowSelection.value = {}
    isAddToAlbumOpen.value = false
  } catch (error) {
    console.error('Failed to add photos to album:', error)
    toast.add({
      title: $t('dashboard.photos.addToAlbum.error'),
      description:
        completedRequests > 0
          ? $t('dashboard.photos.addToAlbum.partialError', {
              processed: formatAddToAlbumResult(added, alreadyPresent, missing),
            })
          : undefined,
      color: 'error',
    })
  } finally {
    isAddingToAlbum.value = false
  }
}

watch(isAddToAlbumOpen, (open) => {
  if (!open) {
    selectedBulkPhotoIds.value = []
    selectedBulkAlbumId.value = null
  }
})

watch(
  () => Object.keys(rowSelection.value).length === 0,
  (isEmpty) => {
    if (isEmpty) rowRangeSelection.resetAnchor()
  },
)

// 列可见性状态,选择结果保存在 localStorage,刷新后恢复
const columnVisibility = useDashboardPhotoColumnVisibility()

const selectedRowsCount = computed((): number => {
  return selectedPhotoRows.value.length
})

const totalRowsCount = computed((): number => {
  return filteredData.value.length
})

const photoFilter = ref<'all' | 'livephoto' | 'static'>('all')

const filteredData = computed(() => {
  if (!filteredPhotos.value) return []

  switch (photoFilter.value) {
    case 'livephoto':
      return filteredPhotos.value.filter((photo: Photo) => photo.isLivePhoto)
    case 'static':
      return filteredPhotos.value.filter((photo: Photo) => !photo.isLivePhoto)
    default:
      return filteredPhotos.value
  }
})

const selectedPhotoRows = computed(() =>
  filteredData.value
    .filter((photo: Photo) => rowSelection.value[photo.id])
    .map((photo: Photo) => ({ original: photo })),
)
watch(
  () => photos.value?.map((photo: Photo) => photo.id),
  (ids) => {
    const available = new Set(ids ?? [])
    rowSelection.value = Object.fromEntries(
      Object.entries(rowSelection.value).filter(([id]) => available.has(id)),
    )
  },
)

// 监听过滤后的照片变化,自动获取表态数据
watch(
  () => filteredData.value,
  async (photos) => {
    if (photos && photos.length > 0) {
      const photoIds = photos.map((p: Photo) => p.id)
      await fetchReactions(photoIds)
    }
  },
  { immediate: true },
)

// 状态检查间隔 Map,每个任务对应一个定时器
const statusIntervals = ref<Map<number, NodeJS.Timeout>>(new Map())

// 启动任务状态检查
const startTaskStatusCheck = (taskId: number, fileId: string) => {
  const intervalId = setInterval(async () => {
    try {
      const response = await consoleApi(`/api/queue/stats/${taskId}`)
      const uploadingFile = uploadingFiles.value.get(fileId)

      if (!uploadingFile) {
        clearInterval(intervalId)
        statusIntervals.value.delete(taskId)
        return
      }

      // 更新任务状态
      uploadingFile.stage =
        response.status === 'in-stages' ? response.statusStage : null
      uploadingFiles.value = new Map(uploadingFiles.value)

      if (response.status === 'completed') {
        // 任务完成
        uploadingFile.status = UploadQueueStatus.Completed
        uploadingFile.stage = null
        if (response.warningCode === QueueWarningCode.AlbumMissing) {
          const warning = $t('common.albumAssignment.missing')
          uploadingFile.warning = uploadingFile.warning
            ? `${uploadingFile.warning} ${warning}`
            : warning
        }
        uploadingFiles.value = new Map(uploadingFiles.value)

        // 停止状态检查
        clearInterval(intervalId)
        statusIntervals.value.delete(taskId)

        // 不再显示单独的成功提示,由上传组件统一处理

        // 刷新照片列表
        await refresh()

        // 2秒后从界面移除成功的任务
        // setTimeout(() => {
        //   uploadingFiles.value.delete(fileId)
        //   uploadingFiles.value = new Map(uploadingFiles.value)
        // }, 2000)
      } else if (response.status === 'failed') {
        // 任务失败
        uploadingFile.status = UploadQueueStatus.Error
        uploadingFile.error = `${$t('dashboard.photos.messages.error')}: ${response.errorMessage || $t('dashboard.photos.table.cells.unknown')}`
        uploadingFile.stage = null
        uploadingFiles.value = new Map(uploadingFiles.value)

        // 停止状态检查
        clearInterval(intervalId)
        statusIntervals.value.delete(taskId)

        // 错误信息已在上传组件中显示,不需要额外通知
        // 失败的任务不自动移除,让用户查看错误信息
      }
    } catch (error) {
      console.error('检查任务状态失败:', error)

      // 如果检查状态失败,清理定时器
      clearInterval(intervalId)
      statusIntervals.value.delete(taskId)

      const uploadingFile = uploadingFiles.value.get(fileId)
      if (uploadingFile) {
        uploadingFile.status = UploadQueueStatus.Error
        uploadingFile.error = $t(
          'dashboard.photos.messages.taskStatusCheckFailed',
        )
        uploadingFiles.value = new Map(uploadingFiles.value)
      }
    }
  }, 1000) // 每秒检查一次

  statusIntervals.value.set(taskId, intervalId)
}

// 手动移除上传任务
const removeUploadingFile = (fileId: string) => {
  const uploadingFile = uploadingFiles.value.get(fileId)

  // 如果任务还在进行中,先清理定时器
  if (uploadingFile?.taskId) {
    const intervalId = statusIntervals.value.get(uploadingFile.taskId)
    if (intervalId) {
      clearInterval(intervalId)
      statusIntervals.value.delete(uploadingFile.taskId)
    }
  }

  // 从列表中移除
  uploadQueue.remove(fileId)
}

// 批量清除已完成和错误的任务
const clearCompletedTasks = () => {
  const toRemove: string[] = []

  for (const [fileId, uploadingFile] of uploadingFiles.value) {
    if (isClearableUploadStatus(uploadingFile.status)) {
      toRemove.push(fileId)

      // 清理可能存在的定时器
      if (uploadingFile.taskId) {
        const intervalId = statusIntervals.value.get(uploadingFile.taskId)
        if (intervalId) {
          clearInterval(intervalId)
          statusIntervals.value.delete(uploadingFile.taskId)
        }
      }
    }
  }

  toRemove.forEach((fileId) => {
    uploadingFiles.value.delete(fileId)
  })

  uploadingFiles.value = new Map(uploadingFiles.value)

  if (toRemove.length > 0) {
    toast.add({
      title: $t('dashboard.photos.uploadQueue.taskCleared'),
      description: $t('dashboard.photos.uploadQueue.tasksCleared', {
        count: toRemove.length,
      }),
      color: 'info',
    })
  }
}

// 清除已完成的上传
const clearCompletedUploads = () => {
  clearCompletedTasks()
}

// 清除所有上传
const clearAllUploads = () => {
  const toRemove: string[] = []

  for (const [fileId, uploadingFile] of uploadingFiles.value) {
    toRemove.push(fileId)

    // 如果是正在上传的任务,先中止
    if (
      isAbortableUploadStatus(uploadingFile.status) &&
      uploadingFile.abortUpload
    ) {
      uploadingFile.abortUpload()
    }

    // 清理状态检查定时器
    if (uploadingFile.taskId) {
      const intervalId = statusIntervals.value.get(uploadingFile.taskId)
      if (intervalId) {
        clearInterval(intervalId)
        statusIntervals.value.delete(uploadingFile.taskId)
      }
    }
  }

  uploadQueue.clearAll()

  if (toRemove.length > 0) {
    toast.add({
      title: $t('dashboard.photos.uploadQueue.allTasksCleared'),
      description: $t('dashboard.photos.uploadQueue.tasksCleared', {
        count: toRemove.length,
      }),
      color: 'info',
    })
  }
}

const photoColumns = usePhotoTableColumns({
  preview: (photo) => openImagePreview(photo),
  reactions: reactionsData,
})

const columns = computed<TableColumn<Photo>[]>(() => [
  {
    id: 'select',
    header: ({ table }) =>
      h(UCheckbox, {
        modelValue: table.getIsSomePageRowsSelected()
          ? 'indeterminate'
          : table.getIsAllPageRowsSelected(),
        'onUpdate:modelValue': (value: boolean | 'indeterminate') =>
          table.toggleAllPageRowsSelected(!!value),
        'aria-label': $t('dashboard.photos.table.selectAllAria'),
      }),
    cell: ({ row, table }) =>
      h(
        'div',
        {
          class: 'flex',
          onClickCapture: rowRangeSelection.captureModifiers,
          onMousedown: rowRangeSelection.preventShiftTextSelection,
        },
        h(UCheckbox, {
          modelValue: row.getIsSelected(),
          'onUpdate:modelValue': (value: boolean | 'indeterminate') =>
            rowRangeSelection.toggleTableRow(table, row, !!value),
          'aria-label': $t('dashboard.photos.table.selectRowAria'),
        }),
      ),
    enableHiding: false,
  },
  ...photoColumns.value,
])

// 文件验证函数
const validateFile = (
  file: File,
): {
  valid: boolean
  error?: string
  reason?: 'unsupported-format' | 'file-too-large'
} => {
  // 检查文件类型
  const allowedTypes = [
    'image/jpeg',
    'image/png',
    'image/heic',
    'image/heif',
    'video/quicktime', // MOV 文件
  ]

  const isValidImageType = allowedTypes.includes(file.type)
  const isValidImageExtension = ['.heic', '.heif'].some((ext) =>
    file.name.toLowerCase().endsWith(ext),
  )
  const isValidVideoExtension = file.name.toLowerCase().endsWith('.mov')

  if (!isValidImageType && !isValidImageExtension && !isValidVideoExtension) {
    return {
      valid: false,
      reason: 'unsupported-format',
      error: $t('dashboard.photos.errors.unsupportedFormat', {
        type: file.type,
      }),
    }
  }

  const maxSize = maxFileSizeMB.value * 1024 * 1024
  if (file.size > maxSize) {
    return {
      valid: false,
      reason: 'file-too-large',
      error: $t('dashboard.photos.errors.fileTooLarge', {
        size: (file.size / 1024 / 1024).toFixed(2),
        maxSize: maxFileSizeMB.value,
      }),
    }
  }

  return { valid: true }
}

const handleUpload = async () => {
  if (!canUseSelectedUploadAlbum.value) return
  const fileList = [...selectedFiles.value]
  const eraseLocation = uploadEraseLocationEnabled.value
  const albumId = selectedUploadAlbumId.value || undefined

  if (fileList.length === 0) {
    return
  }

  const errors: string[] = []
  let tooLargeCount = 0
  let unsupportedCount = 0

  // 先验证所有文件
  const validFiles: File[] = []

  for (const file of fileList) {
    const validation = validateFile(file)
    if (!validation.valid) {
      errors.push(`${file.name}: ${validation.error}`)
      if (validation.reason === 'file-too-large') {
        tooLargeCount += 1
      } else if (validation.reason === 'unsupported-format') {
        unsupportedCount += 1
      }
    } else {
      validFiles.push(file)
    }
  }

  if (validFiles.length === 0) {
    if (tooLargeCount > 0 && unsupportedCount === 0) {
      toast.add({
        title: $t('upload.error.tooLarge.title'),
        description: $t('dashboard.photos.errors.allFilesTooLarge', {
          count: tooLargeCount,
          maxSize: maxFileSizeMB.value,
        }),
        color: 'error',
      })
    } else {
      toast.add({
        title: $t('dashboard.photos.messages.error'),
        description: $t('dashboard.photos.errors.allFilesValidationFailed'),
        color: 'error',
      })
    }

    return
  }

  if (tooLargeCount > 0) {
    toast.add({
      title: $t('upload.error.tooLarge.title'),
      description: $t('dashboard.photos.errors.filesTooLargeSkipped', {
        count: tooLargeCount,
        maxSize: maxFileSizeMB.value,
      }),
      color: 'warning',
    })
  } else if (unsupportedCount > 0) {
    toast.add({
      title: $t('dashboard.photos.errors.fileValidationFailed'),
      description: $t('dashboard.photos.errors.filesUnsupportedSkipped', {
        count: unsupportedCount,
      }),
      color: 'warning',
    })
  }

  const pending = uploadQueue.enqueue(validFiles, (entry, signal) =>
    uploadImage(entry.file, entry.fileId, eraseLocation, albumId, signal),
  )
  selectedFiles.value = []
  isUploadSlideoverOpen.value = false
  await pending

  if (errors.length > 0) {
    console.error('批量上传错误详情:', errors)
  }
}

const openMetadataEditor = (photo: Photo) => {
  const initialTitle = photo.title?.trim() ?? ''
  const initialDescription = photo.description?.trim() ?? ''
  const initialTags = normalizeTagList(photo.tags ?? [])
  const hasCoordinates =
    typeof photo.latitude === 'number' && typeof photo.longitude === 'number'

  editingPhoto.value = photo
  editFormState.title = initialTitle
  editFormState.description = initialDescription
  editFormState.tags = [...initialTags]
  editFormState.rating =
    typeof photo.exif?.Rating === 'number' ? photo.exif.Rating : null

  const initialLocation = hasCoordinates
    ? {
        latitude: photo.latitude as number,
        longitude: photo.longitude as number,
      }
    : null

  originalMetadata.value = {
    title: initialTitle,
    description: initialDescription,
    tags: [...initialTags],
    location: initialLocation ? { ...initialLocation } : null,
    rating: typeof photo.exif?.Rating === 'number' ? photo.exif.Rating : null,
  }

  locationSelection.value = initialLocation ? { ...initialLocation } : null
  locationTouched.value = false

  isEditModalOpen.value = true
}

const handleLocationPick = () => {
  locationTouched.value = true
}

const clearSelectedLocation = () => {
  locationSelection.value = null
  locationTouched.value = true
}

const enqueueEraseLocationTask = async (photo: Photo) => {
  if (!photo?.id) {
    throw new Error($t('dashboard.photos.messages.photoNotFound'))
  }

  const result = await consoleApi('/api/queue/add-task', {
    method: 'POST',
    body: {
      payload: {
        type: 'photo-erase-location',
        photoId: photo.id,
      },
      priority: 2,
      maxAttempts: 3,
    },
  })

  if (!result.success) {
    throw new Error(
      result?.message || $t('dashboard.photos.messages.eraseLocationFailed'),
    )
  }

  return result.taskId
}

const saveMetadataChanges = async () => {
  if (!editingPhoto.value || !isMetadataDirty.value) {
    return
  }

  isSavingMetadata.value = true
  try {
    const payload: {
      title?: string
      description?: string
      tags?: string[]
      location?: { latitude: number; longitude: number } | null
      rating?: number | null
    } = {}

    if (titleChanged.value) {
      payload.title = normalizedTitle.value
    }

    if (descriptionChanged.value) {
      payload.description = normalizedDescription.value
    }

    if (tagsChanged.value) {
      payload.tags = [...editFormState.tags]
    }

    const shouldQueueLocationErase =
      locationChanged.value && locationSelection.value === null

    if (locationChanged.value && locationSelection.value) {
      payload.location = {
        latitude: locationSelection.value.latitude,
        longitude: locationSelection.value.longitude,
      }
    }

    if (ratingChanged.value) {
      payload.rating = editFormState.rating
    }

    let hasAnySuccessfulAction = false

    if (Object.keys(payload).length > 0) {
      await consoleApi(`/api/photos/${editingPhoto.value.id}`, {
        method: 'PUT',
        body: payload,
      })

      toast.add({
        title: $t('dashboard.photos.messages.metadataUpdateSuccess'),
        description: '',
        color: 'success',
      })
      hasAnySuccessfulAction = true
    }

    if (shouldQueueLocationErase) {
      const taskId = await enqueueEraseLocationTask(editingPhoto.value)
      toast.add({
        title: $t('dashboard.photos.messages.eraseLocationQueued'),
        description:
          typeof taskId === 'number'
            ? $t('dashboard.photos.messages.reprocessTaskId', { taskId })
            : '',
        color: 'success',
      })
      hasAnySuccessfulAction = true
    }

    if (!hasAnySuccessfulAction) {
      isEditModalOpen.value = false
      return
    }

    await refresh()
    isEditModalOpen.value = false
  } catch (error: any) {
    console.error('更新照片信息失败:', error)
    const message =
      error?.data?.statusMessage ||
      error?.statusMessage ||
      error?.message ||
      $t('dashboard.photos.messages.metadataUpdateFailed')

    toast.add({
      title: $t('dashboard.photos.messages.metadataUpdateFailed'),
      description: message,
      color: 'error',
    })
  } finally {
    isSavingMetadata.value = false
  }
}

const handleEditSubmit = async (event: FormSubmitEvent<EditFormState>) => {
  event.preventDefault()
  if (!isMetadataDirty.value) {
    return
  }
  await saveMetadataChanges()
}

const handleReverseGeocodeRequest = async (photo: Photo) => {
  if (!photo?.id) {
    return
  }

  setReverseGeocodeLoading(photo.id, true)

  try {
    const result = await consoleApi('/api/queue/add-task', {
      method: 'POST',
      body: {
        payload: {
          type: 'photo-reverse-geocoding',
          photoId: photo.id,
          latitude:
            typeof photo.latitude === 'number' ? photo.latitude : undefined,
          longitude:
            typeof photo.longitude === 'number' ? photo.longitude : undefined,
        },
        priority: 1,
        maxAttempts: 3,
      },
    })

    if (result.success) {
      toast.add({
        title: $t('dashboard.photos.messages.reverseGeocodeQueued'),
        description:
          typeof result.taskId === 'number'
            ? $t('dashboard.photos.messages.reprocessTaskId', {
                taskId: result.taskId,
              })
            : '',
        color: 'success',
      })
    } else {
      toast.add({
        title: $t('dashboard.photos.messages.reverseGeocodeFailed'),
        description:
          result?.message ||
          $t('dashboard.photos.messages.reverseGeocodeFailed'),
        color: 'error',
      })
    }
  } catch (error: any) {
    console.error('Failed to enqueue reverse geocoding task:', error)
    const message =
      error?.data?.statusMessage ||
      error?.statusMessage ||
      error?.message ||
      $t('dashboard.photos.messages.reverseGeocodeFailed')

    toast.add({
      title: $t('dashboard.photos.messages.reverseGeocodeFailed'),
      description: message,
      color: 'error',
    })
  } finally {
    setReverseGeocodeLoading(photo.id, false)
  }
}

const handleEraseLocationRequest = async (photo: Photo) => {
  if (!photo?.id) {
    return
  }

  setEraseLocationLoading(photo.id, true)

  try {
    const taskId = await enqueueEraseLocationTask(photo)
    toast.add({
      title: $t('dashboard.photos.messages.eraseLocationQueued'),
      description:
        typeof taskId === 'number'
          ? $t('dashboard.photos.messages.reprocessTaskId', { taskId })
          : '',
      color: 'success',
    })
  } catch (error: any) {
    console.error('Failed to enqueue erase location task:', error)
    const message =
      error?.data?.statusMessage ||
      error?.statusMessage ||
      error?.message ||
      $t('dashboard.photos.messages.eraseLocationFailed')

    toast.add({
      title: $t('dashboard.photos.messages.eraseLocationFailed'),
      description: message,
      color: 'error',
    })
  } finally {
    setEraseLocationLoading(photo.id, false)
  }
}

// 重新处理单张照片
const handleReprocessSingle = async (photo: Photo) => {
  try {
    if (!photo || !photo.storageKey) {
      toast.add({
        title: $t('dashboard.photos.messages.error'),
        description: $t('dashboard.photos.messages.noStorageKey'),
        color: 'error',
      })
      return
    }

    const reprocessToast = toast.add({
      title: $t('dashboard.photos.messages.reprocessSuccess'),
      description: '',
      color: 'info',
    })

    const result = await consoleApi('/api/queue/add-task', {
      method: 'POST',
      body: {
        payload: {
          type: 'photo',
          storageKey: photo.storageKey,
        },
        priority: 0,
        maxAttempts: 3,
      },
    })

    if (result.success) {
      toast.update(reprocessToast.id, {
        title: $t('dashboard.photos.messages.reprocessSuccess'),
        description: $t('dashboard.photos.messages.reprocessTaskId', {
          taskId: result.taskId,
        }),
        color: 'success',
      })
    } else {
      toast.update(reprocessToast.id, {
        title: $t('dashboard.photos.messages.error'),
        description: $t('dashboard.photos.messages.taskSubmitFailed'),
        color: 'error',
      })
    }
  } catch (error: any) {
    console.error('处理照片失败:', error)
    toast.add({
      title: $t('dashboard.photos.messages.reprocessFailed'),
      description: error.message || $t('dashboard.photos.messages.error'),
      color: 'error',
    })
  }
}

const getRowActions = (photo: Photo): DropdownMenuItem[][] => {
  const isReverseLoading = !!reverseGeocodeLoading.value[photo.id]
  const isEraseLocationLoading = !!eraseLocationLoading.value[photo.id]

  return [
    [
      {
        label: $t('dashboard.photos.actions.editMetadata'),
        icon: 'tabler:pencil',
        onSelect() {
          openMetadataEditor(photo)
        },
      },
      {
        label: $t('dashboard.photos.actions.reprocess'),
        icon: 'tabler:refresh',
        onSelect() {
          handleReprocessSingle(photo)
        },
      },
      {
        label: $t('dashboard.photos.actions.refreshLocation'),
        icon: isReverseLoading ? 'tabler:loader-2' : 'tabler:map-pin',
        disabled: isReverseLoading,
        onSelect() {
          handleReverseGeocodeRequest(photo)
        },
      },
      {
        label: $t('dashboard.photos.actions.eraseLocationInfo'),
        icon: isEraseLocationLoading ? 'tabler:loader-2' : 'tabler:map-off',
        disabled: isEraseLocationLoading,
        onSelect() {
          handleEraseLocationRequest(photo)
        },
      },
      {
        label: $t('dashboard.photos.actions.previewPhoto'),
        icon: 'tabler:photo',
        onSelect() {
          openImagePreview(photo)
        },
      },
    ],
    [
      {
        color: 'error',
        label: $t('dashboard.photos.actions.delete'),
        icon: 'tabler:trash',
        onSelect: () => handleSingleDeleteRequest(photo),
      },
    ],
  ]
}

// 图片预览弹窗
const isImagePreviewOpen = ref(false)
const previewingPhoto = ref<Photo | null>(null)

const openImagePreview = (photo: Photo) => {
  if (photo) {
    previewingPhoto.value = photo
    isImagePreviewOpen.value = true
  }
}

const openInNewTab = (url: string) => {
  if (typeof window !== 'undefined') {
    window.open(url, '_blank')
  }
}

const isDeleteConfirmOpen = ref(false)
const deleteMode = ref<'single' | 'batch'>('single')
const deleteTargetPhotos = ref<Photo[]>([])
const isDeleting = ref(false)

const openDeleteConfirm = (mode: 'single' | 'batch', photos: Photo[]) => {
  deleteMode.value = mode
  deleteTargetPhotos.value = photos
  isDeleteConfirmOpen.value = true
}

const handleSingleDeleteRequest = (photo: Photo) => {
  openDeleteConfirm('single', [photo])
}

// 批量删除功能
const handleBatchDelete = () => {
  const selectedRowModel = { rows: selectedPhotoRows.value }
  const selectedPhotos =
    selectedRowModel?.rows.map((row: any) => row.original) || []

  if (selectedPhotos.length === 0) {
    toast.add({
      title: $t('dashboard.photos.selection.selected', { count: 0, total: 0 }),
      description: $t('dashboard.photos.messages.batchSelectRequired'),
      color: 'warning',
    })
    return
  }

  openDeleteConfirm('batch', selectedPhotos)
}

const confirmDelete = async () => {
  if (deleteTargetPhotos.value.length === 0) {
    isDeleteConfirmOpen.value = false
    return
  }

  const mode = deleteMode.value
  const targetPhotos = [...deleteTargetPhotos.value]

  let deleteToast: ReturnType<typeof toast.add> | null = null

  isDeleting.value = true

  try {
    if (mode === 'batch') {
      deleteToast = toast.add({
        title: $t('dashboard.photos.delete.batch.title'),
        description: $t('dashboard.photos.messages.deleteSuccess'),
        color: 'info',
      })
      await Promise.all(
        targetPhotos.map((photo) =>
          consoleApi(`/api/photos/${photo.id}`, {
            method: 'DELETE',
          }),
        ),
      )

      toast.update(deleteToast.id, {
        title: $t('dashboard.photos.messages.batchDeleteSuccess', {
          count: targetPhotos.length,
        }),
        description: '',
        color: 'success',
      })

      rowSelection.value = {}
    } else {
      const photo = targetPhotos[0]
      if (!photo) {
        throw new Error($t('dashboard.photos.messages.error'))
      }

      await consoleApi(`/api/photos/${photo.id}`, {
        method: 'DELETE',
      })

      toast.add({
        title: $t('dashboard.photos.messages.deleteSuccess'),
        description: '',
        color: 'success',
      })
    }

    await refresh()
    isDeleteConfirmOpen.value = false
    deleteTargetPhotos.value = []
  } catch (error: any) {
    console.error('删除照片失败:', error)
    const message = error?.message || $t('dashboard.photos.messages.error')

    if (mode === 'batch' && deleteToast) {
      toast.update(deleteToast.id, {
        title: $t('dashboard.photos.messages.batchDeleteFailed'),
        description: message,
        color: 'error',
      })
    } else {
      toast.add({
        title: $t('dashboard.photos.messages.deleteFailed'),
        description: message,
        color: 'error',
      })
    }
  }

  isDeleting.value = false
}

// 批量重新处理照片功能
const handleBatchReprocess = async () => {
  const selectedRowModel = { rows: selectedPhotoRows.value }
  const selectedPhotos =
    selectedRowModel?.rows.map((row: any) => row.original) || []

  if (selectedPhotos.length === 0) {
    toast.add({
      title: $t('dashboard.photos.messages.batchSelectRequired'),
      description: '',
      color: 'warning',
    })
    return
  }

  // 检查所有选中照片是否都有 storageKey
  const photosWithStorageKey = selectedPhotos.filter(
    (photo: Photo) => photo.storageKey,
  )
  if (photosWithStorageKey.length !== selectedPhotos.length) {
    toast.add({
      title: $t('dashboard.photos.messages.error'),
      description: $t('dashboard.photos.messages.batchNoStorageKey', {
        count: selectedPhotos.length - photosWithStorageKey.length,
      }),
      color: 'error',
    })
    return
  }

  try {
    const reprocessToast = toast.add({
      title: $t('dashboard.photos.messages.batchReprocessing'),
      description: '',
      color: 'info',
    })

    const result = await consoleApi('/api/queue/add-tasks', {
      method: 'POST',
      body: {
        tasks: photosWithStorageKey.map((photo: Photo) => ({
          payload: {
            type: 'photo',
            storageKey: photo.storageKey,
          },
          priority: 0,
          maxAttempts: 3,
        })),
      },
    })

    if (result.success) {
      toast.update(reprocessToast.id, {
        title: $t('dashboard.photos.messages.reprocessSuccess'),
        description: $t('dashboard.photos.messages.batchReprocessSuccess', {
          count: photosWithStorageKey.length,
        }),
        color: 'success',
      })
    } else {
      toast.update(reprocessToast.id, {
        title: $t('dashboard.photos.messages.error'),
        description: $t('dashboard.photos.messages.batchReprocessFailed'),
        color: 'error',
      })
    }

    // 清空选中状态
    rowSelection.value = {}
  } catch (error: any) {
    console.error('批量处理失败:', error)
    toast.add({
      title: $t('dashboard.photos.messages.batchReprocessFailed'),
      description: error.message || $t('dashboard.photos.messages.error'),
      color: 'error',
    })
  }
}

// 批量抹除位置信息
const handleBatchEraseLocation = async () => {
  const selectedRowModel = { rows: selectedPhotoRows.value }
  const selectedPhotos =
    selectedRowModel?.rows.map((row: any) => row.original) || []

  if (selectedPhotos.length === 0) {
    toast.add({
      title: $t('dashboard.photos.messages.batchSelectRequired'),
      description: '',
      color: 'warning',
    })
    return
  }

  const targetPhotoIds = selectedPhotos
    .map((photo: Photo) => photo.id)
    .filter((id): id is string => !!id)

  if (targetPhotoIds.length === 0) {
    toast.add({
      title: $t('dashboard.photos.messages.photoNotFound'),
      description: '',
      color: 'error',
    })
    return
  }

  for (const photoId of targetPhotoIds) {
    setEraseLocationLoading(photoId, true)
  }

  try {
    const result = await consoleApi('/api/queue/add-tasks', {
      method: 'POST',
      body: {
        tasks: targetPhotoIds.map((photoId) => ({
          payload: {
            type: 'photo-erase-location',
            photoId,
          },
          priority: 2,
          maxAttempts: 3,
        })),
      },
    })

    if (result.success) {
      toast.add({
        title: $t('dashboard.photos.messages.batchEraseLocationQueued', {
          count: targetPhotoIds.length,
        }),
        description: '',
        color: 'success',
      })
      rowSelection.value = {}
    } else {
      toast.add({
        title: $t('dashboard.photos.messages.batchEraseLocationFailed'),
        description:
          result?.message ||
          $t('dashboard.photos.messages.batchEraseLocationFailed'),
        color: 'error',
      })
    }
  } catch (error: any) {
    console.error('批量抹除位置信息入队失败:', error)
    const message =
      error?.data?.statusMessage ||
      error?.statusMessage ||
      error?.message ||
      $t('dashboard.photos.messages.batchEraseLocationFailed')

    toast.add({
      title: $t('dashboard.photos.messages.batchEraseLocationFailed'),
      description: message,
      color: 'error',
    })
  } finally {
    for (const photoId of targetPhotoIds) {
      setEraseLocationLoading(photoId, false)
    }
  }
}

// 批量下载照片
const handleBatchDownload = async () => {
  const selectedRowModel = { rows: selectedPhotoRows.value }
  const selectedPhotos =
    selectedRowModel?.rows.map((row: any) => row.original) || []

  if (selectedPhotos.length === 0) {
    toast.add({
      title: $t('dashboard.photos.messages.batchSelectRequired'),
      description: '',
      color: 'warning',
    })
    return
  }

  // 检查所有选中照片是否都有 originalUrl
  const photosWithUrl = selectedPhotos.filter(
    (photo: Photo) => photo.originalUrl,
  )
  if (photosWithUrl.length === 0) {
    toast.add({
      title: $t('dashboard.photos.messages.error'),
      description: $t('dashboard.photos.messages.batchNoUrl'),
      color: 'error',
    })
    return
  }

  if (photosWithUrl.length !== selectedPhotos.length) {
    toast.add({
      title: $t('dashboard.photos.messages.warning'),
      description: $t('dashboard.photos.messages.batchPartialUrl', {
        count: photosWithUrl.length,
        total: selectedPhotos.length,
      }),
      color: 'warning',
    })
  }

  const downloadToast = toast.add({
    title: $t('dashboard.photos.messages.downloadStarted'),
    description: $t('dashboard.photos.messages.downloadingCount', {
      count: photosWithUrl.length,
    }),
    color: 'info',
  })

  let successCount = 0
  let failureCount = 0

  try {
    for (const photo of photosWithUrl) {
      try {
        const response = await fetch(photo.originalUrl!)
        if (!response.ok) {
          failureCount++
          continue
        }

        const blob = await response.blob()
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        const extension = photo.originalUrl!.split('.').pop() || 'jpg'
        link.download = `${photo.title || `photo-${photo.id}`}.${extension}`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        successCount++

        // 为了避免浏览器限制,每个下载之间加入短延迟
        await new Promise((resolve) => setTimeout(resolve, 200))
      } catch (error) {
        console.error(`Failed to download photo ${photo.id}:`, error)
        failureCount++
      }
    }

    // 更新提示信息
    if (successCount === photosWithUrl.length) {
      toast.update(downloadToast.id, {
        title: $t('dashboard.photos.messages.batchDownloadSuccess'),
        description: $t('dashboard.photos.messages.downloadedCount', {
          count: successCount,
        }),
        color: 'success',
      })
    } else if (failureCount === photosWithUrl.length) {
      toast.update(downloadToast.id, {
        title: $t('dashboard.photos.messages.batchDownloadFailed'),
        description: $t('dashboard.photos.messages.downloadFailedCount', {
          count: failureCount,
        }),
        color: 'error',
      })
    } else {
      toast.update(downloadToast.id, {
        title: $t('dashboard.photos.messages.batchDownloadPartial'),
        description: $t('dashboard.photos.messages.downloadPartialCount', {
          success: successCount,
          failed: failureCount,
        }),
        color: 'warning',
      })
    }
  } catch (error: any) {
    console.error('批量下载出错:', error)
    toast.update(downloadToast.id, {
      title: $t('dashboard.photos.messages.error'),
      description: error.message || $t('dashboard.photos.messages.error'),
      color: 'error',
    })
  }
}

watch(isImagePreviewOpen, (open) => {
  if (!open) {
    previewingPhoto.value = null
  }
})

// 清理定时器
onUnmounted(() => {
  // 清理所有状态检查定时器
  statusIntervals.value.forEach((intervalId) => {
    clearInterval(intervalId)
  })
  statusIntervals.value.clear()
})
</script>

<template>
  <UDashboardPanel>
    <template #header>
      <UDashboardNavbar :title="$t('dashboard.photos.toolbar.title')">
        <template #right>
          <div class="flex gap-2 items-center">
            <UButton
              variant="soft"
              color="neutral"
              icon="tabler:list-check"
              data-tour="photo-queue"
              @click="$router.push('/dashboard/queue')"
            >
              <span class="hidden sm:inline">{{
                $t('dashboard.photos.buttons.queue')
              }}</span>
            </UButton>
            <UButton
              icon="tabler:cloud-upload"
              data-tour="photo-upload"
              @click="openUploadSlideover()"
            >
              <span class="hidden sm:inline">{{
                $t('dashboard.photos.buttons.upload')
              }}</span>
            </UButton>
          </div>
        </template>
      </UDashboardNavbar>
    </template>

    <template #body>
      <div :class="photoLibraryPresentation.body">
        <!-- 上传队列容器 -->
        <UploadQueuePanel
          :uploading-files="uploadingFiles"
          @remove-file="removeUploadingFile"
          @clear-completed="clearCompletedUploads"
          @clear-all="clearAllUploads"
          @go-to-queue="$router.push('/dashboard/queue')"
          class="shrink-0"
        />

        <PhotoUploadSlideover
          v-model:open="isUploadSlideoverOpen"
          v-model:files="selectedFiles"
          :max-file-size-m-b="maxFileSizeMB"
          :can-upload="canUseSelectedUploadAlbum"
          @upload="handleUpload"
        >
          <UCard
            variant="soft"
            class="border border-neutral-200/80 dark:border-neutral-800/80"
          >
            <UFormField
              :label="$t('dashboard.photos.slideover.album.label')"
              :description="$t('dashboard.photos.slideover.album.description')"
            >
              <USelectMenu
                v-model="selectedUploadAlbumId"
                :items="uploadAlbumItems"
                value-key="value"
                label-key="label"
                :loading="isLoadingUploadAlbums"
                :disabled="isLoadingUploadAlbums"
                :aria-label="$t('dashboard.photos.slideover.album.label')"
                class="w-full"
              />
            </UFormField>
            <p
              v-if="
                !isLoadingUploadAlbums &&
                !uploadAlbumsLoadFailed &&
                uploadAlbums.length === 0
              "
              class="mt-2 text-xs text-neutral-500 dark:text-neutral-400"
            >
              {{ $t('dashboard.photos.slideover.album.empty') }}
            </p>
            <p
              v-if="selectedUploadAlbumUnavailable"
              role="alert"
              class="mt-2 text-sm text-error-600 dark:text-error-400"
            >
              {{
                $t(
                  requestedUploadAlbumId === selectedUploadAlbumId
                    ? 'dashboard.photos.slideover.album.requestedUnavailable'
                    : 'dashboard.photos.slideover.album.unavailable',
                )
              }}
            </p>
            <div
              v-if="uploadAlbumsLoadFailed"
              role="alert"
              class="mt-2 flex items-center justify-between gap-2 text-sm text-error-600 dark:text-error-400"
            >
              <span>{{
                $t('dashboard.photos.slideover.album.loadFailedUpload')
              }}</span>
              <UButton
                size="xs"
                variant="soft"
                @click="loadUploadAlbums"
              >
                {{ $t('dashboard.photos.slideover.album.retry') }}
              </UButton>
            </div>
          </UCard>

          <UCard
            variant="soft"
            class="border border-neutral-200/80 dark:border-neutral-800/80"
          >
            <div class="flex items-start justify-between gap-4">
              <div class="space-y-1">
                <p
                  class="text-sm font-medium text-neutral-800 dark:text-neutral-100"
                >
                  {{
                    $t('dashboard.photos.slideover.options.eraseLocation.label')
                  }}
                </p>
                <p class="text-xs text-neutral-500 dark:text-neutral-400">
                  {{
                    $t(
                      'dashboard.photos.slideover.options.eraseLocation.description',
                    )
                  }}
                </p>
              </div>
              <USwitch v-model="uploadEraseLocationEnabled" />
            </div>
          </UCard>
        </PhotoUploadSlideover>

        <!-- 统合容器:工具栏 + 照片列表 -->
        <div :class="photoLibraryPresentation.panel">
          <!-- 工具栏 -->
          <div :class="photoLibraryPresentation.toolbar">
            <ConsolePhotoLibrarySummary :photos="filteredPhotos ?? []" />

            <div class="flex items-center gap-2">
              <OverlayFilterPopover>
                <UTooltip :text="$t('ui.action.filter.tooltip')">
                  <UChip
                    inset
                    size="sm"
                    color="info"
                    :show="totalSelectedFilters > 0"
                  >
                    <UButton
                      variant="soft"
                      :color="hasActiveFilters ? 'info' : 'neutral'"
                      class="bg-transparent rounded-full cursor-pointer relative"
                      icon="tabler:filter"
                      size="sm"
                    />
                  </UChip>
                </UTooltip>
              </OverlayFilterPopover>
              <OverlaySortPopover>
                <UTooltip :text="$t('ui.action.sort.tooltip')">
                  <UButton
                    variant="soft"
                    :color="
                      currentSortOption?.key === 'dateTaken-desc'
                        ? 'neutral'
                        : 'info'
                    "
                    class="bg-transparent rounded-full cursor-pointer"
                    :icon="currentSortIcon"
                    size="sm"
                  />
                </UTooltip>
              </OverlaySortPopover>
              <!-- 过滤器 -->
              <USelectMenu
                data-tour="photo-filter"
                v-model="photoFilter"
                class="w-full sm:w-48"
                :items="[
                  {
                    label: $t('dashboard.photos.photoFilter.all'),
                    value: 'all',
                    icon: 'tabler:photo-scan',
                  },
                  {
                    label: $t('dashboard.photos.photoFilter.livephoto'),
                    value: 'livephoto',
                    icon: 'tabler:live-photo',
                  },
                  {
                    label: $t('dashboard.photos.photoFilter.static'),
                    value: 'static',
                    icon: 'tabler:photo',
                  },
                ]"
                value-key="value"
                label-key="label"
                size="sm"
              >
              </USelectMenu>

              <!-- 刷新按钮 -->
              <UButton
                variant="soft"
                color="info"
                size="sm"
                icon="tabler:refresh"
                :loading="reactionsLoading"
                @click="
                  async () => {
                    await refresh()
                    if (filteredData.length > 0) {
                      await fetchReactions(filteredData.map((p: Photo) => p.id))
                    }
                  }
                "
              >
                <span class="hidden sm:inline">{{
                  $t('dashboard.photos.toolbar.refresh')
                }}</span>
              </UButton>

              <!-- 列可见性按钮 -->
              <UDropdownMenu
                v-if="layout !== 'masonry'"
                :items="
                  table?.tableApi
                    ?.getAllColumns()
                    .filter((column: any) => column.getCanHide())
                    .map((column: any) => ({
                      label: columnNameMap[column.id] || column.id,
                      type: 'checkbox' as const,
                      checked: column.getIsVisible(),
                      disabled:
                        !column.getCanHide() ||
                        column.id === 'thumbnailUrl' ||
                        column.id === 'id' ||
                        column.id === 'actions',
                      onUpdateChecked(checked: boolean) {
                        table?.tableApi
                          ?.getColumn(column.id)
                          ?.toggleVisibility(!!checked)
                      },
                      onSelect(e: Event) {
                        e.preventDefault()
                      },
                    }))
                "
                :content="{ align: 'end' }"
              >
                <UButton
                  label=""
                  color="neutral"
                  variant="outline"
                  size="sm"
                  icon="tabler:columns-3"
                  :title="
                    $t('dashboard.photos.table.columnVisibility.description')
                  "
                >
                  <span class="hidden sm:inline">{{
                    $t('dashboard.photos.table.columnVisibility.button')
                  }}</span>
                </UButton>
              </UDropdownMenu>
              <ConsolePhotoLayoutSwitch v-model="layout" />
            </div>
          </div>

          <!-- 照片列表 -->
          <div :class="photoLibraryPresentation.content">
            <ConsolePhotoMasonry
              v-if="layout === 'masonry' && filteredData.length"
              class="overflow-auto p-3"
              v-model:selection="rowSelection"
              :photos="filteredData as Photo[]"
              :actions="getRowActions"
              @preview="openImagePreview"
            />
            <ConsolePhotoTable
              v-else
              ref="table"
              v-model:row-selection="rowSelection"
              v-model:column-visibility="columnVisibility"
              :get-row-id="getPhotoRowId"
              :column-pinning="{
                right: ['actions'],
              }"
              :data="filteredData as Photo[]"
              :columns="columns"
              :loading="status === 'pending'"
              sticky
              class="h-full flex-1"
            >
              <template #actions-cell="{ row }">
                <ConsolePhotoTableActions
                  :items="getRowActions(row.original)"
                />
              </template>
            </ConsolePhotoTable>

            <ConsoleSelectionToolbar
              :count="selectedRowsCount"
              :total="totalRowsCount"
              range-tip
            >
              <UButton
                color="primary"
                variant="ghost"
                size="sm"
                class="rounded-full"
                icon="tabler:album"
                :aria-label="$t('dashboard.photos.selection.addToAlbum')"
                @click="openAddToAlbum"
              >
                <span class="hidden sm:inline">{{
                  $t('dashboard.photos.selection.addToAlbum')
                }}</span>
              </UButton>
              <UButton
                color="neutral"
                variant="ghost"
                size="sm"
                class="rounded-full text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:text-white dark:hover:bg-neutral-800"
                icon="tabler:refresh"
                :aria-label="$t('dashboard.photos.selection.batchReprocess')"
                @click="handleBatchReprocess"
              >
                <span class="hidden sm:inline">{{
                  $t('dashboard.photos.selection.batchReprocess')
                }}</span>
              </UButton>

              <UButton
                color="neutral"
                variant="ghost"
                size="sm"
                class="rounded-full text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:text-white dark:hover:bg-neutral-800"
                icon="tabler:map-off"
                :aria-label="
                  $t('dashboard.photos.selection.batchEraseLocation')
                "
                @click="handleBatchEraseLocation"
              >
                <span class="hidden sm:inline">{{
                  $t('dashboard.photos.selection.batchEraseLocation')
                }}</span>
              </UButton>

              <UButton
                color="neutral"
                variant="ghost"
                size="sm"
                class="rounded-full text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:text-white dark:hover:bg-neutral-800"
                icon="tabler:download"
                :aria-label="$t('dashboard.photos.selection.batchDownload')"
                @click="handleBatchDownload"
              >
                <span class="hidden sm:inline">{{
                  $t('dashboard.photos.selection.batchDownload')
                }}</span>
              </UButton>

              <UButton
                color="error"
                variant="ghost"
                size="sm"
                class="rounded-full hover:bg-error-50 dark:hover:bg-error-500/20"
                icon="tabler:trash"
                :aria-label="$t('dashboard.photos.selection.batchDelete')"
                @click="handleBatchDelete"
              >
                <span class="hidden sm:inline">{{
                  $t('dashboard.photos.selection.batchDelete')
                }}</span>
              </UButton>
            </ConsoleSelectionToolbar>
          </div>
        </div>

        <USlideover
          v-model:open="isEditModalOpen"
          :title="$t('dashboard.photos.editModal.title')"
          :description="$t('dashboard.photos.editModal.description')"
          :ui="{
            content: 'sm:max-w-xl',
            body: 'p-2',
            header:
              'px-6 py-5 border-b border-neutral-200 dark:border-neutral-800',
            footer:
              'px-6 py-5 border-t border-neutral-200 dark:border-neutral-800',
          }"
        >
          <template #body>
            <div class="space-y-6">
              <div
                v-if="editingPhoto"
                class="space-y-1"
              >
                <p class="text-xs text-neutral-500 dark:text-neutral-500">
                  {{ editingPhoto.title || editingPhoto.id }}
                </p>
              </div>

              <UForm
                id="edit-photo-form"
                :state="editFormState"
                class="space-y-5"
                @submit="handleEditSubmit"
              >
                <ConsolePhotoDetailsFields
                  v-model:title="editFormState.title"
                  v-model:description="editFormState.description"
                  v-model:tags="tagsModel"
                  v-model:rating="editFormState.rating"
                />

                <div class="space-y-3">
                  <div class="flex items-center justify-between">
                    <label
                      class="text-sm font-medium text-neutral-700 dark:text-neutral-200"
                    >
                      {{ $t('dashboard.photos.editModal.fields.location') }}
                    </label>
                    <UButton
                      v-if="locationSelection"
                      variant="ghost"
                      color="neutral"
                      size="xs"
                      icon="tabler:map-off"
                      @click.prevent="clearSelectedLocation"
                    >
                      {{
                        $t('dashboard.photos.editModal.fields.clearLocation')
                      }}
                    </UButton>
                  </div>

                  <MapLocationPicker
                    v-model="locationSelection"
                    class="border border-neutral-200 dark:border-neutral-800"
                    @pick="handleLocationPick"
                  >
                    <template #empty>
                      <span
                        class="px-3 py-2 rounded-full bg-white/80 text-neutral-600 dark:bg-neutral-900/80 dark:text-neutral-200 shadow"
                      >
                        {{
                          $t('dashboard.photos.editModal.fields.locationHint')
                        }}
                      </span>
                    </template>
                  </MapLocationPicker>

                  <div
                    class="text-xs text-neutral-500 dark:text-neutral-400 flex items-center gap-2"
                  >
                    <span
                      >{{
                        $t('dashboard.photos.editModal.fields.coordinates')
                      }}:</span
                    >
                    <span v-if="formattedCoordinates">
                      {{ formattedCoordinates.latitude }},
                      {{ formattedCoordinates.longitude }}
                    </span>
                    <span v-else>
                      {{ $t('dashboard.photos.editModal.fields.noLocation') }}
                    </span>
                  </div>
                </div>
              </UForm>
            </div>
          </template>

          <template #footer>
            <div class="flex items-center justify-end gap-2 w-full">
              <UButton
                variant="ghost"
                color="neutral"
                @click.prevent="isEditModalOpen = false"
              >
                {{ $t('dashboard.photos.editModal.actions.cancel') }}
              </UButton>
              <UButton
                type="submit"
                form="edit-photo-form"
                :loading="isSavingMetadata"
                :disabled="!isMetadataDirty || isSavingMetadata"
                icon="tabler:device-floppy"
              >
                {{ $t('dashboard.photos.editModal.actions.save') }}
              </UButton>
            </div>
          </template>
        </USlideover>

        <UModal
          v-model:open="isAddToAlbumOpen"
          :dismissible="!isAddingToAlbum"
          :close="!isAddingToAlbum"
          :title="$t('dashboard.photos.addToAlbum.title')"
          :description="
            $t('dashboard.photos.addToAlbum.description', {
              photos: selectedBulkPhotoCountLabel,
            })
          "
        >
          <template #body>
            <UFormField :label="$t('dashboard.photos.addToAlbum.albumLabel')">
              <USelectMenu
                v-model="selectedBulkAlbumId"
                :items="bulkAlbumItems"
                value-key="value"
                label-key="label"
                :loading="isLoadingUploadAlbums"
                :disabled="
                  isLoadingUploadAlbums ||
                  uploadAlbumsLoadFailed ||
                  isAddingToAlbum
                "
                :aria-label="$t('dashboard.photos.addToAlbum.albumLabel')"
                :placeholder="$t('dashboard.photos.addToAlbum.albumLabel')"
                class="w-full"
              />
            </UFormField>
            <p
              v-if="
                !isLoadingUploadAlbums &&
                !uploadAlbumsLoadFailed &&
                uploadAlbums.length === 0
              "
              class="mt-3 text-sm text-neutral-500 dark:text-neutral-400"
            >
              {{ $t('dashboard.photos.slideover.album.empty') }}
            </p>
            <div
              v-if="uploadAlbumsLoadFailed"
              role="alert"
              class="mt-3 flex items-center justify-between gap-2 text-sm text-error-600 dark:text-error-400"
            >
              <span>{{
                $t('dashboard.photos.slideover.album.loadFailed')
              }}</span>
              <UButton
                size="xs"
                variant="soft"
                @click="loadUploadAlbums"
              >
                {{ $t('dashboard.photos.slideover.album.retry') }}
              </UButton>
            </div>
          </template>
          <template #footer>
            <div class="flex w-full justify-end gap-2">
              <UButton
                variant="ghost"
                color="neutral"
                :disabled="isAddingToAlbum"
                @click="isAddToAlbumOpen = false"
              >
                {{ $t('dashboard.photos.addToAlbum.cancel') }}
              </UButton>
              <UButton
                icon="tabler:album"
                :loading="isAddingToAlbum"
                :disabled="
                  selectedBulkAlbumId === null ||
                  isLoadingUploadAlbums ||
                  uploadAlbumsLoadFailed ||
                  isAddingToAlbum
                "
                @click="addSelectedPhotosToAlbum"
              >
                {{ $t('dashboard.photos.addToAlbum.confirm') }}
              </UButton>
            </div>
          </template>
        </UModal>

        <UModal v-model:open="isDeleteConfirmOpen">
          <template #body>
            <div class="space-y-4">
              <div class="flex items-start gap-4">
                <div
                  class="flex size-10 items-center justify-center rounded-full bg-error-100 dark:bg-error-900/40 text-error-600 dark:text-error-400 shrink-0"
                >
                  <Icon
                    name="tabler:trash"
                    class="size-6"
                  />
                </div>
                <div class="space-y-1.5 pt-1">
                  <h3
                    class="text-lg font-semibold text-neutral-900 dark:text-white leading-5"
                  >
                    {{
                      deleteMode === 'single'
                        ? $t('dashboard.photos.delete.single.title')
                        : $t('dashboard.photos.delete.batch.title')
                    }}
                  </h3>
                  <p
                    class="text-sm text-neutral-500 dark:text-neutral-400 leading-relaxed"
                  >
                    {{
                      deleteMode === 'single'
                        ? $t('dashboard.photos.delete.single.message')
                        : $t('dashboard.photos.delete.batch.message', {
                            count: deleteTargetPhotos.length,
                          })
                    }}
                  </p>
                  <div
                    class="mt-4 p-3 bg-error-50 dark:bg-error-500/10 border border-error-200/50 dark:border-error-500/20 rounded-lg"
                  >
                    <p
                      class="text-sm font-medium text-error-600 dark:text-error-400 flex items-center gap-2"
                    >
                      <Icon
                        name="tabler:alert-triangle-filled"
                        class="size-4"
                      />
                      {{ $t('dashboard.photos.delete.warning') }}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <template #footer>
            <div class="flex justify-end gap-3 w-full">
              <UButton
                variant="ghost"
                color="neutral"
                :disabled="isDeleting"
                @click="isDeleteConfirmOpen = false"
              >
                {{ $t('dashboard.photos.delete.buttons.cancel') }}
              </UButton>
              <UButton
                color="error"
                icon="tabler:trash"
                :loading="isDeleting"
                @click="confirmDelete"
              >
                {{ $t('dashboard.photos.delete.buttons.confirm') }}
              </UButton>
            </div>
          </template>
        </UModal>

        <!-- 图片预览模态框 -->
        <UModal
          v-model:open="isImagePreviewOpen"
          :title="$t('dashboard.photos.previewTitle')"
          :description="previewingPhoto?.description || ''"
        >
          <template #body>
            <div
              class="flex items-center justify-center w-full"
              style="max-height: calc(100vh - 12rem)"
            >
              <div class="w-full max-w-2xl rounded-lg overflow-hidden">
                <MasonryItemPhoto
                  v-if="previewingPhoto"
                  :photo="previewingPhoto"
                  :index="0"
                  @visibility-change="() => {}"
                  @open-viewer="openInNewTab(`/${previewingPhoto.id}`)"
                />
              </div>
            </div>
          </template>
        </UModal>
      </div>
    </template>
  </UDashboardPanel>
</template>

<style scoped></style>