<template>
  <div class="share" :style="{ 'z-index': zIndex }">
    <div class="share-content" ref="shareContent">
      <div class="header">
        <div class="left-icon">
          <img :src="require('@/assets/shareLeft.png')" />
        </div>
        <div class="right-icon">
          <img :src="require('@/assets/shareRight.png')" />
        </div>
      </div>
      <!-- 点评 -->
      <!-- <template v-for="item in reportTarget.reportRemarks"> -->
      <div
        class="comment summaryDay"
        v-if="
          reportRemarksIndex != -1 &&
          reportTarget.reportRemarks &&
          reportTarget.reportRemarks.length
        ">
        <div class="title-box">
          <div class="title">
            <div class="name">
              {{ reportTarget.reportRemarks[reportRemarksIndex].nickName }}点评
            </div>
            <div class="date">
              {{
                reportTarget.reportRemarks[reportRemarksIndex].createTime
                  ? formatChineseDate(
                      reportTarget.reportRemarks[reportRemarksIndex].createTime.split(' ')[0]
                    )
                  : ''
              }}
            </div>
          </div>
        </div>
        <div class="commentMessage">
          {{ reportTarget.reportRemarks[reportRemarksIndex].remarkContent }}
        </div>
      </div>
      <!-- </template> -->
      <!-- 内容 -->
      <div class="summaryDay">
        <div class="title-box">
          <div class="title">
            <div class="name">{{ reportTarget.nickName }}的日报</div>
            <div class="date">
              {{
                reportTarget.commitTime
                  ? formatChineseDate(reportTarget.commitTime.split(' ')[0])
                  : ''
              }}
            </div>
          </div>
        </div>
        <!-- <template
          v-for="(item, index) in reportTarget.reportContents"
          v-if="reportTarget.reportContents && reportTarget.reportContents.length > 0">
          <div :class="['text']">{{ filterText(index) }}</div>
          <div class="content">{{ item.dayContent }}</div>
        </template> -->
        <div :class="['text']">今日机会与挑战总结</div>
        <div class="content">
          {{ reportTarget.reportContents.length ? reportTarget.reportContents[0].dayContent : '' }}
        </div>
        <div :class="['text']">明日工作计划</div>
        <div class="content">
          {{ reportTarget.reportContents.length ? reportTarget.reportContents[1].dayContent : '' }}
        </div>
        <div class="text">今日拜访照片</div>
        <div class="content-photos">
          <template v-for="item in photosData">
            <img
              :src="'data:image/jpg;base64,' + item"
              crossorigin="anonymous"
              referrerpolicy="no-referrer"
              alt=""
              style="display: block" />
          </template>
          <!-- <template v-for="item in photosData">
            <img
              :src="'data:image/jpg;base64,' + item"
              crossorigin="anonymous"
              referrerpolicy="no-referrer"
              alt=""
              style="display: block" />
          </template> -->
        </div>
      </div>
      <div class="footerShare">
        <div class="QRcodes" ref="QRcodes">
          <div class="logo">
            <img :src="require('@/assets/logo1.png')" />
          </div>
        </div>
        <div class="right-text">
          <div>长按识别二维码查看详情&点评</div>
          <div></div>
        </div>
      </div>
    </div>
    <div
      class="share-mask"
      style="background: #fff; position: fixed; top: 0; width: 100%; height: 100%"></div>
    <div class="html2canvasBox">
      <div class="shareHeader">
        <div class="shareTips">
          长按图片可下载、收藏、转发
          <!-- <img :src="require('@/assets/shareTips.png')" alt="" /> -->
        </div>
        <div class="closeShare" @click="closeShare"><van-icon name="close" /></div>
      </div>
      <div id="html2canvas" ref="html2canvas">
        <div class="scroll-container">
          <img :src="canvasImageUrl" width="100%" />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import html2canvas from 'html2canvas';
import QRCode from 'qrcodejs2';
import { imgToBase64 } from '@/api/index';
export default {
  name: 'share',
  props: {
    // 日报数据
    reportTarget: {
      type: Object,
      default() {
        return {};
      },
    },
    //日报id
    reportId: {
      type: [String, Number],
    },
    // 点评数据
    reportRemarksIndex: {
      type: Number,
      default: -1,
    },
    // 图片转换列表
    urlList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      canvasImageUrl: '',
      retryCount: 0,
      photosData: [],
      zIndex: -1,
    };
  },
  created() {
    this.zIndex = -1;
    this.canvasImageUrl = '';
  },
  mounted() {
    this.toastLoading(0, '生成中...', true);
    // 二维码
    this.creatQrCode();
    if (this.urlList.length) {
      imgToBase64({ urlList: this.urlList }).then((res) => {
        if (res.data && res.code == 200) {
          this.photosData = res.data;
          this.$nextTick(async () => {
            await this.htmlToCanvas();
          });
        } else {
          this.$toast(res.msg);
          this.$nextTick(async () => {
            await this.htmlToCanvas();
          });
        }
      });
    } else {
      this.$nextTick(async () => {
        await this.htmlToCanvas();
      });
    }
  },
  methods: {
    //异步执行
    imageUrlToBase64(imageUrl) {
      return new Promise((resolve, reject) => {
        //一定要设置为let，不然图片不显示
        let image = new Image();
        //解决跨域问题
        image.setAttribute('crossOrigin', 'anonymous');
        image.src = imageUrl;
        image.onload = () => {
          var canvas = document.createElement('canvas');
          canvas.width = image.width;
          canvas.height = image.height;
          var context = canvas.getContext('2d');
          context.drawImage(image, 0, 0, image.width, image.height);
          var quality = 1;
          //这里的dataurl就是base64类型
          let dataURL = canvas.toDataURL('image/png', quality); //使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
          resolve(dataURL);
        };

        image.onerror = () => {
          reject(new Error('图像加载失败'));
        };
      });
    },
    filterText(index) {
      if (index == 0) {
        return '明日工作计划';
      } else {
        return '今日机会与挑战总结';
      }
    },
    htmlToCanvas() {
      html2canvas(this.$refs.shareContent, {
        scale: window.devicePixelRatio || 1,
        useCORS: true,
        allowTaint: false,
        backgroundColor: null,
        logging: false, // 关闭日志提升性能
        onclone: (clonedDoc) => {
          // 确保克隆的DOM保持原始样式
          clonedDoc.getElementById('html2canvas').style.overflow = 'auto';
        },
      })
        .then((canvas) => {
          this.toastLoading().clear();
          let imageUrl = canvas.toDataURL('image/png');
          this.canvasImageUrl = imageUrl;

          // 图片加载完成后设置滚动容器高度
          const img = new Image();
          img.onload = () => {
            const scrollContainer = this.$refs.html2canvas.querySelector('.scroll-container');
            // 根据图片实际高度设置容器高度（增加20px缓冲）
            // 根据设备像素比调整图片高度
            // 使用实际渲染高度而非原始图片高度
            const imgHeight = img.offsetHeight + 20;
            // 设置容器最小高度保证内容显示，同时允许自动扩展
            scrollContainer.style.minHeight = `${imgHeight}px`;
            // 保持父容器为可见滚动
            scrollContainer.parentElement.style.overflow = 'visible';
            // 强制浏览器重排
            scrollContainer.style.display = 'none';
            scrollContainer.offsetHeight; // 触发重排
            scrollContainer.style.display = 'block';

            // 添加移动端滚动优化
            requestAnimationFrame(() => {
              scrollContainer.style.overflow = 'auto';
              scrollContainer.style.overflowScrolling = 'touch';
              scrollContainer.style.webkitOverflowScrolling = 'touch';
              scrollContainer.style.overscrollBehavior = 'contain';
              scrollContainer.style.touchAction = 'pan-y';
            });
          };
          img.src = imageUrl;
          this.zIndex = 9;
          this.$emit('setShareImg', true);
        })
        .catch((error) => {
          this.toastLoading().clear();
          console.error('html2canvas error:', error);
          this.$toast('生成分享图失败，请稍后重试');
        });
    },
    creatQrCode() {
      // let proText = 'https://suishenbang.nipponpaint.com.cn';
      let path =
        process.env.VUE_APP_Target +
          '/mobile/dailyHistoricalDetails&source=share&reportId=' +
          this.reportId || '';
      var qrcode = new QRCode(this.$refs.QRcodes, {
        text: process.env.VUE_APP_SSB_LINK + '/homeIndex?path=' + path,
        colorDark: '#000000',
        colorLight: 'rgba(255,255,255,0)', // 完全透明背景
        correctLevel: QRCode.CorrectLevel.H,
        width: 140, // 固定尺寸保证安卓一致性
        height: 140,
        margin: 2,
        render: 'canvas',
        onRenderingEnd: () => {
          const canvas = this.$refs.QRcodes.querySelector('canvas');
          // 显式设置物理像素尺寸
          const dpr = window.devicePixelRatio || 1;
          canvas.width = 200 * dpr;
          canvas.height = 200 * dpr;

          // 设置CSS显示尺寸保持200x200
          canvas.style.width = '200px';
          canvas.style.height = '200px';

          // 优化安卓设备显示
          canvas.style.imageRendering = 'pixelated';
          canvas.style.transform = 'translateZ(0)'; // 触发硬件加速
          canvas.style.backgroundColor = '#fff';

          // 调整画布缩放比例
          const ctx = canvas.getContext('2d');
          ctx.scale(dpr, dpr);
        },
      });
    },
    closeShare() {
      this.canvasImageUrl = '';
      this.$emit('setShareImg', false);
    },
  },
};
</script>
<style lang="scss" scoped>
.share {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #fff;
  position: fixed;
  top: 0;

  .share-content {
    background: url('../assets/shareBack.png') no-repeat center center;
    background-size: cover;
    background-attachment: local;
    width: 100%;
    padding: vw(30);
    position: absolute;
    padding-bottom: vw(190);
    top: 0;
    z-index: -10;
  }

  .header {
    display: flex;
    justify-content: space-between;
    padding-bottom: vw(40);

    .left-icon {
      width: vw(114);
      height: vw(71);
    }

    .right-icon {
      width: vw(230);
      height: vw(78);
    }

    img {
      width: 100%;
      height: 100%;
    }
  }
  .title-box {
    position: relative;
    width: 100%;
    height: auto;
    display: flex;
    justify-content: center;
    align-items: center;
    top: -6px;
    .title {
      // width: vw(262);
      // height: vw(115);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #600d0e;
      font-weight: bold;
      text-align: center;
      // background: url('../assets/titleBack.png') no-repeat;
      // background-size: 100% 100%;
      padding: vw(20) vw(30);
      background-color: #ecdd9a;
      border-radius: 6px 6px 25px 25px;
      .name {
        font-size: vw(36);
      }
      .date {
        font-size: vw(28);
      }
    }
  }

  .summaryDay {
    background: url('../assets/summaryDay.png') no-repeat;
    background-size: 100%;
    padding: vw(24);
    position: relative;
    margin-top: vw(55);
    border-radius: 0 0 vw(35) vw(35);
    padding-top: 0;
    .text {
      background: url('../assets/textBack.png') no-repeat;
      width: 100%;
      height: vw(94);
      background-size: cover;
      color: #7d0207;
      font-size: vw(36);
      text-align: center;
      line-height: vw(94);
      // margin-top: vw(152);
      // margin-bottom: vw(45);
      margin: vw(35) 0;
      font-weight: bold;
    }

    .content {
      font-size: vw(28);
      font-weight: bold;
      color: #ffff;
      line-height: vw(63);
      white-space: pre-wrap;
    }

    .content-photos {
      display: flex;
      flex-wrap: wrap;
      //   justify-content: space-between;

      img {
        width: 30%;
        height: vw(188);
        margin-bottom: 15px;
        margin-right: 5%;
        background-color: rgba(255, 255, 255, 0.1);
        &:nth-child(3n) {
          margin-right: 0;
        }
      }
    }
  }
  .comment {
    .title {
      // background: url('../assets/comment.png') no-repeat;
      // background-size: 100% 100%;
      background-color: #032371;
      border-radius: 6px 6px 25px 25px;
      color: #e6cd78;
    }
    .commentMessage {
      padding: vw(60) 0;
      font-family: PingFang-SC-Medium;
      font-size: vw(28);
      font-weight: bold;
      color: #ffffff;
    }
  }

  .footerShare {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: vw(100);

    .right-text {
      // margin-left: vw(12.5);
      display: flex;
      // flex-direction: column;
      // justify-content: space-between;
      align-items: center;
      justify-content: center;
      padding: vw(10) 0;
      div {
        color: #ffffff;
        font-size: vw(30);
        font-weight: bold;
      }
    }
  }
  .html2canvasBox {
    width: 100%;
    height: 100%;
    min-height: auto;
    min-height: 100vh;
    overflow: hidden !important;
    display: flex;
    flex-direction: column;
    .shareHeader {
      position: absolute;
      z-index: 1;
      top: 10px;
      width: 100%;
      display: flex;
      align-items: center;
      padding: 0 vw(30);
      .closeShare {
        // position: absolute;
        // z-index: 1;
        // right: 10px;
        // top: 10px;
        color: #fff;
        .van-icon {
          font-size: vw(40);
        }
      }
      .shareTips {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #f8f8fa;
        width: 90%;
        // flex: 1;
        margin-right: 10px;
        background: rgba(157, 157, 188, 0.8);
        height: vw(60);
        font-weight: 600;
        font-size: vw(26);
        img {
          width: 100%;
          // height: vw(60);
        }
      }
    }
  }
  #html2canvas {
    width: 100%;
    height: 100%;
    position: static; /* 改为静态定位 */

    .scroll-container {
      width: 100%;
      height: 100%;
      flex: 1;
      overflow-y: auto !important;
      -webkit-overflow-scrolling: touch;
      overscroll-behavior: contain;
      touch-action: pan-y;
      // padding: 20px 0;
      box-sizing: border-box;
      /* 修复iOS弹性滚动 */
      overflow-scrolling: touch;
      max-height: 100vh; /* 添加最大高度限制 */
      position: relative; /* 修复定位上下文 */
      img {
        width: 100%;
        display: block;
      }
    }
  }
}
</style>
<style lang="scss">
.share {
  .QRcodes {
    width: 140px; /* 固定像素尺寸 */
    height: 140px;
    margin-right: 12px;
    position: relative;
    background: #ffffff;
    image-rendering: crisp-edges;
    image-rendering: -webkit-optimize-contrast; /* 安卓浏览器兼容 */
    // padding: 2px;
    .logo {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 40px;
      height: 40px;
      img {
        width: 100% !important;
        height: 100% !important;
        object-fit: contain;
      }
      z-index: 3;
    }

    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
