<template>
  <Teleport to="body">
    <div v-if="show" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50" @click.self="handleClose">
    <div class="admin-card max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
      <div class="flex items-center justify-between mb-6">
        <h2 class="text-xl font-serif italic text-white">附件详情</h2>
        <button @click="handleClose" class="text-white/40 hover:text-white transition-colors">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>
      
      <div v-if="attachment" class="space-y-6">
        <!-- 图片预览 -->
        <div v-if="attachment.fileType === 'image'" class="w-full rounded-lg overflow-hidden bg-white/5">
          <img :src="attachment.fileUrl" :alt="attachment.originalName" class="w-full h-auto max-h-96 object-contain" />
        </div>
        
        <!-- 文件信息 -->
        <div class="space-y-4">
          <div>
            <label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件名</label>
            <p class="text-white">{{ attachment.originalName }}</p>
          </div>
          
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件大小</label>
              <p class="text-white">{{ formatFileSize(attachment.fileSize) }}</p>
            </div>
            
            <div>
              <label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件类型</label>
              <p class="text-white">{{ getFileTypeLabel(attachment.fileType) }}</p>
            </div>
          </div>
          
          <div v-if="attachment.mimeType">
            <label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">MIME类型</label>
            <p class="text-white font-mono text-sm">{{ attachment.mimeType }}</p>
          </div>
          
          <div>
            <label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">存储类型</label>
            <p class="text-white">{{ getStorageTypeLabel(attachment.storageType) }}</p>
          </div>
          
          <div>
            <label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">分类</label>
            <CustomSelect
              v-model="localCategoryId"
              :options="categoryOptions"
              placeholder="无分类"
            />
          </div>
          
          <div>
            <label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件URL</label>
            <div class="flex gap-2">
              <input
                type="text"
                :value="attachment.fileUrl"
                readonly
                class="admin-input flex-1 font-mono text-sm"
              />
              <button
                @click="handleCopyUrl"
                class="admin-btn-secondary px-4 whitespace-nowrap"
              >
                复制
              </button>
            </div>
          </div>
          
          <div v-if="attachment.createdAt" class="text-xs text-art-muted">
            创建时间: {{ formatDate(attachment.createdAt) }}
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="flex gap-3 pt-4 border-t border-white/10">
          <button @click="handleClose" class="admin-btn-secondary flex-1">
            取消
          </button>
          <button @click="handleSave" :disabled="saving" class="admin-btn-primary flex-1">
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>
  </div>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import CustomSelect from '../CustomSelect.vue'

interface Attachment {
  id: number
  originalName: string
  fileUrl: string
  fileSize: number
  fileType: string
  categoryId?: number
  mimeType?: string
  storageType?: string
  createdAt?: string
}

interface Category {
  id: number
  name: string
}

interface Props {
  show: boolean
  attachment: Attachment | null
  categories: Category[]
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:show': [value: boolean]
  'save': [data: { categoryId: number | null }]
  'copy-url': [url: string]
}>()

const localCategoryId = ref<number>(0)
const saving = ref(false)

// 计算属性：分类选项
const categoryOptions = computed(() => {
  return [
    { value: 0, label: '无分类' },
    ...props.categories.map(cat => ({ value: cat.id, label: cat.name }))
  ]
})

// 监听attachment变化，更新本地分类ID
watch(() => props.attachment, (newAttachment) => {
  if (newAttachment) {
    localCategoryId.value = newAttachment.categoryId || 0
  }
}, { immediate: true })

const handleClose = () => {
  emit('update:show', false)
}

const handleSave = () => {
  saving.value = true
  const categoryId = localCategoryId.value === 0 ? null : localCategoryId.value
  emit('save', { categoryId })
  // saving状态由父组件控制
}

const handleCopyUrl = () => {
  if (props.attachment) {
    emit('copy-url', props.attachment.fileUrl)
  }
}

const formatFileSize = (bytes: number): string => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

const getFileTypeLabel = (fileType: string): string => {
  const labels: Record<string, string> = {
    image: '图片',
    video: '视频',
    document: '文档',
    other: '其他'
  }
  return labels[fileType] || fileType
}

const getStorageTypeLabel = (storageType?: string): string => {
  const labels: Record<string, string> = {
    local: '本地存储',
    qcloud: '腾讯云COS',
    aliyun: '阿里云OSS',
    qiniu: '七牛云'
  }
  return labels[storageType || 'local'] || storageType || '本地存储'
}

const formatDate = (timestamp: string | number): string => {
  const date = new Date(typeof timestamp === 'string' ? parseInt(timestamp) * 1000 : timestamp * 1000)
  return date.toLocaleString('zh-CN')
}

// 暴露saving状态给父组件
defineExpose({
  saving
})
</script>

<style scoped>
/* 使用全局admin样式，无需额外样式 */
</style>
