<!--
  上传组件
  type: 类型，默认image
  identify: key值，通过val获取
  disabled: 是否可用
  index: 父组件的下标
  imageIndex: 图片下标
  isShow: 图片的显示
 -->
<template>
  <div id="saga-upload" v-loading="loading">
    <div id="uploadFile">
      <el-upload
        class="upload-file"
        action drag
        :show-file-list="false"
        :http-request="uploadAndSubmit">
        <el-button size="small" type="primary" v-if="!readOnly">点击上传</el-button>
        <div slot="tip" class="el-upload__tip" v-if="!readOnly">请上传文件，且不大于50M</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>
          <i v-if="!readOnly" title="删除" class="el-icon-close delete-icon" style="margin-left:10px; cursor:pointer" @click="deleteFile(index,item)"></i>
        </p>
      </div>
    </div>
  </div>
</template>

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

export default {
  props: {
    keysArr: {
      type: [Array, String],
      default: function () {
        return []
      }
    },
    readOnly: {
      type: Boolean,
      default: false
      },
      max: {
        type: [Number, String],
        default: 6
      },
      defined: null,
      firmDataType: {
        type: String
      },
      information: {
        type: Object
      },
      infoType: {
        type: String
      }
    },
    data() {
      return {
        filesArr: [],
        isShow: Boolean,
        loading:false
      };
    },
    created() {
      this.fileFalg()
      // this.resetFile()
    },
    computed: {
      showFileList() {
        if (this.firmDataType === 'dialog') {
          this.isShow = false
        } else {
          this.isShow = true
        }
        return this.isShow
      }
    },
    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) {
        // var form = document.forms["demoForm"];

        // if (form["file"].files.length > 0) {
        // 寻找表单域中的 <input type="file" ... /> 标签
        // var file = form["file"].files[0];

        let file = item.file;
        // try sending
        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;
            console.log(p.loaded,size,value,'loaded')
          };

          reader.onload = function () {

            // 这个事件在读取成功结束后触发
          };
          reader.onloadend = function () {

            this.loading = false
            // 这个事件在读取结束后，无论成功或者失败都会触发
            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,
                      name: file.name,
                      createTime: CreateTime,
                      systemId: 'dataPlatform'
                    }
                    vm.filesArr.push(fileObject);
                    this.loading =false
                    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">
  #saga-upload {
    .dill-image {
      position: absolute;
      right: 0;
      top: 0;
      font-size: 20px;
    }

    .el-upload-dragger {
      width: 180px;
      height: 180px;
    }

    img {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      width: 100%;
      height: 100%;
    }

    #uploadFile {
      .upload-file {
        overflow: hidden;
        .el-upload-dragger {
          width: inherit;
          height: inherit;
          border: none;
        }
      }
      .file-list {
        .file-name {
          display: inline-block;
          width: 400px;
          font-size: 12px;
          color: #409eff;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          vertical-align: top;
          cursor: pointer;
        }
        .file-name:hover {
          color: #66b1ff;
        }
      }
    }
  }
</style>
