<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>
          智库报告原文
        </div>
        <div class="btn-box">
          <div class="translate">
            <div class="search-input-wrap" v-if="showSearchInput">
              <input v-model="searchKeywordText" class="search-input" placeholder="回车查询"
                @keyup.enter="handleSearchInPdf" />
              <div class="search-match-count">{{ matchInfo.current }}/{{ matchInfo.total }}</div>
              <button class="search-nav-btn" type="button" @click="handlePrevMatch"
                :disabled="matchInfo.total === 0 || matchInfo.current <= 1">
                上一个
              </button>
              <button class="search-nav-btn" type="button" @click="handleNextMatch"
                :disabled="matchInfo.total === 0 || matchInfo.current >= matchInfo.total">
                下一个
              </button>
            </div>
            <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">
        <div class="pdf-pane-wrap" v-if="valueSwitch && reportUrlEnWithPage">
          <pdf ref="leftPdfRef" :pdfUrl="reportUrlEnWithPage" class="pdf-pane-inner" />
        </div>
        <div class="pdf-pane-wrap" :class="{ 'is-full': !valueSwitch }" v-if="reportUrlWithPage">
          <pdf
            :key="`right-pdf-${valueSwitch ? 'split' : 'full'}`"
            ref="rightPdfRef"
            :pdfUrl="reportUrlWithPage"
            class="pdf-pane-inner"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, watch } 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(true)
const searchKeywordText = ref('')
const leftPdfRef = ref(null)
const rightPdfRef = ref(null)
const matchInfo = ref({ current: 0, total: 0 })
const activePdfRef = ref(null)

const clearPdfSearchState = () => {
  activePdfRef.value = null
  matchInfo.value = { current: 0, total: 0 }
  const leftPdf = leftPdfRef.value
  const rightPdf = rightPdfRef.value
  if (leftPdf && typeof leftPdf.clearSearch === 'function') {
    leftPdf.clearSearch()
  }
  if (rightPdf && typeof rightPdf.clearSearch === 'function') {
    rightPdf.clearSearch()
  }
}

const updateMatchInfo = () => {
  const pdf = activePdfRef.value
  if (pdf && typeof pdf.getMatchInfo === 'function') {
    matchInfo.value = pdf.getMatchInfo()
    return
  }
  matchInfo.value = { current: 0, total: 0 }
}

watch(
  () => searchKeywordText.value,
  (val) => {
    const keyword = String(val ?? '').trim()
    if (!keyword) {
      clearPdfSearchState()
    }
  }
)

watch(
  () => valueSwitch.value,
  () => {
    // 切换「显示原文」会导致 PDF 重新挂载/布局变化：清空搜索与计数，回到初始状态
    searchKeywordText.value = ''
    clearPdfSearchState()
  }
)

const handleSearchInPdf = async () => {
  const keyword = searchKeywordText.value?.trim()
  if (!keyword) return
  activePdfRef.value = null
  matchInfo.value = { current: 0, total: 0 }
  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)
    activePdfRef.value = targetRef
    updateMatchInfo()
  } else {
    try {
      const { ElMessage } = await import('element-plus')
      ElMessage.warning('未找到包含该关键词的页面')
    } catch (_) { }
  }
}

const handlePrevMatch = () => {
  const pdf = activePdfRef.value
  if (!pdf || typeof pdf.prevMatch !== 'function') return
  pdf.prevMatch()
  updateMatchInfo()
}

const handleNextMatch = () => {
  const pdf = activePdfRef.value
  if (!pdf || typeof pdf.nextMatch !== 'function') return
  pdf.nextMatch()
  updateMatchInfo()
}

// 下载：中英文都下载，与政令原文页相同的 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;
      align-items: center;
      overflow: visible;

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

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



          :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;
          flex-shrink: 0;
        }

        .search-input {
          width: 160px;
          height: 24px;
          box-sizing: border-box;
          border: 1px solid rgba(231, 243, 255, 1);
          background: rgba(246, 250, 255, 1);
          border-radius: 4px;
          padding: 0 10px;

          font-family: "Source Han Sans CN";
          font-size: 14px;
          line-height: 22px;
          outline: none;
        }



        .search-match-count {

          font-family: "Source Han Sans CN";
          font-weight: 400;
          font-size: 14px;
          line-height: 22px;
          min-width: 48px;
          text-align: center;
          flex-shrink: 0;
        }

        .search-nav-btn {
          width: 68px;
          height: 24px;
          box-sizing: border-box;
          border: 1px solid rgba(231, 243, 255, 1);
          background: rgba(246, 250, 255, 1);
          border-radius: 4px;
          font-family: "Source Han Sans CN";
          font-weight: 400;
          font-size: 14px;
          line-height: 22px;

          cursor: pointer;
          padding: 0;
          flex-shrink: 0;
          white-space: nowrap;
        }

        .search-nav-btn:disabled {
          opacity: 0.45;
          cursor: not-allowed;
        }
      }
    }

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

    .pdf-pane-wrap {
      flex: 0 0 50%;
      max-width: 50%;
      height: 100%;
      min-width: 0;
    }

    .pdf-pane-wrap.is-full {
      flex: 0 0 100%;
      max-width: 100%;
    }

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