<template>
  <!-- :headers="uploadHeaders" -->
  <!--
    :on-remove="(file, fileList) => {
        handleRemove(file, fileList, 'fileLists')
      }"
  -->
  <div class="cy-upload">
    <el-upload
      :class="{'cy-upload-content': disabled, 'upload-form': uploadFromStatus, 'upload-file-length': !fileLists.length  }"
      :file-list="fileLists"
      :action="actionUrl"
      :disabled="disabled"
      :before-upload="exceptZipAndRar"
      multiple
      :on-success="(response, file, fileList) => {
        uploadMoreSuccess(fileList, 'fileLists')
      }"
      :data="uploadData"
      :before-remove="(file, fileList) => {
        return handleRemove(file, fileList, 'fileLists')
      }"
      :on-error="fileError"
      :on-progress="uploadProgress"
      :on-preview="previewFile"
      :limit="limit"
    >
      <template v-if="!disabled">
        <el-button type="primary" :size="size">上传附件</el-button>
      </template>

      <template v-if="disabled && !fileLists.length">
        <div style="margin-left: 10px; color: #b6b6b6; font-size: 13px;">暂无附件</div>
      </template>
    </el-upload>
    <!-- <template v-if="fileLists.length">
      <div class="upload-download">
        <div v-for="(item, index) in fileLists" :key="index" >
          <i class="el-icon-download"></i>
        </div>
      </div>
    </template> -->
    <template v-if="!fileLists.length && placeholder">
      <div class="cy-upload-placeholder">{{ placeholder }}</div>
    </template>
  </div>
</template>

<script>
module.exports = {
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    isAdd: {
      type: Boolean,
      default: true
    },
    limit: {
      type: null,
      default: null
    },
    size: {
      type: String,
      default: 'small'
    },
    fileData: {
      type: Array,
      default: () => []
    },
    uploadParams: {
      type: Object,
      default: () => {}
    },
    uploadFromStatus: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      actionUrl: '/fileStorage/doUploadFiles',
      fileLists: [],
      uploadLoading: null,
      uploadData: {}
    }
  },
  watch: {
    fileData: {
      handler(newV) {
        if(newV.length) {
          this.fileLists = newV.map(item => {
            const { id, path, originalName} = item
            return {
              id,
              url: path,
              name: originalName
            }
          })
        }
      },
      immediate: true,
      deep: true
    },
    uploadParams: {
      handler(newV) {
        this.uploadData = {
          ...newV
        }
      },
      immediate: true,
      deep: true
    },
  },
  computed: {
    getFileLists() {
      const list = this.fileLists.map(item => {
        if(item.response) {
          const { response: { data }} = item
          return {
            id: data[0].id,
            name: data[0].originalName,
            url: data[0].path
          }
        }else {
          return item
        }
      })
      return list
    }
  },
  created() {},
  destroyed() {
    this.fileLists = []
  },
  methods: {
    fetchFile() {
      this.uploadData = {
      }
      this.getFileLoad().then(data => {
        this.fileLists = data.map(item => {
          item.name = item.fileName
          item.url = item.fileUrl
          return item
        })
      })
    },

      // 设置上传限制大小 在文件上传之前进行的操作
    beforeUploadM(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const testMsgM = testmsg === 'jpg'
      const isLtM = file.size / 1024 / 20 >= 1 && file.size / 1024 / 750 <= 1

      if (!testMsgM) {
        this.$message.warning('请上传jpg格式的图片')
      }
      if (!isLtM) {
        this.$message.warning('上传文件大小不得小于20KB,不得大于750kB!')
      }
      if (testMsgM && isLtM) {
        this.uploadLoading = this.handlerUploadMark()
      }
      return testMsgM && isLtM
    },

     // 限制1M
    beforeUpload1M(file) {
      const testMsg1M = /^image\/(jpeg|png|jpg)$/.test(file.type)
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!testMsg1M) {
        this.$message.warning('请上传jpeg/png/jpg格式的图片')
      }
      if (!isLt1M) {
        this.$message.warning('上传文件大小不能超过 1M!')
      }
      if (testMsg1M && isLt1M) {
        this.uploadLoading = this.handlerUploadMark()
      }
      return isLt1M && testMsg1M
    },

    beforeUpload2M(file) {
      const testMsg2M = /^image\/(jpeg|png|jpg)$/.test(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!testMsg2M) {
        this.$message.warning('请上传jpeg/png/jpg格式的图片')
      }
      if (!isLt2M) {
        this.$message.warning('上传文件大小不能超过 2M!')
      }
      if (testMsg2M && isLt2M) {
        this.uploadLoading = this.handlerUploadMark()
      }
      return isLt2M && testMsg2M
    },

     // 限制10M
    beforeUpload10M(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.warning('上传文件大小不能超过 10M!')
      } else {
        this.uploadLoading = this.handlerUploadMark()
      }
      return isLt10M
    },

    beforeUpload50M(file, limitName = '') {
      if (limitName) {
        this[limitName](file)
      }
      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        this.$message.warning('上传文件大小不能超过 50M!')
      } else {
        this.uploadLoading = this.handlerUploadMark()
      }
      return isLt50M
    },

     // 格式限制
     docxAndDoc(file) {
      const last = file.name.lastIndexOf('.')
      const type = file.name.slice(last)
      const typeList = ['.docx', '.doc']
      const isType = typeList.includes(type)
      if (!isType) {
        this.$message.error('上传文件图片只能是 docx 或 doc 格式!')
        this.uploadLoading.close()
      } else {
        this.uploadLoading = this.handlerUploadMark()
      }
      return isType
    },

    // 格式限制-现在zip和RAR
    exceptZipAndRar(file) {
      const last = file.name.lastIndexOf('.')
      const type = file.name.slice(last)
      const typeList = ['.zip', '.rar']
      const isType = typeList.includes(type.toLowerCase())
      if (isType) {
        this.$message.error('上传文件格式不能是 zip 或 rar 格式!')
        // this.uploadLoading.close()
      } else {
        // this.uploadLoading = this.handlerUploadMark()
      }
      return !isType
    },

    // 文件个数限制
    handleExceed(files, fileList) {
      console.log(files)
    },

     // 上传遮罩的问题
    handlerUploadMark() {
      const loading = this.$loading({
        lock: true,
        text: '正在上传中，请稍等...',
        color: '#fff',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return loading
    },

    // 上传报错的问题
    fileError(err, file, fileList) {
      console.log(err)
      this.uploadLoading.close()
      this.$message.warning('附件上传失败')
    },

    // 文件上传时的钩子
    uploadProgress(event, file, fileList) {

    },

    // 文件移除
    handleRemove(file, fileList, fileListName = 'fileList') {
      if((file.response && file.response.data[0].id )|| file.id) {
        return this.$confirm('确认删除该附件么？', '删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var id = ''
          if (file.response) {
            id = file.response.data[0].id
          } else {
            id = file.id
          }
          this.$api.upload.deleteFile(id).then(res => {
            this[fileListName] = fileList
            return  Promise.resolve()
          }).catch(() => {
            deleStatus = false
            return  Promise.reject()
          })
        }).catch(() => {
          return  Promise.reject()
        })
      }
    },

    // 文件上传成功
    uploadMoreSuccess(fileList, fileListName = 'fileList') {
      this[fileListName] = fileList
      this.uploadLoading.close()
    },

    // 点击文件列表中已上传的文件时的钩子
    previewFile(file) {
      var idNum = ''; var name = ''
      if (file.response) {
        const { response: { data }} = file
        idNum = data[0].id
        name = data[0].name
      } else {
        idNum = file.id
        name = file.name
      }
      window.open('/fileStorage/preview?fileId=' + idNum)
      // this.$api.upload.downLoadFile(idNum).then((res) => {
      //   this.$utils.exportFiles(res, name)
      // })
    }
  }
}
</script>

<style scoped>
.cy-upload {
  width: 100%;
  position: relative;
}
.cy-upload-content .el-upload-list  {
  margin-top: -42px;
}
.cy-upload .el-icon-close-tip {
  display: none !important;
}

.cy-upload .upload-form {
  border: 1px solid #E4E7ED;
  position: relative;
  border-radius: 4px;
}

.cy-upload .upload-form > div {
  float: right;
  position: absolute;
  right: 0px;
  height: 100%;
  background: #F0F9FC;
  display: flex;
}

.cy-upload .upload-form > ul {
  margin-top: -12px;
  width: calc(100% - 88px);
  min-height: 32px;
}

.cy-upload  .upload-file-length > ul {
  margin-top: 0px !important;
}
.cy-upload .upload-form > ul.is-disabled {
  width: 100%;
}
.cy-upload .el-upload-list__item {
  line-height: 32px;
}
.cy-upload-placeholder {
  font-size: 13px;
  color: #C0C4CC;
  line-height: 32px;
  position: absolute;
  top: 0px;
  left: 16px;
}

.cy-upload .el-upload-list__item .el-icon-close {
  line-height: 26px;
}
.cy-upload .upload-download {
  position: absolute;
  top: 0px;
  right: 115px;
  line-height: 32px;
  color: #67C23A;
  cursor: pointer;
}
.cy-upload .upload-download > div {
  margin-bottom: 5px;
}
</style>
