<template>
  <div class="page-box">
		<div class="page-top">
			<div class="head-box">
				<div class="head-icon">
					<img :src="codeInfo.sortImageUrl || Img337" alt="" />
				</div>
				<div class="head-info">
					<div class="head-name one-line-ellipsis">{{ baseInfo.SEARCHNAME }}</div>
					<div class="head-text">{{ baseInfo.SEARCHDATE }}</div>
				</div>
				<div :class="`item-tag tag-${codeInfo.sortCode}`">{{ codeInfo.sortName }}</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="@/views/thinkTank/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="@/views/thinkTank/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, reactive } from "vue";
import pdf from "@/views/thinkTank/reportOriginal/pdf.vue";
import { getSurvyInfo, getOriginalUrl } from "@/api/marketAccessRestrictions/index.js";
import { useRoute } from "vue-router";

const route = useRoute();
const reportUrl = ref('')
const reportUrlEn = ref('')
const thinkInfo = ref({})
const defaultPdfPage = ref(1)

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 codeInfo = reactive({
	sortCode: route.query.id,
	sortName: "",
	sortImageUrl: "",
})
const onSurvyInfo = async () => {
  try {
    const res = await getSurvyInfo({sortCode: route.query.id});
    console.log("获取调查信息", res);
		if (res.code == 200) {
			Object.assign(codeInfo, res.data)
		}
  } catch (error) {
    console.error("获取调查信息error", error);
  }
};

//获取原文
const baseInfo = reactive({
	SEARCHNAME: "调查详情",
	SEARCHDATE: "",
})
const onOriginalUrl = async () => {
  try {
    const res = await getOriginalUrl({id: route.query.searchId});
    console.log("获取原文", res);
    if (res.code === 200 && res.data) {
      reportUrl.value = res.data.urlZh
      reportUrlEn.value = res.data.url
			baseInfo.SEARCHNAME = res.data.investTitleZh
			baseInfo.SEARCHDATE = res.data.investDate
    }
		document.title = baseInfo.SEARCHNAME;
  } catch (error) {
    console.error("获取原文error", error);
  }
};

onMounted(() => {
  onSurvyInfo()
  onOriginalUrl()
});
</script>

<style lang="scss" scoped>
.page-box {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	background-color: #f7f8f9;
	.page-top {
		width: 100%;
		box-sizing: border-box;
		background-color: white;
		.head-box {
			width: 1600px;
			display: flex;
			margin: 0 auto;
			padding: 30px 0 20px;
			.head-icon {
				width: 54px;
				height: 54px;
				font-size: 0px;
				margin-right: 16px;
				img {
					width: 100%;
					height: 100%;
				}
			}
			.head-info {
				width: 20px;
				flex: auto;
				.head-name {
					width: 100%;
					height: 26px;
					color: rgba(59, 65, 75, 1);
					font-family: Microsoft YaHei;
					font-size: 20px;
					font-weight: bold;
					line-height: 26px;
				}
				.head-text {
					margin-top: 4px;
					width: 100%;
					height: 24px;
					color: rgba(95, 101, 108, 1);
					font-family: Microsoft YaHei;
					font-size: 16px;
					font-weight: 400;
					line-height: 24px;
				}
			}
			.item-tag {
        height: 24px;
        line-height: 24px;
        padding: 0 8px;
        border-radius: 4px;
        font-weight: bold;
        font-size: 16px;
				letter-spacing: 2px;
      }
      .tag-337 {
        border: 1px solid #91caff;
        background: #e6f4ff;
        color: #055fc2;
      }
      .tag-232 {
        border: 1px solid #b37feb;
        background: #f9f0ff;
        color: #722ed1;
      }
      .tag-301 {
        border: 1px solid #ffd591;
        background: #fff7e6;
        color: #fa8c16;
      }
			.head-button {
				margin-left: 100px;
				width: 120px;
				height: 36px;
				border-radius: 6px;
				background: var(--color-main-active);
				display: flex;
				justify-content: center;
				align-items: center;
				cursor: pointer;
				.button-icon {
					width: 16px;
					height: 16px;
					font-size: 0;
					img {
						width: 100%;
						height: 100%;
					}
				}
				.button-text {
					margin-left: 8px;
					color: rgba(255, 255, 255, 1);
					font-family: Microsoft YaHei;
					font-size: 16px;
					font-weight: 400;
				}
			}
		}
	}

  .main {
    margin: 0 auto;
    background: rgb(255, 255, 255);
    width: 1600px;
    height: 948px;
    margin-bottom: 86px;

    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;
          cursor: pointer;
          ;


          .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>