<template>
  <div style="text-align: center" v-loading="loading">
    <div>
      <el-image :src="pictureUrl" fit="contain" :preview-src-list="[pictureUrl]" :style="imgStyle" class="picture">
        <div slot="error" :style="errorStyle" class="image-error">
          {{ value ? '加载失败' : '没有图片' }}
        </div>
      </el-image>
    </div>
    <div>
      <el-upload
        :action="uploadUrl"
        :show-file-list="false"
        :on-success="handleUploadSuccess"
        :before-upload="handleBeforeUpload"
        :on-error="handleUploadError"
        :data="{ fileModule }"
        :headers="{ token }"
        :accept="accept"
      >
        <el-button slot="trigger" size="mini" type="primary"> 点击上传 </el-button>
        <el-button
          size="mini"
          type="danger"
          style="margin-left: 10px"
          v-if="value"
          @click="handleDelete"
        >
          删除
        </el-button>
        <div style="margin-top: 20px; line-height: 20px" slot="tip" class="el-upload__tip">
          <p v-if="whiteList.length > 0">只能上传 {{whiteList.join(' / ')}} 文件</p>
          <p v-if="maxSize > 0">大小不超过 {{maxSizeStr}}</p>
        </div>
      </el-upload>
    </div>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'UplaodPicture',
  computed: {
    uploadUrl() {
      return process.env.VUE_APP_BASE_API + '/file/uploadFile'
    },
    pictureUrl() {
      return this.value ? process.env.VUE_APP_BASE_API + this.value : ''
    },
    whiteList() {
      return this.accept ? this.accept.replace(/\./g, '').split(',') : []
    },
    maxSizeStr() {
      return this.maxSize >= 1024 * 1024 * 1024
        ? (this.maxSize / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
        : this.maxSize >= 1024 * 1024
        ? (this.maxSize / (1024 * 1024)).toFixed(2) + 'MB'
        : this.maxSize >= 1024
        ? (this.maxSize / 1024).toFixed(2) + 'KB'
        : this.maxSize > 0
        ? this.maxSize + 'B'
        : '无限制'
    },
    imgStyle(){
        return {
            height: this.previewHeight,
            width: this.previewWidth
        }
    },
    errorStyle(){
        return{
            'line-height': this.previewHeight,
        }
    }
  },
  props: {
    value: {
      type: String,
      require: true,
      default: null,
    },
    maxSize: {
      type: Number,
      default: 0,
    },
    accept: {
      type: String,
      default: '.jpg,.jpeg,.gif,.png',
    },
    previewWidth: {
        type: String,
        default: '200px',
    },
    previewHeight: {
        type: String,
        default: '200px',
    },
    fileModule: {
        type: Number,
        default: 1,
    }
  },
  data() {
    return {
      token: getToken() ?? '',
      loading: false
    }
  },
  methods: {
    handleBeforeUpload(file) {
      if (this.maxSize > 0) {
        if (file.size > this.maxSize) {
          this.$message.warning(`文件最大限制为 ${this.maxSizeStr}`)
          return false
        }
      }
      if (this.whiteList.length > 0) {
        let fileName = file.name
        let fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
        let whiteListLowerCase = this.whiteList.map((a) => a.toLowerCase())
        if (!whiteListLowerCase.includes(fileExtension)) {
          this.$message.warning(`只能上传扩展名为 ${this.whiteList.join(' / ')} 的文件`)
          return false
        }
      }
      this.changeLoading(true)
    },
    handleUploadSuccess(res, file, fileList) {
      if (res.code === 20000) {
        this.$emit('input', res.data.path)
      } else {
        this.$message.error(res.msg)
      }
      this.changeLoading(false)
    },
    handleUploadError(err, file, fileList) {
      console.log(err)
      this.$message.error('上传失败')
      this.changeLoading(false)
    },
    handleDelete() {
      this.$emit('input', null)
    },
    changeLoading(value) {
      this.loading = value
      this.$emit('update:loading', value)
    }
  },
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .picture {
  border: 1px solid #ebebeb;
}
::v-deep .image-error {
  width: 100%;
  height: 100%;
  color: #6d6d6d;
}
</style>