<template>
  <Upload v-show="show" ref="upload" :type="canUpload?'drag':null" :data="formData"
          :multiple="multiple" :format="format" :max-size="maxSize" :action="action" :default-file-list="defaultFileList"
          :before-upload="beforeUpload" :on-progress="onProgress" :on-success="onSuccess" :on-error="onError"
          :on-preview="onPreview" :on-remove="onRemove" :on-format-error="onFormatError" :show-upload-list="showUploadList
          " :on-exceeded-size="onExceededSize">
    <!--<Button icon="ios-cloud-upload-outline">上传文件</Button>-->
    <div v-if="canUpload" :style="{padding: '20px 0;',width: divWidth,height: divHeight}">
      <Icon type="ios-cloud-upload" :size="iconSize" style="color: #3399ff"></Icon>
      <p>点击或拖动文件到此处上传</p>
    </div>
  </Upload>
</template>

<script>
  import uuid from 'uuid'
  let _this;
  import { getToken, TOKEN_KEY } from '../bc-libs/token-util'
  import { deleteAttachment } from './attachment-api'
  import { getAttachmentList } from '../bc-upload/attachment-api'
  export default {
    name: 'bcUpload',
    props: {
      show: {
        type: Boolean,
        default: true
      },
      showUploadList:{//是否显示上传文件列表
        type: Boolean,
        default: true
      },
      canUpload: {
        type: Boolean,
        default: false
      },
      multiple: {//是否支持多选文件
        type: Boolean,
        default: false
      },
      action: {//上传的地址，必填
        type: String,
        default: '/api/v1/attach/binary?'+TOKEN_KEY+'='+getToken()
      },
      format: {//支持的文件类型，与 accept 不同的是，format 是识别文件的后缀名，accept 为 input 标签原生的 accept 属性，会在选择文件时过滤，可以两者结合使用
        type: Array,
        default: function () {
          return []
        }
      },
      maxSize: {//文件大小限制，单位 kb
        type: Number,
        default: null,
      },
      fileArr: {//当前已上传文件集合
        type: Array,
        default: function () {
          return []
        }
      },
      fid: {
        type: String,
        default: ''
      },
      iconSize:{//图标大小
        type: String,
        default: '52'
      },
      divWidth:{//上传按钮宽度
        type: String,
        default: ''
      },
      divHeight:{//上传按钮高度
        type: String,
        default: ''
      },
    },
    data(){
      return{
        //showUploadModal:false,
        fileSize:null,//文件大小
        defaultFileList: [],//默认已上传的文件列表  属性必含 name,url
        batchKey: null,//批次key
        fid2:'',
        formData:{batchKey: this.batchKey, fid: this.fid},
      }
    },methods: {
      beforeUpload(file){//上传文件之前的钩子
        this.fileSize=file.size;
        if (!this.batchKey) {//如果没有生产批次key,那就初始化生成一下
          this.batchKey = uuid.v4();
          this.$set(this.formData,'batchKey',this.batchKey)
        }
        if (!this.fid) {//如果没有生产批次key,那就初始化生成一下
          this.fid2 = uuid.v4();
          this.$set(this.formData,'fid',this.fid2)
        }
        this.$set(this.formData,'fileSize',this.fileSize)
      },
      onProgress(event, file, fileList){//文件上传时的钩子

      },
      onSuccess(response, file, fileList) {//文件上传成功时的钩子
        this.fileArr.push(file.response.result[0])
        this.$emit('on-success',this.batchKey,file.response.result[0],this.fileArr);
      },
      onError(response, file, fileList) {//文件上传失败时的钩子
        this.$Modal.error({
          title: '上传失败',
          content: response.error.message,
        });
        this.$emit('on-error',fileList);
        return false;
      },
      onPreview(file){//点击已上传的文件链接时的钩子
        if (file.id) {
          this.$downFileFdfs(file.id);
        }else if (file.response.result[0].id){
          this.$downFileFdfs(file.response.result[0].id);
        }
      },
      onRemove(file, fileList){//文件列表移除文件时的钩子
        let id = null;
        let files = null;
        if(file.response){
          id = file.response.result[0].id
          files = file.response.result[0];
        }else {
          id = file.id;
          files = file
        }
        deleteAttachment(id).then(data => {
          this.$emit('on-remove',files);
        }).catch(err => {
          this.$Message.error('操作失败！')
          console.log(err)
        })

      },
      onFormatError(file, fileList){//文件格式验证失败时的钩子

      },
      onExceededSize(file, fileList){//文件超出指定大小限制时的钩子

      },
      clearCaChe(){//文件超出指定大小限制时的钩子

      },
      clearFiles(){//清除文件列表，同时刷新批次id
        this.batchKey = uuid.v4();
        this.$set(this.formData,'batchKey',this.batchKey)
        this.$refs.upload.clearFiles();
      },
      getFileList(params){
        getAttachmentList(params).then(res=>{
          if(res.data && res.data.result){
            /* this.$nextTick(function () {*/
            for (let i = 0; i < res.data.result.length; i++) {
              res.data.result[i]['name'] = res.data.result[i].oldName;
            }
            this.defaultFileList=res.data.result;
            /*   })*/
          }
        }).catch(err=>{
          this.$Message.error("获取附件信息出错！<br>错误信息："+err)
        })
      }
    },mounted: function(){
      _this = this;
    },watch:{
      fid:{
        immediate:true,
        handler:function(){
          this.$set(this.formData,'fid',this.fid);
          if(this.fid){
            this.getFileList({fid:this.fid});
          }
        }
      },
    }
  }
</script>

<style scoped>

</style>
