<script>
export default {
  name: "UploadFile",
  data(){
    return{
      preVisible:false,
      dialogUrl:null, //  弹窗图片
      preImgsUrls:[]//{url:"",id:0,}
    }
  },
  props:{
    fileType: {
      default:"文件"
    }
  },
  methods:{
    uploadSuccessful(response, file, fileList){
      console.log(response.data)
      let fileSlice = file.response.data.split("/")
      if(fileSlice){
        let fileName = fileSlice[fileSlice.length-1] // 最后一串是文件名称
        this.$message.success(`${fileName} 上传成功`)
        this.preImgsUrls.push({
          name:fileName,
          url:response.data,
          id:this.preImgsUrls.length+1
        })
        this.$emit("update:uploadFile",this.preImgsUrls); // 传递更新的信息
      }else {
        this.$message.success(`上传成功`)
      }
    },
    onRemove(file, fileList){
      let fileSlice = file.response.data.split("/")
      let fileName = fileSlice[fileSlice.length-1] // 最后一串是文件名称
      this.$request.delete(`/files/delete/${fileName}`).then(res=>{
        if(res.code == 200){
          this.$message.info(`${fileName} 取消上传`)
        }
      })
      const deleteFileUrl =  file.response.data
      console.log(deleteFileUrl)
      this.preImgsUrls = this.preImgsUrls.filter(item=>item.url=!deleteFileUrl) // 删除
      this.$emit("update:cancelUpload",this.preImgsUrls)
    },
    onError(err, file, fileList){
      this.$message.error(`${err}`)
    },
    handlePreview(file){
      console.log(file,"handlePreview")
      this.dialogUrl = file.response.data;
      this.preVisible = true;
    },
  }
}
</script>

<template>
<div>
  <el-upload
      class="upload-demo"
      drag
      :on-preview="handlePreview"
      :action="$baseUrl+'/files/upload'"
      :show-file-list="true"
      :on-success="uploadSuccessful"
      :on-remove="onRemove"
      list-type="picture"
      multiple
  >
    <i class="el-icon-upload" ></i>
<!--    <template slot="file" slot-scope="{file}">-->
<!--      <img-->
<!--          class="el-upload-list__item-thumbnail"-->
<!--          :src="file.url" :alt="file.name"-->
<!--      >-->

<!--      <span class="el-upload-list__item-actions">-->
<!--&lt;!&ndash;      图片预览&ndash;&gt;-->
<!--        <span-->
<!--            class="el-upload-list__item-preview"-->
<!--            @click="handlePreview(file)"-->
<!--        >-->
<!--          <i class="el-icon-zoom-in"></i>-->
<!--        </span>-->
<!--        <i class="el-icon-delete"></i>-->
<!--        <span-->
<!--            class="el-upload-list__item-delete"-->
<!--            @click="onRemove(file)"-->
<!--        >-->

<!--        </span>-->
<!--      </span>-->
<!--    </template>-->
    <div class="el-upload__text">将{{this.fileType}}拖到此处，或<em>点击上传</em></div>
  </el-upload>
  <el-dialog :visible.sync="preVisible" >
    <img width="100%" :src="dialogUrl" alt="">
  </el-dialog>
</div>
</template>

<style scoped>

</style>