<template>
  <div id="uploadFile">
    <el-upload class="upload-file" action drag :show-file-list="false" :http-request="uploadAndSubmit">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
    <div v-show="item && filesArr.length" v-for="(item,index) in filesArr" :key="item.Key">
      <p class="file-list">
        <span class="file-name" :title="item.Name">{{item.Name}}</span>
        <!-- <i title="下载" class="el-icon-download" style="margin-left:10px; cursor:pointer" @click="download(item)"></i>-->
        <span v-if="!readOnly" title="删除" class="el-icon-circle-close file-icon" @click="deleteFile(index,item)"></span>
      </p>
    </div>
  </div>
</template>

<script>
import tools from "@/utils/tools";

export default {
props: {
  keysArr: {
    type: [Array, String],
    default: function () {
      return []
    }
  },
  readOnly: {
    type: Boolean,
    default: false
  },
  defined: String,
},
data() {
  return {
    filesArr: [],
  };
},
created() {
  this.fileFalg()
  // this.resetFile()
},
computed: {},
methods: {
  //判断是否为空
  fileFalg() {
    let type = typeof (this.keysArr)
    if (type == 'string') {
      this.filesArr = [this.keysArr]
    } else {
      this.filesArr = tools.deepCopy(this.keysArr)
    }
    this.filesArr = tools.deepCopy(this.keysArr)
    if (!this.keysArr) {
      this.filesArr = []
    }
  },
  resetFile() {
    this.filesArr = []
  },


  //点击下载
  // download(item) {
  //   if (item.Key) {
  //     let a = document.createElement("a");
  //     a.href = `/image-service/common/file_get/${item.Key}?systemId=dataPlatform`;
  //     a.download = `${item.Name}`;
  //     a.click();
  //     document.body.removeChild(a);
  //   } else {
  //     this.$message({
  //       message: "无该获取该文件资源链接！",
  //       type: "error"
  //     });
  //   }
  // },

  //删除图片
  deleteFile(i, key) {
    this.filesArr.splice(i, 1);
    this.$emit("change", this.filesArr, this.defined);
  },

  //上传
  uploadAndSubmit(item) {
    let file = item.file;
    let size = item.file.size;
    if (size > 50 * 1024 * 1024) { //文件大于50M
      this.$message.error('文件不可大于50M，请重新上传')
      return false
    } else {
      let reader = new FileReader();
      let vm = this;
      let fileType = file.name.split(".");
      let type = fileType[fileType.length - 1];
      let key = "&key=" + fileType[0] + file.uid + "." + type
      // let CreateTime = tools.formatDate(new Date(file.lastModified))
      reader.onloadstart = function () {
        // 这个事件在读取开始时触发
      };
      reader.onprogress = function (p) {
        // 这个事件在读取进行中定时触发
        let value = (p.loaded / size) * 100;
      };

      reader.onload = function () {
        // 这个事件在读取成功结束后触发
      };
      reader.onloadend = function () {
        // 这个事件在读取结束后，无论成功或者失败都会触发
        if (reader.error) {
        } else {
          // document.getElementById("bytesRead").textContent = file.size;
          // 构造 XMLHttpRequest 对象，发送文件 Binary 数据
          var xhr = new XMLHttpRequest();
          xhr.open(
            /* method */
            "POST",
            /* target url */
            "/image-service/common/file_upload?systemId=dataPlatform&secret=9e0891a7a8c8e885&overwrite=true" + key
            /*, async, default to true */
          );
          //xhr.overrideMimeType("application/octet-stream");
          xhr.send(reader.result);
          xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
              console.log(xhr)
              if (xhr.status == 200) {
                let fileObject = {
                  Key: key.split("=")[1],
                  Type: type,
                  Name: file.name,
                  // CreateTime,
                  SystemId: 'dataPlatform'
                }

                vm.filesArr.push(fileObject);
                vm.$emit("change", vm.filesArr, vm.defined);
              } else {
                this.$message.error(res.data.ResultMsg)
              }
            }
          };
        }
      };
      reader.readAsArrayBuffer(file);
    }

  }
},
watch: {
  keysArr: function (val) {
    this.fileFalg()
  }
}
};
</script>
<style lang="less" scoped>
#uploadFile {
  .file-list {
    border: 1px solid #e9e9e9;
    height: 48px;
    width: 360px;
    line-height: 48px;
    border-radius: 4px;
    margin-bottom: 10px;

    .file-name {
      display: inline-block;
      margin-left: 10px;
      width: 300px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .file-icon {
      float: right;
      cursor: pointer;
      line-height: 48px;
      margin-right: 15px;
    }
  }
}
</style>

