<template>
 <div id="ls-upload-wrap">
   <el-upload
     v-if="showuploadbtn"
     ref="uploadRef"
     :action="action"
     :data="params"
     :multiple="ismult"
     :limit="limitnum"
     :show-file-list="false"
     :before-upload="beforeUpload"
     :on-error="handleError"
     :auto-upload="true"
     :file-list="uploadFile"
     :on-success="successHandle"
     class="ls-upload"
     v-loading.fullscreen.lock="loading"
     element-loading-text="拼命加载中"
     element-loading-spinner="el-icon-loading"
     element-loading-background="rgba(0, 0, 0, 0.8)"
     list-type="text">
      <el-button v-if="showuploadbtn"
        size="mini" type="primary"
        icon="iconfont icon-shangchuanwendang">点击上传</el-button>
   </el-upload>
   <div v-if="!ismult && uploadFile.length" class="file-btn">
     <span @click="preview(uploadFile[0].name, uploadFile[0].response.data.fileId)"
      class="name button">{{uploadFile[0].name}}</span>
     <span @click="download(uploadFile[0].name, uploadFile[0].response.data.fileId)"  >
       <i class="el-icon-download"></i>
       <span class="button">下载</span>
     </span>
     <span  @click="preview(uploadFile[0].name, uploadFile[0].response.data.fileId)"  >
       <i class="el-icon-view"></i>
       <span class="button">预览</span>
     </span>
     <span v-show="showdeletebtn"  @click="handleDelete(0)"  >
       <i class="el-icon-delete"></i>
       <span class="button">删除</span>
     </span>
   </div>
   <div class="file-box"  v-show=" ismult && uploadFile.length">
     <div class="header" >
       <span style="flex: 2;">名称</span>
       <span style="flex: 1;margin-left: 8px;">大小</span>
       <span style="flex: 4;margin-left: 15px;">操作</span>
     </div>
   </div>
   <template v-if="ismult">
   <div v-show="isExtend || (!isExtend && index<3)"
        v-for="(item,index) in uploadFile"
        :key="index" class="opert-btns">
     <span @dblclick="preview(item.name, item.response.data.fileId, item.response.data.ext)"
        class="name">{{item.name}}</span>
     <span @dblclick="preview(item.name, item.response.data.fileId, item.response.data.ext)"
        class="size">{{(item.size / 1024).toFixed(2)}}KB</span>
     <div class="btn">
       <span @click="download(item.name, item.response.data.fileId)"  >
         <i class="el-icon-download"></i>
         <span class="button">下载</span>
       </span>
       <span  @click="preview(item.name, item.response.data.fileId, item.response.data.ext)"  >
         <i class="el-icon-view"></i>
         <span class="button">预览</span>
       </span>
       <span v-show="showdeletebtn"  @click="handleDelete(index)"  >
         <i class="el-icon-delete"></i>
         <span class="button">删除</span>
       </span>
     </div>
   </div>
   </template>
   <div v-show="showTips" class="tips-msg" >支持格式：{{fileTypeList | capitalize}}，单个文件不能超过100MB</div>
   <div v-show="uploadFile.length>=5" class="extend">
     <el-button  @click="handleExtend" type="text"  size="small" >
       <span v-if="isExtend">收起</span>
       <span v-else>展开</span>附件
       <i :class="isExtend?'el-icon-arrow-up':'el-icon-arrow-down' "></i>
     </el-button>
   </div>
  </div>
</template>

<script>
export default {
	name: 'ls-upload',
	mounted() {
    this.fileList.forEach(item=>{
      this.transData(item);
    })
    if(this.attachFileObj && this.attachFileObj.fileId){
      this.uploadFile = [];
      this.transData(this.attachFileObj);
    }
	},
	methods: {

    beforeUpload(file) {
      let extension = file.name.substring(file.name.lastIndexOf('.')+1);
      let size = file.size / 1024 / (1024 * 100);
      if(this.limitFileType) {
        let valid = this.fileTypeList.some(item=>{
            return extension.toLowerCase() === item;
        })
        if(!valid){
          this.$message({
            type: 'warning',
            message: `不支持后缀是.${extension}的文件`
          })
          return false;
        }
      }
      if(!this.ismult && this.uploadFile.length >= 1) {
        this.$message({
          type: 'warning',
          message: `项目文档仅支持上传个单文件`
        })
        return false;
      }
      if(!size) {
        this.$message({
          type: 'warning',
          message: `文件大小为${size},请上传有效文件`
        })
        return false;
      }
      if(size > this.fileSize) {
        this.$message({
          type: 'warning',
          message: `单个文件大小不得超过${this.fileSize}M`
        })
        return false;
      }
      this.loading = true;
		},
    //文件上传成功
    successHandle: function(response, file, fileList) {
      this.loading = false;
      if(response.errorCode === 200) {
        this.uploadFile = fileList;
        this.handleUpdate();
      } else {
        this.$message.error(response.msg);
      }
    },
		handleError(err, file, fileList) {
      this.$message({
        type: 'error',
        message: `上传出错!`
      })
		},
    //获取文件 url
    getFileUrl(name, fileId){
      return new Promise((resolve, reject)=>{
        let param = {
          fileId: fileId,
          busSystem: 'cloud-crm-project',
          busModel: 'cloud-crm-project',
          uid: this.uid,
        };
        this.$ajax.post({
          domain: 'attachUrl',
          url: 'downLoadFile',
          data: param,
          requestType: 'form',
          showLoad: true,
          success: function (res) {
            if (res.errorCode === 200) {
                resolve(res.data);
            }
          }.bind(this),
          error: function (res) {
            reject(res);
            this.$message({
              type: 'error',
              message: res.body.msg || res.msg
            })
          }.bind(this)
        })
      })
    },
    handleDelete(index){
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.uploadFile.splice(index, 1);
        this.handleUpdate();
        this.$message.success('已从列表中移除');
      }).catch(() => { });
    },
    async download(fileName, fileId){
      // this.$common.downloadByUrl(this.$common.getDownFileUrl(fileId,this.uid), name);
      let fileUrl = await this.getFileUrl(fileName, fileId);
      fileUrl=this.$ajax.setDynamicProtocol(fileUrl);
      this.$common.downloadByXHR(fileUrl, fileName)
    },
    //预览
    async preview(name, fileId, suffix){
      if(suffix === 'msg'){
        this.$message('请下载文件后再打开');
        return;
      }
      let fileUrl = await this.getFileUrl(name, fileId);
      fileUrl=this.$ajax.setDynamicProtocol(fileUrl);
      window.open('./preview/preview.html?url=' + fileUrl + '&fileId=' + fileId);
    },
    handleUpdate(){
      let files = [];
      let obj = {};//转换数据结构
      this.uploadFile.forEach(item=>{
        obj.fileSize =  item.size;
        obj.fileName = item.name;
        obj.fileId = item.response['data'].fileId;
        obj.ext = item.response['data'].ext;
        files.push(obj);
      })
      if(this.ismult){
        this.$emit('upload', files, this.index);
      }else {
        this.$emit('upload', obj, this.index);
      }
    },
    handleExtend(){
      this.isExtend = !this.isExtend;
    },
    transData(item){
      let response = {
          data: {
            fileId: item.fileId
          }
      };
      let obj = {
        size:  item.fileSize,
        name: item.fileName,
        response: response
      };
      this.uploadFile.push(obj);
    },
    clearFile(){
      this.uploadFile = [];
    },

	},
	computed: {
    action: function(){
      return this.$config.getDomain('attachUrl') + 'upload';
    },
    params:function(){
      return{
         'busSystem': this.sysId,
         'busModel': this.busId,
         'userName': this.$common.getUrlParams('uid') || this.uid
        }
      },
	},

  props:{
    /*   数组元素对象包含  fileName ,fileId fileSize 字段,
        例如： fileList = [{fileName: 'name', fielId: 'id', fileSize: 'size'}]
    */
    fileList: { // 接收 已上传文件列表 的值
      type: Array,
      default: ()=> [],
      required: false
    },
    attachFileObj:{
      type: Object,
      default: ()=>{}
    },
    index: { //使用数组动态生成组件时，当前组件所处索引位置
      type: Number,
      default: null,
      required: false,
    },
    sysId: {  //所属系统
      type: String,
      default: 'cloud-crm-project',
      required: false
    },
    busId: { //业务ID
      type: String,
      default: 'def',
      required: false
    },
    uid: {  //用户账号
      type: String,
      default: 'admin',
      required: false
    },
    limitFileType:{ //是否限制上传文件类型
      type: Boolean,
      default: true,
      required: false
    },
    fileTypeList: { // 支持的文件类型数组
      type: Array,
      default (){
        return ['rar', 'zip', 'doc', 'docx','pdf', 'xlsx','pptx','ppt', 'xls','jpg', 'png', 'msg'];
      }
    },
    ismult: { //是否多上传
      type: Boolean,
      default: true,
    },
    limitnum: {  //最大允许上传个数
      type: Number,
      default: 10,
    },
    fileSize: { //限制的文件大小
      type: Number,
      default: 100,
    },
    showdeletebtn: {  //显示删除按钮
      type: Boolean,
      default: true,
    },
    showuploadbtn: {  //显示上传按钮
      type: Boolean,
      default: true,
    },
    showTips:{ //显示提示信息
      type: Boolean,
      default: true,
    },

  },
  filters: {
    capitalize(val){
      if(!val.length) return '';
      let str = '';
      return val.join('，');
    },
  },
  watch:{
   fileList(newVal, old){
    if(newVal && newVal.length){
      this.uploadFile = [];
      newVal.forEach(item=>{
        this.transData(item);
      })
    }
   },
    attachFileObj(newVal, old){
      this.uploadFile = [];
      if(newVal && newVal.fileId){
        this.transData(newVal);
      }
    },

  },
	data: function() {
		return {
		  loading: false,
      uploadFile: [], //上传的文件列表，需要指定数据结构
      isExtend: true,
		}
	},

}
</script>

<style  lang="scss">
#ls-upload-wrap{
  position: relative;
  .extend{
    position: absolute;
    top: 0;
    right: 0;
    z-index: 999;
  }

.ls-upload {

    .el-upload {
       text-align: left;
    }
}
.file-box {
  .header{
    font-size: 12px;
    display: flex;
    padding:10px 0;
    >span{
      font-weight: bold;
    }
  }
}
  .opert-btns {
    font-size: 12px;
    display: flex;
    align-items: center;
    border-top: 1px solid #dcdfe6;
    padding: 2px 0;
    .name{
      flex: 2;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .size{
      flex: 1;
    }
    .btn {
      flex: 4;
    }
    .button, i{
      cursor: pointer;
      color: #0077FA;
      &:hover{
        color: #66b1ff;
      }
    }
    .button{
      text-decoration: underline;
    }
    i {
      margin-left: 10px;
    }

  }
  .tips-msg{
    color: #999;
    font-size: 10px;
    line-height: 15px;
  }
  .file-btn {
    font-size: 12px;
    // position: absolute;
    // top: 0px;
    // left: 82px;
    // z-index: 99;
    .name {
      // margin-left: 15px;
    }
    .button, i{
      cursor: pointer;
      color: #0077FA;
      &:hover{
        color: #66b1ff;
      }
    }
    .button{
      text-decoration: underline;
    }
    i {
      margin-left: 10px;
    }
  }

}
</style>
