<template>
  <div class="upload-image-container">
    <div v-for="(image, index) in photos" :key="index" class="image-item">
      <el-image 
        :src="image" 
        fit="cover"
        style="width: 100px; height: 100px">
      </el-image>
      <i 
        class="el-icon-close remove-icon" 
        @click="_removeImage(image)">
      </i>
    </div>
    
    <div 
      v-if="photos.length < imageCount"
      class="upload-button"
      @click="_uploadPhoto">
      <i class="el-icon-plus"></i>
    </div>
    
    <input 
      type="file" 
      class="file-input" 
      accept="image/*" 
      ref="fileInput"
      hidden
      @change="_choosePhoto">
  </div>
</template>

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

export default {
  name: 'UploadImageUrl',
  props: {
    imageCount: {
      type: Number,
      default: 99
    }
  },
  data() {
    return {
      photos: [], // 显示图片数组(base64格式)
      photosUrl: [], // 向父组件传递的数组({fileId, url})
      communityId: ''
    }
  },
  created() {
    this.communityId = getCommunityId()
  },
  methods: {
    open(photos) {
      this.photos = []
      this.photosUrl = []
      
      if (!photos || photos.length === 0) return
      
      photos.forEach(photo => {
        if (photo.indexOf('base64,') > -1) {
          this.photos.push(photo)
          return
        }
        
        if (photo.indexOf("https") > -1 || photo.indexOf("http") > -1) {
          this.urlToBase64(photo)
          const urlParams = this._getUrlParams(photo)
          if (urlParams.fileId) {
            this.photosUrl.push({fileId: urlParams.fileId, url: photo})
          }
          return
        }
        
        const url = `/callComponent/download/getFile/file?fileId=${photo}&communityId=-1&time=${new Date()}`
        this.urlToBase64(url)
        this.photosUrl.push({fileId: photo, url})
      })
    },
    clear() {
      this.photos = []
      this.photosUrl = []
    },
    _uploadPhoto() {
      this.$refs.fileInput.click()
    },
    _choosePhoto(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.imageSizeLimit'))
        return
      }
      
      const reader = new FileReader()
      reader.onload = (e) => {
        this.photos.push(e.target.result)
        this._doUploadImageUrl(file)
      }
      reader.readAsDataURL(file)
      
      event.target.value = null
    },
    _removeImage(image) {
      const index = this.photos.indexOf(image)
      this.photos.splice(index, 1)
      this.photosUrl.splice(index, 1)
      this.$emit('notifyUploadImage', this.photosUrl)
    },
    async _doUploadImageUrl(file) {
      try {
        const formData = new FormData()
        formData.append("uploadFile", file)
        formData.append('communityId', this.communityId)
        
        const data = await uploadImage(formData)
        this.photosUrl.push(data)
        this.$emit('notifyUploadImage', this.photosUrl)
      } catch (error) {
        this.$message.error(this.$t('uploadImage.uploadError'))
      }
    },
    _getUrlParams(url) {
      if (url.indexOf('?') < 0) {
        return { fileId: url }
      }
      
      const urlStr = url.split('?')[1]
      const obj = {}
      const paramsArr = urlStr.split('&')
      
      for (let i = 0; i < paramsArr.length; i++) {
        const arr = paramsArr[i].split('=')
        obj[arr[0]] = arr[1]
      }
      
      return obj
    },
    urlToBase64(url) {
      const image = new Image()
      image.setAttribute('crossOrigin', 'anonymous')
      image.src = url
      
      image.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const ctx = canvas.getContext('2d')
        ctx.drawImage(image, 0, 0, image.width, image.height)
        const base64 = canvas.toDataURL('image/png')
        this.photos.push(base64)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-image-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  
  .image-item {
    position: relative;
    
    .remove-icon {
      position: absolute;
      top: 5px;
      right: 5px;
      color: #f56c6c;
      font-size: 16px;
      cursor: pointer;
      background: #fff;
      border-radius: 50%;
      padding: 2px;
      
      &:hover {
        color: #f00;
      }
    }
  }
  
  .upload-button {
    width: 100px;
    height: 100px;
    border: 1px dashed #dcdfe6;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    color: #909399;
    font-size: 24px;
    
    &:hover {
      border-color: #409eff;
      color: #409eff;
    }
  }
}
</style>