<template>
  <div class="uploadImage">
    <div v-for="(image, index) in photos" :key="index" class="image-item">
      <img :src="image" width="100" height="100" />
      <i class="el-icon-close remove-icon" @click="removeImage(index)"></i>
    </div>
    <div v-if="photos.length < imageCount" class="upload-button" @click="triggerUpload">
      <i class="el-icon-plus"></i>
    </div>
    <input type="file" ref="fileInput" accept="image/*" hidden @change="handleFileChange">
  </div>
</template>

<script>
export default {
  name: 'UploadImageUrl',
  props: {
    imageCount: {
      type: Number,
      default: 99
    }
  },
  data() {
    return {
      photos: [],
      photosUrl: []
    }
  },
  watch: {
    photosUrl: {
      handler(val) {
        this.$emit('update:photosUrl', val)
      },
      deep: true
    }
  },
  methods: {
    triggerUpload() {
      this.$refs.fileInput.click()
    },
    handleFileChange(event) {
      const file = event.target.files[0]
      if (!file) return
      
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error(this.$t('enterCommunity.fileSizeError'))
        return
      }
      
      const reader = new FileReader()
      reader.onload = (e) => {
        this.photos.push(e.target.result)
        this.uploadImage(file)
      }
      reader.readAsDataURL(file)
      
      // 重置input
      event.target.value = null
    },
    removeImage(index) {
      this.photos.splice(index, 1)
      this.photosUrl.splice(index, 1)
    },
    uploadImage(file) {
      const formData = new FormData()
      formData.append('uploadFile', file)
      formData.append('communityId', this.$store.getters.currentCommunity.communityId)
      
      this.$http.upload('uploadFile', 'uploadImage', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then(res => {
        const data = JSON.parse(res.data)
        this.photosUrl.push({
          fileId: data.fileId,
          url: `/callComponent/download/getFile/file?fileId=${data.fileId}`
        })
      }).catch(err => {
        this.$message.error(this.$t('enterCommunity.uploadError'))
      })
    },
    setPhotos(photos) {
      this.photos = photos
    }
  }
}
</script>

<style scoped>
.uploadImage {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.image-item {
  position: relative;
  display: inline-block;
}
.remove-icon {
  position: absolute;
  top: -10px;
  right: -10px;
  color: #f56c6c;
  cursor: pointer;
  background: white;
  border-radius: 50%;
}
.upload-button {
  width: 100px;
  height: 100px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #8c939d;
  cursor: pointer;
}
.upload-button:hover {
  border-color: #409eff;
}
</style>