<template>
  <div :class="['container-cygx', reportInfo.IsResearch && 'no-cv', reportInfo.IsSpecialArticle && 'container-cygx-bg']" v-show="haveData">
    <trackForm v-model:isShowFollowButton="reportInfo.IsShowFollowButton" :sourceId="rerportId" v-model:isFollowData="reportInfo.IsFollowButton" />
    <div class="z-index-content" ref="contentBox">
      <div class="content-top">
        <div class="report-title">{{ reportInfo.Title }}</div>
        <div class="report-text">
          <template v-if="!reportInfo.IsResearch">
            <div v-if="reportInfo.IsSpecialArticle">
              <span>{{ reportInfo.PublishDate }} &nbsp;&nbsp;&nbsp;&nbsp;</span>
              <span class="author">{{ reportInfo.SellerAndMobile }}</span>
            </div>
            <template v-else>
              <div class="report_desc">
                <span class="author">{{ reportInfo.Department }}</span>
                <span>{{ reportInfo.PublishDate }}</span>
              </div>
              <div class="seller-list" v-if="reportInfo.IsSpecialArticle">
                <span>联系人:</span>
                <span v-for="(item, index) in reportInfo.SellerList" :key="index"> {{ item.SellerName }}({{ item.SellerMobile }})&nbsp;&nbsp; </span>
              </div>
            </template>
          </template>
          <template v-else>
            <div class="report-research">
              <div style="display: flex">
                <img :src="reportInfo.DepartmentImgUrl" @click="goAuthorPages" />
                <div class="research-author">
                  <p @click="goAuthorPages">{{ reportInfo.SellerAndMobile }}</p>
                  <p class="time">{{ reportInfo.PublishDate }}</p>
                </div>
              </div>
              <div @click="attentionBtn" :style="{ 'background-color': isYanxuan ? '#F1A84A' : '#376CBB' }" class="is-follow" :class="reportInfo.IsFollow ? 'follow-cancel' : ''" v-if="isBinding">
                {{ reportInfo.IsFollow ? "取消关注" : "+ 关注" }}
              </div>
            </div>
          </template>
          <!-- <div v-if="!reportInfo.IsSpecialArticle">注：请务必阅读<span class="tip" @click="showTips = true"> &nbsp;免责声明</span></div> -->
          <div :class="['container-abstract', isYanxuan && 'container-abstract-yx']">&nbsp;&nbsp;摘要:&nbsp;{{ reportInfo.Abstract }}</div>
        </div>
      </div>
      <template v-if="isBinding">
        <div class="report-link" v-if="fileLink">
          报告全文:
          <span style="color: #0808e5" @click="downloadFile">（PDF格式报告下载.pdf）</span>
        </div>
        <div class="detail-report" :class="reportInfo.IsResearch ? '' : 'detail-bottom'">
          <div id="report-content" v-html="reportInfo.Body"></div>
        </div>
        <div class="deeperReport" @click="lookDeeperReport" v-if="reportInfo.ReportLink">查看报告链接</div>
        <div class="host-collect" v-if="reportInfo.IsResearch && reportResearch.length">
          <h4>相关热门收藏：</h4>
          <div class="host-content" v-for="item in reportResearch" :key="item.ArticleId">
            <p class="host-title" @click="goDetail(item)">{{ item.Title }}</p>
            <div class="item-more">
              <p>{{ item.PublishDate }}</p>
              <div class="pv-ollect">
                <div>
                  <img class="pv" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/czbk/examine_icon.png" />
                  {{ item.Pv }}
                </div>
                <div @click="collectClick(item)">
                  <img v-if="item.IsCollect" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/czbk/collect_act.png" />
                  <img v-else src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/czbk/collect_ico.png" />
                  {{ item.CollectNum }}人收藏
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- <div v-if="reportInfo.IsSpecialArticle" class="statement-content">
          <p class="title">免责声明</p>
          <p class="content">
            本报告仅供弘则弥道（上海）投资咨询有限公司正式签约的机构客户使用，不会仅因接收人/接受机构收到本报告而将其视为客户。本报告根据国际和行业通行的准则，以合法渠道获得这些信息，尽可能保证可靠、准确和完整，但并不保证报告所述信息的准确性和完整性，也不保证本报告所包含的信息或建议在本报告发出后不会发生任何变更。本报告中所提供的信息仅供参考。报告中的内容不对投资者做出的最终操作建议做任何的担保，也没有任何形式的分享投资收益或者分担投资损失的书面或口头承诺。不作为客户在投资、法律、会计或税务等方面的最终操作建议，也不作为道义的、责任的和法律的依据或者凭证，无论是否已经明示或者暗示。在任何情况下，本公司不对客户/接受人/接受机构因使用报告中内容所引致的一切损失负责任，客户/接受人/接受机构需自行承担全部风险。
          </p>
        </div> -->
      </template>
      <template v-else>
        <div class="detail-report" :class="reportInfo.IsResearch ? '' : 'detail-bottom'" v-if="reportInfo.Body">
          <div id="report-content" v-html="reportInfo.Body.slice(0, 200)"></div>
        </div>
        <div class="please-login" @click="pleaseGoLogin">请登录后查看更多内容</div>
      </template>
    </div>
    <div class="statement-content-box" v-if="rerportId >= 1000000">
      <p>郑重声明：</p>
      本文为用户投稿，用户在平台中发表的所有资料、言论等仅代表个人或嘉宾观点，与本网站、任何公司与任何机构立场无关。本平台对文中陈述、观点判断保持中立，不对所包含内容及数据的真实性、准确性、可靠性或完整性提供任何明示或暗示的保证。
      股市波动与很多因素有关，任何用户或嘉宾的发言，都有其特定立场，投资决策是个人基于自己的研究分析所做的决定，本文章或会议目的在于事实、观点分享，不构成任何的投资建议。投资者应当自主进行投资决策，对投资者因依赖上述信息进行投资决策而导致的财产损失，本平台不承担法律责任。
      本文章或会议未经本平台和作者的书面许可，任何机构和个人不得以任何形式转发、转载、翻版、复制、刊登、发表、修改、仿制或引用文章或会议的全部或部分内容。本平台对任何第三方的未经授权行为所产生的的影响不承担任何责任，同时保持实施法律行动的权利。
    </div>
    <div class="btn-returntop" v-if="isBinding">
      <img v-if="isYanxuan" src="~@/assets/cygx/returntop_yx.png" @click="scrolltop" style="width: 40px" />
      <img v-else src="~@/assets/cygx/returntop.png" @click="scrolltop" style="width: 40px" />
    </div>
    <div class="btn-freecharge" v-if="isShowFreeBtn && from_type == 'mpwechat'">
      <img @click="toggle" class="image" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/czbk/free_icon.png" />
      <img @click="removeBton" class="remove-icon" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/czbk/free_%20remove.png" />
    </div>
    <!-- 底部悬浮固定 -->
    <div class="fixed_cont" v-if="from_type == 'mpwechat' && isBinding">
      <div class="handle-item" @click="quizBtn">
        <img src="@/assets/cygx/leaving_message.png" class="img_ico" />
        <div>留言</div>
      </div>
      <div class="handle-item" v-if="reportInfo?.IsApplyAppointmentExpert" @click="appointment(reportInfo?.ArticleId)">
        <img src="@/assets/cygx/appointment-expert.png" class="img_ico" />
        <div>约访专家</div>
      </div>
      <div class="handle-item" @click="collectHandle">
        <template v-if="reportInfo.IsCollect">
          <img v-if="isYanxuan" src="https://hzstatic.hzinsights.com/yx_xcx/collect_act.png" />
          <img src="@/assets/cygx/collect_act.png" class="img_ico" v-else />
        </template>
        <img src="@/assets/cygx/collect_ico.png" class="img_ico" v-else />

        <div v-if="reportInfo.IsResearch">
          {{ `${reportInfo.CollectionNum}  人收藏` }}
        </div>
        <div v-else>{{ reportInfo.IsCollect ? "已收藏" : "收藏" }}</div>
      </div>
    </div>
    <dlg :showTips="showTips" :reportInfo="reportInfo" @hideDlg="showTips = false" />
  </div>
</template>

<script setup>
import { reactive, onMounted, toRefs, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { RaiApi, FreeButton } from "@/api/cygx/api.js";
import { Icon, Dialog, Toast } from "vant";
import dlg from "./dlg.vue";
import trackForm from "./isTrackFollow.vue";
const router = useRouter();
const route = useRoute();
const state = reactive({
  reportInfo: {},
  reportResearch: [],
});
const rerportId = ref(null);
const from_type = ref(null);
const haveData = ref(false);
const fileLink = ref(false);
const showTips = ref(false);
const contentBox = ref(null);
const isBinding = ref(true);
const isSendWx = ref("");
const isYanxuan = ref("");

/* 访谈接口 */
const interviewApi = () => {
  RaiApi.applyRpt({
    ArticleId: Number(rerportId.value),
  }).then((res) => {
    if (res.Ret === 200) {
      state.reportInfo.IsInterviewApply = !state.reportInfo.IsInterviewApply;
      state.reportInfo.InterviewApplyStatus = state.reportInfo.IsInterviewApply ? "待邀请" : "";
      Toast(res.Msg);
    }
  });
};
//跳转到免费送月卡页面
const toggle = () => {
  wx.miniProgram.navigateTo({
    url: `/${isYanxuan.value ? "pages-user" : "pageMy"}/freeTrial/freeTrial`,
  });
};
const isShowFreeBtn = ref(false);

//隐藏当天的按钮
const removeBton = async () => {
  const res = await FreeButton.userFreeButtonUpdate();
  if (res.Ret === 200) {
    isShowFreeBtn.value = false;
  }
};

const userIsShowFreeButton = async () => {
  const res = await FreeButton.userIsShowFreeButton();
  if (res.Ret === 200) {
    isShowFreeBtn.value = res.Data.IsShow;
  }
};
// 跳转到作者页面
const goAuthorPages = () => {
  wx.miniProgram.navigateTo({
    url: `/${isYanxuan.value ? "pages-report" : "reportPages"}/authorPages/authorPages?id=` + state.reportInfo.DepartmentId,
  });
};
const downloadFile = async () => {
  Toast.loading({
    message: "下载中...",
    duration: 0,
    forbidClick: true,
  });
  const res = await RaiApi.articlePdfwatermark({
    ArticleId: Number(rerportId.value),
  });
  if (res.Ret === 200) {
    Toast.clear();
    wx.miniProgram.navigateTo({
      url: `/${isYanxuan.value ? "pages-user" : "pageMy"}/downloadFile/downloadFile?url=` + res.Data.FileLink,
    });
  }
};
/* 访谈申请 */
const applyHandle = () => {
  !state.reportInfo.IsInterviewApply &&
    Dialog.confirm({
      title: "",
      message: "专家访谈申请会提交给您的对口销售，销售会线下与您取得联系，确定申请吗？",
      confirmButtonColor: "#fff",
      cancelButtonColor: "#fff",
      theme: "round-button",
    }).then(() => {
      interviewApi();
    });
  // 取消申请访谈 区分状态 '待邀请','待访谈','已完成','已取消'
  if (state.reportInfo.IsInterviewApply) {
    Dialog.confirm({
      title: "",
      message:
        state.reportInfo.InterviewApplyStatus == "待访谈"
          ? "当前无法取消访谈，若有疑问，请联系对口销售" + state.reportInfo.SellerMobile
          : state.reportInfo.InterviewApplyStatus == "待邀请"
          ? "您要取消此次访谈申请吗？"
          : "该访谈已完成",
      confirmButtonColor: "#fff",
      cancelButtonColor: "#fff",
      theme: "round-button",
    }).then(() => {
      state.reportInfo.InterviewApplyStatus == "待邀请" ? interviewApi() : state.reportInfo.InterviewApplyStatus == "待访谈" ? (window.location.href = "tel://" + state.reportInfo.SellerMobile) : "";
    });
  }
};
const scrolltop = () => {
  document.body.scrollTop = document.documentElement.scrollTop = 0;
};
/* 文章相关热门 */
const researcharticleHotList = async () => {
  const res = await FreeButton.researcharticleHotList({ ArticleId: Number(rerportId.value) });
  if (res.Ret === 200) {
    state.reportResearch = res.Data.List || [];
  }
};
//关注作者事件
const attentionBtn = () => {
  RaiApi.fllowDepartment({
    DepartmentId: state.reportInfo.DepartmentId,
  }).then((res) => {
    if (res.Ret === 200) {
      state.reportInfo.IsFollow = !state.reportInfo.IsFollow;
      if (res.Data.Status == 1) {
        state.reportInfo.FollowNum += 1;
        if (res.Data.GoFollow) {
          Dialog.confirm({
            title: "作者关注成功",
            message: "想要及时获取该作者的报告更新提示，请关注【查研观向小助手】公众号",
            confirmButtonColor: "#fff",
            confirmButtonText: "去关注",
            cancelButtonColor: "#fff",
            theme: "round-button",
          })
            .then(() => {
              wx.miniProgram.navigateTo({
                url: `/${isYanxuan.value ? "pages-activity" : "activityPages"}/accountsOfficial/accountsOfficial`,
              });
            })
            .catch(() => {
              // on cancel
            });
        } else {
          Dialog.alert({
            title: "",
            message: "作者关注成功，请关注【查研观向小助手】公众号，及时获取作者的报告更新提示",
            confirmButtonColor: "#3385FF",
            confirmButtonText: "知道了",
          });
        }
      } else {
        state.reportInfo.FollowNum -= 1;
        Toast("已取消关注");
      }
    }
  });
};
/* 收藏 */
const collectHandle = () => {
  RaiApi.collectRpt({
    ArticleId: Number(rerportId.value),
  }).then((res) => {
    if (res.Ret === 200) {
      state.reportInfo.IsCollect = !state.reportInfo.IsCollect;
      if (res.Data.Status == 2) {
        state.reportInfo.CollectionNum -= 1;
      } else {
        state.reportInfo.CollectionNum += 1;
      }
      Toast(res.Msg);
    }
  });
};
/* 文章相关热门跳转 */
const goDetail = (item) => {
  wx.miniProgram.navigateTo({
    url: `/${isYanxuan.value ? "pages-user" : "pageMy"}/reportDetail/reportDetail?id=` + item.ArticleId,
  });
};
/* 文章相关热门收藏 */
const collectClick = async (item) => {
  const res = await RaiApi.collectRpt({ ArticleId: item.ArticleId });
  if (res.Ret === 200) {
    item.IsCollect = !item.IsCollect;
    item.IsCollect ? (item.CollectNum += 1) && Toast("收藏成功") : (item.CollectNum -= 1);
    !item.IsCollect && Toast("已取消收藏");
  }
};
/* 复制 */
const copyMonitor = () => {
  RaiApi.pageHistoryCopy({
    DetailId: rerportId.value + "",
    PageType: "ArticleCopy",
  }).then((res) => {});
};
const waterMark = (text) => {
  let canvas = document.createElement("canvas");
  let ctx = canvas.getContext("2d");
  ctx.font = "20px Arial";
  ctx.rotate((-45 * Math.PI) / 200);
  ctx.fillStyle = "#DCDCDC";
  ctx.fillText(text, 30, 160);
  ctx.fillText(text, -40, 80);

  // 将canvas的内容转换为base64编码
  let data = canvas.toDataURL("image/png");
  // 将容器的的背景图片设置为生成的base64图片,并平铺
  contentBox.value.style.background = "url(" + data + ") repeat";
};
//点击到提问页面
const quizBtn = () => {
  wx.miniProgram.navigateTo({
    url: `/${isYanxuan.value ? "pages-activity" : "activityPages"}/generationAsk/generationAsk?id=` + state.reportInfo.ArticleId + "&type=文章",
  });
};
// 约访专家
const appointment = (articleId) => {
  console.log(articleId);
  if (!articleId) {
    Toast("ArticleId 值错误");
    return;
  }
  Dialog.confirm({
    message: "约访专家的请求会提醒您的对口销售，确定要发起吗？",
    messageAlign: "left",
    showCancelButton: true,
    confirmButtonColor: isYanxuan.value ? "#F1A84A" : "#3385FF",
  })
    .then(() => {
      RaiApi.appointmentExpert({ ArticleId: articleId }).then((res) => {
        if (res.Ret === 200 || res.Ret === 403) {
          Dialog.confirm({
            message: "约访申请已提醒您的对口销售，请等待销售与您联系",
            messageAlign: "left",
            showConfirmButton: false,
            cancelButtonText: "知道了",
          })
            .then(() => {})
            .catch(() => {});
        }
      });
    })
    .catch(() => {});
};
/* 获取报告详情 */
const getReport = (id, token, type) => {
  if (type == "mpwechat") {
    RaiApi.reportDtl({
      ArticleId: id,
      Authorization: token,
      IsSendWx: isSendWx.value,
    }).then((res) => {
      if (res.Ret === 200) {
        haveData.value = res.Data.HasPermission === 1 ? true : false;
        if (res.Data.HasPermission === 1) {
          //有访问权限
          state.reportInfo = res.Data.Detail;
          fileLink.value = res.Data.Detail.FileLink;
          if (state.reportInfo.IsResearch || state.reportInfo.IsBelongSummary) {
            waterMark(res.Data.Mobile);
          }
          $(document).on("click", "#report-content img", function (event) {
            let imgArray = [];
            let src_tag = $(this).attr("src");
            let parent_tag = $(this).parent();
            if (src_tag && !parent_tag.attr("href")) {
              $("#report-content img").each(function (index, el) {
                let itemSrc = $(this).attr("src");
                imgArray.push(itemSrc);
              });
              wx.previewImage({ current: src_tag, urls: imgArray });
            }
          });
        }
      }
    });
  } else {
    RaiApi.lookReport({
      ArticleIdMd5: id,
    }).then((res) => {
      if (res.Ret === 200) {
        haveData.value = res.Data.HasPermission === 1 ? true : false;
        if (res.Data.HasPermission === 1) {
          //有访问权限
          state.reportInfo = res.Data.Detail;
          $(document).on("click", "#report-content img", function (event) {
            let imgArray = [];
            let src_tag = $(this).attr("src");
            let parent_tag = $(this).parent();
            if (src_tag && !parent_tag.attr("href")) {
              $("#report-content img").each(function (index, el) {
                let itemSrc = $(this).attr("src");
                imgArray.push(itemSrc);
              });
              wx.previewImage({ current: src_tag, urls: imgArray });
            }
          });
        }
      }
    });
  }
};

const lookDeeperReport = () => {
  router.push({
    path: "/strategyReport",
    query: {
      url: state.reportInfo.ReportLink,
    },
  });
};
const pleaseGoLogin = () => {
  Dialog.alert({
    message: "即将前往登录页面，请确认是否继续",
    showCancelButton: true,
    confirmButtonColor: "#3385ff",
  }).then((res) => {
    if (res == "confirm") {
      wx.miniProgram.navigateTo({
        url: `/${isYanxuan.value ? "pages-user" : "pageMy"}/login/login`,
      });
    }
  });
};
onMounted(() => {
  document.title = "报告详情";
  if (route.query.id) {
    rerportId.value = +route.query.id;
    isSendWx.value = route.query.IsSendWx || "";
    from_type.value = route.query.fromType;
    let access_token = route.query.token || "";
    isBinding.value = route.query.isBinding == "true" ? true : false;
    isYanxuan.value = route.query.isYanxuan ? true : false;
    localStorage.setItem("access_token", access_token);
    getReport(rerportId.value, access_token, from_type.value);
    userIsShowFreeButton();
    if (from_type.value == "mpwechat") {
      document.addEventListener("copy", (e) => {
        copyMonitor();
      });
    } else if (from_type.value == "manage") {
      router.push({
        path: "/cygx/report",
        query: {
          id: rerportId.value,
        },
      });
      return;
    }
    researcharticleHotList();
  }
});
const { reportInfo, reportResearch } = toRefs(state);
// url: raiReportDtl?id=3001&token=20ec44c7fe0e02ff597c324406ce49ca4b6b838e1988df75bd82084a6c0672fc&fromType=mpwechat
</script>

<style lang="scss">
@import "./index.scss";
.please-login {
  margin: 50px auto 150px;
  width: 556px;
  height: 64px;
  color: #fff;
  font-size: 24px;
  font-weight: 600;
  background-color: #376cbb;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 9px;
}
</style>
