<template>
  <div class="img-wrap bgques">
    <div class="box">
      
      <ul class="upload-imgs">
        <li v-for='(value, key) in imgs' class="imgLis">
          <p class="imgbox">
            <img
              :src="value"
              :preview="item.id"
              class="img"
              preview-text=""
            >
          </p>
          <a
            class="close"
            @click="delImg(key)"
          ></a>
        </li>
        <li
          v-show="imgLen<6"
          class="uploadBox"
        >
          <input
            type="file"
            class="upload"
            @change="addImg"
            accept="image/*"
            ref="inp"
          />
          <!-- <img src="../images/addimg.png"> -->
          <p>点击上传</p>
        </li>
      </ul>
    </div>
  </div>
</template>
<script type="text/javascript">
import {isIos,isWX,isQQ} from '@utils/tools';
import $ from 'jquery';
export default {
  name: 'UploadImg',
  data() {
    return {
      mag: "上传图片",
      imgs: {},
      imgLen: 0,
      flag:true //图片处理完成后才可以再次点击上传
    }
  },
  props: ['item', 'moduleType', 'imgList'],
  mounted() {
    this.imgs = this.imgList; //回读
    this.imgLen = Object.keys(this.imgList).length;
    this.$previewRefresh();//预览刷新
    /*if(isIos()){
      $('.upload').removeAttr("capture")
    }else if(!isWX()){ 
    // 微信端添加这个属性直接调拍照
    //安卓手机且非微信端添加相机属性，否则QQ浏览器打不开相机
      $('.upload').attr("capture","camera")
    }*/
    if(isQQ() && !isIos()){
      $('.upload').attr("capture","camera")
    }else{
      $('.upload').removeAttr("capture")
    }
  },
  methods: {
    handleUpload() {
      const inp = this.$refs.inp;
      if(this.flag){
        inp.click();
      } 
    },
    delImg(key) {
      let obj = this.imgs;
      delete (obj[key]);
      this.imgLen--;
      this.imgs = Object.assign({}, obj);
      this.$store.commit('deleImg', { key: key, type: this.moduleType });
      this.$store.commit('deleSrc', { key: key, type: this.moduleType });
    },
    addImg() {
      // 上传图片进行压缩，压缩后超过4M则不允许上传
      this.flag = false;
      let fileTag = this.$refs.inp;
      // let img = this.$refs.img;
      let file = fileTag.files[0];
      const that = this;
      this.imgBase64(file, function (image, canvas) {
        var maxSize = 0.5 * 1024; // 4M
        var fileSize = file.size / 1024; //kb 图片大小
        var uploadSrc;
        var uploadFile,imgWidth=image.width,imgHeight=image.height;
        // console.log(fileSize,'大小')
        if (fileSize > maxSize) { // 如果图片大小大于4m，进行压缩
          uploadSrc = canvas.toDataURL(file.type, 0.1);
          uploadFile = that.dataURLtoFile(uploadSrc, file.name); // 转成file文件
          // uploadFile = that.convertBase64UrlToBlob(uploadSrc); // 转成blob
        } else {
          uploadSrc = image.src;
          uploadFile = file;
        }

        var compressedSize = uploadFile.size / 1024 / 1024;
        // console.log('压缩',compressedSize)
        if (compressedSize.toFixed(2) > 4.00) {
          alert('上传图片不可超过4M');
        } else {
          let key = file.name + new Date().getTime();
          that.$set(that.imgs, key, uploadSrc);
          that.imgLen++;
          // 将图片信息存到store
          that.$store.commit('setImgFile', { type: that.moduleType, pId: that.item.id, key: key, file: uploadFile,imgWidth:imgWidth, imgHeight:imgHeight})
          that.$store.commit('setImgSrc', { key: key, src: uploadSrc, type: that.moduleType })
          that.$previewRefresh(); //异步获取的图片需要刷新下
        }
        // that.$refs.inp.value = '';
        fileTag.value = '';
        that.flag = true
      });
    },
    imgBase64(file, callback) {
      var self = this;
      // 看支持不支持FileReader
      if (!file || !window.FileReader) return;
      // 创建一个 Image 对象
      var image = new Image();
      // 绑定 load 事件处理器，加载完成后执行
      image.onload = function () {
        // 获取 canvas DOM 对象
        var canvas = document.createElement('canvas')
        // 返回一个用于在画布上绘图的环境, '2d' 指定了您想要在画布上绘制的类型
        var ctx = canvas.getContext('2d')
        // 如果高度超标 // 参数，最大高度
        var MAX_HEIGHT = 3000;
        if (image.height > MAX_HEIGHT) {
          // 宽度等比例缩放 *=
          image.width *= MAX_HEIGHT / image.height;
          image.height = MAX_HEIGHT;
        }
        // 获取 canvas的 2d 环境对象,
        // canvas清屏
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // 重置canvas宽高
        canvas.width = image.width;
        canvas.height = image.height;
        // 将图像绘制到canvas上
        ctx.drawImage(image, 0, 0, image.width, image.height);
        callback(image, canvas);
      };
      if (/^image/.test(file.type)) {
        var reader = new FileReader();
        // 将图片将转成 base64 格式
        reader.readAsDataURL(file);
        // 读取成功后的回调
        reader.onload = function () {
          // 设置src属性，浏览器会自动加载。
          // 记住必须先绑定事件，才能设置src属性，否则会出同步问题。
          image.src = this.result;
        }
      }
    },
    // 将以base64的图片url数据转换为Blob
    convertBase64UrlToBlob(urlData) {
      var bytes = window.atob(urlData.split(',')[1]); //去掉url的头，并转换为byte
      //处理异常,将ascii码小于0的转换为大于0
      var ab = new ArrayBuffer(bytes.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      return new Blob([ab], { type: 'image/jpg' });
    },
    // 将以base64的图片url数据转换为file
    dataURLtoFile(dataurl, filename) { //将base64转换为文件
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },

  }
}
</script>
<style lang="less" scoped>
.img-wrap {
  font-size: 0.3rem;
  .upload-imgs {
    margin-bottom: 0.2rem;
    .upload{
      width: 1.9rem;
      height: 100%;
      position: absolute;
      left: 0;
      z-index: 66;
      opacity: 0;
    }
    .uploadBox {
      // border: 1px solid #dfe0e4;
      box-sizing: border-box;
      text-align: center;
      background: url('../images/addimg.png') no-repeat;
      background-size: cover;
      position: relative;
      img {
        width: 0.6rem;
        margin: 0.45rem 0 0.23rem 0;
      }
      p {
        position: absolute;
        bottom: .16rem;
        left: 0;
        width: 100%;
        color: #AAAAAA;
      }
    }
    li {
      width: 1.9rem;
      height: 1.9rem;
      display: inline-block;
      position: relative;
      vertical-align: top;
      border-radius: 0.08rem;
      margin: 0 0 0.3rem 0.3rem;
      .close {
        width: 0.54rem;
        height: 0.54rem;
        background: url(../images/closeimg.png) no-repeat;
        background-size: cover;
        position: absolute;
        top: -0.27rem;
        right: -0.27rem;
        z-index: 3;
      }
    }
    .imgLis {
      border: 1px solid #dfe0e4;
    }
    li:nth-child(3n + 1) {
      margin-left: 0;
    }
    .imgbox {
      width: 100%;
      height: 100%;
      overflow: hidden;
      border-radius: 0.08rem;
      position: relative;
      .img {
        width: 100%;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
      }
    }
  }
}
</style>
