<template>
  <div class="wrap">
    <div class="header">
      <div class="header-top">
        <div class="header-top-left">
          <img :src="thinkInfo.imageUrl" alt="" />
          <div>
            <div class="title">{{ thinkInfo.name }}</div>
            <div class="en-title">
              {{ thinkInfo.ename }}
            </div>

          </div>
        </div>
        <div class="header-top-right">
          <div class="image-name-box">
            <div class="image"> <img :src=thinkInfo.thinkTankLogoUrl alt="" /></div>
            <div class="name">{{ thinkInfo.thinkTankName }}</div>
          </div>
          <div class="time">{{ thinkInfo.times }}</div>
        </div>
      </div>

    </div>
    <div class="main">
      <div class="main-header">
        <div style=" margin-top: 17px;">
          智库报告原文
        </div>
        <div class="btn-box">
          <div class="translate">
            <div class="switch">
              <el-switch v-model="valueSwitch" />
            </div>
            <div class="translate-image">
              <img class="translate-icon" src="../ReportDetail/images/image-translate.png" alt=""
                style="width: 16px; height: 16px; max-width: 16px; max-height: 16px; display: block; object-fit: contain;" />
            </div>
            <div class="translate-text">{{ "显示原文" }}</div>
          </div>
          <div class="btn" @click="handleDownload">
            <div class="icon">
              <img src="../ReportDetail/images/image-pdf.png" alt="" />
            </div>
            <div class="text">{{ "下载" }}</div>
          </div>

        </div>
      </div>
      <div class="report-box">
        <pdf v-if="valueSwitch && reportUrlEnWithPage" ref="leftPdfRef" :pdfUrl="reportUrlEnWithPage"
          class="pdf-pane" />
        <pdf v-if="reportUrlWithPage" ref="rightPdfRef" :pdfUrl="reportUrlWithPage"
          :class="['pdf-pane', { 'pdf-pane-full': !valueSwitch }]" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from "vue";
import pdf from "./pdf.vue";
import {
  getThinkTankReportSummary,
  getThinkTankReportcontentUrl
} from "@/api/thinkTank/overview";
import { useRoute, useRouter } from "vue-router";




const router = useRouter();
const route = useRoute();
const reportUrl = ref('')
const reportUrlEn = ref('')
const thinkInfo = ref({})
const defaultPdfPage = ref(1)
const sourceCurrentPage = ref(Number(route.query.currentPage) || 1)
const sourcePageSize = ref(Number(route.query.pageSize) || 12)
const opinionId = ref(route.query.opinionId || "")
const opinionContent = ref(route.query.opinionContent || "")

const buildPdfPageUrl = url => {
  if (!url) return ''
  return `${url}#page=${defaultPdfPage.value}`
}

const reportUrlWithPage = computed(() => buildPdfPageUrl(reportUrl.value))
const reportUrlEnWithPage = computed(() => buildPdfPageUrl(reportUrlEn.value))
const valueSwitch = ref(true)
const showSearchInput = ref(false)
const searchKeywordText = ref('')
const leftPdfRef = ref(null)
const rightPdfRef = ref(null)

const handleSearchInPdf = async () => {
  const keyword = searchKeywordText.value?.trim()
  if (!keyword) return
  const leftPdf = leftPdfRef.value
  const rightPdf = rightPdfRef.value
  let page = 0
  let targetRef = null
  if (leftPdf && typeof leftPdf.searchKeyword === 'function') {
    page = await leftPdf.searchKeyword(keyword)
    if (page) targetRef = leftPdf
  }
  if (!page && rightPdf && typeof rightPdf.searchKeyword === 'function') {
    page = await rightPdf.searchKeyword(keyword)
    if (page) targetRef = rightPdf
  }
  if (page && targetRef && typeof targetRef.goToPage === 'function') {
    targetRef.goToPage(page)
  } else {
    try {
      const { ElMessage } = await import('element-plus')
      ElMessage.warning('未找到包含该关键词的页面')
    } catch (_) { }
  }
}

// 下载：中英文都下载，与政令原文页相同的 fetch → blob → a 标签触发下载
const downloadOnePdf = async (url, filename) => {
  const response = await fetch(url, {
    method: 'GET',
    headers: { 'Content-Type': 'application/pdf' },
  })
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
  const blob = await response.blob()
  const blobUrl = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = blobUrl
  link.download = filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(blobUrl)
}

const handleDownload = async () => {
  const urlZh = reportUrl.value ? String(reportUrl.value).split('#')[0] : ''
  const urlEn = reportUrlEn.value ? String(reportUrlEn.value).split('#')[0] : ''
  if (!urlZh && !urlEn) {
    try {
      const { ElMessage } = await import('element-plus')
      ElMessage.warning('暂无下载链接')
    } catch (_) { }
    return
  }
  const baseName = (thinkInfo.value?.name || '报告原文').replace(/[/\\?%*:|"<>]/g, '-')
  const { ElMessage } = await import('element-plus')
  try {
    if (urlZh) {
      await downloadOnePdf(urlZh, `${baseName}_中文.pdf`)
    }
    if (urlEn) {
      if (urlZh) await new Promise(r => setTimeout(r, 300))
      await downloadOnePdf(urlEn, `${baseName}_英文.pdf`)
    }
    if (urlZh || urlEn) {
      ElMessage.success(urlZh && urlEn ? '已下载中文、英文两份 PDF' : '下载成功')
    }
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('PDF 下载失败，请稍后重试')
  }
}

// 获取报告全局信息
const handleGetThinkTankReportSummary = async () => {
  try {
    const res = await getThinkTankReportSummary(router.currentRoute._value.params.id);
    console.log("报告全局信息", res);
    if (res.code === 200 && res.data) {

      thinkInfo.value = res.data
    }
  } catch (error) {
    console.error("获取报告全局信息error", error);
  }
};
//获取原文
const handleGetThinkTankReportcontentUrl = async () => {
  try {
    const res = await getThinkTankReportcontentUrl(router.currentRoute._value.params.id);
    console.log("获取原文", res);
    if (res.code === 200 && res.data) {
      reportUrl.value = res.data.content
      reportUrlEn.value = res.data.contentEn

    }
  } catch (error) {
    console.error("获取原文error", error);
  }
};

const tabActiveName = ref("报告分析");

const switchTab = name => {
  tabActiveName.value = name;
};
onMounted(async () => {
  handleGetThinkTankReportSummary()
  handleGetThinkTankReportcontentUrl()
});
</script>

<style lang="scss" scoped>
.wrap {



  .header {
    width: 100%;
    height: 88px;
    box-sizing: border-box;
    border-bottom: 1px solid rgba(234, 236, 238, 1);
    box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
    background: rgba(255, 255, 255, 1);
    position: sticky;
    top: 0;
    z-index: 99999;
    overflow: hidden;

    .header-top {
      margin: 0 auto;
      margin-top: 20px;
      width: 1600px;
      display: flex;
      justify-content: space-between;

      .header-top-left {
        display: flex;

        img {
          width: 44px;
          height: 54px;
        }

        .title {
          margin-left: 20px;
          height: 26px;
          color: rgba(59, 65, 75, 1);
          font-family: Microsoft YaHei;
          font-size: 20px;
          font-weight: 700;
          line-height: 26px;
          letter-spacing: 0px;
          text-align: left;
        }

        .en-title {
          margin-top: 4px;
          margin-left: 20px;
          height: 24px;
          color: rgba(95, 101, 108, 1);
          font-family: Microsoft YaHei;
          font-size: 16px;
          font-weight: 400;
          line-height: 24px;
          letter-spacing: 0px;
          text-align: left;
        }

        .tag-box {
          margin-top: 11px;
          display: flex;
          gap: 8px;
          margin-left: 20px;
        }
      }

      .header-top-right {
        display: flex;
        flex-direction: column;
        text-align: right;
        align-items: flex-end;

        .image-name-box {
          width: 118px;
          height: 24px;
          gap: 6px;

          text-align: right;
          display: flex;
          justify-content: flex-end;

          .name {
            height: 24px;
            color: rgba(95, 101, 108, 1);
            font-family: Microsoft YaHei;
            font-size: 16px;
            font-weight: 400;
            line-height: 24px;
            letter-spacing: 0px;
            text-align: right;

          }

          .image {
            width: 16px;
            height: 16px;

            margin-top: 5px;


            img {
              width: 100%;
              height: 100%;


            }
          }
        }

        .time {
          height: 24px;
          margin-top: 5px;
          color: rgba(95, 101, 108, 1);
          font-family: Microsoft YaHei;
          font-size: 16px;
          font-weight: 400;
          line-height: 24px;
          letter-spacing: 0px;
          text-align: right;
        }
      }
    }

    .header-bottom {
      margin: 0 auto;
      margin-top: 30px;
      width: 1600px;
      height: 48px;
      display: flex;
      justify-content: space-between;

      .tab-box {
        width: 224px;
        height: 48px;
        display: flex;
        gap: 24px;

        .tab {
          width: 94px;
          height: 48px;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 4px;
          cursor: pointer;
          border-bottom: 2px solid transparent;

          .icon {
            width: 16px;
            height: 16px;

            img {
              width: 100%;
              height: 100%;
            }
          }

          .text {
            height: 24px;
            color: rgba(59, 65, 75, 1);
            font-family: Microsoft YaHei;
            font-size: 18px;
            font-weight: 400;
            line-height: 24px;
          }

          .textActive {
            color: rgba(5, 95, 194, 1);
            font-weight: 700;
          }
        }

        .tabActive {
          border-bottom: 2px solid rgba(5, 95, 194, 1);
        }
      }


    }
  }

  .main {
    margin: 0 auto;
    background: rgb(255, 255, 255);
    width: 1600px;
    height: 928px;
    overflow: hidden;
    border: 1px, solid, rgb(234, 236, 238);
    box-shadow: 0 0 20px 0 rgba(25, 69, 130, 0.1);

    .main-header {
      height: 64px;
      /* box-sizing: border-box; */
      border-bottom: 1px solid rgb(234, 236, 238);
      background: rgb(255, 255, 255);
      margin: 0 70px;
      color: rgba(59, 65, 75, 1);
      font-family: "Source Han Sans CN";
      font-style: Bold;
      font-size: 20px;
      font-weight: 700;
      line-height: 26px;
      letter-spacing: 0px;
      width: 1456px;
      text-align: left;
      display: flex;
      justify-content: space-between;

      .btn-box {
        display: flex;
        align-items: center;
        gap: 8px;

        .translate {
          display: flex;
          flex-wrap: nowrap;
          align-items: center;
          height: 24px;
          margin-right: 16px;



          :deep(.el-switch) {
            width: 22px !important;
            height: 14px !important;
            margin-bottom: 5px;
            margin-right: 8px;
          }

          :deep(.el-switch__core) {
            width: 22px !important;
            height: 14px !important;
            min-width: 22px !important;
          }


          :deep(.el-switch__button),
          :deep(.el-switch__action) {
            width: 10px !important;
            height: 10px !important;
          }

          /* 打开时圆球从左边移到最右边：轨道 22px - 圆球 10px = 12px */
          :deep(.el-switch.is-checked .el-switch__button),
          :deep(.el-switch.is-checked .el-switch__action) {
            transform: translateX(6px) !important;
          }

          .translate-image {
            display: flex;
            width: 16px;
            height: 16px;
            overflow: hidden;


            img {
              width: 100%;
              height: 100%;
            }
          }

          .translate-text {

            font-size: 14px;
            font-weight: 400;
            line-height: 22px;
          }
        }

        .btn {
          width: 88px;
          height: 32px;

          box-sizing: border-box;
          border: 1px solid rgba(230, 231, 232, 1);
          border-radius: 6px;
          background: rgba(255, 255, 255, 1);
          display: flex;
          gap: 8px;


          .icon {
            width: 16px;
            height: 16px;
            display: inline-flex;
            margin-top: 8px;
            margin-left: 16px;



            img {
              width: 100%;
              height: 100%;
            }
          }

          .text {
            margin-top: 4px;
            width: 32px;
            height: 24px;
            color: rgb(59, 65, 75);
            font-family: "Source Han Sans CN";
            font-size: 16px;
            font-weight: 400;
            line-height: 24px;
            letter-spacing: 0px;
            text-align: left;
          }
        }

        .search-btn {
          cursor: pointer;
        }

        .search-input-wrap {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          margin-left: 4px;
        }
      }
    }

    .report-box {
      margin-left: 70px;
      width: 1456px;
      height: 881px;
      display: flex;
      overflow-y: auto;
      /* 右侧统一滚动条，控制两侧原文+译文一起滚动 */
      overflow-x: hidden;
    }

    .pdf-pane {
      width: 50%;
      height: 100%;
    }

    .pdf-pane-full {
      width: 100%;
    }
  }
}
</style>