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

<script setup>
import { ref,defineEmits } from 'vue'
import {staffAvatorApi} from '../../../api/other' 
import { Delete, Plus, ZoomIn, InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { message } from 'ant-design-vue'

// 获取父组件传递的值
const emits = defineEmits(['getAvatar'])
const props = defineProps(['updataImageCount'])

// 组件引用
const uploadRef = ref(null)
// 对话框状态
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// 文件列表状态
const fileList = ref([])
// 上传状态
const uploading = ref(false)
// 事件派发


/**
 * 文件变化处理
 */
const handleFileChange = (file, files) => {
    
  if (file.status === 'ready') {
    fileList.value = files
    // console.log('文件列表', fileList.value[0].url)
    try {
      staffAvatorApi({file:fileList.value[0].raw}).then(res => { 
        emits('getAvatar',  res.fileAddress)
      })
      
    } catch (error) {
      message.error('上传失败',err)
    }
    
  }
}

/**
 * 删除文件处理
 */
const handleRemove = (file) => {
  console.log('删除文件',file)

  if (file) {
    fileList.value = fileList.value.filter(item => item.uid !== file.uid)
    ElMessage.success(`已移除 ${file.name}`)
  }else {
    fileList.value = []
  }
  
   
}
// 暴露方法给父组件
defineExpose({
  handleRemove,
});
/**
 * 预览图片处理
 */
const handlePictureCardPreview = (file) => {
  if (!file.url) {
    ElMessage.warning('无法预览：图片URL无效')
    return
  }
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

/**
 * 上传前验证
 */
const 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 = (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('文件不存在')
    }
    
    // 模拟上传过程
    // await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 触发父组件事件传递图片URL
    emit('changeAerialView', fileList.value[0].url)
    
    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>