<template>
  <div ref="sharePic" class="container" style="width: 1080px; height: 1920px; padding: 48px;">
    <div class="groupInfo" style="width: 100%; height: 319px;">
      <!-- 组团头像信息 -->
      <div class="avatorGroup">
        <template v-if="avatorList.length !== 0">
          <div
            v-for="(item, index) in avatorList"
            :key="index"
            class="item"
            style="width: 94px;height: 94px;margin: 0 21px;"
            :class="{ leader: index == 0, normal: index != 0 }"
          >
            <img class="avator" style="width: 94px; height: 94px;" :src="item" alt="" />
            <template v-if="index == 0">
              <div
                class="leaderName"
                style="width: 76px;height: 36px;border-radius: 8px;font-size: 24px;bottom: -18px;"
              >
                团长
              </div>
              <div class="leaderBorder">
                <img
                  src="https://img.lkbang.net/activity/share/default/leaderBorder.png?i=9"
                  alt=""
                />
              </div>
              <div class="crown" style="top: -18px;right: -5px;width: 49px;height: 43px;">
                <img src="https://img.lkbang.net/activity/share/default/crown.png?i=1" alt="" />
              </div>
            </template>
          </div>
          <div
            v-for="num in maxCount - avatorList.length"
            :key="`placeholder${num}`"
            class="item placeholder"
            style="width: 94px;height: 94px;margin: 0 21px;font-size: 34px;"
          />
        </template>
        <template v-else>
          <div
            class="item leader bg"
            style="width: 94px;height: 94px;margin: 0 21px; font-size: 34px;"
          >
            <div
              class="leaderName"
              style="width: 76px;height: 36px;border-radius: 8px;font-size: 24px;bottom: -18px;"
            >
              团长
            </div>
            <div class="leaderBorder">
              <img
                src="https://img.lkbang.net/activity/share/default/leaderBorder.png?i=9"
                alt=""
              />
            </div>
            <div class="crown" style="top: -18px;right: -5px;width: 49px;height: 43px;">
              <img src="https://img.lkbang.net/activity/share/default/crown.png?i=9" alt="" />
            </div>
          </div>
          <div
            v-for="num in maxCount - avatorList.length"
            :key="`placeholder${num}`"
            class="item placeholder"
            style="width: 94px;height: 94px;margin: 0 21px;font-size: 34px;"
          />
        </template>
        <div
          v-if="openGroupCnt >= 7"
          class="item more"
          style="width: 94px;height: 94px;margin: 0 21px;font-size: 34px;"
        />
      </div>
      <div class="groupProcess" style="width: 920px;height: 123px;padding-top: 50px;">
        <div class="desc" style="border-radius: 36.5px;font-size: 34px;">
          <template v-if="avatorList.length == 0">
            开团0元拿商品，
          </template>
          <template v-else>
            还差 <span style="margin: 0 10px;">{{ sharePicData.needGuys }}人</span> 成团，
          </template>
          <template v-if="endTime != ''">
            <template v-if="avatorList.length == 0">活动</template>
            <template v-else>参团</template>截止时间 {{ endTime }}
          </template>
        </div>
      </div>
    </div>
    <div class="skuImg" style="width: 984px;height: 984px;">
      <!-- 商品图 -->
      <img :src="sharePicData.skuImg" alt="" />
      <div class="skuInfo" style="height: 134px;">
        <div
          class="skuPrice"
          style="width: 653px;font-size: 34px;padding-left: 32px;margin-right: 10px;"
        >
          <span class="groupPriceContainer">成团价 ¥</span>
          <span class="groupPrice" style="font-size: 64px;margin-right: 15px;">0</span>
          <span class="salePrice" style="line-height: 134px;font-size: 34px;"
            >售价¥{{ sharePicData.activityPrice }}</span
          >
        </div>
        <div class="skuSuccess">
          <p style="font-size: 34px;margin-bottom: 15px;">
            已有<span>{{ sharePicData.groupBuySuccessGuys }}人</span>
          </p>
          <p>参与拼团</p>
        </div>
      </div>
    </div>
    <div
      class="skuName"
      style="height: 132px;margin: 28px 0 42px;font-size: 44px;line-height: 62px;"
      v-html="skuName"
    />
    <div class="shareInfo" style="height: 318px;border-radius: 24px;padding: 0 48px;">
      <!-- 底部分享信息 -->
      <div class="qrcode" style="width: 353px;height: 278px;padding: 0 75px 0 0;">
        <img :src="qrcodeUrl" alt="" />
      </div>
      <div class="shareDesc" style="font-size: 34px;">
        <p style="margin-bottom: 25px;">分享自 <span>羊小咩小程序</span></p>
        <p>扫码或长按识别二维码0元拿好物</p>
      </div>
    </div>
  </div>
</template>
<script>
import html2canvas from '@/service/html2canvas.service';
import qiNiuApi from '@/api/qiniu.api';
import groupBuyApi from '@/api/groupBuy';
import { upload } from 'qiniu-js';
import config from '@/config';
export default {
  data() {
    return {
      qrcodeUrl: '',
      avatorList: [],
      openGroupCnt: 7,
      maxCount: 0,
      sharePicData: {},
      endTime: '',
      skuName: '' // 兼容safari做的特殊处理，每个文字都加一个span标签
    };
  },
  methods: {
    // 参团人数小于7时，头像全部显示；大于时展示6个头像...
    handleAvator(sharePicData) {
      const openGroupCnt = sharePicData.openGroupCnt || 7;
      let peoplePhotoList = sharePicData.peoplePhotoList || [];
      this.maxCount = openGroupCnt >= 6 ? 6 : openGroupCnt;
      this.openGroupCnt = openGroupCnt;
      this.avatorList = peoplePhotoList.slice(0, openGroupCnt);
      this.$nextTick(() => {
        if (this.avatorList.length === 0) {
          this.maxCount -= 1;
        }
      });
    },
    randomString(e) {
      e = e || 10;
      let t = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
      let a = t.length;
      let n = '';
      for (let i = 0; i < e; i++) {
        n += t.charAt(Math.floor(Math.random() * a));
      }
      return n;
    },
    async prepare(rawData) {
      this.sharePicData = rawData;

      this.handleAvator(rawData);

      // 将每个字符套入行内标签，用于解决canvas fillText的不换行问题
      // let skuName = '';
      // const originSkuName = rawData.skuName || '';
      // for (let i = 0; i < originSkuName.length; i++) {
      //   skuName += `<span>${originSkuName[i]}</span>`;
      // }
      this.skuName = rawData.skuName || '';

      const [endTimeYMD, endTimeHMS = ''] = (rawData.endTime && rawData.endTime.split(' ')) || [];
      if (endTimeYMD) {
        const day = new Date(endTimeYMD);
        this.endTime = `${day.getMonth() + 1}月${day.getDate()}日 ${endTimeHMS}`;
      }

      const [qrcodeUrl] = await groupBuyApi.getQrcodeUrl(rawData);
      this.qrcodeUrl = qrcodeUrl;
    },
    async createAndUploadPic(sharePicData) {
      this.$store.dispatch('change_loading_pic', true);

      await this.prepare(sharePicData);

      this.$nextTick(() => {
        html2canvas(this.$refs.sharePic, {
          width: 1080,
          height: 1920,
          useCORS: true,
          scale: 1,
          allowTaint: false
        })
          .then(canvas => {
            canvas.name = `${this.randomString()}.jpeg`;
            canvas.toBlob(blob => this.uploadPic(blob), 'image/jpeg', 0.85);
          })
          .catch(error => {
            this.errorHandler(error);
          });
      });
    },
    // 上传海报到七牛，成功后触发outputPicUr事件，参数是七牛文件地址
    async uploadPic(blob) {
      console.log('海报生成成功');
      const [res] = await qiNiuApi.getQiniuToken();
      const token = (res && res.token) || '';
      if (!token) {
        this.errorHandler(new Error('七牛token无效'));
        return;
      }

      upload(blob, null, token).subscribe({
        complete: this.uploadSuccess,
        error: this.errorHandler
      });
    },
    uploadSuccess({ hash }) {
      const fileLink = config.qiniuHost + hash;
      console.log('海报上传成功', fileLink);
      this.$store.dispatch('change_loading_pic', false);
      this.$emit('outputPicUrl', fileLink);
    },
    errorHandler(err) {
      console.error('海报创建失败', err);
      this.$store.dispatch('change_loading_pic', false);
    }
  }
};
</script>

<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
}
div,
span,
p,
img {
  box-sizing: border-box;
}
html,
body {
  width: 100%;
  height: 100%;
  font-size: 12px;
}
.container {
  position: fixed;
  top: -9999px;
  left: -9999px;
  color: #333;
  // 默认的字体包含了-apple-system，html2canvas解析导致bug，需要在根元素覆盖
  @font-family: BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Segoe UI, Arial, Roboto,
    'PingFang SC', 'Hiragino Sans GB', 'Microsoft Yahei', sans-serif;
}
.groupInfo {
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.groupInfo .avatorGroup {
  display: flex;
}
.groupInfo .avatorGroup .item {
  background-color: #ffe1e1;
  border-radius: 50%;
  position: relative;
}
.groupInfo .avatorGroup .normal,
.groupInfo .avatorGroup .leader.bg {
  background-color: #ffe1e1;
  color: #ec1500;
}
.groupInfo .avatorGroup .leader.bg::after {
  content: '?';
}
.groupInfo .avatorGroup .leader {
  background: transparent;
}
.groupInfo .avatorGroup .leader {
  display: flex;
  align-items: center;
  justify-content: center;
}
.groupInfo .avatorGroup .leader .avator {
  border-radius: 50%;
}
.groupInfo .avatorGroup .leader .leaderBorder {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}
.groupInfo .avatorGroup .leader .leaderBorder img {
  width: 100%;
  height: 100%;
}
.groupInfo .avatorGroup .leader .crown {
  position: absolute;
  z-index: 3;
}
.groupInfo .avatorGroup .leader .crown img {
  width: 100%;
  height: 100%;
}
.groupInfo .avatorGroup .leader .leaderName {
  position: absolute;
  transform: translateX(-50%);
  z-index: 3;
  left: 50%;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ff9700;
}
.groupInfo .avatorGroup .normal img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
.groupInfo .avatorGroup .more {
  display: flex;
  align-items: center;
  align-content: center;
  justify-content: center;
  color: #ec1500;
}
.groupInfo .avatorGroup .more::after {
  content: '...';
  margin-top: -15px;
}
.groupInfo .avatorGroup .placeholder {
  border: 2px dashed #ff9393;
  display: flex;
  align-items: center;
  align-content: center;
  justify-content: center;
  color: #ec1500;
}
.groupInfo .avatorGroup .placeholder::after {
  content: '?';
}
.groupInfo .avatorGroup .placeholder .crown {
  z-index: 3;
}
.groupInfo .groupProcess .desc {
  width: 100%;
  height: 100%;
  background: #ffe8e8;
  color: #333;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
.groupInfo .groupProcess .desc span {
  color: #ec1500;
}
.skuImg {
  position: relative;
}
.skuImg img {
  width: 100%;
  height: 100%;
}
.skuImg .skuInfo {
  position: absolute;
  bottom: -1px;
  left: 0;
  display: flex;
  width: 100%;
  background: #fff url('https://img.lkbang.net/activity/share/default/skuInfoBg.png');
  background-repeat: no-repeat;
  background-size: cover;
}
.skuImg .skuInfo .skuPrice {
  display: flex;
  align-items: baseline;
  height: 100%;
  flex-shrink: 0;
  color: @white;
}
.skuImg .skuInfo .skuPrice .groupPrice {
  display: inline-block;
  color: @white;
}
// .skuImg .skuInfo .skuPrice .salePrice {
// text-decoration: line-through;
// font-weight: lighter;
// }
.skuImg .skuInfo .skuSuccess {
  height: 100%;
  flex: 1;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.skuImg .skuInfo .skuSuccess p {
  text-align: center;
}
.skuImg .skuInfo .skuSuccess p span {
  color: #ec1500;
}
.skuName {
  color: #333333;
  overflow: hidden;
}
.shareInfo {
  background: #f7f8f9;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.shareInfo .qrcode {
  flex-shrink: 0;
}
.shareInfo .qrcode img {
  width: 100%;
  height: 100%;
}
.shareInfo .shareDesc {
  flex: 1;
  color: #666;
}
.shareInfo .shareDesc span {
  font-weight: bold;
}
</style>
