<template>
  <div class="image-uploader">
    <!-- 图片上传区域 -->
    <div class="upload-area"
         @drop.prevent="handleDrop"
         @dragover.prevent="dragover = true"
         @dragleave.prevent="dragover = false"
         :class="{ 'is-dragover': dragover }">
      
      <!-- 预览区域 -->
      <div v-if="previewUrls.length" class="preview-list">
        <div v-for="(url, index) in previewUrls" 
             :key="index" 
             class="preview-item">
          <img :src="url" alt="preview" class="preview-image">
          <div class="preview-overlay">
            <button @click="removeImage(index)" 
                    class="remove-btn">
              ✕
            </button>
          </div>
        </div>
        
        <!-- 添加更多按钮 -->
        <div v-if="canAddMore" 
             class="add-more"
             @click="triggerFileInput">
          <span>+</span>
        </div>
      </div>
      
      <!-- 上传提示区域 -->
      <div v-else class="upload-placeholder" @click="triggerFileInput">
        <i class="fas fa-cloud-upload-alt text-4xl mb-2"></i>
        <p>点击或拖拽图片到此处上传</p>
        <p class="text-sm text-gray-500">
          支持 jpg、png、gif 格式，单张大小不超过 5MB
        </p>
      </div>
    </div>

    <!-- 隐藏的文件输入框 -->
    <input type="file"
           ref="fileInput"
           class="hidden"
           accept="image/*"
           :multiple="multiple"
           @change="handleFileChange">
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useToast } from '../composables/useToast'

export default {
  name: 'ImageUploader',
  props: {
    multiple: {
      type: Boolean,
      default: true
    },
    maxFiles: {
      type: Number,
      default: 9
    },
    maxSize: {
      type: Number,
      default: 5 * 1024 * 1024 // 5MB
    }
  },
  
  emits: ['upload', 'remove'],
  
  setup(props, { emit }) {
    const fileInput = ref(null)
    const dragover = ref(false)
    const previewUrls = ref([])
    const { showToast } = useToast()

    const canAddMore = computed(() => {
      return props.multiple && previewUrls.value.length < props.maxFiles
    })

    const triggerFileInput = () => {
      if (canAddMore.value || !previewUrls.value.length) {
        fileInput.value.click()
      }
    }

    const validateFile = (file) => {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        showToast('请上传图片文件', 'error')
        return false
      }

      // 检查文件大小
      if (file.size > props.maxSize) {
        showToast(`图片大小不能超过 ${props.maxSize / 1024 / 1024}MB`, 'error')
        return false
      }

      return true
    }

    const processFiles = (files) => {
      const validFiles = Array.from(files).filter(validateFile)
      
      if (!validFiles.length) return
      
      // 检查文件数量限制
      if (previewUrls.value.length + validFiles.length > props.maxFiles) {
        showToast(`最多只能上传 ${props.maxFiles} 张图片`, 'warning')
        return
      }

      // 处理每个文件
      validFiles.forEach(file => {
        const reader = new FileReader()
        reader.onload = (e) => {
          previewUrls.value.push(e.target.result)
          emit('upload', file)
        }
        reader.readAsDataURL(file)
      })
    }

    const handleFileChange = (event) => {
      const files = event.target.files
      if (!files.length) return
      
      processFiles(files)
      event.target.value = '' // 重置input，允许上传相同文件
    }

    const handleDrop = (event) => {
      dragover.value = false
      const files = event.dataTransfer.files
      if (!files.length) return
      
      processFiles(files)
    }

    const removeImage = (index) => {
      previewUrls.value.splice(index, 1)
      emit('remove', index)
    }

    return {
      fileInput,
      dragover,
      previewUrls,
      canAddMore,
      triggerFileInput,
      handleFileChange,
      handleDrop,
      removeImage
    }
  }
}
</script>

<style scoped>
.image-uploader {
  width: 100%;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  transition: all 0.3s;
}

.upload-area.is-dragover {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
}

.upload-placeholder {
  cursor: pointer;
  padding: 20px;
}

.preview-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 8px;
}

.preview-item {
  position: relative;
  aspect-ratio: 1;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.preview-item:hover .preview-overlay {
  opacity: 1;
}

.remove-btn {
  color: white;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 20px;
}

.add-more {
  aspect-ratio: 1;
  border: 2px dashed #ddd;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 24px;
  color: #999;
}

.add-more:hover {
  border-color: #409eff;
  color: #409eff;
}
</style>
