<template>
  <div>
    <el-upload 
      :http-request="handleUpload" 
      :on-preview="handlePictureCardPreview" 
      :on-remove="handleRemove" 
      :on-exceed="handleExceed"
      :on-success="handleSuccess" 
      :before-upload="beforeUpload" 
      :before-remove="beforeRemove" 
      :file-list="fileList" 
      :limit="limit"
      accept=".jpg, .jpeg, .png, .gif" 
      action 
      list-type="picture-card">
      <i class="el-icon-plus"></i>
    </el-upload>
     <div slot="tip" class="el-upload__tip">{{ tip }}</div>
    <el-dialog :visible.sync="dialogVisible">
      <img :src="dialogImageUrl" width="100%" alt="">
    </el-dialog>
  </div>

</template>


<script>
import {
  put,
  getFileNameUUID
} from '@api/ali-oss'
export default {
  props: {
    
    tip: {
      type: String,
      default: '上传大小不能超过80M'
    },
    limit: {
      type: Number,
      default: 3
    },
    max: {
      type: Number,
      default: 2
    },
    	fileList:{
		type: Array,
		default: () => []
	},
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
    }
  },
  methods: {
    beforeUpload(file) {
      const max = this.max
      const isLt2M = file.size / 1024 / 1024 < max
      if (!isLt2M) {
        this.$message.error(`上传附件大小不能超过 ${max} MB!`)
      }
      return isLt2M
    },
    emitInput(fileList) {
      let value = []
      console.log(fileList)
      for (let i = 0; i < fileList.length; i++) {
        let message = {}
         message.name = fileList[i].name
     message.url = fileList[i].url  
        message.fileName = fileList[i].name
        message.fileUrl = fileList[i].url
        value.push(message)
      }
      this.$emit('input', value)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`每次只能上传 ${this.limit} 个文件`)
    },

    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.emitInput(fileList)
    },
    handleSuccess(response, file, fileList) {
      console.log('成功')
      this.fileList = fileList
      this.$emit('on-success', file, fileList)
    },
    handleUpload(option) {
      const max = this.max
      const isLt2M = option.file.size / 1024 / 1024 < max
      if (isLt2M) {
        // 生成的文件名称
        let objName = getFileNameUUID()
        // 调用 ali-oss 中的方法
        put(`${objName}${option.file.name}`, option.file).then(res => {
          this.fileList.push(res)
          this.emitInput(this.fileList)
        })	
      } 
    }
  }
}
</script>
