<template>
  <div class="shareModel">
    <div class="shareContent" id="shareContent">
      <img src="./images/share-bg.png" class="shareBg" />
      <div class="share_content__title">
        <p class="large">我在管乐迷发布了演奏作品</p>
        <p class="small">赶快扫码看看吧！</p>
      </div>

      <div class="share_music__container, sectionFile">
        <div class="uploadImg">
          <img src="../img/audio-pan.png" class="audioPan" crossorigin="anonymous" />
          <img class="muploader" :src="musicDetail.img ? musicDetail.img + '?t=' + new Date().getTime() : musicBg" crossorigin="anonymous" />
          <img class="imgLabel" :src="musicDetail.videoUrl && musicDetail.videoUrl.lastIndexOf('mp4') !== -1 ? require('./images/videoLabel.png') : require('./images/audioLabel.png')" />
        </div>
        <div class="musicDetail">
          <p class="musicName van-ellipsis">
            {{ musicDetail.musicSheetName }}
          </p>
          <p class="username">演奏者：{{ musicDetail.username }}</p>
        </div>
      </div>

      <div class="downloadSection">
        <div class="qrcode" :class="{animate: isAnimate}"               
            @mousedown="startOpenOutLink"
            @touchstart="startOpenOutLink"
            @mouseup="canceOpenOutLink"
            @mouseleave="canceOpenOutLink"
            @touchend="canceOpenOutLink">
          <!-- <canvas ref="canvasRef" class="qrcodeCanvas"></canvas> -->
          <vue-qr v-if="config" :text="config" :margin="10" :size="250" />
          <img src="../../../assets/images/icon_app.png" class="qrcodeLogo" />
        </div>
        <div class="qrtips">
          <div class="tit">温馨提示：</div>
          <p class="tip">
            保存图片到相册后，请在微信里扫码查看～
          </p>
          <img src="../../../assets/images/logo-black.png" class="iconLogo" />
        </div>
      </div>
    </div>

    <div class="shareBottom">
      <van-icon name="cross" class="iconClose" @click="$emit('close')" />
      <div class="share__header">海报已生成！快来分享吧！</div>
      <van-grid :columnNum="5" :border="false" class="gridSection">
        <van-grid-item :icon="iconDownload" text="保存本地" @click="onSavePath('')"></van-grid-item>
        <van-grid-item :icon="iconWechat" text="微信好友" @click="onSavePath('wechat')"></van-grid-item>
        <van-grid-item :icon="iconFriendRing" text="朋友圈" @click="onSavePath('wechat_circle')"></van-grid-item>
        <van-grid-item :icon="iconLink" text="复制链接" @click="copyText(config)"></van-grid-item>
      </van-grid>
      <div class="btn van-hairline--top" @click="$emit('close')">
        取消
      </div>
    </div>
  </div>
</template>

<script>
import html2canvas from "html2canvas";
import { postMessage } from "@/helpers/native-message";
import VueQr from "vue-qr";
export default {
  name: "share-model",
  components: { VueQr },
  props: ["musicDetail"],
  data() {
    return {
      iconDownload: require("./images/icon-download.png"),
      iconWechat: require("./images/icon-wechat.png"),
      iconFriendRing: require("./images/icon-friend-ring.png"),
      iconLink: require("./images/icon-link.png"),
      musicBg: require("./images/music-bg.png"),
      saveLoading: false,
      image: null,
      canvasRef: null,
      config: null,
      _time: null,
      isAnimate: false
    };
  },
  mounted() {
    this.config = location.origin + location.pathname + "#/shareCreation?id=" + this.musicDetail.id;
    console.log(this.musicDetail);
  },
  methods: {
    startOpenOutLink(){
      this.isAnimate = true
      this._time = setTimeout(() => {
        this.isAnimate = false
        postMessage({
          api: 'openOutLink',
          content : {
            "url" :  this.config
          }
        })
      }, 1000);
    },
    canceOpenOutLink(){
      this.isAnimate = false
      clearTimeout(this._time)
    },
    async saveImg() {
      setTimeout(() => {
        this.saveLoading = false;
        this.$toast.clear();
      }, 100);
      postMessage(
        {
          api: "savePicture",
          content: {
            base64: this.image,
          },
        },
        (res) => {
          if (res?.content?.status === "success") {
            this.$toast.success("已保存到相册");
          } else {
            this.$toast.fail("保存失败");
          }
        }
      );
    },

    async onSaveWe(type) {
      // this.$toast.loading({
      //   message: "图片分享中...",
      //   forbidClick: true,
      // });

      setTimeout(() => {
        this.saveLoading = false;
      }, 100);
      postMessage(
        {
          api: "shareTripartite",
          content: {
            title: "我在管乐迷发布了演奏作品",
            desc: this.musicDetail.desc,
            // image: this.image,
            video: "",
            type: "link",
            url: this.config,
            thumb: encodeURI(decodeURI(this.musicDetail.img)),
            shareType: type,
          },
        },
        (res) => {
          if (res?.content?.status) {
            this.$toast.success("分享成功");
          } else {
            this.$toast.fail("分享失败");
          }
        }
      );
    },
    onSavePath(type) {
      // 判断是否在保存中...
      if (this.saveLoading) {
        return;
      }
      this.saveLoading = true;
      if(type){
        this.onSaveWe(type);
      }else{
        this.$toast.loading({
          forbidClick: true,
          message: "下载中",
          duration:0
        });
        if (this.image) {
          this.saveImg();
        } else {
          const container = document.getElementById("shareContent");
          html2canvas(container, {
            allowTaint: true,
            useCORS: true,
            backgroundColor: null,
          })
            .then(async (canvas) => {
              const url = canvas.toDataURL("image/png");
              this.image = url;
                this.saveImg();
            })
            .catch(() => {
              this.$toast.clear();
              this.saveLoading = false;
            });
        }
      }
    },
    copyText(text) {
      // 数字没有 .length 不能执行selectText 需要转化成字符串
      const textString = text.toString();
      let input = document.querySelector("#copy-input");
      if (!input) {
        input = document.createElement("input");
        input.id = "copy-input";
        input.readOnly = true; // 防止ios聚焦触发键盘事件
        input.style.position = "fixed";
        input.style.left = "-1000px";
        input.style.zIndex = "-1000";
        // 为了处理，页面滑动到底部的问题
        document.body.appendChild(input);
        // document.querySelector('#input-copy-container')?.appendChild(input)
      }

      input.value = textString;
      // ios必须先选中文字且不支持 input.select();
      selectText(input, 0, textString.length);
      if (document.execCommand("copy")) {
        document.execCommand("copy");
        this.$toast("复制成功");
      }
      input.blur();

      // input自带的select()方法在苹果端无法进行选择，所以需要自己去写一个类似的方法
      // 选择文本。createTextRange(setSelectionRange)是input方法
      function selectText(textbox, startIndex, stopIndex) {
        if (textbox.createTextRange) {
          //ie
          const range = textbox.createTextRange();
          range.collapse(true);
          range.moveStart("character", startIndex); //起始光标
          range.moveEnd("character", stopIndex - startIndex); //结束光标
          range.select(); //不兼容苹果
        } else {
          //firefox/chrome
          textbox.setSelectionRange(startIndex, stopIndex);
          textbox.focus();
        }
      }
    },
  },
};
</script>

<style lang="less">
.shareContent {
  position: relative;
  width: 3.35rem;
  height: 3.55rem;
  margin: 0 auto 0.56rem;

  .shareBg {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 3.35rem;
    height: 3.55rem;
  }

  .share_content__title {
    position: relative;
    z-index: 3;
    padding-top: 0.54rem;
    padding-left: 0.14rem;
    color: #ffffff;
    text-shadow: 0px 0.02rem 0.04rem rgba(10, 181, 192, 0.7);
    width: 170px;

    .large {
      font-size: 0.19rem;
      font-weight: 600;
      line-height: 0.26rem;
    }

    .small {
      padding-top: 0.06rem;
      font-size: 0.14rem;
      line-height: 0.2rem;
    }
  }
}

.sectionFile {
  position: relative;
  z-index: 3;
  margin: 25px 0.15rem 0.14rem;
  padding: 12px;
  display: flex;
  background: rgba(255, 255, 255, 0.79);
  border-radius: 0.1rem;

  .muploader {
    position: relative;
    z-index: 9;
    width: 56px;
    height: 56px;
    object-fit: cover;
    border-radius: 8px;
  }

  .uploadImg {
    position: relative;
    border-radius: 8px;
    margin-right: 0.16rem;
    line-height: 0;

    .audioPan {
      position: absolute;
      top: 0;
      right: -6px;
      z-index: 1;
      width: 56px;
      height: 56px;
    }
    .imgLabel{
      position: absolute;
      right: 0;
      top: 0;
      width: 28px;
      height: 14px;
      z-index: 10;
    }
  }

  .musicDetail {
    display: flex;
    justify-content: center;
    flex-direction: column;

    .musicName {
      font-size: 0.16rem;
      font-weight: 600;
      color: #131415;
      line-height: 22px;
      max-width: 200px;
    }

    .username {
      padding-top: 0.04rem;
      font-size: 13px;
      color: #aaa;
      line-height: 0.2rem;
    }
  }
}

.downloadSection {
  display: flex;
  align-items: center;
  margin: 0 0.2rem;
  position: relative;
  z-index: 3;

  .qrcode {
    position: relative;
    width: 0.84rem;
    height: 0.84rem;
    padding: 0.03rem;
    border-radius: 0.04rem;
    // opacity: 0.53;
    border: 1px solid #2bd1b2;

    flex-shrink: 0;
    overflow: hidden;
    &.animate{
      transform: scale(1.1)
    }
    .qrcodeCanvas {
      width: 100% !important;
      height: 100% !important;
    }

    & > img {
      width: 0.84rem;
      height: 0.84rem;
    }

    .qrcodeLogo {
      position: absolute;
      top: 50%;
      left: 50%;
      z-index: 10;
      margin-left: -0.08rem;
      margin-top: -0.08rem;
      width: 0.16rem;
      height: 0.16rem;
      border-radius: 0.04rem;
    }
  }

  .qrtips {
    margin-left: 0.1rem;
    padding-left: 0.09rem;
    border-left: 1px dashed #d8d8d8;
    .tit{
      color: #01C1B5;
      line-height: .24rem;
      font-size: .13rem;
    }
    .tip {
      font-size: 0.12rem;
      color: #777777;
      line-height: 0.17rem;
    }

    .iconLogo {
      width: 0.68rem;
      height: 0.19rem;
      margin: .05rem 0 0;
      display: block;
    }

    .downTip {
      font-size: 0.12rem;
      font-weight: 500;
      color: #333333;
      line-height: 0.17rem;
    }
  }
}

.shareBottom {
  position: relative;
  background-color: #fff;
  border-radius: 0.12rem 0.12rem 0 0;
  //padding-bottom: env(safe-area-inset-bottom);
  padding-bottom: 0.1rem;

  .iconClose {
    position: absolute;
    top: 0.12rem;
    right: 0.12rem;
    font-size: 0.16rem;
    color: #999999;
  }
}

.share__header {
  padding: 0.12rem 0.15rem 0.08rem;
  font-size: 0.16rem;
  color: #333333;
  line-height: 22px;
}

.gridSection {
  justify-content: space-between;
  padding: 0 .13rem;
  .van-grid-item__icon {
    font-size: 0.44rem;
  }
  .van-grid-item__text {
    font-size: 0.12rem;
    color: #646566;
  }
}

.btn {
  font-size: 0.16rem;
  color: #aaaaaa;
  line-height: 0.55rem;
  text-align: center;
}
</style>
