<template>
  <view class="sub-page">
    <TopBar title="知识详情" show-back />

    <view v-if="knowledge" class="content-wrap">
      <!-- 封面大图 -->
      <view class="hero-card">
        <image v-if="knowledge.cover" :src="knowledge.cover" mode="aspectFill" class="hero-image" />
        <view v-else class="hero-fallback">
          <text class="hero-icon">{{ categoryIcon(knowledge.category) }}</text>
        </view>
        <view class="hero-overlay" />
        <view class="hero-info">
          <view class="category-chip">
            <text class="category-text">{{ categoryName(knowledge.category) }}</text>
          </view>
          <text class="hero-title">{{ knowledge.title }}</text>
        </view>
      </view>

      <!-- 元信息 -->
      <view class="meta-bar">
        <view class="meta-item">
          <text class="uni-icons uniui-calendar-filled meta-icon" />
          <text class="meta-text">{{ formatDate(knowledge.createTime) }}</text>
        </view>
        <view class="meta-divider" />
        <view class="meta-item">
          <text class="uni-icons uniui-eye-filled meta-icon" />
          <text class="meta-text">{{ knowledge.readCount || 0 }} 阅读</text>
        </view>
      </view>

      <!-- 正文 -->
      <view class="article-card">
        <view v-for="(block, index) in contentBlocks" :key="index" class="block">
          <view v-if="block.type === 'text'" class="text-block">
            <rich-text :nodes="block.content" />
          </view>
          <view v-else-if="block.type === 'image'" class="image-block">
            <image :src="block.src" mode="widthFix" class="article-image" @click="previewImage(block.src)" />
          </view>
        </view>
      </view>
    </view>

    <view v-else class="empty-state">
      <EmptyState message="知识内容不存在" />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import TopBar from '../../components/common/TopBar.vue'
import EmptyState from '../../components/common/EmptyState.vue'
import { getKnowledgeDetail, categoryName, type KnowledgeItem } from '../../api/knowledge'
import { formatDate } from '../../utils'

interface ContentBlock {
  type: 'text' | 'image'
  content?: string
  src?: string
}

const knowledge = ref<KnowledgeItem | null>(null)

const contentBlocks = computed<ContentBlock[]>(() => {
  if (!knowledge.value?.content) return []
  return splitContent(knowledge.value.content)
})

function categoryIcon(category?: string): string {
  const iconMap: Record<string, string> = {
    industry: '',
    safety: '️',
    equipment: '',
  }
  return iconMap[category || ''] || ''
}

function splitContent(html: string): ContentBlock[] {
  const decoded = html.replace(/\u0026amp;/g, '\u0026')
  const blocks: ContentBlock[] = []
  const imgRegex = /<img[^\u003e]+src=["']([^"']+)["'][^\u003e]*>/gi
  let lastIndex = 0
  let match: RegExpExecArray | null

  while ((match = imgRegex.exec(decoded)) !== null) {
    const textBefore = decoded.slice(lastIndex, match.index)
    if (textBefore.trim().length > 0) {
      blocks.push({ type: 'text', content: normalizeHtml(textBefore) })
    }
    blocks.push({ type: 'image', src: match[1] })
    lastIndex = imgRegex.lastIndex
  }

  const textAfter = decoded.slice(lastIndex)
  if (textAfter.trim().length > 0) {
    blocks.push({ type: 'text', content: normalizeHtml(textAfter) })
  }

  return blocks.length > 0 ? blocks : [{ type: 'text', content: normalizeHtml(decoded) }]
}

function normalizeHtml(html: string): string {
  return html
    .replace(/\s+/g, ' ')
    .replace(/<br\s*\/?>/gi, '<br/>')
    .replace(/<p>\s*<\/p>/gi, '<p><br/></p>')
    .trim()
}

function previewImage(src?: string) {
  if (!src) return
  const images: string[] = []
  contentBlocks.value.forEach((b) => {
    if (b.type === 'image' && b.src) {
      images.push(b.src)
    }
  })
  uni.previewImage({
    current: src,
    urls: images.length > 0 ? images : [src],
  })
}

onLoad(async (options) => {
  if (!options?.id) return
  try {
    knowledge.value = await getKnowledgeDetail(Number(options.id))
  } catch (error) {
    console.error('获取知识详情失败:', error)
  }
})
</script>

<style scoped>
.sub-page {
  min-height: 100vh;
  background: #f4f9f7;
}

.content-wrap {
  padding: 16px;
  padding-bottom: 40px;
}

.hero-card {
  position: relative;
  border-radius: 24px;
  overflow: hidden;
  height: 260px;
  box-shadow: 0 20px 50px -16px rgba(54, 143, 111, 0.28);
}

.hero-image,
.hero-fallback {
  width: 100%;
  height: 100%;
}

.hero-fallback {
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #368f6f 0%, #5ab8d0 100%);
}

.hero-icon {
  font-size: 72px;
  opacity: 0.95;
}

.hero-overlay {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 140px;
  background: linear-gradient(180deg, transparent 0%, rgba(0, 0, 0, 0.55) 100%);
}

.hero-info {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20px;
}

.category-chip {
  display: inline-flex;
  align-items: center;
  padding: 5px 12px;
  border-radius: 999px;
  background: rgba(255, 255, 255, 0.95);
  margin-bottom: 10px;
}

.category-text {
  font-size: 12px;
  font-weight: 700;
  color: #368f6f;
}

.hero-title {
  display: block;
  font-size: 22px;
  font-weight: 700;
  color: #ffffff;
  line-height: 1.4;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
}

.meta-bar {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin-top: 16px;
  padding: 12px;
  border-radius: 16px;
  background: #ffffff;
  box-shadow: 0 8px 24px -10px rgba(54, 143, 111, 0.18);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.meta-icon {
  font-size: 13px;
  color: #9ca3af;
}

.meta-text {
  font-size: 13px;
  color: #6b7280;
}

.meta-divider {
  width: 1px;
  height: 12px;
  background: #d1d5db;
}

.article-card {
  margin-top: 16px;
  padding: 22px 18px;
  border-radius: 24px;
  background: #ffffff;
  box-shadow: 0 14px 40px -12px rgba(54, 143, 111, 0.14);
}

.block {
  margin-bottom: 16px;
}

.block:last-child {
  margin-bottom: 0;
}

.text-block {
  font-size: 15px;
  line-height: 1.85;
  color: #374151;
}

.image-block {
  display: flex;
  justify-content: center;
}

.article-image {
  width: 100%;
  max-width: 100%;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.empty-state {
  padding-top: 100px;
}
</style>
