<template>
  <div class="uploadCont">
    <ul class="showImage">
      <li @click="chooseImage">
        <img src />
      </li>
      <li
        @click="previewImage(saveImages.previewImageList[index])"
        v-for="(item,index) in saveImages.previewThumbList"
        :key="index"
      >
        <img :src="item" />
        <button @click.stop @click="remove(index)"></button>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      userCode: localStorage.userCode || "", //用户code
      images: {
        localId: [], //已选择的本地图片
        serverId: [] //微信服务器返回的mediaId
      },
      saveImages: {
        previewImageList: [], //预览大图数组,
        previewThumbList: [], //预览缩略图数组
        saveImageList: [] //预览大图数组//保存图片
      },
      uploadPath: "" //图片上传的路径：为空时，默认下载到当前项目的/mcupload路径下
    };
  },
  methods: {
    /**
     * 选择图片
     */
    chooseImage() {
      let _this = this;
      wx.chooseImage({
        success: function(res) {
          //res.localIds 是一个数组　保存了用户一次性选择的所有图片的信息
          _this.images.localId = res.localIds; //把图片的路径保存在images[localId]中--图片本地的id信息，用于上传图片到微信浏览器时使用
          //alert('已选择 ' + res.localIds.length + '张图片 ');
          //===上传
          let length = res.localIds.length;
          if (length == 0) {
            _this.$alert("请选择图片");
            return;
          }
          var i = 0;

          _this.images.serverId = [];

          function upload() {
            wx.uploadImage({
              localId: _this.images.localId[i],
              success: function(res) {
                i++;
                _this.images.serverId.push(res.serverId);
                //下载刚刚上传的图片
                JssdkService.getMediaByUser(
                  res.serverId,
                  _this.uploadPath,
                  _this.userCode,
                  function(res) {
                    //  alert(res.substr(45));
                    var path = res.responseParam1.split("mecwish")[1];
                    var path_thumb = path.replace(
                      "/mcupload/",
                      "/mcupload/_thumb/"
                    );
                    if (path != null && path.length != 0) {
                      _this.saveImages.saveImageList.push(path);
                      _this.saveImages.previewImageList.push(
                        window.location.protocol +
                          "//" +
                          window.location.host +
                          "/mecwish" +
                          path
                      ); //将图片上传的位置
                      _this.saveImages.previewThumbList.push(
                        window.location.protocol +
                          "//" +
                          window.location.host +
                          "/mecwish" +
                          path_thumb
                      ); //将缩略图上传的位置
                    }
                  }
                );

                if (i < length) {
                  upload();
                }
              },
              fail: function(res) {
                alert(JSON.stringify(res));
              }
            });
            _this.$emit("saveImages", _this.saveImages.saveImageList);
          }

          upload();
        }
      });
    },
    //预览图片
    previewImage(currentImg) {
      let _this = this;
      wx.previewImage({
        current: currentImg, //当前图片
        urls: _this.saveImages.previewImageList
      });
    },
    //删除图片，数据库里没删除
    remove(index) {
      this.$emit("removed", index);
      this.saveImages.saveImageList.splice(index, 1);
      this.saveImages.previewImageList.splice(index, 1);
      this.saveImages.previewThumbList.splice(index, 1);
    }
  },
  created() {
    let _this = this;
    let clientUrl = location.href;
    // let url = $config.rootPath + '/js/sdk/getWxConfig?wxCode=' + $config.wxCode + '&clientUrl=' + clientUrl
    let url = process.env.basePathRl + "getSignature";
    let param = {
      apiKey: "handexinxi",
      url: clientUrl
    };
    hlsHttp.post(url, param).then(function(res) {
      wx.config({
        beta: true,
        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: res.result.appId, // 必填，公众号的唯一标识
        timestamp: res.result.timestamp, // 必填，生成签名的时间戳
        nonceStr: res.result.nonceStr, // 必填，生成签名的随机串
        signature: res.result.signature, // 必填，签名，见附录1
        jsApiList: [
          "chooseImage",
          "previewImage",
          "downloadImage",
          "getLocalImgData",
          "uploadImage"
        ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      });
      wx.error(function(res) {
        this.$alert(res.errMsg);
      });
    });
  }
};
</script>
<style scoped>
.uploadCont .showImage {
  display: flex;
  list-style: none;
  flex-wrap: wrap;
  margin: 7px 0 5px 10px;
}

.uploadCont .showImage li {
  position: relative;
  width: 28vw;
  height: 28vw;
  list-style: none;
  /*background: #f00;*/
  margin: 5px 2vw 7px 0;
}

.uploadCont .showImage .remove {
  z-index: 11;
  position: absolute;
  top: -14px;
  right: -20px;
  font-size: 26px;
}

.uploadCont .showImage img {
  width: 28vw;
  height: 28vw;
}
</style>