<template>
	<el-scrollbar>
		<div class="flex-display common-page top-box-news-deatail" style="align-items: center">
			<!-- <color-svg :svg-url="NewsLogo" :size="72" style="margin-right:10px"></color-svg> -->
			<img :src="NewsLogo" style="margin-right: 24px" />
			<el-space direction="vertical" class="flex-fill" alignment="flex-start">
				<common-text class="text-title-1-bold" color="var(--text-primary-80-color)">
					{{ newsDetail.titleZh }}
				</common-text>
				<common-text class="text-tip-1-bold" color="var(--text-primary-80-color)">
					{{ newsDetail.title }}
				</common-text>
				<common-text class="text-tip-1-bold" color="var(--text-primary-65-color)">
					{{ `${newsDetail.publishedTime} · ${newsDetail.source} ` }}
					<el-space>
						<area-tag v-for="item in newsDetail.domainList" :key="item" :tag-name="item.industryName" />
					</el-space>
				</common-text>
			</el-space>
			<!-- <el-button type="primary" @click="() => gotoNewsDetail(newsDetail.newsId)">
                <el-icon class="icon">
                    <el-icon>
                        <top-right />
                    </el-icon>
                </el-icon>
                查看原网页
            </el-button> -->
		</div>
		<div class="flex-display common-page content-box-news-detail">
			<el-space direction="vertical" class="background-as-card flex-fill" fill alignment="flex-start">
				<div style="margin-top: 10px; margin-right: 24px; gap: 10px" class="flex-display">
					<color-prefix-title height="20px">
						<div class="text-title-2-bold">新闻内容</div>
					</color-prefix-title>
					<div class="flex-fill"></div>
					<el-switch v-model="isHightLightEntity" active-text="高亮实体" @change="handleHighlightEntity" />
					<el-button
						v-if="textZns.length > 0"
						:type="isOpenTranslation ? 'primary' : ''"
						plain
						@click="handleTranslation"
					>
						<color-svg
							:svg-url="TranslationSvg"
							color="var(--color-primary-100)"
							:size="18"
							style="margin-right: 10px"
						></color-svg>
						译文
					</el-button>
				</div>
				<text-translate-pane
					class="common-padding-h"
					:texts-raw="textEns"
					:texts-translate="textZns"
					:text-entities="textEntities"
					:is-open-translation="isOpenTranslation"
					:is-highlight-entity="isHightLightEntity"
					@on-entity-click="e => gotoSearchResults(e.text_span, '')"
				>
				</text-translate-pane>
				<div>
					<img
						v-if="newsDetail.coverUrl"
						class="common-padding"
						:src="newsDetail.coverUrl"
						:width="320"
						:height="240"
					/>
				</div>
			</el-space>
			<el-space direction="vertical" class="background-as-card relation-news-box" fill>
				<el-space style="margin-top: 10px">
					<color-prefix-title height="20px">
						<div class="text-title-2-bold">相关新闻</div>
					</color-prefix-title>
				</el-space>
				<el-space v-if="relationNews?.length > 0" direction="vertical" fill class="common-padding">
					<news-item-mini
						v-for="item in relationNews"
						:key="item.newsId"
						:news="item"
						:img="item.newsImage"
						:title="item.newsTitle"
						:from="`${item.newsDate} · ${item.newsOrg}`"
						@click="gotoNewsDetail(item.newsId)"
					/>
				</el-space>
				<el-empty v-else style=""></el-empty>
			</el-space>
		</div>
	</el-scrollbar>
</template>
<script setup>
import { getNewsDetail } from "@/api/news/newsBrief";
import "@/styles/container.scss";
import "@/styles/common.scss";
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { ElSpace, ElButton, ElScrollbar, ElSwitch, ElEmpty, ElImage } from "element-plus";
import CommonText from "@/components/base/texts/CommonText.vue";
import AreaTag from "@/components/base/AreaTag/index.vue";
import ColorPrefixTitle from "@/components/base/texts/ColorPrefixTitle.vue";
import { getRelationNews } from "@/api/news/newsDetail";
import NewsItemMini from "@/components/base/newsList/NewsItemMini.vue";
import ColorSvg from "@/components/base/images/ColorSvg.vue";
import TranslationSvg from "./assets/images/翻译 1.svg";
import NewsLogo from "./assets/images/组合 293.svg";
import { extractTextEntity } from "@/api/intelligent";
import { useGotoNewsDetail } from "@/router/modules/news";
import { useGotoSearchResults } from "@/router/modules/comprehensiveSearch";
import TextTranslatePane from "@/components/base/texts/TextTranslatePane.vue";

const newsDetail = ref({});
const relationNews = ref([]);
const isOpenTranslation = ref(true);
const isHightLightEntity = ref(true);
const textEntities = ref([]);
const textZns = ref([]);
const textEns = ref([]);
const route = useRoute();
const gotoNewsDetail = useGotoNewsDetail();
const gotoSearchResults = useGotoSearchResults();

const decodeMaybeBase64 = (raw) => {
	if (raw == null) return null;
	let s0 = String(raw).trim();
	if (!s0) return null;
	// 兼容 URL 里被 encodeURIComponent 的 base64（例如 OTg%3D）
	if (s0.includes("%")) {
		try {
			const decodedOnce = decodeURIComponent(s0);
			if (decodedOnce) s0 = String(decodedOnce).trim();
		} catch (_) { }
	}
	// 明显不是 base64 的（例如包含 '-' 的新闻明文 id），直接返回
	if (!/^[A-Za-z0-9+/_-]+={0,2}$/.test(s0)) return s0;

	const encodeBase64Param = (val) => {
		const s = String(val ?? "").trim();
		if (!s) return "";
		try {
			return btoa(encodeURIComponent(s));
		} catch (_) {
			return s;
		}
	};
	const normalizeBase64 = (s) => {
		const normalized = String(s ?? "").replace(/-/g, "+").replace(/_/g, "/");
		return normalized + "===".slice((normalized.length + 3) % 4);
	};

	// base64(encodeURIComponent(id)) 解码：仅在“可逆校验通过”时才当作加密参数
	try {
		const padded = normalizeBase64(s0);
		const decoded = atob(padded);
		const decodedStr = (() => {
			try {
				return decodeURIComponent(decoded);
			} catch (_) {
				return decoded;
			}
		})();
		const reEncoded = encodeBase64Param(decodedStr);
		if (!reEncoded) return s0;
		if (normalizeBase64(reEncoded) === padded) {
			return decodedStr;
		}
	} catch (_) { }
	return s0;
};

onMounted(async () => {
	const params = {
		newsId: decodeMaybeBase64(route.params.id)
	};
	const { data: newsDetailData } = await getNewsDetail(params);
	newsDetail.value = newsDetailData ?? {};
	textZns.value = newsDetail.value?.contentZh?.split("\n") ?? [];
	textEns.value = newsDetail.value?.content?.split("\n") ?? [];
	const { data: relationNewsData } = await getRelationNews(params);
	relationNews.value = relationNewsData ?? [];
	await handleHighlightEntity();
});

async function handleHighlightEntity() {
	if (textEntities.value.length > 0 || (!newsDetail.value?.contentZh && !newsDetail.value?.content)) return;
	const { result: entityDataZh } = await extractTextEntity(newsDetail.value.contentZh ?? "");
	textEntities.value = [...(entityDataZh ?? [])];
	if (newsDetail.value.contentZh !== newsDetail.value.content) {
		const { result: entityData } = await extractTextEntity(newsDetail.value.content ?? "");
		textEntities.value = [...textEntities.value, ...(entityData ?? [])];
	}
	console.log(isHightLightEntity.value);
}
function handleTranslation() {
	isOpenTranslation.value = !isOpenTranslation.value;
}
</script>
<style lang="scss" scoped>
@import url("./style.css");

.top-box-news-deatail {
	background-color: var(--bg-white-100);
	box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
}

.content-box-news-detail {
	align-items: flex-start;
	gap: 16px;
}

.relation-news-box {
	width: 520px;
}

.p-news-content {
	//首行缩进
	text-indent: 2em;
}
</style>
