<template>
  <!-- 协议预览弹窗 — 通过 Teleport 挂载到 body -->
  <Teleport to="body">
    <!-- 遮罩层 -->
    <div v-if="modelValue" class="agreement-preview-overlay" @click="$emit('update:modelValue', false)">
      <!-- 弹窗主体 -->
      <div class="agreement-preview-dialog" @click.stop>
        <!-- 顶部标题栏 -->
        <div class="agreement-preview-dialog__header">
          <h2 class="agreement-preview-dialog__title">{{ agreementName || '协议内容' }}</h2>
          <span class="agreement-preview-dialog__close" @click="$emit('update:modelValue', false)">✕</span>
        </div>
        <!-- 内容区域 — 可滚动 -->
        <div class="agreement-preview-dialog__body">
          <!-- 加载中 -->
          <div v-if="loading" class="agreement-preview-dialog__loading">加载中...</div>
          <!-- 渲染协议 Markdown 内容 -->
          <div v-else class="agreement-preview-dialog__content" v-html="contentHtml"></div>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { fetchAgreement } from '@/api/common'
// @ts-ignore
import markdownit from 'markdown-it'

/** markdown-it 实例 */
const md = markdownit({ html: false, breaks: true, linkify: true })

/** 组件属性 */
const props = defineProps<{
  /** 控制弹窗显示/隐藏 */
  modelValue: boolean
  /** 协议码 */
  code: string
}>()

/** 组件事件 */
defineEmits<{ (e: 'update:modelValue', value: boolean): void }>()

/** 协议名称 */
const agreementName = ref('')
/** 渲染后的 HTML 内容 */
const contentHtml = ref('')
/** 加载状态 */
const loading = ref(false)
/** 已加载过的协议缓存（key: code, value: { name, html }） */
const cache = new Map<string, { name: string; html: string }>()

/** 加载协议内容 */
async function loadAgreement() {
  const code = props.code
  if (!code) return

  // 有缓存直接使用
  const cached = cache.get(code)
  if (cached) {
    agreementName.value = cached.name
    contentHtml.value = cached.html
    return
  }

  loading.value = true
  contentHtml.value = ''
  try {
    const res = await fetchAgreement(code)
    if (res.data?.content) {
      const name = res.data.agreementName || '协议内容'
      const html = md.render(res.data.content)
      agreementName.value = name
      contentHtml.value = html
      cache.set(code, { name, html })
    } else {
      contentHtml.value = '<p>暂无协议内容</p>'
    }
  } catch {
    contentHtml.value = '<p>加载失败，请稍后重试</p>'
  } finally {
    loading.value = false
  }
}

/** 监听弹窗打开 — 触发加载（使用 nextTick 确保 code 已更新） */
watch(() => props.modelValue, (val) => {
  if (val) {
    nextTick(() => loadAgreement())
    document.body.style.overflow = 'hidden'
  } else {
    document.body.style.overflow = ''
  }
})
</script>
