<template>
  <div class="upload-image-container">
    <div v-for="(image, index) in photos" :key="index" class="image-item">
      <img :src="getImageUrl(image)" @error="handleImageError" />
      <span class="remove-icon" @click="removeImage(index)">
        <i class="el-icon-delete"></i>
      </span>
    </div>
    
    <div v-if="photos.length < imageCount" class="upload-btn" @click="triggerUpload">
      <i class="el-icon-plus"></i>
    </div>
    
    <input 
      ref="fileInput"
      type="file" 
      accept="image/*" 
      style="display: none" 
      @change="handleFileChange"
    />
  </div>
</template>

<script>
import { uploadFile } from '@/api/common'

export default {
  name: 'UploadImageUrl',
  props: {
    imageCount: {
      type: Number,
      default: 99
    }
  },
  data() {
    return {
      photos: [],       // 用于显示的图片数组
      photosUrl: []     // 实际存储的图片信息数组
    }
  },
  methods: {
    triggerUpload() {
      this.$refs.fileInput.click()
    },
    async handleFileChange(event) {
      const files = event.target.files
      if (!files || files.length === 0) return

      const file = files[0]
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error(this.$t('uploadImage.validate.sizeLimit'))
        return
      }

      try {
        // 显示本地预览
        const reader = new FileReader()
        reader.onload = (e) => {
          this.photos.push(e.target.result)
        }
        reader.readAsDataURL(file)

        // 上传到服务器
        const formData = new FormData()
        formData.append('uploadFile', file)
        formData.append('communityId', this.$store.getters.communityId)

        const { data } = await uploadFile(formData)
        this.photosUrl.push(data)
        this.$emit('change', this.photosUrl)
      } catch (error) {
        this.$message.error(this.$t('uploadImage.message.uploadFailed'))
      } finally {
        event.target.value = null
      }
    },
    removeImage(index) {
      this.photos.splice(index, 1)
      this.photosUrl.splice(index, 1)
      this.$emit('change', this.photosUrl)
    },
    handleImageError(e) {
      e.target.src = '/img/noPhoto.jpg'
    },
    getImageUrl(image) {
      if (typeof image === 'string') {
        if (image.startsWith('http') || image.startsWith('https') || image.startsWith('data:')) {
          return image
        }
        return `/callComponent/download/getFile/file?fileId=${image}&communityId=-1&time=${new Date().getTime()}`
      }
      return image.url || '/img/noPhoto.jpg'
    },
    clear() {
      this.photos = []
      this.photosUrl = []
    },
    setImages(images) {
      this.photos = []
      this.photosUrl = []
      images.forEach(image => {
        if (image.startsWith('data:')) {
          this.photos.push(image)
          return
        }
        this.photosUrl.push({ fileId: image, url: image })
        this.photos.push(this.getImageUrl(image))
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-image-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;

  .image-item {
    position: relative;
    width: 100px;
    height: 100px;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .remove-icon {
      position: absolute;
      top: 0;
      right: 0;
      color: #f56c6c;
      background: rgba(255, 255, 255, 0.7);
      padding: 4px;
      cursor: pointer;
      font-size: 16px;

      &:hover {
        color: #f78989;
      }
    }
  }

  .upload-btn {
    width: 100px;
    height: 100px;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    color: #8c939d;
    font-size: 28px;
    background-color: #f5f7fa;

    &:hover {
      border-color: #409eff;
      color: #409eff;
    }
  }
}
</style>