<template>
	<view class="agreement-detail-page">
		<nav-bar :title="title"></nav-bar>
		<view class="content-card" v-if="!loading">
			<text class="title">{{ agreementData.title || title }}</text>
			<rich-text :nodes="contentHtml" class="rich-content"></rich-text>
		</view>
		<view v-else class="loading-state">
			<text>协议内容加载中...</text>
		</view>
	</view>
</template>

<script setup>
// @Author: Antigravity
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getAgreement } from '@/api/system/agreement'
import navBar from '@/components/nav-bar/index.vue'

const title = ref('协议详情')
const agreementData = ref({})
const contentHtml = ref('')
const loading = ref(true)

onLoad(async (options) => {
	if (options.title) title.value = decodeURIComponent(options.title)
	if (options.id) {
		fetchAgreement(options.id)
	}
})

const fetchAgreement = async (id) => {
	loading.value = true
	try {
		const res = await getAgreement(id)
		if (res) {
			agreementData.value = res
			// 解码 Base64 内容 (Admin端采用 btoa(unescape(encodeURIComponent(content))) 编码)
			if (res.content) {
				const cleanStr = String(res.content).trim().replace(/\s+/g, '')
				// 检查是否是 base64 格式（仅包含 A-Z, a-z, 0-9, +, /, =）
				const isBase64 = /^[A-Za-z0-9+/=]+$/.test(cleanStr)
				
				if (isBase64) {
					try {
						// 1. Base64 解码为二进制字符串
						const atobPolyfill = (str) => {
							if (typeof atob === 'function') return atob(str)
							const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
							let output = ''
							const clean = str.replace(/=+$/, '')
							for (let bc = 0, bs, buffer, idx = 0; idx < clean.length; ) {
								const char = clean.charAt(idx++)
								const buffer = chars.indexOf(char)
								if (buffer === -1) throw new Error('Invalid base64 character')
								bs = bc % 4 ? bs * 64 + buffer : buffer
								if (bc++ % 4) {
									output += String.fromCharCode(255 & bs >> (-2 * bc & 6))
								}
							}
							return output
						}
						
						const decodedBinary = atobPolyfill(cleanStr)
						
						// 2. 将二进制字符串解码为 UTF-8 字符串
						const decodeUtf8 = (str) => {
							let result = ''
							let i = 0
							while (i < str.length) {
								const c1 = str.charCodeAt(i++)
								if (c1 < 128) {
									result += String.fromCharCode(c1)
								} else if (c1 > 191 && c1 < 224) {
									const c2 = str.charCodeAt(i++)
									result += String.fromCharCode(((c1 & 31) << 6) | (c2 & 63))
								} else if (c1 > 223 && c1 < 240) {
									const c2 = str.charCodeAt(i++)
									const c3 = str.charCodeAt(i++)
									result += String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))
								} else {
									const c2 = str.charCodeAt(i++)
									const c3 = str.charCodeAt(i++)
									const c4 = str.charCodeAt(i++)
									const codepoint = ((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)
									if (codepoint > 0xffff) {
										const offset = codepoint - 0x10000
										result += String.fromCharCode((offset >> 10) + 0xd800, (offset & 0x3ff) + 0xdc00)
									} else {
										result += String.fromCharCode(codepoint)
									}
								}
							}
							return result
						}
						
						contentHtml.value = decodeUtf8(decodedBinary)
					} catch (e) {
						// 解码失败，回显原始内容
						contentHtml.value = res.content
					}
				} else {
					// 非 base64 格式，直接回显原始 HTML 页面
					contentHtml.value = res.content
				}
			} else {
				contentHtml.value = '暂无协议内容'
			}
		}
	} catch (error) {
		console.error('获取协议详情失败', error)
		uni.showToast({ title: typeof error === 'string' ? error : '获取协议详情失败', icon: 'none' })
	} finally {
		loading.value = false
	}
}
</script>

<style lang="scss" scoped>
.agreement-detail-page { min-height: 100vh; background: #f7f8fa; padding-bottom: calc(40rpx + env(safe-area-inset-bottom)); }
.content-card { background: #fff; margin: 24rpx; border-radius: 24rpx; padding: 40rpx 32rpx; box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.03); }
.title { display: block; font-size: 36rpx; font-weight: 800; color: #333; margin-bottom: 32rpx; position: relative; padding-bottom: 24rpx; border-bottom: 2rpx solid #EEEEEE; }
.rich-content { display: block; font-size: 28rpx; color: #555; line-height: 1.8; word-break: break-all; }
.loading-state { text-align: center; padding: 100rpx 0; color: #999; font-size: 28rpx; }
</style>
