<template>
  <div class="share" :style="{ 'z-index': zIndex }">
    <!-- canvasImageUrl canvase 渲染成功后删除原始元素，避免当前页面元素太多出现卡顿 -->
    <div class="share-content" ref="shareContent">
      <!-- <div class="share-content" ref="shareContent" v-if="!canvasImageUrl"> -->
      <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-if="checkedPlan && reportContents && isHistory == '1'">
          <template v-for="value in reportContents">
            <div :class="['text']">{{ value.dictValue }}</div>
            <div class="content">{{ value.content }}</div>
          </template>
        </template>
        <!-- 日报指标 -->
        <template v-if="isTarget">
          <template v-if="reportTarget.targetType == '1'">
            <!--targetType 0-历史指标  1-动态指标，String类型 -->
            <shareCommonTarget
              :homePageIndicatorDate="reportTarget.homePageIndicatorList"></shareCommonTarget>
          </template>
          <template v-else>
            <!-- YFQuota:应用服务平台 不显示各项指标 -->
            <shareAtarget :reportInfo="reportTarget"></shareAtarget>
            <shareBtarget :reportInfo="reportTarget"></shareBtarget>
          </template>
          <!-- <shareAtarget :reportInfo="reportTarget"></shareAtarget>
          <shareBtarget :reportInfo="reportTarget"></shareBtarget> -->
        </template>
        <!-- 日报填写内容 -->
        <template v-if="isReportCustom">
          <shareReportCustom
            :disabled="true"
            :reportCustomData="reportTarget.customTaskList"></shareReportCustom>
        </template>
        <!-- 今日拜访照片 -->
        <template v-if="photosData && photosData.length">
          <div class="text">今日拜访照片</div>
          <div class="content-photos">
            <div class="imgBox" v-for="item in photosData">
              <img
                :src="'data:image/jpg;base64,' + item"
                crossorigin="anonymous"
                referrerpolicy="no-referrer"
                alt=""
                style="display: block" />
            </div>
            <!-- <template v-for="item in urlList">
            <img
              :src="item + '&' + new Date().getTime()"
              crossOrigin="anonymous"
              referrerpolicy="no-referrer"
              alt=""
              style="display: block" />
          </template> -->
          </div>
        </template>
      </div>
      <div class="footerShare">
        <div class="right-text">
          <div>长按识别二维码查看详情&点评</div>
          <!-- <div></div> -->
        </div>
        <vue-qr
          class="QRcodes"
          :callback="QRCallback"
          :text="vueQrText"
          :dotScale="0.8"
          :margin="8"
          :logoSrc="require('@/assets/logo1.png')"
          :logoMargin="2"></vue-qr>
      </div>
      <div class="footerTips">来自立邦好邦手</div>
    </div>
    <div
      class="share-mask"
      style="background: #000; position: fixed; top: 0; width: 100%; height: 100%"></div>
    <div class="html2canvasBox">
      <div id="html2canvas" ref="html2canvas">
        <div class="scroll-container">
          <div style="position: relative">
            <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 class="closeShare" @click="closeShare">返回</div>
            </div>
            <img :src="canvasImageUrl" width="100%" class="canvasImage" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import html2canvas from 'html2canvas';
import { imgToBase64, shareReportMobile } from '@/api/index';
import VueQr from 'vue-qr';
import ShareAtarget from './shareAtarget.vue';
import shareBtarget from './shareBtarget.vue';
import shareReportCustom from './shareReportCustom.vue';
import uploadAliOss from '@/utils/uploadAliOss';
import shareCommonTarget from './shareCommonTarget.vue';
export default {
  name: 'share',
  components: { VueQr, ShareAtarget, shareReportCustom, shareBtarget, shareCommonTarget },
  props: {
    // 日报数据
    reportTarget: {
      type: Object,
      default() {
        return {};
      },
    },
    //日报id
    reportId: {
      type: [String, Number],
    },
    // 点评数据
    reportRemarksIndex: {
      type: Number,
      default: -1,
    },
    // 图片转换列表
    urlList: {
      type: Array,
      default() {
        return [];
      },
    },
    // 是否显示 今日总结&明日规划
    checkedPlan: {
      type: Boolean,
      default: true,
    },
    reportContents: {
      type: Array,
      default() {
        return [];
      },
    },
    // 是否显示 指标
    isTarget: {
      type: Boolean,
      default: true,
    },
    // 是否显示 日报填写内容
    isReportCustom: {
      type: Boolean,
      default: true,
    },
    // 是否为历史汇报：0-新汇报 1-历史汇报
    isHistory: {
      type: String,
      default: '0',
    },
  },
  data() {
    return {
      canvasImageUrl: '',
      retryCount: 0,
      photosData: [],
      zIndex: -1,
      qrcode: null,
      vueQrText: '',
      heightFlag: 'start', //图片高度不足，居中显示
      shareDuration: 0, //分享时间
      shareInterval: null,
    };
  },
  created() {
    this.shareDuration = 0;
    this.shareInterval = setInterval(() => {
      this.shareDuration++;
    }, 1000);
    this.zIndex = -1;
    this.canvasImageUrl = '';
    let links = process.env.NODE_ENV == 'production' ? 'http://1.npz.cn/3/' : 'http://1.npz.cn/2/';
    this.vueQrText = links + this.reportId;
    this.toastLoading(0, '生成中...', true);
  },
  methods: {
    // 初始化会先执行二维码生成，成功后回调
    QRCallback() {
      // 二维码
      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();
        });
      }
    },
    //异步执行
    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';
        // },
        // ignoreElements: (e) => {
        //   if (
        //     e.contains(element) ||
        //     element.contains(e) ||
        //     e.tagName === 'STYLE' ||
        //     e.tagName === 'LINK' ||
        //     e.getAttribute('data-html2canvas') != null // header里面的样式不能筛掉
        //   ) {
        //     console.log(e);
        //     return false;
        //   }
        //   return true;
        // },
      })
        .then((canvas) => {
          this.toastLoading().clear();
          let imageUrl = canvas.toDataURL('image/png');
          this.canvasImageUrl = imageUrl;
          // 图片加载完成后设置滚动容器高度
          const img = new Image();
          img.onload = () => {
            const canvasImage = this.$refs.html2canvas.querySelector('.canvasImage');
            const scrollContainer = this.$refs.html2canvas.querySelector('.scroll-container');
            const shareHeader = this.$refs.html2canvas.querySelector('.shareHeader');
            console.log(scrollContainer.style);
            if (canvasImage.height < window.innerHeight) {
              scrollContainer.style.alignItems = 'center';
              shareHeader.style.position = 'absolute';
            } else {
              scrollContainer.style.alignItems = 'start';
              shareHeader.style.position = 'fixed';
            }
            this.$forceUpdate();
            // // 根据图片实际高度设置容器高度（增加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);
          this.$emit('setDailyDetailsBox', false);
          // 上传阿里云oss
          // 图片名称：用户名-时间戳
          let username = this.reportTarget.nickName;
          let imgName = username + '-' + new Date().getTime();
          uploadAliOss(imageUrl, imgName).then((res) => {
            if (res.url && res.url.indexOf('http') != -1) {
              console.log(res.url);
              shareReportMobile({
                reportId: this.reportId, //	long	汇报主键id
                imageUrl: res.url, //	String	分享日报的图片的URL
                shareDuration: this.shareDuration, //	long	分享用时（秒）
              }).then((res) => {
                if (this.shareInterval) clearInterval(this.shareInterval);
              });
            }
          });
        })
        .catch((error) => {
          this.toastLoading().clear();
          console.error('html2canvas error:', error);
          this.$toast('生成分享图失败，请稍后重试');
        });
    },
    closeShare() {
      this.canvasImageUrl = '';
      this.$emit('setShareImg', false);
      this.$emit('setDailyDetailsBox', true);
    },
  },
  beforeDestroy() {
    // 组件销毁时清除实例
    if (this.qrcode) {
      this.$refs.qrcode.innerHTML = '';
    }
  },
};
</script>
<style lang="scss" scoped>
.share {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #fff;
  position: fixed;
  top: 0;

  .share-content {
    background: url('../assets/shareBack.webp') no-repeat center;
    background-size: 100% 100%;
    // background-attachment: local;
    width: 100%;
    // min-height: 100%;
    padding: vw(30);
    position: absolute;
    // padding-bottom: vw(30);
    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/textBack1.png') no-repeat;
      width: 100%;
      min-height: vw(94);
      background-size: cover;
      color: #7d0207;
      font-size: vw(36);
      text-align: center;
      line-height: vw(50);
      margin: vw(35) 0 vw(20) 0;
      font-weight: bold;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: vw(18) 0;
    }

    .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;
      .imgBox {
        width: 47.5%;
        margin-bottom: 15px;
        margin-right: 5%;
        background-color: rgb(0, 0, 0);
        height: 200px;
        display: flex;
        align-items: center;
        border-radius: 10px;
        overflow: hidden;
        &:nth-child(2n) {
          margin-right: 0;
        }
      }
      img {
        // width: 100%;
        // height: 42vw;
        // width: 30%;
        // height: vw(188);
        // margin-bottom: 15px;
        // margin-right: 5%;
        // background-color: rgba(255, 255, 255, 0.1);
        // &:nth-child(2n) {
        //   margin-right: 0;
        // }
        width: 100%;
        // height: 100%;
        background-color: rgba(255, 255, 255, 0.1);
        max-height: 200px;
        // object-fit: contain;
      }
    }
  }
  .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-size: vw(28);
      color: #ffffff;
      line-height: vw(50);
    }
  }

  .footerShare {
    // position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    // justify-content: flex-end;
    margin-top: vw(30);
    margin-right: 2px;

    .right-text {
      // margin-left: vw(12.5);
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      // margin-right: vw(24);

      div {
        color: #ffffff;
        font-size: vw(26);
        // font-weight: bold;
        padding: 6px 0;
      }
    }
    // 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;
    //   }
    // }
  }
  .footerTips {
    width: 100%;
    text-align: center;
    padding: 10px 0;
    color: rgba(255, 255, 255, 0.721);
    font-size: 14px;
    font-family: PingFang-SC-Medium;
    font-weight: 600;
  }
  .html2canvasBox {
    width: 100%;
    height: 100%;
    min-height: auto;
    min-height: 100vh;
    overflow: hidden !important;
    display: flex;
    flex-direction: column;
    -webkit-user-select: none; /* Safari */
  }
  #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; /* 修复定位上下文 */
      display: flex;
      // align-items: start;
      img {
        width: 100%;
        display: block;
      }
      .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;
          font-size: vw(30);
          background: #a2819c;
          text-align: center;
          line-height: 28px;
          border-radius: 6px;
          padding: 0 7px;
          border: 2px solid #11224e;
          .van-icon {
            font-size: vw(40);
          }
        }
        .shareTips {
          display: flex;
          align-items: center;
          justify-content: center;
          color: #f8f8fa;
          width: 82%;
          // 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);
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.share {
  .QRcodes {
    // width: 45px; /* 固定像素尺寸 */
    // height: 45px;
    width: vw(280);
    height: vw(280);
    position: relative;
    background: #ffffff;
    image-rendering: crisp-edges;
    image-rendering: -webkit-optimize-contrast; /* 安卓浏览器兼容 */
    // padding: 2px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 3px;
    .logo {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 10px;
      height: 10px;
      img {
        object-fit: contain;
      }
      z-index: 3;
    }

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