<template>
  <div class="upload-container">
    <el-upload 
      ref="uploadRef"
      action="#" 
      list-type="picture-card" 
      :auto-upload="false"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :on-change="handleFileChange"
      :before-upload="beforeUpload"
      :limit="1"
      :on-exceed="handleExceed"
      accept="image/*"
      class="custom-upload"
    >
      <template #trigger>
        <div class="upload-area">
          <el-icon class="plus-icon"><Plus /></el-icon>
          <div class="upload-text">点击上传图片</div>
        </div>
      </template>
      
      <template #tip>
        <div class="el-upload__tip">
          <el-icon><InfoFilled /></el-icon>
          <span>支持 JPG/PNG 格式，大小不超过 2MB</span>
        </div>
      </template>

      <template #file="{ file }">
        <div class="uploaded-file-container">
          <img 
            class="el-upload-list__item-thumbnail" 
            :src="file.url" 
            :alt="file.name || '上传的图片'" 
          />
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-preview"
              @click.stop="handlePictureCardPreview(file)"
              title="预览"
            >
              <el-icon><ZoomIn /></el-icon>
            </span>
            <span
              class="el-upload-list__item-delete"
              @click.stop="handleRemove(file)"
              title="删除"
            >
              <el-icon><Delete /></el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>

    <el-button 
      v-if="fileList.length > 0"
      type="primary" 
      class="confirm-upload-btn"
      @click="handleConfirmUpload"
      :loading="uploading"
      round
    >
      <el-icon class="btn-icon"><Upload /></el-icon>
      <span>确认上传</span>
    </el-button>

    <el-dialog v-model="dialogVisible" title="图片预览" width="70%">
      <div class="preview-container">
        <img 
          class="preview-image" 
          :src="dialogImageUrl" 
          alt="预览图片" 
        />
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { Delete, Plus, ZoomIn, Upload, InfoFilled } from '@element-plus/icons-vue'
import type { UploadFile, UploadInstance, UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'

const uploadRef = ref<UploadInstance>()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileList = ref<UploadFile[]>([])
const uploading = ref(false)
const emit = defineEmits(['changeAerialView'])

const handleFileChange: UploadProps['onChange'] = (file, files) => {
  if (file.status === 'ready') {
    fileList.value = files
  }
}

const handleRemove: UploadProps['onRemove'] = (file) => {
  fileList.value = fileList.value.filter(item => item.uid !== file.uid)
  ElMessage.success(`已移除 ${file.name}`)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (file) => {
  if (!file.url) {
    ElMessage.warning('无法预览：图片URL无效')
    return
  }
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const validTypes = ['image/jpeg', 'image/png', 'image/webp']
  const isJpgOrPng = validTypes.includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('只能上传 JPG/PNG 格式图片!')
    return false
  }

  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  return true
}

const handleExceed: UploadProps['onExceed'] = (files) => {
  ElMessage.warning('只能上传一张图片，已替换为最新选择的图片')
  
  // 保留最新选择的文件
  const newFile = files[0]
  fileList.value = [{
    uid: newFile.uid,
    name: newFile.name,
    size: newFile.size,
    raw: newFile,
    url: URL.createObjectURL(newFile)
  }]
  
}

const handleConfirmUpload = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择要上传的图片')
    return
  }

  uploading.value = true
  
  try {
    const file = fileList.value[0].raw
    if (!file) {
      throw new Error('文件不存在')
    }
    
    // 模拟上传过程
    // console.log(".00000000000000000.",fileList.value[0].url)
    // await new Promise(resolve => setTimeout(resolve, 1500))
    emit('changeAerialView', fileList.value[0].url)

    // 实际项目中可能是这样的：
    // const formData = new FormData()
    // formData.append('file', file)
    // await axios.post('/api/upload', formData)

    
    ElMessage.success('图片上传成功')
    fileList.value = []
    uploadRef.value?.clearFiles()
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败，请重试')
  } finally {
    uploading.value = false
  }
}
</script>

<style scoped>
.upload-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.custom-upload {
  :deep(.el-upload) {
    width: 148px;
    height: 148px;
    border: 1px dashed var(--el-border-color);
    border-radius: 8px;
    transition: all 0.2s;
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: var(--el-text-color-secondary);
  transition: all 0.2s;
}

.plus-icon {
  font-size: 28px;
  margin-bottom: 8px;
  color: var(--el-text-color-secondary);
}

.upload-text {
  font-size: 14px;
  text-align: center;
}

.el-upload__tip {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
  
  .el-icon {
    margin-right: 6px;
    font-size: 14px;
  }
}

.uploaded-file-container {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.el-upload-list__item-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.el-upload-list__item-actions {
  position: absolute;
  inset: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
  
  .el-upload-list__item-preview,
  .el-upload-list__item-delete {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    color: #fff;
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
      background-color: rgba(255, 255, 255, 0.3);
      transform: scale(1.1);
    }
    
    .el-icon {
      font-size: 16px;
    }
  }
}

.uploaded-file-container:hover .el-upload-list__item-actions {
  opacity: 1;
}

.confirm-upload-btn {
  align-self: flex-start;
  margin-top: 16px;
  padding: 10px 24px;
  
  .btn-icon {
    margin-right: 6px;
  }
}

.preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60vh;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
</style>