<script setup lang="ts">
/**
 * 思考详情：正文 + 分类/专栏/标签导航 + 专栏其它文章 + 相关推荐。
 */
import { computed, ref } from 'vue'
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import AppPageShell from '@/components/layout/AppPageShell.vue'
import PostCard from '@/components/c-end/PostCard.vue'
import {
  getColumn,
  getColumnPosts,
  getPost,
  getRecommendedPosts,
  type Column,
  type Post,
} from '@/api'
import { resolveMediaUrl } from '@/utils/request'
import { renderMarkdown, preloadMarkdownRenderer } from '../../lib/markdownRenderer'

const postId = ref('')
const post = ref<Post | null>(null)
const html = ref('')
const loading = ref(false)
const recommended = ref<Post[]>([])
const columnInfo = ref<Column | null>(null)
const columnPosts = ref<Post[]>([])

const DEFAULT_AVATAR = '/static/default-avatar.svg'

const avatarSrc = computed(() => {
  const raw = post.value?.userAvatar
  if (!raw) return DEFAULT_AVATAR
  return resolveMediaUrl(String(raw)) || DEFAULT_AVATAR
})

const tagList = computed(() => {
  const tags = post.value?.tags
  if (!Array.isArray(tags)) return [] as { id?: number, name: string }[]
  return tags.map((t) => {
    if (typeof t === 'string') return { name: t }
    return { id: t?.id, name: String(t?.name || '') }
  }).filter(t => t.name)
})

const columnName = computed(() => {
  if (columnInfo.value?.name || columnInfo.value?.title) {
    return String(columnInfo.value.name || columnInfo.value.title)
  }
  return String(post.value?.columnName || '')
})

const otherColumnPosts = computed(() =>
  columnPosts.value
    .filter(p => String(p.id) !== String(postId.value))
    .slice(0, 8),
)

/** 按 id 拉文章、推荐、专栏列表并渲染 Markdown */
async function loadDetail() {
  if (!postId.value) return
  loading.value = true
  preloadMarkdownRenderer()
  try {
    const postData = await getPost(postId.value)
    post.value = postData
    html.value = await renderMarkdown(String(postData?.content || ''))

    const tasks: Promise<void>[] = [
      getRecommendedPosts(postId.value, 3)
        .then((list) => { recommended.value = Array.isArray(list) ? list : [] })
        .catch(() => { recommended.value = [] }),
    ]

    const colId = postData?.columnId as number | undefined
    if (colId) {
      tasks.push(
        Promise.all([
          getColumn(colId).catch(() => null),
          getColumnPosts(colId).catch(() => []),
        ]).then(([col, posts]) => {
          columnInfo.value = col
          columnPosts.value = Array.isArray(posts) ? posts : []
        }),
      )
    }
    else {
      columnInfo.value = null
      columnPosts.value = []
    }

    await Promise.all(tasks)
  }
  catch (e: unknown) {
    uni.showToast({ title: e instanceof Error ? e.message : '加载失败', icon: 'none' })
  }
  finally {
    loading.value = false
  }
}

onLoad((q) => {
  postId.value = String(q?.id || '')
  loadDetail()
})

onPullDownRefresh(async () => {
  try {
    await loadDetail()
  }
  finally {
    uni.stopPullDownRefresh()
  }
})

function goCategory() {
  const id = post.value?.categoryId
  const name = post.value?.categoryName
  if (id) {
    uni.navigateTo({
      url: `/subPackages/content/pages/blog/index?categoryId=${id}&categoryName=${encodeURIComponent(String(name || ''))}`,
    })
    return
  }
  uni.navigateTo({ url: '/subPackages/content/pages/blog/index' })
}

function goColumn() {
  const id = post.value?.columnId
  if (!id) return
  uni.navigateTo({ url: `/subPackages/content/pages/columns/detail?id=${id}` })
}

function goTag(tag: { id?: number, name: string }) {
  const q = tag.id
    ? `tagId=${tag.id}&tagName=${encodeURIComponent(tag.name)}`
    : `tagName=${encodeURIComponent(tag.name)}`
  uni.navigateTo({ url: `/subPackages/content/pages/blog/index?${q}` })
}

function goPost(id: string | number) {
  uni.redirectTo({ url: `/subPackages/content/pages/blog/detail?id=${id}` })
}
</script>

<template>
  <AppPageShell>
    <AppNavbar :title="post?.title || '思考详情'" show-back />
    <view class="page-pad">
      <wd-loading v-if="loading" />
      <template v-else-if="post">
        <view class="meta-row">
          <text
            v-if="post.categoryName"
            class="chip text-art-accent"
            @click="goCategory"
          >
            {{ post.categoryName }}
          </text>
          <text
            v-if="columnName"
            class="chip text-art-accent"
            @click="goColumn"
          >
            {{ columnName }}
          </text>
          <text v-if="post.date" class="font-mono-label text-art-muted">{{ post.date }}</text>
        </view>

        <text class="title">{{ post.title }}</text>

        <view v-if="post.userName" class="author">
          <image class="avatar" :src="avatarSrc" mode="aspectFill" />
          <text class="name">{{ post.userName }}</text>
        </view>

        <view v-if="tagList.length" class="tags">
          <view
            v-for="(t, i) in tagList"
            :key="`${t.id || t.name}-${i}`"
            class="tag"
            @click="goTag(t)"
          >
            #{{ t.name }}
          </view>
        </view>

        <view class="article-md body">
          <mp-html :content="html" container-style="overflow-x:auto;" />
        </view>

        <view v-if="otherColumnPosts.length" class="section">
          <view class="section-head">
            <text class="section-title">专栏其它文章</text>
            <text v-if="post.columnId" class="more text-art-accent" @click="goColumn">全部 ›</text>
          </view>
          <view
            v-for="item in otherColumnPosts"
            :key="String(item.id)"
            class="col-row"
            @click="goPost(item.id)"
          >
            <text class="col-title">{{ item.title }}</text>
            <text class="col-date text-art-muted">{{ item.date || '' }}</text>
          </view>
        </view>

        <view v-if="recommended.length" class="section">
          <text class="section-title">相关推荐</text>
          <PostCard
            v-for="item in recommended"
            :key="String(item.id)"
            :post="item"
            @click="goPost(item.id)"
          />
        </view>
      </template>
      <wd-empty v-else-if="!loading" description="文章不存在" />
    </view>
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 64rpx; display: flex; flex-direction: column; gap: 20rpx; }
.meta-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16rpx;
}
.chip {
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
  background: rgba(212, 179, 131, 0.12);
}
.title {
  font-size: 44rpx;
  line-height: 1.35;
  color: rgb(var(--art-text));
  font-family: 'Playfair Display', serif;
}
.author { display: flex; align-items: center; gap: 12rpx; margin-bottom: 8rpx; }
.avatar {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background: rgba(127, 127, 127, 0.15);
}
.name { font-size: 26rpx; color: rgb(var(--art-text)); }
.tags { display: flex; flex-wrap: wrap; gap: 12rpx; }
.tag {
  font-size: 22rpx;
  padding: 6rpx 14rpx;
  border-radius: 8rpx;
  color: rgb(var(--art-muted));
  background: rgba(127, 127, 127, 0.1);
}
.body { margin-top: 12rpx; }
.section {
  margin-top: 40rpx;
  padding-top: 28rpx;
  border-top: 1px solid var(--art-border);
}
.section-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}
.section-title {
  font-family: 'Playfair Display', 'Noto Serif SC', serif;
  font-style: italic;
  font-size: 36rpx;
  color: rgb(var(--art-text));
  margin-bottom: 20rpx;
}
.section-head .section-title { margin-bottom: 0; }
.more { font-size: 24rpx; }
.col-row {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 20rpx 0;
  border-bottom: 1px solid var(--art-border);
}
.col-title {
  flex: 1;
  min-width: 0;
  font-size: 28rpx;
  color: rgb(var(--art-text));
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.col-date { font-size: 22rpx; flex-shrink: 0; }
:deep(.ios-code-container) {
  background: #1e1e1e;
  border-radius: 16rpx;
  overflow: hidden;
  margin: 24rpx 0;
  border: 1px solid rgba(255, 255, 255, 0.06);
}
:deep(.mac-window-header) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 24rpx;
  background: #282828;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
:deep(.mac-dots) { display: flex; gap: 10rpx; }
:deep(.dot) {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  display: inline-block;
}
:deep(.dot.red) { background: #ff5f56; }
:deep(.dot.yellow) { background: #ffbd2e; }
:deep(.dot.green) { background: #27c93f; }
:deep(.mac-lang) {
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.3);
  font-family: 'JetBrains Mono', monospace;
}
:deep(.code-pre) {
  margin: 0;
  padding: 24rpx;
  overflow-x: auto;
  background: #1e1e1e !important;
}
:deep(.hljs) {
  background: transparent !important;
  color: #abb2bf;
  font-family: 'JetBrains Mono', monospace;
  font-size: 24rpx;
  line-height: 1.65;
  white-space: pre;
}
:deep(.hljs-comment),
:deep(.hljs-quote) { color: #5c6370; font-style: italic; }
:deep(.hljs-keyword),
:deep(.hljs-selector-tag),
:deep(.hljs-subst) { color: #c678dd; }
:deep(.hljs-number),
:deep(.hljs-literal),
:deep(.hljs-variable),
:deep(.hljs-template-variable),
:deep(.hljs-tag .hljs-attr) { color: #d19a66; }
:deep(.hljs-string),
:deep(.hljs-doctag) { color: #98c379; }
:deep(.hljs-title),
:deep(.hljs-section),
:deep(.hljs-selector-id) { color: #e06c75; }
:deep(.hljs-type),
:deep(.hljs-class .hljs-title) { color: #e5c07b; }
:deep(.hljs-tag),
:deep(.hljs-name),
:deep(.hljs-attribute) { color: #e06c75; }
:deep(.hljs-regexp),
:deep(.hljs-link) { color: #56b6c2; }
:deep(.hljs-symbol),
:deep(.hljs-bullet) { color: #61afef; }
:deep(.hljs-built_in),
:deep(.hljs-builtin-name) { color: #e6c07b; }
:deep(.hljs-meta) { color: #61afef; }
</style>
