<template>
  <div>
    <el-upload
      ref="pictureUpload"
      :action="imagesUploadApi"
      list-type="picture-card"
      :limit="limit"
      accept=".jpg,.jpeg,.png,.svg,.bmp"
      :auto-upload="true"

      :on-success="handleSuccess"
      :on-error="handleError"
      :file-list="fileList"
    >
      <i slot="default" class="el-icon-plus" :visible.sync="plusVisible" />
      <div slot="file" slot-scope="{file}">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in" />
          </span>
          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
            <i class="el-icon-download" />
          </span>
          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemoveFile(file)">
            <i class="el-icon-delete" />
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { del, getFiles } from '@/api/tools/localStorage.js'
import { crud } from '@crud/crud'
export default {
  mixins: [crud()],
  props: {
    uploadParams: {
      type: Object,
      required: true,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      fileIds: this.uploadParams.fileIds || [], // 文件列表
      fileList: this.uploadParams.fileList, // 文件列表
      dialogImageUrl: this.uploadParams.dialogImageUrl, // 展示的图片路径
      dialogVisible: this.uploadParams.dialogVisible,
      disabled: this.uploadParams.disabled,
      limit: this.uploadParams.limit, // 可上传个数
      plusVisible: true
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'imagesUploadApi', // 图片上传
      'fileUploadApi' // 文件上传
    ])
  },
  watch: {
    // 编辑框隐藏时,更新图片展示状态
    'crud.status.cu': {
      handler: function(val, oldVal) {
        if (val <= 0) {
          this.fileList = []
          this.fileIds = []
          // this.$set(this.uploadParams, 'fileList', [])
          // this.$set(this.uploadParams, 'fileIds', [])
        }
      }
    },
    'fileList'() {
      // console.log('上传图片,监听fileList || fileList进行修改')
      if (this.fileList.length === 0) {
        this.$emit('callback', '')
      } else {
        let ids = ''
        let realName = ''
        for (var i = 0; i < this.fileList.length; i++) {
          var file = this.fileList[i]
          if (ids.length === 0) {
            ids += file.id
            realName += file.name
          } else {
            ids += ',' + file.id
            realName += ',' + file.name
          }
        }
        if ((!this.uploadParams.fileIds) || (this.uploadParams.fileIds && this.uploadParams.fileIds !== ids)) {
          console.log('realName:', realName)
          this.$emit('callback', ids, realName)
        }
      }
    },
    'uploadParams.fileList': {
      handler: function(val, oldVal) {
        // console.log('上传图片,监听uploadParams.fileList || fileList进行修改 ==>> val : ' + val)
        this.fileList = val
      },
      immediate: true
    },
    'uploadParams.fileIds': {
      handler: function(val, oldVal) {
        console.log(val)
        // this.fileList = [];
        // console.log('图片上传监听 || uploadParams.fileIds : ' + val)
        if (this.uploadParams.fileIds.length > 0) {
          getFiles(val).then(res => {
            for (var i = 0; i < res.length; i++) {
              this.fileList.push({
                id: res[i].id || res[i].storageId,
                name: res[i].realName,
                url: res[i].url
              })
            }
          })
        } else {
          this.fileList = []
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 监听上传成功
    handleSuccess(response, file, fileList) {
      file.id = response.id
      for (const f of fileList) {
        f.id = f.response.storageId
      }
      this.fileList = fileList
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    handleRemoveFile(file) {
      // console.log('删除图片 handleRemove')
      del([file.id || file.storageId]).then(res => {
        this.removeFileListObj(file)
        this.$refs.pictureUpload.handleRemove(file)
      })
    },
    handlePictureCardPreview(file) {
      // console.log('预览图片 handlePictureCardPreview')
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
      this.downloadByBlob(file.url, file.name)
    },
    removeFileListObj(file) {
      console.log('移除图片')
      for (var i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].id === file.id) {
          this.fileList.splice(i, 1)
          break
        }
      }
      console.log(this.fileList)
    },
    downloadByBlob(url, name) {
      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)
        canvas.toBlob((blob) => {
          const url = URL.createObjectURL(blob)
          this.download(url, name)
          // 用完释放URL对象
          URL.revokeObjectURL(url)
        })
      }
    },
    download(href, name) {
      var eleLink = document.createElement('a')
      eleLink.download = name
      eleLink.href = href
      eleLink.click()
      eleLink.remove()
    }
  }
}
</script>

<style>
</style>
