<template>
  <div class="upload-pic">
    <dl v-show="!isWeixin" class="upload-dl">
      <dd class="pic-dd" v-for="(item,index) in pcPics" :key="index">
        <!--<input type="file" accept="image/jpg, image/jpeg, image/png" capture="camera"/>-->
        <img class="addImg" :src="item.imageUrl" @click="previewImage(item)">
        <span @click="deletePic(index)">&nbsp;</span>
      </dd>
      <dd class="add-dd" v-show="addMore" @click.stop="addPic">
        <!-- <input class="add-input" type="file" accept="image/jpg, image/jpeg, image/png" capture="camera"
               @change="pcChange($event)"
        /> -->
        <img class="addImg" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==">
        <span>&nbsp;</span>
      </dd>
      <dt v-show="addMore" v-if="maxImages && maxImages>0">
        <label>最多可上传{{maxImages}}张图片</label>
      </dt>
    </dl>
    <dl v-show="isWeixin" class="upload-dl">
      <dd class="pic-dd" v-for="(item,index) in localIds" :key="index">
        <img class="addImg" :src="getWechatPic(index)">
        <span @click="deleteWechatPic(index)">&nbsp;</span>
      </dd>
      <dd class="add-dd" v-show="addMore">
        <img class="addImg" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="
             @touchend="wechatAddPic">
        <span>&nbsp;</span>
      </dd>
      <dt v-show="addMore" v-if="maxImages && maxImages>0">
        <label>最多可上传{{maxImages}}张图片</label>
      </dt>
    </dl>
  </div>
</template>

<script>
  // import {putJsSDKConfig} from '@/service/getData'
  import util from './../util/util.js';

  export default {
    name: 'uploadPic',
    props:{
      maxImages:{
        type:Number,
      }
    },
    data() {
      return {
        pcPics: [],
        localIds: [],
        serverIds: [],
        wechatTempPics: [],
        maxsize: 100 * 1024,
        imagePath: "http://wx.bjyijiequ.com/yjqapp/",
        isWeixin: util.isWeixin(),
      }
    },
    computed: {
      addMore: function () {
        if (!this.isWeixin) {
          if (this.maxImages && this.maxImages > 0 && this.pcPics.length === this.maxImages) {
            return false;
          } else {
            return true;
          }
        } else {
          if (this.maxImages && this.maxImages > 0 && this.localIds.length === this.maxImages) {
            return false;
          } else {
            return true;
          }
        }

      },
      // isWeixin: function () {
      //   var ua = navigator.userAgent.toLowerCase();
      //   if (ua.match(/MicroMessenger/i) == "micromessenger") {
      //     return true;
      //   } else {
      //     return false;
      //   }
      // }
    },
    created: function () {
      var targetUrl = window.location.href.split('#')[0];
      var projectType = localStorage.projectType;
      var self = this;
      if (this.isWeixin) {
        if (localStorage.getItem('wpt_localIds') !== '') {
          self.localIds = JSON.parse(localStorage.getItem('wpt_localIds'));
          self.serverIds = JSON.parse(localStorage.getItem('wpt_serverIds'));
        }

        if (!self.localIds) {
          self.localIds = [];
        }
        if (!self.serverIds) {
          self.serverIds = [];
        }
        putJsSDKConfig(targetUrl, projectType).then(res => {
          res.debug = false;
          self.$wechat.config(res)
          console.log(res)
        });
      } else {
        var file_bases = localStorage.getItem('file_bases');
        if (!util.isStrEmpty(file_bases) && file_bases!="undefined") {
          this.pcPics = JSON.parse(file_bases);
        }
        if (!self.pcPics) {
          self.pcPics = [];
        }
      }
    },
    methods: {
      getWechatPic: function (index) {
        var uuid = this.serverIds[index].split("&")[0];
        var localId = this.localIds[index];
        var url = localId ? localId : this.imagePath + uuid;
        return url;
      },

      addPic () {
        let that = this
        // self.pcPics.push(result);
              // localStorage.setItem('file_bases', JSON.stringify(self.pcPics));
        EbeiPlugins.takePhoto({enabledcamera: true, enabledphoto: true}, (array) => {
          console.log(array)
          let length = array.length
          for (let index = 0; index < length; index++) {
            const element = array[index];
            that.pcPics.push(element);
            localStorage.setItem('file_bases', JSON.stringify(that.pcPics));
          }
        }, () => {
          // 获取失败
        })
      },

      getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
        var dataURL = canvas.toDataURL("image/"+ext);
        return dataURL;
      },

      pcChange: function (event) {
        var self = this;
        if (event.target.files && event.target.files[0]) {
          var file = event.target.files[0];
          if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
          var reader = new FileReader();
//          获取图片大小
          var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
          reader.onload = function () {
            var result = this.result;
            $('.add-input').val('');
            var img = new Image();
            img.src = result;
            //如果图片大小小于100kb，则直接上传
            if (result.length <= self.maxsize) {
              self.pcPics.push(result);
              localStorage.setItem('file_bases', JSON.stringify(self.pcPics));
              return;
            }
            //图片加载完毕之后进行压缩，然后上传
            if (img.complete) {
              callback();
            } else {
              img.onload = callback;
            }

            function callback() {
              var data = self.compress(img);
              self.pcPics.push(data);
              localStorage.setItem('file_bases', JSON.stringify(self.pcPics));
              img = null;
            }
          };

          reader.readAsDataURL(file);
        }
      },
      compress: function (img) {
        //用于压缩图片的canvas
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext('2d');
        //    瓦片canvas
        var tCanvas = document.createElement("canvas");
        var tctx = tCanvas.getContext("2d");
        var maxsize = 100 * 1024;
        var initSize = img.src.length;
        var width = img.width;
        var height = img.height;
        //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
        var ratio;
        if ((ratio = width * height / 4000000) > 1) {
          ratio = Math.sqrt(ratio);
          width /= ratio;
          height /= ratio;
        } else {
          ratio = 1;
        }
        canvas.width = width;
        canvas.height = height;
        //	        铺底色
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        //如果图片像素大于100万则使用瓦片绘制
        var count;
        if ((count = width * height / 1000000) > 1) {
          count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
          //	            计算每块瓦片的宽和高
          var nw = ~~(width / count);
          var nh = ~~(height / count);
          tCanvas.width = nw;
          tCanvas.height = nh;
          for (var i = 0; i < count; i++) {
            for (var j = 0; j < count; j++) {
              tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
              ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
            }
          }
        } else {
          ctx.drawImage(img, 0, 0, width, height);
        }
        //进行最小压缩
        var ndata = canvas.toDataURL('image/jpeg', 0.7);
        console.log('压缩前：' + initSize);
        console.log('压缩后：' + ndata.length);
        console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
        tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
        return ndata;
      },
      deletePic(index) {
        var self = this;
        this.pcPics.splice(index, 1);
        localStorage.setItem('file_bases', JSON.stringify(self.pcPics));
      },
      deleteWechatPic(index) {
        this.localIds.splice(index, 1);
        this.serverIds.splice(index, 1);
        localStorage.setItem('wpt_serverIds', JSON.stringify(this.serverIds));
        localStorage.setItem('wpt_localIds', JSON.stringify(this.localIds));
      },
      wechatAddPic() {
        var self = this;
        var count = 9;
        if (self.maxImages != undefined && self.maxImages > 0) {
          count = self.maxImages;
        }
        count = count - self.localIds.length;
        self.$wechat.chooseImage({
          count: count, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            self.wechatTempPics = res.localIds;
            self.wechatUpload();
          },
          cancel: function () {
          },
          fail: function (e) {
          }
        });
      },
      wechatUpload() {
        var self = this;
        if (self.wechatTempPics.length > 0) {
          var localId = self.wechatTempPics.shift();
          self.$wechat.uploadImage({
            localId: localId,
            isShowProgressTips: 0,
            success: function (res) {
              var _serverId = self.uuid() + "&" + res.serverId;
              self.serverIds.push(_serverId);
              self.localIds.push(localId);
              // $(document.body).trigger('wptLoading_view:msg', '正在上传...<div class="process">' + index + " / " + imgList.length + '</div>');
              if (self.wechatTempPics.length > 0) {
                 setTimeout(self.wechatUpload(), 300);

              } else {
                localStorage.setItem('wpt_serverIds', JSON.stringify(self.serverIds));
                localStorage.setItem('wpt_localIds', JSON.stringify(self.localIds));
                // setTimeout(function () {
                //   $(document.body).trigger('wptLoading_view:hide');
                // }, 300);
              }
            },
            fail: function (res) {
              // $(document.body).trigger('wptLoading_view:hide');
            }
          });
        }
      },
      uuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
      },
      previewImage (item) {
        if (this.util.isWeixin) {
          return
        }

        console.log('预览图片'+ JSON.stringify(item));
        try {
          EbeiPlugins.previewFile(item.bigimageUrl, null, null);
        } catch (e) {

        }
      },
    }
  }
</script>

<style scoped>
  .addImg {width: 55px;height: 55px;}
  .upload-dl dd {
    margin-left: 10px;
  }

  .upload-dl dt {
    margin-left: 15px;
  }

  .upload-dl dd span {
    right: -10px;
  }

  .upload-dl dd img[src^="data:"] {
    background: url(../assets/images/uploadFile/icon_camera.png) no-repeat center center;
    background-size: 40px auto;
    width: 100%;
    height: 100%;
    display: block;
  }

  .upload-dl dd input[type="file"] {
    display: block;
    position: absolute;
    z-index: 100;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
  }

  .upload-dl dd img[src^="data:image/gif"] + span {
    visibility: hidden;
  }

  .upload-dl dd span {
    display: block;
    width: 20px;
    height: 20px;
    position: absolute;
    z-index: 110;
    right: 0px;
    top: -10px;
    border-radius: 30px;
    background: url(../assets/images/uploadFile/icons.png) no-repeat center -98px;
    background-size: 31px auto;
    background-color: red;
    -webkit-transform: rotate(45deg);
  }

  .upload-dl dt {
    display: inline-block;
    height: 55px;
    line-height: 55px;
    width: 130px;
    font-size: 12px;
    margin: 15px 0px;
    font-size: 12px;
    margin-left: 15px;
    color: #b0b0b0;
  }

  .upload-pic dd {
    display: inline-block;
    width: 55px;
    height: 55px;
    margin: 15px 3px;
    position: relative;
    float: left;
  }

  .upload-pic {
    overflow: hidden;
    padding-left: 7px;
    background-color: #fff;
  }

  .upload-pic dd + dd {
    margin-left: 15px;
  }

  .upload-pic pic-dd img {
    border: 0;
  }
</style>
