<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-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
          </svg>
          图片上传
        </h2>
      </div>

      <!-- 上传表单 -->
      <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules" label-width="120px">
        <el-form-item label="广告账户ID" prop="accountId">
          <el-input 
            v-model.number="uploadForm.accountId" 
            placeholder="请输入广告账户ID" 
            clearable
            style="width: 100%">
          </el-input>
        </el-form-item>

        <el-form-item label="选择图片" prop="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-exceed="handleExceed"
            :file-list="fileList"
            accept="image/jpeg,image/jpg,image/png"
            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">
                支持JPG、JPEG、PNG格式，文件大小不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="是否添加水印">
          <el-switch v-model="uploadForm.hasWatermark" @change="onWatermarkChange"></el-switch>
        </el-form-item>

        <el-form-item label="选择剧" prop="dramaId" v-if="uploadForm.hasWatermark">
          <el-select 
            v-model="uploadForm.dramaId" 
            placeholder="请选择剧" 
            filterable 
            style="width: 100%">
            <el-option
              v-for="drama in dramaList"
              :key="drama.id"
              :label="drama.marketingAssetName"
              :value="drama.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="图片描述">
          <el-input 
            v-model="uploadForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入图片描述（可选）"
            maxlength="500"
            show-word-limit>
          </el-input>
        </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="loadImageList">
          <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>

      <!-- 查询条件 -->
      <el-form :inline="true" :model="queryForm" class="query-form">
        <el-form-item label="账户ID">
          <el-input v-model="queryForm.accountId" placeholder="账户ID" clearable style="width: 150px"></el-input>
        </el-form-item>
        <el-form-item label="上传状态">
          <el-select v-model="queryForm.uploadStatus" placeholder="全部" clearable style="width: 120px">
            <el-option label="成功" value="SUCCESS"></el-option>
            <el-option label="失败" value="FAILED"></el-option>
          </el-select>
        </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>

      <!-- 表格 -->
      <el-table :data="imageList" border style="width: 100%" v-loading="tableLoading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="accountId" label="账户ID" width="120"></el-table-column>
        <el-table-column prop="originalFilename" label="文件名" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column label="预览" width="120">
          <template #default="scope">
            <el-image 
              v-if="scope.row.previewUrl"
              style="width: 80px; height: 60px"
              :src="scope.row.previewUrl"
              :preview-src-list="[scope.row.previewUrl]"
              fit="cover">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="imageId" label="腾讯图片ID" width="150"></el-table-column>
        <el-table-column label="尺寸" width="120">
          <template #default="scope">
            {{ scope.row.imageWidth }}x{{ scope.row.imageHeight }}
          </template>
        </el-table-column>
        <el-table-column label="大小" width="100">
          <template #default="scope">
            {{ formatFileSize(scope.row.imageFileSize) }}
          </template>
        </el-table-column>
        <el-table-column label="水印" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.hasWatermark" type="success" size="small">已添加</el-tag>
            <el-tag v-else type="info" size="small">未添加</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="watermarkText" label="水印文字" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.uploadStatus === 'SUCCESS'" type="success" size="small">成功</el-tag>
            <el-tag v-else type="danger" size="small">失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" link @click="viewDetail(scope.row)">详情</el-button>
            <el-button type="danger" size="small" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-6 flex justify-center">
        <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="detailDialogVisible" title="图片详情" width="800px">
      <el-descriptions :column="2" border v-if="currentImage">
        <el-descriptions-item label="ID">{{ currentImage.id }}</el-descriptions-item>
        <el-descriptions-item label="账户ID">{{ currentImage.accountId }}</el-descriptions-item>
        <el-descriptions-item label="腾讯图片ID">{{ currentImage.imageId }}</el-descriptions-item>
        <el-descriptions-item label="文件名">{{ currentImage.originalFilename }}</el-descriptions-item>
        <el-descriptions-item label="图片宽度">{{ currentImage.imageWidth }}px</el-descriptions-item>
        <el-descriptions-item label="图片高度">{{ currentImage.imageHeight }}px</el-descriptions-item>
        <el-descriptions-item label="图片大小">{{ formatFileSize(currentImage.imageFileSize) }}</el-descriptions-item>
        <el-descriptions-item label="图片类型">{{ currentImage.imageType }}</el-descriptions-item>
        <el-descriptions-item label="是否添加水印">
          <el-tag v-if="currentImage.hasWatermark" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="水印文字">{{ currentImage.watermarkText || '-' }}</el-descriptions-item>
        <el-descriptions-item label="上传状态">
          <el-tag v-if="currentImage.uploadStatus === 'SUCCESS'" type="success">成功</el-tag>
          <el-tag v-else type="danger">失败</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentImage.createdTime }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ currentImage.description || '-' }}</el-descriptions-item>
        <el-descriptions-item label="预览地址" :span="2">
          <el-link :href="currentImage.previewUrl" target="_blank" type="primary">{{ currentImage.previewUrl }}</el-link>
        </el-descriptions-item>
        <el-descriptions-item label="预览图" :span="2">
          <el-image 
            v-if="currentImage.previewUrl"
            style="width: 100%; max-width: 600px"
            :src="currentImage.previewUrl"
            :preview-src-list="[currentImage.previewUrl]"
            fit="contain">
          </el-image>
        </el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2" v-if="currentImage.errorMessage">
          <el-text type="danger">{{ currentImage.errorMessage }}</el-text>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

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

import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { uploadImage, getImageList, deleteImage } from '../../api/image'
import { getDramaList } from '../../api/drama'

// 上传表单
const uploadFormRef = ref()
const uploadForm = reactive({
  accountId: null,
  file: null,
  hasWatermark: false,
  dramaId: null,
  description: ''
})

// 表单验证规则
const uploadRules = {
  accountId: [
    { required: true, message: '请输入广告账户ID', trigger: 'blur' },
    { type: 'number', message: '广告账户ID必须为数字', trigger: 'blur' }
  ],
  file: [{ required: true, message: '请选择图片文件', trigger: 'change' }],
  dramaId: [{ required: true, message: '请选择剧', trigger: 'change' }]
}

// 文件列表
const fileList = ref([])
const uploadRef = ref()

// 剧列表
const dramaList = ref([])

// 上传中
const uploading = ref(false)

// 查询表单
const queryForm = reactive({
  accountId: null,
  uploadStatus: ''
})

// 图片列表
const imageList = ref([])
const tableLoading = ref(false)

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

// 详情对话框
const detailDialogVisible = ref(false)
const currentImage = ref(null)

// 加载剧列表
const loadDramaList = async () => {
  try {
    const res = await getDramaList({ page: 1, size: 1000 })
    if (res.success) {
      dramaList.value = res.data || []
    }
  } catch (error) {
    console.error('加载剧列表失败', error)
  }
}

// 水印开关变化
const onWatermarkChange = (value) => {
  if (!value) {
    uploadForm.dramaId = null
  }
}

// 文件变化
const handleFileChange = (file) => {
  uploadForm.file = file.raw
  fileList.value = [file]
}

// 文件超出限制
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件')
}

// 提交上传
// 10MB 文件大小限制
const MAX_FILE_SIZE = 10 * 1024 * 1024
const submitUpload = async () => {
  try {
    await uploadFormRef.value.validate()

    if (!uploadForm.file) {
      ElMessage.error('请选择图片文件')
      return
    }

    if (uploadForm.file.size > MAX_FILE_SIZE) {
      ElMessage.warning('图片文件大小不能超过10MB')
      return
    }

    if (uploadForm.hasWatermark && !uploadForm.dramaId) {
      ElMessage.error('添加水印时必须选择剧')
      return
    }

    uploading.value = true

    const formData = new FormData()
    formData.append('file', uploadForm.file)
    formData.append('accountId', uploadForm.accountId)
    formData.append('hasWatermark', uploadForm.hasWatermark)
    if (uploadForm.dramaId) {
      formData.append('dramaId', uploadForm.dramaId)
    }
    if (uploadForm.description) {
      formData.append('description', uploadForm.description)
    }

    const res = await uploadImage(formData)
    if (res.success) {
      ElMessage.success('图片上传成功')
      resetForm()
      loadImageList()
    } else {
      ElMessage.error(res.message || '图片上传失败')
    }
  } catch (error) {
    console.error('上传失败', error)
    if (error !== false) {  // 不是表单验证错误
      ElMessage.error('上传失败: ' + (error.message || '未知错误'))
    }
  } finally {
    uploading.value = false
  }
}

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

// 加载图片列表
const loadImageList = async () => {
  try {
    tableLoading.value = true
    const params = {
      page: pagination.page,
      size: pagination.size
    }
    if (queryForm.accountId) {
      params.accountId = queryForm.accountId
    }
    if (queryForm.uploadStatus) {
      params.uploadStatus = queryForm.uploadStatus
    }

    const res = await getImageList(params)
    if (res.success) {
      imageList.value = res.data.records || []
      pagination.total = res.data.total || 0
    }
  } catch (error) {
    console.error('加载图片列表失败', error)
    ElMessage.error('加载图片列表失败')
  } finally {
    tableLoading.value = false
  }
}

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

// 重置查询
const handleReset = () => {
  queryForm.accountId = null
  queryForm.uploadStatus = ''
  pagination.page = 1
  loadImageList()
}

// 分页大小变化
const handleSizeChange = () => {
  loadImageList()
}

// 页码变化
const handlePageChange = () => {
  loadImageList()
}

// 查看详情
const viewDetail = (row) => {
  currentImage.value = row
  detailDialogVisible.value = true
}

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

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '-'
  if (bytes < 1024) return bytes + 'B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + 'KB'
  return (bytes / 1024 / 1024).toFixed(2) + 'MB'
}

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

<style scoped>
/* 使用Tailwind CSS类替代自定义样式 */
</style>
