<template>
  <view>
    <!-- 自定义导航栏 -->
    <nav-bar :title="$t('news.newsDetail')" />

    <view v-if="urlVisible" class="web-view-container"><web-view :webview-styles="{ progress: { color: '#55aaff' } }" :src="surl"></web-view></view>
    <view v-else class="box">
			<view class="title">{{ news.title }}</view>
			<view 
				class="content" 
				v-html="formattedContent"
			></view>
		</view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { newsApi } from '@/api/modules/news'

const newsId = ref<string | number | null>(null)
const type = ref<number | null>(null)
const urlVisible = ref(false)
const surl = ref('')
const source = ref('')

onLoad((e: any) => {
	newsId.value = e.newsId
	type.value = Number(e.type)
	surl.value = e.url || ''
	source.value = e.source || ''
  if(type.value == 1 && surl.value != ''){
		urlVisible.value = true
		// APP 设置导航栏按钮
		// #ifdef APP-PLUS
		const pages = getCurrentPages()
		const page = pages[pages.length - 1]
		const currentWebview = page.$getAppWebview()

		currentWebview.setStyle({
			titleNView: {
				buttons: [{
					float: 'right',
					type: 'close',
					onclick: () => {
						uni.navigateBack({ delta: 1 })
					}
				}]
			}
		})
		// #endif
  } else {
		getData()
  }
})

// 新闻详情
const news = ref({
  title: '',
  content: ''
})
// 获取新闻详情
const getData = async () => {
  let res = null
	if (source.value === 'taihuzhiguang') {
		res = await newsApi.getTaihuWelfareArticleDetail(newsId.value)
	} else {
    res = await newsApi.getNewsDetail(newsId.value)
	}
  news.value.title = res.result?.title || ''
  news.value.content = res.result?.content || ''
}

// 格式化富文本内容
const formatRichText = (html: string) => {
	if (!html) return ""

	let newContent = html.replace(/<img[^>]*>/gi, (match) => {
		match = match.replace(/style="[^"]+"/gi, '')
		match = match.replace(/width="[^"]+"/gi, '')
		match = match.replace(/height="[^"]+"/gi, '')
		return match
	})

	newContent = newContent.replace(/style="[^"]+"/gi, (match) => {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;')
		return match
	})

	newContent = newContent.replace(/<br[^>]*\/>/gi, '')
	newContent = newContent.replace(
		/\<img/gi,
		'<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"'
	)

	return newContent
}
// 格式化后内容
const formattedContent = computed(() => formatRichText(news.value.content))
</script>

<style lang="scss" scoped>
.web-view-container {
  padding-top: 60px;
}
.box {
	background-color: #fff;		
	padding: 10px;
	min-height: calc(100vh - 270rpx);
}

.title {
	font-size: 32rpx;
	font-weight: bold; 
	text-align: center;
}

.content { 
	font-size: 26rpx; 
	line-height: 48rpx; 
	margin-top: 10rpx;
}
</style>