<template>
  <div class="media-section" v-if="hasAttachments || canAddAttachments">
    <div class="section-header">
      <router-link :to="`/app/file`" class="section-title-link" target="_blank">
        <h4>{{ t('Attachments') }}</h4>
      </router-link>
      <n-button 
        v-if="canAddAttachments"
        type="default" 
        size="small" 
        text
        @click="addAttachment"
        :title="t('Add Attachment')"
        class="add-attachment-btn"
      >
        <template #icon>
          <n-icon><Icon icon="tabler:plus" /></n-icon>
        </template>
      </n-button>
    </div>
    
    <!-- 图片附件网格布局 -->
    <div class="image-attachment-list" v-if="hasImageAttachments">
      <div 
        v-for="(attachment, index) in imageAttachments" 
        :key="`image-${index}`"
        class="image-attachment-item"
      >
        <div class="image-attachment">
          <div class="image-container">
            <img 
              :src="attachment.file_url" 
              :alt="attachment.file_name"
              loading="lazy"
              @click="openImageGallery(index)"
              @error="handleImageError"
            />
            <div class="image-overlay">
              <button 
                @click.stop="deleteAttachment(attachment)"
                :title="t('Delete Attachment')"
                class="delete-btn"
              >
                <Icon icon="tabler:x" />
              </button>
            </div>
          </div>
          <div class="image-filename">
            <router-link 
              :to="`/app/file/${attachment.name}`" 
              class="file-name-link"
              target="_blank"
              @click.stop
            >
              {{ attachment.file_name }}
            </router-link>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 普通附件列表布局 -->
    <div class="file-attachment-list" v-if="hasFileAttachments">
      <div 
        v-for="(attachment, index) in fileAttachments" 
        :key="`file-${index}`"
        class="file-attachment-item"
      >
        <div class="file-attachment">
          <div class="attachment-icon">
            <Icon :icon="getFileIcon(attachment.file_url)" />
          </div>
          <div class="attachment-info">
            <div class="file-name-container">
              <router-link 
                :to="`/app/file/${attachment.name}`" 
                class="file-name-link"
                target="_blank"
                @click.stop
              >
                {{ attachment.file_name }}
              </router-link>
              <button 
                @click.stop="deleteAttachment(attachment)"
                :title="t('Delete Attachment')"
                class="delete-btn-inline"
              >
                <Icon icon="tabler:x" />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 更多附件按钮 -->
    <div v-if="hasMoreAttachments" class="load-more-container">
      <n-button 
        type="default" 
        size="small" 
        text
        @click="loadMoreAttachments"
        class="load-more-btn"
      >
        <template #icon>
          <n-icon><Icon icon="tabler:chevron-down" /></n-icon>
        </template>
        {{ t('Load More') }} ({{ remainingAttachmentsCount }})
      </n-button>
    </div>
    
    <!-- 添加附件按钮（当没有附件时显示） -->
    <div v-if="!hasAttachments && canAddAttachments" class="add-attachment-placeholder">
      <n-button type="default" @click="addAttachment" class="add-button">
        <template #icon>
          <n-icon><Icon icon="tabler:plus" /></n-icon>
        </template>
        {{ t('Add Attachment') }}
      </n-button>
    </div>
    
    <!-- 图片预览组件 -->
    <ImageGallery 
      ref="imageGalleryRef"
      :images="imageUrls"
      @close="onGalleryClose"
    />

    <!-- 上传对话框 -->
    <FileUploadDialog 
      v-model:show="showUploadDialog"
      :pagetype="currentPagetype"
      :pagename="currentPagename"
      @uploaded="onUploaded"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { NButton, NIcon } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'
import ImageGallery from '@/core/components/ImageGallery.vue'
import FileUploadDialog from '@/views/pagetype/file/FileUploadDialog.vue'

const props = defineProps<{
  metaFields: any[]
  record: Record<string, any>
  canEdit?: boolean
}>()

const emit = defineEmits<{
  'add-attachment': []
  'attachment-uploaded': []
  'delete-attachment': [attachment: any]
}>()

const showUploadDialog = ref(false)

// 当前记录的上下文信息
const currentPagetype = computed(() => props.record?.pagetype || '')
const currentPagename = computed(() => props.record?.name || '')

const attachmentFields = computed(() => {
  const attachments = props.record.attachments || []
  
  if (attachments.length === 0) {
    return []
  }
  
  return attachments.map((attachment: any) => ({
    file_name: attachment.file_name || attachment.name,
    file_url: attachment.file_url || attachment.url,
    name: attachment.name,
    is_private: attachment.is_private || false
  }))
})

// 分页显示控制
const imageDisplayCount = ref(8)
const fileDisplayCount = ref(20)
const imagePageSize = 8
const filePageSize = 20

// 分离图片和普通附件
const allImageAttachments = computed(() => {
  return attachmentFields.value.filter((attachment: any) => isImageAttachment(attachment))
})

const allFileAttachments = computed(() => {
  return attachmentFields.value.filter((attachment: any) => !isImageAttachment(attachment))
})

// 显示的图片附件（分页）
const imageAttachments = computed(() => {
  return allImageAttachments.value.slice(0, imageDisplayCount.value)
})

// 显示的普通附件（分页）
const fileAttachments = computed(() => {
  return allFileAttachments.value.slice(0, fileDisplayCount.value)
})

// 是否还有更多图片附件
const hasMoreImageAttachments = computed(() => {
  return allImageAttachments.value.length > imageDisplayCount.value
})

// 是否还有更多普通附件
const hasMoreFileAttachments = computed(() => {
  return allFileAttachments.value.length > fileDisplayCount.value
})

// 是否还有更多附件（用于显示加载更多按钮）
const hasMoreAttachments = computed(() => {
  return hasMoreImageAttachments.value || hasMoreFileAttachments.value
})

// 是否有图片附件
const hasImageAttachments = computed(() => imageAttachments.value.length > 0)

// 是否有普通附件
const hasFileAttachments = computed(() => fileAttachments.value.length > 0)

// 剩余附件数量
const remainingAttachmentsCount = computed(() => {
  const remainingImages = Math.max(0, allImageAttachments.value.length - imageDisplayCount.value)
  const remainingFiles = Math.max(0, allFileAttachments.value.length - fileDisplayCount.value)
  return remainingImages + remainingFiles
})

// 加载更多附件
const loadMoreAttachments = () => {
  imageDisplayCount.value += imagePageSize
  fileDisplayCount.value += filePageSize
}

const hasAttachments = computed(() => attachmentFields.value.length > 0)
const canAddAttachments = computed(() => props.canEdit !== false)

// 图片预览相关
const imageGalleryRef = ref()

// 获取所有图片URL
const imageUrls = computed(() => {
  return attachmentFields.value
    .filter((attachment: any) => isImageAttachment(attachment))
    .map((attachment: any) => attachment.file_url)
})

// 判断是否为图片附件
const isImageAttachment = (attachment: any) => {
  const url = attachment.file_url || ''
  const fileName = attachment.file_name || ''
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg']
  
  return imageExtensions.some(ext => 
    url.toLowerCase().includes(ext) || 
    fileName.toLowerCase().includes(ext)
  )
}

// 工具函数
const getFileIcon = (url: string) => {
  const ext = url.split('.').pop()?.toLowerCase()
  switch (ext) {
    case 'pdf': return 'tabler:file-type-pdf'
    case 'doc':
    case 'docx': return 'tabler:file-type-doc'
    case 'xls':
    case 'xlsx': return 'tabler:file-type-xls'
    case 'ppt':
    case 'pptx': return 'tabler:file-type-ppt'
    case 'zip':
    case 'rar': return 'tabler:file-zip'
    case 'txt': return 'tabler:file-text'
    default: return 'tabler:file'
  }
}



// 打开图片预览
const openImageGallery = (index: number) => {
  // 找到图片在imageUrls中的索引
  const imageIndex = attachmentFields.value
    .slice(0, index + 1)
    .filter((attachment: any) => isImageAttachment(attachment))
    .length - 1
  
  imageGalleryRef.value?.open(imageIndex)
}

const onGalleryClose = () => {
}

const openByUrl = (url: string) => {
  const index = imageUrls.value.indexOf(url)
  if (index >= 0) imageGalleryRef.value?.open(index)
}

defineExpose({ openByUrl })


// 添加附件
const addAttachment = () => {
  showUploadDialog.value = true
}

// 上传成功回调
const onUploaded = () => {
  emit('attachment-uploaded')
}

// 删除附件
const deleteAttachment = (attachment: any) => {
  emit('delete-attachment', attachment)
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  // 如果图片加载失败，尝试重新加载（可能文件正在下载中）
  if (img.src && !img.src.includes('?retry=')) {
    setTimeout(() => {
      img.src = img.src.split('?')[0] + '?retry=' + Date.now()
    }, 1000)
  }
}
</script>

<style scoped>
/* 媒体区域 */
.media-section {
  margin-bottom: 24px;
}

.media-section:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.section-title-link {
  text-decoration: none;
  color: inherit;
}

.section-title-link:hover h4 {
  text-decoration: underline;
}

.add-attachment-btn {
  color: #6b7280;
  transition: color 0.2s ease;
}

.add-attachment-btn:hover {
  color: #374151;
}

/* 图片附件网格布局 */
.image-attachment-list {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
  width: 100%;
  margin-bottom: 12px;
}

.image-attachment-item {
  width: 100%;
  min-height: 0;
}

/* 普通附件列表布局 */
.file-attachment-list {
  display: flex;
  flex-direction: column;
  gap: 0;
  width: 100%;
}

.file-attachment-item {
  width: 100%;
  min-height: 0;
}


.image-attachment img {
  width: 100%;
  height: auto;
  border-radius: 8px;
  object-fit: contain;
  cursor: pointer;
  transition: transform 0.2s ease;
  overflow: hidden !important;
}

.image-container {
  position: relative;
  border-radius: 12px;
}

.image-attachment img:hover {
  transform: scale(1.02);
}

.image-overlay {
  position: absolute;
  top: 4px;
  right: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
  z-index: 10;
}

.image-container img:hover + .image-overlay,
.image-container .image-overlay:hover {
  opacity: 1;
}

.delete-btn {
  width: 20px;
  height: 20px;
  border: none;
  border-radius: 50%;
  background: rgba(239, 68, 68, 0.9);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 12px;
  backdrop-filter: blur(4px);
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
}

.delete-btn:hover {
  background: rgba(220, 38, 38, 0.95);
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
}

.image-filename {
  text-align: center;
}

.image-filename .file-name {
  font-size: 11px;
  color: #374151;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  display: block;
  width: 100%;
}

.file-name-link {
  font-size: 11px;
  color: #374151;
  text-decoration: none;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  display: block;
  width: 100%;
  transition: color 0.2s ease;
}

.file-name-link:hover {
  color: #374151;
  text-decoration: underline;
}

/* 普通附件样式 */
.file-attachment {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 0;
  border-bottom: 1px solid #e5e7eb;
}

.attachment-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background: #e5e7eb;
  border-radius: 4px;
  color: #6b7280;
  flex-shrink: 0;
}

.attachment-info {
  flex: 1;
  min-width: 0;
}

.file-name-container {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
}

.file-name-link {
  font-size: 12px;
  font-weight: 500;
  color: #1f2937;
  text-decoration: none;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  flex: 1;
  transition: color 0.2s ease;
}

.file-name-link:hover {
  color: #1f2937;
  text-decoration: underline;
}

/* 内联删除按钮样式 */
.delete-btn-inline {
  width: 16px;
  height: 16px;
  border: none;
  border-radius: 50%;
  background: rgba(239, 68, 68, 0.9);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 10px;
  margin-left: 8px;
  opacity: 0;
  transform: scale(0.8);
  flex-shrink: 0;
}

.file-name-container:hover .delete-btn-inline {
  opacity: 1;
  transform: scale(1);
}

.delete-btn-inline:hover {
  background: rgba(220, 38, 38, 0.95);
  transform: scale(1.1);
}

/* 添加附件占位符 */
.add-attachment-placeholder {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.add-button {
  width: 100%;
}

/* 更多附件按钮 */
.load-more-container {
  display: flex;
  justify-content: center;
  padding: 12px 0;
  margin-top: 8px;
}

.load-more-btn {
  color: #6b7280;
  font-size: 12px;
  transition: color 0.2s ease;
}

.load-more-btn:hover {
  color: #374151;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .image-attachment-list {
    grid-template-columns: 1fr;
  }
  
  .file-attachment-list {
    display: flex;
    flex-direction: column;
  }
}
</style>
