<template>
  <div class="file-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>文件管理</span>
          <el-button type="primary" @click="handleUpload">
            <el-icon><Upload /></el-icon>
            上传文件
          </el-button>
        </div>
      </template>

      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="文件名">
          <el-input v-model="searchForm.filename" placeholder="请输入文件名" clearable />
        </el-form-item>
        <el-form-item label="文件类型">
          <el-select v-model="searchForm.fileType" placeholder="请选择" clearable style="width: 140px">
            <el-option label="全部类型" value="" />
            <el-option label="图片" value="image">
              <el-icon style="margin-right: 6px; vertical-align: middle"><Picture /></el-icon>
              <span style="vertical-align: middle">图片</span>
            </el-option>
            <el-option label="文档" value="document">
              <el-icon style="margin-right: 6px; vertical-align: middle"><Document /></el-icon>
              <span style="vertical-align: middle">文档</span>
            </el-option>
            <el-option label="视频" value="video">
              <el-icon style="margin-right: 6px; vertical-align: middle"><VideoCamera /></el-icon>
              <span style="vertical-align: middle">视频</span>
            </el-option>
            <el-option label="音频" value="audio">
              <el-icon style="margin-right: 6px; vertical-align: middle"><Headset /></el-icon>
              <span style="vertical-align: middle">音频</span>
            </el-option>
            <el-option label="其他" value="other">
              <el-icon style="margin-right: 6px; vertical-align: middle"><Files /></el-icon>
              <span style="vertical-align: middle">其他</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="filename" label="文件名" min-width="200">
          <template #default="{ row }">
            <div class="file-name-cell">
              <el-icon class="file-icon" :size="20">
                <component :is="getFileIcon(row.fileType)" />
              </el-icon>
              <span class="filename">{{ row.filename }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="fileType" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getFileTypeTag(row.fileType)" size="small">
              {{ getFileTypeText(row.fileType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小" width="100">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="uploader" label="上传者" width="120" />
        <el-table-column prop="uploadTime" label="上传时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDownload(row)">下载</el-button>
            <el-button type="primary" link @click="handlePreview(row)">预览</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pageInfo.page"
          v-model:page-size="pageInfo.pageSize"
          :total="pageInfo.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 上传文件对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文件"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        drag
        action="/api/file/upload"
        :headers="uploadHeaders"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :file-list="fileList"
        :auto-upload="true"
        accept="*"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持上传任意类型文件，单个文件最大 100MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="文件预览"
      width="800px"
      :close-on-click-modal="true"
    >
      <div class="preview-container">
        <img v-if="previewType === 'image'" :src="previewUrl" alt="预览" class="preview-image" />
        <div v-else class="preview-not-support">
          <el-icon :size="60"><Document /></el-icon>
          <p>该文件类型暂不支持预览</p>
          <el-button type="primary" @click="handleDownload(currentFile)">下载查看</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, UploadFilled, Document, Picture, VideoCamera, Headset, Files } from '@element-plus/icons-vue'
import type { UploadFile, UploadInstance } from 'element-plus'
import { http } from '@/utils/request'

const loading = ref(false)
const uploadDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const previewUrl = ref('')
const previewType = ref('')
const currentFile = ref<any>(null)
const uploadRef = ref<UploadInstance>()
const fileList = ref<UploadFile[]>([])

const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token') || ''
  return {
    Authorization: `Bearer ${token}`
  }
})

const searchForm = reactive({
  filename: '',
  fileType: ''
})

const pageInfo = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

const tableData = ref<any[]>([])

// 获取文件图标
const getFileIcon = (fileType: string) => {
  const iconMap: Record<string, any> = {
    image: Picture,
    document: Document,
    video: VideoCamera,
    audio: Headset,
    other: Files
  }
  return iconMap[fileType] || Files
}

// 获取文件类型标签样式
const getFileTypeTag = (fileType: string) => {
  const typeMap: Record<string, any> = {
    image: 'success',
    document: 'primary',
    video: 'warning',
    audio: 'info',
    other: ''
  }
  return typeMap[fileType] || ''
}

// 获取文件类型文本
const getFileTypeText = (fileType: string) => {
  const textMap: Record<string, string> = {
    image: '图片',
    document: '文档',
    video: '视频',
    audio: '音频',
    other: '其他'
  }
  return textMap[fileType] || '其他'
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const handleSearch = () => {
  ElMessage.success('搜索成功')
  // 实际项目中这里调用 API 获取数据
  fetchFileList()
}

const handleReset = () => {
  searchForm.filename = ''
  searchForm.fileType = ''
  fetchFileList()
}

const fetchFileList = async () => {
  loading.value = true
  try {
    const res = await http.get<{ list: any[], total: number }>('/file/list', {
      page: pageInfo.page,
      size: pageInfo.pageSize,
      ...searchForm
    })
    tableData.value = res.list
    pageInfo.total = res.total
  } catch (error) {
    console.error('获取文件列表失败:', error)
    ElMessage.error('获取文件列表失败')
  } finally {
    loading.value = false
  }
}

const handleUpload = () => {
  uploadDialogVisible.value = true
  fileList.value = []
}

const beforeUpload = (file: File) => {
  const maxSize = 100 * 1024 * 1024 // 100MB
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过 100MB')
    return false
  }
  return true
}

const handleUploadSuccess = (response: any) => {
  ElMessage.success('上传成功')
  fetchFileList()
}

const handleUploadError = (error: any) => {
  ElMessage.error('上传失败，请重试')
}

const handleDownload = (row: any) => {
  http.download('/file/download', { id: row.id }, row.filename)
    .then(() => {
      ElMessage.success('开始下载')
    })
    .catch(() => {
      ElMessage.error('下载失败')
    })
}

const handlePreview = (row: any) => {
  currentFile.value = row
  if (row.fileType === 'image') {
    previewType.value = 'image'
    previewUrl.value = row.url || '/api/file/preview/' + row.id
    previewDialogVisible.value = true
  } else {
    previewType.value = 'other'
    previewDialogVisible.value = true
  }
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除文件 "${row.filename}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await http.delete('/file/delete', { id: row.id })
      ElMessage.success('删除成功')
      fetchFileList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

const handleSizeChange = (val: number) => {
  pageInfo.pageSize = val
  pageInfo.page = 1
  fetchFileList()
}

const handleCurrentChange = (val: number) => {
  pageInfo.page = val
  fetchFileList()
}

// 初始化
fetchFileList()
</script>

<style scoped lang="scss">
.file-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .file-name-cell {
    display: flex;
    align-items: center;
    gap: 8px;

    .file-icon {
      color: #409EFF;
      flex-shrink: 0;
    }

    .filename {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .preview-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;

    .preview-image {
      max-width: 100%;
      max-height: 600px;
    }

    .preview-not-support {
      text-align: center;
      color: #909399;

      p {
        margin: 16px 0;
      }
    }
  }
}
</style>
