<template>
  <div>
    <upload-button ref="uploadButtonRef" :accept="accept" :show-file-list="true" :file-list.sync="localFileList"
      list-type="picture-card" :limit="5" :multiple="true" :class="{ 'disabled-upload': localFileList.length >= limit }"
      :disabled="localFileList.length >= limit" :before-upload="beforeUpload" :http-request="localUploadImg">
      <i slot="default" class="el-icon-plus" />
      <div slot="file" slot-scope="{file}" class="image-wrapper">
        <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="handlePreviewLogo(file)">
            <i class="el-icon-zoom-in" />
          </span>
          <span class="el-upload-list__item-delete" @click="handleRemoveLogo(file)">
            <i class="el-icon-delete" />
          </span>
        </span>
      </div>
    </upload-button>
    <span class="form-tip">{{ placeholder }}</span>
  </div>

</template>

<script>
import UploadButton from '@/components/Upload/UploadButton'
import { uploadFile } from '@/api/upload'
import { compressImg, urlToBase64ToFile } from '@/utils'

export default {
  name: 'UploadBookImg',
  components: { UploadButton },
  props: {
    fileList: {
      type: Array,
      default: () => []
    },
    formState: {
      type: Object,
      default: () => ({
        bookCoverUrl: null,
        fileId: null
      })
    },
    uploadFileList: {
      type: Array,
      default: () => []
    },
    limit: {
      type: Number,
      default: 10
    },
    placeholder:{
      type:String,
      default:'10M以内'
    }
  },
  data() {
    return {
      uploadFile: null,
      accept: '.jpg,.jpeg,.png,.gif'
    }
  },
  computed: {
    localFileList: {
      get() {
        return this.fileList
      },
      set(val) {
        this.$emit('update:fileList', val)
      }
    },
    localFormState: {
      get() {
        return this.formState
      },
      set(val) {
        this.$emit('update:formState', val)
      }
    }
  },
  watch: {
    localFileList(val) {
      this.localFormState.fileId = val && val.length > 0 ? val.map(file => file.id).join(',') : null
      if (!val || val.length === 0) this.localFormState.bookCoverUrl = null
      this.checkLimit(this.localFileList)
    }
  },
  methods: {
    // 检查对比图片数量，对新增按钮进行隐藏
    checkLimit(filelist) {
      const limit = this.limit
      this.$nextTick(() => {
        const uploadDom = this.$refs['uploadButtonRef']
        if (filelist.length === limit) {
          uploadDom.$children[1].$children[1].$el.style.display = 'none'
        } else {
          uploadDom.$children[1].$children[1].$el.style.display = ''
        }
      })
    },
    beforeUpload(file) {
      const accept = this.accept
      const fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
      const fileName = file.name.slice(0, file.name.lastIndexOf('.'))
      if (!accept.split(',').includes(`.${fileExtension.toLowerCase()}`)) {
        this.$message.error('暂不支持上传该格式文件')
        return false
      } else {
        return true
      }
    },
    localUploadImg(value) {
      compressImg(value.file, null, 300).then(res => {
        const formData = new FormData()
        formData.append('file', res.file)
        uploadFile(formData).then(({ data }) => {
          data.name = data.fileName
          data.url = data.fileUrl
          data.uploadFile = res.file
          data.uid = res.file.uid
          data.deletable = true
          this.localFileList.push(data)
          this.localFormState.fileId = this.localFileList.map(file => file.id).join(',')
        })
      })
    },
    handlePreviewLogo(file) {
      this.$refs.uploadButtonRef.handleFilePreview(file)
    },
    handleRemoveLogo(file) {
      // 删除主图 默认将 第一张设为主图
      this.$refs.uploadButtonRef.handleFileRemove(file)

    }
  }
}
</script>

<style scoped lang="scss">
.disabled-upload {
  ::v-deep .el-upload.el-upload--picture-card {
    cursor: not-allowed;
  }
}
</style>

<style lang="scss" scoped>
.disabled-upload {
  ::v-deep .el-upload.el-upload--picture-card {
    cursor: not-allowed;
  }
}
//移除动画
::v-deep .el-upload-list__item {
  transition: none !important;
  -webkit-transition: none !important;
}

::v-deep .el-upload-list__item-name {
  transition: none !important;
  -webkit-transition: none !important;
}
::v-deep .disabled .el-upload--picture-card {
  display: none !important;
}
</style>
