<script setup>
import apiReport from '@/api/modules/report'
import { useRoute } from 'vue-router'
import { Message } from 'tdesign-mobile-vue';
import apiCommon from '@/api/modules/common'
import apiUser from '@/api/modules/user'
import { useThrottleFn } from '@vueuse/core'

const route = useRoute()

// 获取系统配置
let systemConfig = null
function getSystemConfig() {
  apiCommon.systemConfig().then(res => {
    if (res.Ret === 200) {
      systemConfig = res.Data
      console.log(res.Data);
    }
  })
}
getSystemConfig()

// 获取用户信息
let userInfo = null
async function getUserInfo() {
  const res = await apiUser.userInfo()
  if (res.Ret === 200) {
    userInfo = res.Data
  }
}



const reportId = route.query.reportid
const reportInfo = ref(null)
const reportContent = ref('')
const reportStatus = ref(0)//1已过期，2没有该品种权限，3没有权限，4有权限，5未绑定
const reportCollected = ref(false)//报告是否收藏
const isBind=ref(false)
async function getReportInfo() {
  if (!reportId) return
  const res = await apiReport.getReportDetail({
    ReportId: Number(reportId)
  })
  if (res.Ret === 200) {
    reportInfo.value = res.Data.Report
    reportStatus.value = res.Data.Status
    reportCollected.value = res.Data.IsCollect || false
    isBind.value=res.Data.IsSignIn
    nextTick(() => {
      handlePreviewImgs()
    })


    // 设置分享文案
    wx.miniProgram.postMessage({
      data: {
        title: res.Data.Report.Title
      }
    });

    await getUserInfo()
    if (res.Data.Status === 4) {
      if (userInfo.Status === 2 && userInfo.HasPermission === '私有权限') {
        reportInfo.value.Content=modifyReportContentIframeData(reportInfo.value.Content)
        formatIframeData()
      }else{
        reportContent.value = modifyReportContentIframeData(reportInfo.value.Content)
        splitReportContent(reportContent.value)
      }
    } else {//无权限
      reportContent.value = modifyReportContentIframeData(reportInfo.value.ContentSub)
    }
  }
}
getReportInfo()

// 修改报告中嵌入的图表地址
function modifyReportContentIframeData(str){
  let temStr=str.replace(/http:\/\/eta.dwfutures.com:8001/g,'https://dwresearch.dwfutures.com')
  return temStr.replace(/http:\/\/58.210.74.21:9100\/etastatic/g,'https://dwresearch.dwfutures.com/etastatic')
}

// 给报告详情中图表加参数
function formatIframeData() {
  reportContent.value = reportInfo.value.Content.replace(/\/chartshow\?code=/g, `/chartshow?source=etamini&token=${localStorage.getItem('token')}&reportId=${reportId}&code=`)
  splitReportContent(reportContent.value)
}

// 报告内容分页
const pageSize=20
let page=0
let endPageNum=0
let contentTotals=[]
const renderContentList=ref([])
function splitReportContent(data){
  const arr=data.split('</p>');
  contentTotals=arr.map(_ => _+'</p>')
  renderContentList.value=contentTotals.slice(0,pageSize)
  endPageNum=parseInt(contentTotals.length / pageSize) + 1;
}
function handleLoadContent(){
  renderContentList.value=renderContentList.value.concat(contentTotals.slice(page*pageSize,(page+1)*pageSize))
}

// 拨打电话
function handleCallPhone() {
  let tel = userInfo.SellerPhone
  if (!tel) {
    systemConfig.forEach(item => {
      if (item.ConfKey === 'ServicePhone') {
        tel = item.ConfVal
      }
    });
  }

  var phoneLink = 'tel:' + tel;
  var link = document.createElement('a');
  link.setAttribute('href', phoneLink);
  link.onclick = function () {
    return true;
  };
  link.click();
}

// 点击收藏
async function handleCollect() {
  const res = reportCollected.value ? await apiReport.reportCollectCancel({ ReportId: Number(reportId) }) : await apiReport.reportCollect({ ReportId: Number(reportId) })
  if (res.Ret === 200) {
    Message.success(reportCollected.value ? '取消收藏成功' : '收藏成功')
    reportCollected.value = !reportCollected.value
    // 通知更新收藏列表
    wx.miniProgram.postMessage({
      data: 'refreshCollectList'
    });
  }
}

// 显示免责声明
const isShowMZSM = ref(false)

// 显示返回顶部
const showToTop = ref(false)
const handlePageScroll=useThrottleFn(()=>{
  const top = document.documentElement.scrollTop || document.body.scrollTop
  if (top > window.outerHeight) {
    showToTop.value = true
  } else {
    showToTop.value = false
  }

  if(page >= endPageNum) return
  const clientHeight = document.documentElement.clientHeight || document.body.clientHeight; // 可视高度
  const scrollHeight = document.body.scrollHeight; // 总高度
  const bufferHeight = 400;
  if((scrollHeight - top - clientHeight) < bufferHeight+100) {
    console.log('触底')
    page++
    handleLoadContent();
  }
},300)

function handleBackTop() {
  document.body.scrollTop = document.documentElement.scrollTop = 0
}

// 点击报告内容中的图片
function handlePreviewImgs() {
  document.getElementById('rich-content').addEventListener('click', function (event) {
    let imgArray = [];
    let curImageSrc = event.target.src;
    let oParent = event.target.parentNode;
    if (curImageSrc && !oParent.hasAttribute('href')) {
      let imgs = document.querySelectorAll('.rich-content img');
      for (let i = 0; i < imgs.length; i++) {
        let itemSrc = imgs[i].src;
        imgArray.push(itemSrc);
      }
      wx.previewImage({ current: curImageSrc, urls: imgArray });
    }
  });
}

onMounted(() => {
  window.addEventListener('scroll', handlePageScroll)
})
onUnmounted(() => {
  window.removeEventListener('scroll', handlePageScroll)
})

function handleGoLogin(){
  const redirectUrl=encodeURIComponent(`/pages-report/reportDetail/index?id=${route.query.reportid}`) 
  wx.miniProgram.reLaunch({
    url:`/pages/login/index?redirectUrl=${redirectUrl}`
  })
}

</script>

<template>
  <div class="report-detail-page" v-if="reportInfo">
    <div class="title-box">{{ reportInfo.Title }}</div>
    <div class="author-box">{{ reportInfo.Author }}</div>
    <div class="time-box">
      <span>{{ reportInfo.PublishTime }}</span>
      <span class="btn" @click="isShowMZSM = true">免责声明</span>
    </div>
    <div class="des-box" v-if="reportInfo.Abstract">
      <svg-icon name="icon01"></svg-icon>
      <div>{{ reportInfo.Abstract }}</div>
    </div>
    <div
      id="rich-content"
      class="report-content-box rich-content"
    >
      <div v-for="item in renderContentList" :key="item" v-html="item"></div>
    </div>
    <!-- 右侧悬浮操作栏 -->
    <div class="right-fix-box">
      <!-- 收藏 -->
      <svg-icon
        @click="handleCollect"
        class="item collect-icon"
        :name="reportCollected ? 'collected' : 'collect'"
        v-if="reportStatus === 4"
      />
      <!-- 返回顶部 -->
      <div class="item back-top-img">
        <svg-icon
          name="backtop"
          v-show="showToTop"
          @click="handleBackTop"
          class="back-top-img"
        />
      </div>
    </div>
  </div>
  <!-- 无权限  -->
  <div class="no-auth-wrap" v-if="reportStatus !== 4">
    <div class="opcity-box"></div>
    <div class="content-box">
      <img class="icon" src="@/assets/imgs/lock-img.png" alt="" />
      <div class="text" v-if="reportStatus === 3">
        您暂无权限查看，<br />请联系客服人员开通！
      </div>
      <div class="text" v-if="reportStatus === 2">
        您暂无该品种权限，<br />请联系销售人员开通！
      </div>
      <div class="text" v-if="reportStatus === 1">
        您的权限已过期，<br />请联系销售人员开通！
      </div>
      <t-button
        theme="primary"
        block
        style="width: 300px; margin: 30px auto"
        @click="handleCallPhone"
        >立即联系</t-button
      >
    </div>
  </div>
  <!-- 未绑定 -->
  <div class="no-auth-wrap" v-if="reportStatus === 5&&!isBind">
    <div class="opcity-box"></div>
    <div class="content-box">
      <img class="icon" src="@/assets/imgs/lock-img.png" alt="" />
      <div class="text">
        为了优化您的用户体验<br />请登录后查看更多信息！
      </div>
      <t-button
        theme="primary"
        block
        style="width: 300px; margin: 30px auto"
        @click="handleGoLogin"
        >去登陆</t-button
      >
    </div>
  </div>
  <!-- 免责声明 -->
  <disclaimers-wrap v-model:show="isShowMZSM" />
</template>

<style lang="scss" scoped>
.report-detail-page {
  background-color: #fff;
  padding: var(--page-padding);
  .title-box {
    font-size: 36px;
    line-height: 44px;
    margin-bottom: 20px;
  }
  .time-box {
    margin-top: 10px;
    font-size: var(--font-size-small);
    color: var(--text-color-grey);
    .btn {
      float: right;
      color: var(--primary-color);
    }
  }
  .des-box {
    background-color: #f8f8f8;
    padding: 20px;
    margin: 20px 0;
    display: flex;
    gap: 0 10px;
    color: var(--text-color-sub);
    font-size: var(--font-size-small);
    line-height: 36px;
  }
  .report-content-box {
    margin-top: 20px;
    line-height: 1.8;
    font-size: 36px;
    :deep(img) {
      width: 100% !important;
    }
    :deep(span) {
      font-size: 36px !important;
      line-height: 1.8 !important;
      background-color: rgba(255, 255, 255, 0) !important;
    }
    :deep(p) {
      font-size: 36px !important;
      line-height: 1.8 !important;
      background-color: rgba(255, 255, 255, 0) !important;
    }
    :deep(ul) {
      font-size: 36px !important;
      line-height: 1.8 !important;
      background-color: rgba(255, 255, 255, 0) !important;
    }
    :deep(ol) {
      font-size: 36px !important;
      line-height: 1.8 !important;
      background-color: rgba(255, 255, 255, 0) !important;
    }
    :deep(iframe) {
      width: 100% !important;
    }
    :deep(li) {
      font-size: 36px !important;
      line-height: 1.8 !important;
      background-color: rgba(255, 255, 255, 0) !important;
      list-style: inherit !important;
      list-style-position: inside !important;
    }
    :deep(span.fr-emoticon) {
      width: 36px !important;
      height: 36px !important;
      background-repeat: no-repeat !important;
      background-size: cover !important;
      display: inline-block !important;
      vertical-align: middle !important;
    }
  }
  .right-fix-box {
    position: fixed;
    z-index: 99;
    right: 34px;
    bottom: 130px;
    .item {
      margin-top: 10px;
    }
    .back-top-img {
      width: 100px;
      height: 100px;
      display: block;
    }
    .collect-icon {
      width: 100px;
      height: 100px;
      display: block;
    }
  }
}
.no-auth-wrap {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99;
  .opcity-box {
    height: 129px;
    background: linear-gradient(
      360deg,
      #ffffff 0%,
      rgba(255, 255, 255, 0) 100%
    );
  }
  .content-box {
    background-color: #fff;
    padding-bottom: 200px;
    text-align: center;
    color: var(--primary-color);
  }

  .icon {
    display: block;
    margin: 0 auto;
    width: 200px;
    height: 200px;
  }
}

@media (min-width: 600px) {
  .report-detail-page {
    .title-box {
      font-size: 18px;
      line-height: 22px;
      margin-bottom: 10px;
    }
    .time-box {
      margin-top: 5px;
    }
    .des-box {
      padding: 10px;
      margin: 10px 0;
      gap: 0 5px;
      line-height: 18px;
    }
    .report-content-box {
      margin-top: 10px;
      font-size: 18px;
      :deep(span) {
        font-size: 18px !important;
      }
      :deep(p) {
        font-size: 18px !important;
      }
      :deep(ul) {
        font-size: 18px !important;
      }
      :deep(ol) {
        font-size: 18px !important;
      }
      :deep(li) {
        font-size: 18px !important;
      }
      :deep(span.fr-emoticon) {
        width: 18px !important;
        height: 18px !important;
      }
    }
    .right-fix-box {
      right: 17px;
      bottom: 65px;
      .item {
        margin-top: 5px;
      }
      .back-top-img {
        width: 50px;
        height: 50px;
      }
      .collect-icon {
        width: 50px;
        height: 50px;
      }
    }
  }
  .no-auth-wrap {
    .opcity-box {
      height: 65px;
    }
    .content-box {
      padding-bottom: 100px;
    }
    .icon {
      width: 100px;
      height: 100px;
    }
  }
}
</style>