<template>
  <div class="file-upload upload-small">
    <el-input v-model="uploadImageUrl" style="display:none;" />
    <el-upload
      ref="uploadImage"
      :disabled="uploadLoading"
      :file-list="uploadFileList"
      :class="{'upload-but-hide': !isShowUpload}"
      action=""
      list-type="picture-card"
      :http-request="uploadImage"
      :show-file-list="!isShowUpload"
      :on-remove="handleUploadImageFileRemove"
      accept="image/*"
      :on-change="changeUploadImage"
    >
      <i slot="default" v-loading="uploadLoading" class="el-icon-plus" />
      <div v-if="tips" slot="tip" class="el-upload__tip">{{ tips }}</div>
    </el-upload>
  </div>
</template>

<script>
/**
 * upload-imgage.
 * 单文件图片上传,主要解决内部文件上模块统一.
 * 不支持连续多文件上传
 * @auth pengliang
 */
import { getElementUiUploadFile } from '@/utils'
export default {
  name: 'UploadImage',
  props: {
    value: {
      type: [String],
      default: ''
    },
    fileDir: {
      type: String,
      default: 'other'
    },
    tips: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      uploadLoading: false,
      uploadFileList: [],
      uploadImageUrl: ''
    }
  },
  computed: {
    isShowUpload() {
      return !this.uploadImageUrl
    }
  },
  watch: {
    uploadImageUrl: {
      handler(newVal) {
        if (newVal) {
          this.uploadFileList = getElementUiUploadFile(newVal)
        } else {
          this.uploadFileList = []
        }
        this.$emit('input', newVal)
      },
      immediate: true
    },
    value(newVal) {
      this.uploadImageUrl = newVal
    }
  },
  created() {
    this.uploadImageUrl = this.value
  },
  methods: {
    uploadImage(file) {
      const that = this
      that.uploadLoading = true
      that.$simpleUploadFlie(file, that.fileDir).then(res => {
        that.uploadLoading = false
        that.uploadImageUrl = that.$getAccessImgUrl(res.name)
        this.$emit('success')
      }).catch(er => {
        that.uploadLoading = false
        this.$emit('fail')
      })
    },
    handleUploadImageFileRemove(file, fileList) {
      this.uploadImageUrl = ''
      this.uploadLoading = false
    },
    changeUploadImage(file, fileList) {
      if (fileList.length > 1) {
        this.$refs.uploadImage.clearFiles()
        this.uploadFileList = getElementUiUploadFile(fileList[fileList.length - 1].url)
      }
    }
  }
}
</script>
