<template>
  <div class="upload-image-container">
    <div v-for="(image, index) in photos" :key="index" class="image-item">
      <el-image
        :src="getImageUrl(image)"
        fit="cover"
        :preview-src-list="[getImageUrl(image)]"
        class="image-preview"
      >
        <div slot="error" class="image-slot">
          <i class="el-icon-picture-outline"></i>
        </div>
      </el-image>
      <i class="el-icon-close remove-icon" @click="removeImage(index)"></i>
    </div>

    <el-upload
      v-if="photos.length < imageCount"
      action=""
      :show-file-list="false"
      :before-upload="beforeUpload"
      :http-request="handleUpload"
      class="upload-button"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
  </div>
</template>

<script>
import { uploadImage } from '@/api/oa/questionAnswerManageApi'
import { getCommunityId } from '@/api/community/communityApi'

export default {
  name: 'UploadImageUrl',
  props: {
    imageCount: {
      type: Number,
      default: 99
    }
  },
  data() {
    return {
      photos: [],
      photoUrls: []
    }
  },
  methods: {
    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 || ''
    },
    setPhotos(photos) {
      this.photos = photos || []
      this.photoUrls = photos.map(photo => {
        return typeof photo === 'string' ? { fileId: photo } : photo
      })
      this.$emit('change', this.photoUrls)
    },
    clear() {
      this.photos = []
      this.photoUrls = []
      this.$emit('change', [])
    },
    beforeUpload(file) {
      const isImage = file.type.includes('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error(this.$t('uploadImage.validate.imageType'))
      }
      if (!isLt2M) {
        this.$message.error(this.$t('uploadImage.validate.imageSize'))
      }
      return isImage && isLt2M
    },
    async handleUpload({ file }) {
      try {
        const formData = new FormData()
        formData.append('uploadFile', file)
        formData.append('communityId', getCommunityId())

        const response = await uploadImage(formData)
        this.photos.push(response.data)
        this.photoUrls.push(response.data)
        this.$emit('change', this.photoUrls)
      } catch (error) {
        this.$message.error(error.message || this.$t('uploadImage.message.uploadError'))
      }
    },
    removeImage(index) {
      this.photos.splice(index, 1)
      this.photoUrls.splice(index, 1)
      this.$emit('change', this.photoUrls)
    }
  }
}
</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 #d9d9d9;
    border-radius: 6px;
    overflow: hidden;

    .image-preview {
      width: 100%;
      height: 100%;
    }

    .remove-icon {
      position: absolute;
      top: 0;
      right: 0;
      padding: 5px;
      color: #fff;
      background-color: rgba(0, 0, 0, 0.5);
      cursor: pointer;
      z-index: 10;
    }
  }

  .upload-button {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100px;
    height: 100px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    font-size: 28px;
    color: #8c939d;

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