<!--
  上传组件
  type: 类型，默认image
  identify: key值，通过val获取
  disabled: 是否可用
  index: 父组件的下标
  imageIndex: 图片下标
  isShow: 图片的显示
 -->
<template>
    <div id="saga-upload">
      <el-upload
      v-if="type == 'image'"
      class="avatar-uploader"
      :http-request="uploadAndSubmit"
      :show-file-list="false"
      action=""
      accept="image/*"
      drag
      :disabled="disabled"
      style="position: relation"
      >
          <i class="el-icon-plus avatar-uploader-icon"></i>
          <img v-if="identify" :src="imageGetUrl + '&key=' + identify"></img>
          <div 
          v-if="!disabled && identify && isShow" 
          style="width: 20px; height:20px; background: #e6e6e6; position: absolute; top: 5px; right: 0px;"
          @click.stop="deleteImg">
            <i class="el-icon-close" ></i>
          </div>
      </el-upload>
    <div v-else id="uploadFile">
        <div v-if="name">
            <el-button type="text" @click="download">
                {{name}}          
            </el-button>
            <i v-if="disabled" class="el-icon-close delete-icon" style="margin-left:10px; cursor:pointer" @click="deleteImg"></i>
        </div>
        <el-upload
        class="upload-file"
        action=""
        :http-request="uploadAndSubmit"
        :show-file-list="false"
        drag
        >
            <el-button size="small" type="primary" v-if="disabled">点击上传</el-button>
        </el-upload>
    </div>
  </div>
</template>

<script>
import store from '@/store'
export default {
  name: "upload",
  props: {
    type: {
      type: String,
      default: "image"
    },
    identify: {
      type: String,
      default: ""
    },
    disabled: {
      type: Boolean,
      default: false
    }, //是否禁用上传功能
    index: {
      type: Number
    }, //下标，非必传项
    imgIndex: {
      type: Number
    }, //图片附件上传的第几个附件（同一index下的不同附件）
    isShow: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      baseUrl: "",
      fileGetUrl: "",
      fileUploadUrl: "",
      imageGetUrl: "",
      imageUploadUrl: "",
      name: ""
    };
  },
  created() {
    console.log(this.identify,'identify')
    this.name = this.identify
    this.getUrl();
  },
  methods: {

    //获取地址
    getUrl() {
      this.baseUrl = store.getters.getBaseUrl
      this.fileGetUrl = store.getters.getFileGetUrl
      this.fileUploadUrl = store.getters.getFileUploadUrl
      this.imageGetUrl = store.getters.getImageGetUrl
      this.imageUploadUrl = store.getters.getImageUploadUrl
    },
    //下载
    download(){
      window.open(this.baseUrl + this.fileGetUrl + '&key=' + this.identify)
    },
    //提交
    uploadAndSubmit(item) {
      let file = item.file;
      // try sending
      let reader = new FileReader();

      let vm = this;

      reader.onloadstart = function() {
        // 这个事件在读取开始时触发
      };
      reader.onprogress = function(p) {
        // 这个事件在读取进行中定时触发
      };

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

      let url = vm.type == "image" ? vm.imageUploadUrl : vm.fileUploadUrl;

      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 */
            url + "&key=" + file.name
            /*, async, default to true */
          );
          //xhr.overrideMimeType("application/octet-stream");
          xhr.send(reader.result);
          xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
              if (xhr.status == 200) {
                vm.name = file.name;
                vm.$emit("getKey", file.name, vm.index, vm.imgIndex);
              }
            }
          };
        }
      };
      reader.readAsArrayBuffer(file);
    },
    //删除指定图片
    deleteImg() {
      this.$confirm("您正在删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.name = "";
          this.$emit("delete-img", this.index, this.imgIndex);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  },
  watch:{
    identify: function(val,old){
      // console.log(old,val,1111)
      this.name = val
    }
  }
};
</script>

<style lang="scss">
#saga-upload {
  .dill-image {
    position: absolute;
    right: 0px;
    top: 0px;
    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;
      }
    }
  }
}
</style>