<template>
  <div class="space-y-6">
    <!-- 上传卡片 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
      <div class="border-b border-gray-200 pb-4 mb-6">
        <h2 class="text-xl font-semibold text-gray-800 flex items-center gap-2">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
          </svg>
          文件上传
        </h2>
      </div>

      <!-- 上传表单 -->
      <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules" label-width="120px">
        <el-form-item label="业务分类" prop="businessType">
          <el-select @change="handleBusinessTypeChange" v-model="uploadForm.businessType" placeholder="请选择业务分类" style="width: 100%">
            <el-option label="创意" :value="1"></el-option>
            <el-option label="品牌形象" :value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文件类型" prop="fileType">
          <el-select @change="handleFileTypeChange" v-model="uploadForm.fileType" placeholder="请选择文件类型" style="width: 100%" :disabled="uploadForm.businessType === 2">
            <el-option label="图片" value="image"></el-option>
            <el-option label="视频" value="video" v-if="uploadForm.businessType !== 2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择文件" prop="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="20"
            multiple
            :accept="fileAccept"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :on-exceed="handleExceed"
            :file-list="uploadFileList"
            drag>
            <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">
                <template v-if="uploadForm.businessType === 2">
                  品牌形象图片要求：尺寸 512x512，大小不超过 400KB，格式：jpg/jpeg/png，最多20个文件
                </template>
                <template v-else-if="uploadForm.fileType === 'image'">
                  支持 jpg/png/gif 格式图片，最多20个文件，单个文件不超过 10MB
                </template>
                <template v-else>
                  支持 mp4/mov/avi 格式视频，最多20个文件，单个文件建议不超过100MB
                </template>
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <div class="flex gap-3 pt-4">
          <el-button type="primary" @click="submitUpload" :loading="uploading" class="btn-primary">
            {{ uploading ? '上传中...' : '上传文件' }}
          </el-button>
          <el-button @click="resetForm" class="btn-secondary">重置</el-button>
        </div>
      </el-form>
    </div>

    <!-- 文件列表 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
      <div class="flex items-center justify-between mb-6 pb-4 border-b border-gray-200">
        <h2 class="text-xl font-semibold text-gray-800 flex items-center gap-2">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-purple-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
          文件列表
        </h2>
        <el-button type="primary" size="small" @click="loadFileList">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
          </svg>
          刷新
        </el-button>
      </div>

      <!-- 筛选条件 -->
      <div class="mb-6 p-4 bg-gray-50 rounded-lg">
        <el-form :inline="true" :model="queryForm" class="flex flex-wrap gap-4">
          <el-form-item label="业务分类">
            <el-select v-model="queryForm.businessType" placeholder="全部分类" clearable style="width: 150px">
              <el-option label="创意" :value="1"></el-option>
              <el-option label="品牌形象" :value="2"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="文件类型">
            <el-select v-model="queryForm.fileType" placeholder="全部类型" clearable style="width: 150px">
              <el-option label="图片" value="image"></el-option>
              <el-option label="视频" value="video"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="文件名">
            <el-input v-model="queryForm.fileName" placeholder="请输入文件名" clearable style="width: 200px"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 批量操作 -->
      <div class="mb-4 flex items-center gap-3" v-if="selectedFiles.length > 0">
        <span class="text-sm text-gray-600">已选择 {{ selectedFiles.length }} 项</span>
        <el-button type="danger" size="small" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <!-- 文件表格 -->
      <el-table 
        :data="fileList" 
        v-loading="loading"
        @sort-change="handleSortChange"
        :default-sort="{ prop: 'normalCnt', order: 'descending' }"
        style="width: 100%"
        :header-cell-style="{ background: '#f9fafb', color: '#374151', fontWeight: '600' }">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="assetId" label="资产ID" width="120"></el-table-column>
        <el-table-column prop="normalCnt" label="审核通过数" width="120" sortable="custom"></el-table-column>
        <el-table-column prop="deniedCnt" label="审核拒绝数" width="120" sortable="custom"></el-table-column>
        <el-table-column prop="businessType" label="业务分类" width="120">
          <template #default="{ row }">
            <el-tag :type="row.businessType === 1 ? 'primary' : 'success'" size="small">
              {{ row.businessType === 1 ? '创意' : '品牌形象' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="文件预览" width="120">
          <template #default="{ row }">
            <div v-if="row.fileType === 'image'" class="w-20 h-20 overflow-hidden rounded border border-gray-200">
              <img :src="row.fileUrl" alt="预览" class="w-full h-full object-cover cursor-pointer" @click="previewFile(row)">
            </div>
            <div v-else class="w-20 h-20 flex items-center justify-center bg-gray-100 rounded border border-gray-200">
              <svg @click="previewFile(row)" xmlns="http://www.w3.org/2000/svg" class="h-10 w-10 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="originalFileName" label="文件名" min-width="200" show-overflow-tooltip></el-table-column>
        
        <el-table-column prop="fileType" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getFileTypeColor(row.fileType)" size="small">{{ getFileTypeLabel(row.fileType) }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="fileSize" label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column prop="fileMd5" label="MD5" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="goToCreativeList(row.fileMd5)">
              {{ row.fileMd5 }}
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column prop="folder" label="存储路径" width="150" show-overflow-tooltip></el-table-column>
        
        <el-table-column prop="createdByName" label="上传人" width="120"></el-table-column>
        
        <el-table-column prop="createdTime" label="上传时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="flex gap-2">
              <el-button type="primary" size="small" link @click="copyUrl(row)">复制链接</el-button>
              <el-button type="primary" size="small" link @click="downloadFile(row)">下载</el-button>
              <el-button type="danger" size="small" link @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-6 flex justify-end">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="800px">
      <div class="flex justify-center">
        <img :src="previewUrl" alt="预览" style="max-width: 100%; max-height: 600px;">
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
defineOptions({
  name: 'OssFile'
})

import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { uploadFile, getFileList, deleteFile, batchDeleteFiles } from '@/api/ossFile'

const router = useRouter()

// 上传表单
const uploadFormRef = ref(null)
const uploadRef = ref(null)
const uploadForm = reactive({
  businessType: 1,
  fileType: 'image',
  folder: 'images/',
  files: []
})

const handleBusinessTypeChange = (value) => {
  uploadForm.businessType = value
  // 品牌形象只能选图片
  if (value === 2) {
    uploadForm.fileType = 'image'
    uploadForm.folder = 'images/'
  }
  // 切换业务类型时清空已选文件
  clearSelectedFiles()
}

const handleFileTypeChange = (value) => {
  uploadForm.fileType = value
  if (value === 'image') {
    uploadForm.folder = 'images/'
  } else if (value === 'video') {
    uploadForm.folder = 'videos/'
  }
  // 切换文件类型时清空已选文件
  clearSelectedFiles()
}

// 清空已选文件
const clearSelectedFiles = () => {
  uploadRef.value?.clearFiles()
  uploadFileList.value = []
  uploadForm.files = []
}

const uploadRules = {
  businessType: [{ required: true, message: '请选择业务分类', trigger: 'change' }],
  fileType: [{ required: true, message: '请选择文件类型', trigger: 'change' }],
}

const uploadFileList = ref([])
const uploading = ref(false)

// 根据文件类型计算接受的文件格式
const fileAccept = computed(() => {
  if (uploadForm.fileType === 'image') {
    // 品牌形象只接受 jpg/jpeg/png
    if (uploadForm.businessType === 2) {
      return 'image/jpeg,image/png'
    }
    // 非品牌形象图片：jpg、png、gif
    return 'image/jpeg,image/png,image/gif'
  } else if (uploadForm.fileType === 'video') {
    return 'video/mp4,video/quicktime,video/x-msvideo'
  }
  return ''
})

// 验证品牌形象图片
const validateBrandImage = (file) => {
  return new Promise((resolve, reject) => {
    // 验证文件大小（400KB = 400 * 1024 bytes）
    const maxSize = 400 * 1024
    if (file.size > maxSize) {
      reject(`图片大小不能超过 400KB，当前大小：${formatFileSize(file.size)}`)
      return
    }

    // 验证图片尺寸
    const img = new Image()
    img.onload = () => {
      if (img.width !== 512 || img.height !== 512) {
        reject(`图片尺寸必须为 512x512，当前尺寸：${img.width}x${img.height}`)
      } else {
        resolve(true)
      }
    }
    img.onerror = () => {
      reject('图片加载失败，请检查文件格式')
    }
    img.src = URL.createObjectURL(file)
  })
}

// 查询表单
const queryForm = reactive({
  businessType: null,
  fileType: '',
  fileName: ''
})

// 文件列表
const fileList = ref([])
const loading = ref(false)
const selectedFiles = ref([])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 排序
const sortParams = reactive({
  sortField: 'normalCnt',
  sortOrder: 'descending'
})

// 预览
const previewVisible = ref(false)
const previewUrl = ref('')

// 验证普通图片
const validateNormalImage = (file) => {
  return new Promise((resolve, reject) => {
    // 验证文件大小（10MB = 10 * 1024 * 1024 bytes）
    const maxSize = 10 * 1024 * 1024
    if (file.size > maxSize) {
      reject(`图片大小不能超过 10MB，当前大小：${formatFileSize(file.size)}`)
      return
    }
    resolve(true)
  })
}

// 文件选择
const handleFileChange = async (file, fileList) => {
  const rawFile = file.raw
  
  // 如果是品牌形象图片，进行额外验证
  if (uploadForm.businessType === 2) {
    // 验证文件格式
    const validTypes = ['image/jpeg', 'image/png', 'image/jpg']
    if (!validTypes.includes(rawFile.type)) {
      ElMessage.error('品牌形象图片仅支持 jpg、jpeg、png 格式')
      uploadRef.value?.handleRemove(file)
      return
    }
    
    try {
      await validateBrandImage(rawFile)
    } catch (error) {
      ElMessage.error(error)
      uploadRef.value?.handleRemove(file)
      return
    }
  } else if (uploadForm.fileType === 'image') {
    // 非品牌形象图片验证
    const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg']
    if (!validTypes.includes(rawFile.type)) {
      ElMessage.error('图片仅支持 jpg、jpeg、png、gif 格式')
      uploadRef.value?.handleRemove(file)
      return
    }
    
    try {
      await validateNormalImage(rawFile)
    } catch (error) {
      ElMessage.error(error)
      uploadRef.value?.handleRemove(file)
      return
    }
  }
  
  uploadForm.files = fileList.map(f => f.raw)
}

// 文件移除
const handleFileRemove = (file, fileList) => {
  uploadForm.files = fileList.map(f => f.raw)
}

const handleExceed = () => {
  ElMessage.warning('最多只能上传20个文件')
}

// 提交上传
const submitUpload = async () => {
  if (!uploadFormRef.value) return
  
  await uploadFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    if (!uploadForm.files || uploadForm.files.length === 0) {
      ElMessage.warning('请选择文件')
      return
    }

    uploading.value = true
    let successCount = 0
    let failCount = 0

    for (const file of uploadForm.files) {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('folder', uploadForm.folder)
      formData.append('fileType', uploadForm.fileType)
      formData.append('businessType', uploadForm.businessType)

      try {
        const res = await uploadFile(formData)
        if (res.success) {
          successCount++
        } else {
          failCount++
        }
      } catch (error) {
        console.error('上传失败:', error)
        failCount++
      }
    }

    uploading.value = false

    if (successCount > 0 && failCount === 0) {
      ElMessage.success(`${successCount}个文件上传成功`)
      resetForm()
      loadFileList()
    } else if (successCount > 0 && failCount > 0) {
      ElMessage.warning(`上传完成：${successCount}个成功，${failCount}个失败`)
      resetForm()
      loadFileList()
    } else {
      ElMessage.error('所有文件上传失败')
    }
  })
}

// 重置表单
const resetForm = () => {
  uploadFormRef.value?.resetFields()
  uploadRef.value?.clearFiles()
  uploadFileList.value = []
  uploadForm.files = []
}

// 加载文件列表
const loadFileList = async () => {
  loading.value = true
  try {
    const res = await getFileList({
      page: pagination.page,
      size: pagination.size,
      fileType: queryForm.fileType,
      businessType: queryForm.businessType,
      fileName: queryForm.fileName,
      sortField: sortParams.sortField,
      sortOrder: sortParams.sortOrder
    })
    if (res.success) {
      fileList.value = res.data.records
      pagination.total = res.data.total
    } else {
      ElMessage.error(res.message || '查询失败')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

// 排序变化
const handleSortChange = ({ prop, order }) => {
  if (order) {
    sortParams.sortField = prop
    sortParams.sortOrder = order
  } else {
    sortParams.sortField = ''
    sortParams.sortOrder = ''
  }
  loadFileList()
}

// 查询
const handleQuery = () => {
  pagination.page = 1
  loadFileList()
}

// 重置查询
const handleReset = () => {
  queryForm.businessType = null
  queryForm.fileType = ''
  queryForm.fileName = ''
  handleQuery()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedFiles.value = selection
}

// 删除文件
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该文件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteFile(row.id)
    if (res.success) {
      ElMessage.success('删除成功')
      loadFileList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedFiles.value.length} 个文件吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const fileIds = selectedFiles.value.map(item => item.id)
    const res = await batchDeleteFiles(fileIds)
    if (res.success) {
      ElMessage.success('批量删除成功')
      loadFileList()
    } else {
      ElMessage.error(res.message || '批量删除失败')
    }
  })
}

// 复制URL
const copyUrl = (row) => {
  navigator.clipboard.writeText(row.fileUrl).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 下载文件
const downloadFile = (row) => {
  window.open(row.fileUrl, '_blank')
}

// 预览文件
const previewFile = (row) => {
  if (row.fileType === 'image') {
    previewUrl.value = row.fileUrl
    previewVisible.value = true
  } else {
    window.open(row.fileUrl, '_blank')
  }
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  loadFileList()
}

const handlePageChange = (page) => {
  pagination.page = page
  loadFileList()
}

// 工具函数
const getFileTypeLabel = (type) => {
  const labels = {
    image: '图片',
    video: '视频',
    document: '文档',
    other: '其他'
  }
  return labels[type] || type
}

const getFileTypeColor = (type) => {
  const colors = {
    image: 'success',
    video: 'primary',
    document: 'warning',
    other: 'info'
  }
  return colors[type] || 'info'
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return dateTime.replace('T', ' ')
}

// 跳转到创意列表
const goToCreativeList = (md5) => {
  if (!md5) {
    ElMessage.warning('MD5为空，无法跳转')
    return
  }
  router.push({
    path: '/ad-plan-creative',
    query: { md5: md5 }
  })
}

// 初始化
onMounted(() => {
  loadFileList()
})
</script>

<style scoped>
.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
}

.btn-primary:hover {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
}

.btn-secondary {
  border-color: #e5e7eb;
  color: #6b7280;
}

.btn-secondary:hover {
  background-color: #f9fafb;
}

:deep(.el-upload-dragger) {
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  background-color: #f9fafb;
  transition: all 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: #667eea;
  background-color: #f3f4f6;
}
</style>
