<!--
    @param keysArr 承接数组
    @param readOnly  删除按钮是否显示,上传是否显示
    @param max     上传最大数限制
    @click change  承接数组发生变化时触发函数
-->
<template>
  <div id="sagaUploads">
    <div class="saga-upload-images">
      <div v-if="type != 'video'" class="point-image" v-for="(item,index) in imagesArr">
        <i v-if="!readOnly" class="el-icon-delete" @click="delImage(index,item)"></i>
        <img :src="imageGetUrl + '&key=' +item.key" @click="lookImg" alt v-load>
      </div>
      <div v-if="type == 'video'" class="point-image" v-for="(item,index) in imagesArr">
        <i v-if="!readOnly" class="el-icon-delete" @click="delImage(index,item)"></i>
        <video
          width="100%"
          height="100%;"
          :src="imageGetUrl + '&key=' +item.key"
          controls="controls"
        >您的浏览器不支持 video 标签。</video>
      </div>
      <div v-if="!readOnly && imagesArr.length < max" style="float:left;">
        <el-upload
          class="avatar-uploader"
          :http-request="uploadAndSubmit"
          :show-file-list="false"
          :accept="accept"
          action
          drag
          style="position: relation"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <video style="display:none;" id="video" controls/>
      </div>
    </div>
    <details-dialog :title="'图片'" :iframeSrc="iframeSrc" :dialog="dialog" :setData="imagesArr"></details-dialog>
  </div>
</template>
<script>
import tools from "@/utils/scan/tools";
import detailsDialog from "@/components/business_space/lib/detailsDia"
export default {
  components: {
    detailsDialog
  },
  props: {
    keysArr: {
      type: [Array, String]
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    max: {
      type: [Number, String],
      default: 6
    },
    accept: {
      type: String,
      default: "image/*"
    },
    type: {
      type: String,
      default: "image"
    },
    defined: null,
    videoPicArr: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data() {
    return {
      baseUrl: "",
      imageGetUrl: "/image-service/common/image_get?systemId=dataPlatform",
      imageUploadUrl: "/image-service/common/image_upload?systemId=dataPlatform&secret=9e0891a7a8c8e885&overwrite=true",
      imagesArr: [],
      iframeSrc: "",
      dialog: {
        details: false
      }
    };
  },
  created() {
    this.imageFalg();
  },
  methods: {
    //判断是否为空
    imageFalg() {
      let type = typeof this.keysArr;
      console.log(this.keysArr)
      if (type == "string") {
        this.imagesArr = [this.keysArr];
      } else {
        this.imagesArr = tools.deepCopy(this.keysArr);
      }

      if (!this.keysArr) {
        this.imagesArr = [];
      }
    },
    //查看图片
    lookImg() {
      this.dialog.details = true
      this.iframeSrc = process.env.BASE_URL + ":8890/photo-View.html"
    },
    //删除图片
    delImage(i, key) {
      if (this.type == "video") {
        this.videoPicArr = this.videoPicArr.map(item => {
          if (item.substring(0, item.length - 3) == this.imagesArr[i].substring(0, this.imagesArr[i].length - 3)) {
            return undefined
          } else {
            return item
          }
        }).filter(p => p)
      }
      this.imagesArr.splice(i, 1);
      this.$emit("change", this.imagesArr, this.defined, this.videoPicArr);
    },

    //上传
    uploadAndSubmit(item, key) {
      // 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 reader = new FileReader();

      let vm = this;

      let fileType = file.name.split(".");
      let type = fileType[fileType.length - 1];

      let uploadKey = file.uid
      if (!!key) {
        uploadKey = key
      }

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

      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 */
            vm.imageUploadUrl + "&key=" + uploadKey + "." + type
            /*, async, default to true */
          );
          //xhr.overrideMimeType("application/octet-stream");
          xhr.send(reader.result);
          xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
              if (xhr.status == 200) {
                if (vm.type == 'image') {
                  vm.imagesArr.push({
                    name: uploadKey + '',
                    key: uploadKey + "." + type,
                    systemId: "dataPlatform",
                    type: "image"
                  });
                }
                if (type == 'mp4') {
                  vm.imagesArr.push({
                    name: uploadKey + '',
                    key: uploadKey + "." + type,
                    systemId: "dataPlatform",
                    type: "video"
                  });
                  vm.creatImg(vm.imageGetUrl + "&key=" + uploadKey + "." + type, uploadKey)
                }
                console.log(vm.type, type)
                if (vm.type == "video" && type == "png") {
                  console.log("触发时评上传图片回调")
                  vm.videoPicArr.push(uploadKey + "." + type)
                }
                vm.$emit("change", vm.imagesArr, vm.defined, vm.videoPicArr);
              }
            }
          };
        }
      };
      reader.readAsArrayBuffer(file);
    },
    dataURLtoBlob: function (dataURI, type) {
      var binary = atob(dataURI.split(',')[1]);
      var array = [];
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], { type: type });
    },

    creatImg(reader, key) {
      var videoDom = document.getElementById('video');
      videoDom.src = reader;
      let vm = this
      videoDom.onloadeddata = function () {
        // 这里可以打印视频时长
        // 这里取得视频封面
        var canvas = document.createElement('canvas');
        canvas.width = 300;
        canvas.height = 300 * this.videoHeight / this.videoWidth;
        canvas.getContext('2d').drawImage(this, 0, 0, canvas.width, canvas.height);
        //将canvas的base64位图片转换成图片png的file
        var blob = vm.dataURLtoBlob(canvas.toDataURL('image/png'), "image/png")
        //将其转换成file对象
        var file = new File([blob], "video_image.png", { type: "image/png", lastModified: Date.now() })//blob转file
        vm.uploadAndSubmit({ file: file }, key)
      }
    },
  },
  watch: {
    keysArr: function (val) {
      this.imageFalg();
    }
  },
  //自定义指令
  directives: {
    load: function (el) {
      let imgDom = document.createElement("img");
      imgDom.style.position = "absolute";
      imgDom.style.top = "-999px";
      imgDom.style.opacity = 0;
      imgDom.src = el.src;
      el.src = "";
      imgDom.onload = () => {
        let width = imgDom.width;
        let height = imgDom.height;
        if (width > height) {
          el.style.height = "100%";
          el.style.width = "auto";
          el.style.position = "absolute";
          el.style.left = "50%";
          el.style.top = "0";
          el.style.transform = "translateX(-50%)";
          el.style.webkitTransform = "translateX(-50%) translateY(0)";
          el.style.MozTransform = "translateX(-50%) translateY(0)";
          el.style.msTransform = "translateX(-50%) translateY(0)";
          el.style.OTransform = "translateX(-50%) translateY(0)";
        } else if (width < height) {
          el.src = imgDom.src;
          el.style.width = "100%";
          el.style.height = "auto";
          el.style.position = "absolute";
          el.style.top = "50%";
          el.style.left = "0";
          el.style.transform = "translateY(-50%) translateX(0)";
          el.style.webkitTransform = "translateY(-50%) translateX(0)";
          el.style.MozTransform = "translateY(-50%) translateX(0)";
          el.style.msTransform = "translateY(-50%) translateX(0)";
          el.style.OTransform = "translateY(-50%) translateX(0)";
        } else {
          el.style.width = "100%";
          el.style.height = "100%";
          el.style.position = "absolute";
          el.style.top = "0";
          el.style.left = "0";
          el.style.transform = "translateY(0) translateX(0)";
          el.style.webkitTransform = "translateY(0) translateX(0)";
          el.style.MozTransform = "translateY(0) translateX(0)";
          el.style.msTransform = "translateY(0) translateX(0)";
          el.style.OTransform = "translateY(0) translateX(0)";
        }
        el.src = imgDom.src;
      };
    }
  }
};
</script>
<style lang="less">
#sagaUploads {
  overflow: hidden;
  .avatar-uploader {
    height: 180px;
    width: 180px;
    overflow: hidden;
    .el-upload {
      width: 180px;
      height: 180px;
      .el-upload-dragger {
        width: 180px;
        height: 180px;
        .el-icon-plus {
          display: block;
          width: 20px;
          height: 20px;
          font-size: 20px;
          margin: 80px;
        }
      }
    }
  }
  .point-image {
    width: 180px;
    height: 180px;
    float: left;
    position: relative;
    margin-right: 10px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    overflow: hidden;
    image {
      z-index: 11;
    }
    i {
      position: absolute;
      bottom: 10px;
      right: 10px;
      background-color: #fff;
      padding: 5px;
      cursor: pointer;
      z-index: 66;
    }
  }
}
</style>
