<template>
  <div class="component-upload-image relative">
    <el-upload action="string" :before-upload="handleBeforeUpload" :file-list="fileList" :limit="limit"
               :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess"
               :on-remove="handleDelete" :show-file-list="true" :accept="uploadFileTypes.toString()"
               :http-request="handleUpload" list-type="picture-card" ref="upload"
               :class="{'el-upload-hidden':!enableAdd}">
      <i v-if="enableAdd" class="el-icon-plus"></i>
      <template #file="{file,index}">
        <img :src="file.url" alt="" class="el-upload-list__item-thumbnail" :ref='"file_"+file.uid'>
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </template>
    </el-upload>
    <el-dialog v-if="previewUrl" :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
      <img :src="previewUrl" style="display: block; max-width: 100%; margin: 0 auto;">
    </el-dialog>
    <div v-if="uploading" class="el-loading-mask"></div>
    <el-progress v-if="uploading" type="circle" :color="themeColor" :percentage="uploadPercent"
                 class="absolute el-progress-loading"></el-progress>
  </div>
</template>

<script>
import uploadMixin from '../ali-oss-upload-mixins'
import config from '@/common/mx-config'

export default {
  mixins: [uploadMixin],
  props: {
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      previewUrl: null,
      fileType: ['png', 'jpg', 'jpeg'],
      limit: 10,
      themeColor: config.color.primary
    }
  },
  computed: {
    enableAdd() {
      return !this.disabled && this.limit > 0 && this.fileList.length < this.limit
    }
  },
  methods: {
    handlePictureCardPreview(file) {
      this.previewUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file) {
      this.fileList.remove(file)
      this.handleDelete(file, this.fileList)
    },
    handleNotify() {
      this.$emit('input', this.fileList.map(f => f.url))
    }
  }
}
</script>

<style scoped lang="scss">
.el-progress-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 2001;
}
</style>
<style scoped>
/deep/ .el-upload.el-upload--text {
  text-align: left !important;
}

/deep/ .el-upload-hidden .el-upload--picture-card {
  display: none; /* 上传按钮隐藏, disabled的控制效果不好 */
}
</style>
