<template>
  <div class="min-h-screen pb-10 text-slate-800 flex justify-center px-20">
    <div class="w-full space-y-4">
      <!-- 1. 问题卡片 -->
      <div
        class="bg-white rounded-lg p-6 shadow-[0_1px_3px_rgba(0,0,0,0.02)] border border-slate-100 relative"
      >
        <BackButton />
        <el-skeleton
          :rows="5"
          animated
          :loading="loading"
          :throttle="{ leading: 0, trailing: 300 }"
        >
          <template #template>
            <!-- 顶部标签行 -->
            <div class="flex flex-wrap gap-2 mb-4 justify-between">
              <!-- 标签 -->
              <div class="flex gap-2">
                <el-skeleton-item
                  v-for="i in 3"
                  :key="i"
                  variant="text"
                  style="width: 60px; height: 18px; border-radius: 9999px"
                />
              </div>

              <!-- 编辑按钮 -->
              <el-skeleton-item variant="text" style="width: 40px; height: 18px" />
            </div>

            <!-- 发布人信息 -->
            <div class="flex items-center gap-3 pb-3 border-b border-slate-100">
              <!-- 头像 -->
              <el-skeleton-item variant="circle" style="width: 40px; height: 40px" />

              <!-- 用户名 + 时间 -->
              <div class="flex flex-col gap-2">
                <el-skeleton-item variant="text" style="width: 100px; height: 14px" />
                <el-skeleton-item variant="text" style="width: 180px; height: 12px" />
              </div>
            </div>

            <!-- 标题 -->
            <div class="mt-3 mb-3">
              <el-skeleton-item variant="text" style="width: 90%; height: 28px" />
            </div>

            <!-- 内容描述 -->
            <div class="space-y-2">
              <el-skeleton-item variant="text" style="width: 100%" />
              <el-skeleton-item variant="text" style="width: 95%" />
              <el-skeleton-item variant="text" style="width: 85%" />
            </div>

            <!-- 图片列表 -->
            <!-- <div class="mt-3 flex gap-2 flex-wrap">
              <el-skeleton-item
                v-for="i in 3"
                :key="i"
                variant="image"
                style="width: 96px; height: 96px; border-radius: 8px"
              />
            </div> -->

            <!-- 底部操作栏 -->
            <div class="flex items-center justify-between mt-4">
              <!-- 写回答按钮 -->
              <el-skeleton-item variant="button" style="width: 88px; height: 32px" />

              <!-- 右侧点赞 / 收藏 -->
              <div class="flex items-center gap-6">
                <el-skeleton-item variant="text" style="width: 48px; height: 16px" />
                <el-skeleton-item variant="text" style="width: 48px; height: 16px" />
              </div>
            </div>
          </template>
          <template #default>
            <!-- 顶部标签行 -->
            <div class="flex flex-wrap gap-2 mb-4 justify-between">
              <div>
                <span
                  v-for="tag in questionDetail.tagNameList"
                  :key="tag"
                  class="px-2.5 py-0.5 rounded-full bg-blue-50 text-blue-500 text-xs font-semibold hover:bg-blue-100 transition-colors cursor-pointer mr-2"
                >
                  #{{ tag }}
                </span>
              </div>

              <!-- 后面加一个编辑 -->
              <el-link
                v-if="isAuthor"
                type="primary"
                :underline="false"
                @click="
                  router.push(`/publishLongArticle/${questionDetail.type}?id=${questionDetail.id}`)
                "
                class="text-sm"
              >
                编辑
              </el-link>
            </div>
            <!-- 👇 新增：发布人信息 -->
            <div class="flex items-center gap-3 pb-3 border-b border-slate-100">
              <el-avatar
                :src="questionDetail.createUserAvatar"
                :size="40"
                class="flex-shrink-0 cursor-pointer"
                @click="
                  jumpToUserHomePage({
                    userId: questionDetail.createUserId,
                    type: ArticleTypeEnum.QUESTION,
                  })
                "
              >
                {{ questionDetail.createUserName }}
              </el-avatar>
              <div class="flex flex-col">
                <span class="text-sm text-slate-900">
                  {{ questionDetail.createUserName }}
                </span>
                <span class="text-sm text-slate-500 flex items-center gap-1">
                  {{ dayjs(questionDetail.createTime * 1000).format('YYYY-MM-DD HH:mm') }} ·
                  <span
                    v-if="questionDetail?.region"
                    class="text-sm text-slate-500 flex items-center gap-1"
                  >
                    {{ questionDetail.region }}
                    ·
                  </span>
                  {{ questionDetail.viewCount }}阅读
                </span>
              </div>
            </div>
            <!-- 标题：主要信息，黑重粗 -->
            <h1 class="text-2xl font-bold text-slate-900 mb-3 leading-snug tracking-tight">
              {{ questionDetail.title }}
            </h1>

            <!-- 描述：次要信息，深灰 -->
            <div class="text-gray-600 text-base leading-relaxed transition-all duration-300">
              <div :class="{ 'line-clamp-3': !isExpand }" ref="questionContentRef">
                {{ questionDetail.content }}
              </div>
              <button
                v-if="isOverThreeLine"
                class="text-blue-500 text-sm font-medium hover:text-blue-600 mt-1 flex items-center gap-0.5 cursor-pointer"
                @click="isExpand = !isExpand"
              >
                {{ isExpand ? '收起' : '显示全部' }}
                <el-icon :class="{ 'rotate-180': isExpand }" class="transition-transform"
                  ><IEpCaretBottom
                /></el-icon>
              </button>
            </div>
            <div
              v-if="questionDetail.imgUrl"
              class="mt-3 flex gap-2 flex-wrap items-center justify-start"
            >
              <el-image
                v-for="(item, i) in questionDetail.imgUrl.split(',')"
                :key="item"
                :src="item"
                fit="cover"
                class="rounded-lg w-24 h-24 hover:scale-105 transition-transform cursor-pointer"
                :preview-src-list="questionDetail.imgUrl.split(',')"
                :initial-index="i"
                :preview-teleported="true"
              />
            </div>
            <!-- 底部操作栏 -->
            <div class="flex items-center justify-between mt-4">
              <div class="flex gap-3">
                <button
                  class="px-5 py-1.5 border !bg-blue-500 !text-white rounded-[4px] text-sm font-medium transition-colors flex items-center gap-1 cursor-pointer"
                  @click="openCommentDialog"
                >
                  <el-icon><IEpEditPen /></el-icon>
                  写回答
                </button>
              </div>

              <!-- 右侧数据 -->
              <div class="flex items-center gap-6 text-slate-500 text-sm select-none">
                <span
                  @click="handleLikeArticle"
                  class="hover:text-slate-600 cursor-pointer transition-colors flex items-center gap-1"
                >
                  <el-icon>
                    <svg-icon
                      :name="questionDetail?.hasPraised ? 'praise_fill' : 'praise'"
                    ></svg-icon>
                  </el-icon>
                  <span :class="{ 'text-blue-500': questionDetail?.hasPraised }">{{
                    questionDetail?.praiseCount || 0
                  }}</span>
                </span>
                <span
                  @click="handleCollectArticle"
                  class="hover:text-slate-600 cursor-pointer transition-colors flex items-center gap-1"
                >
                  <el-icon>
                    <svg-icon
                      :name="questionDetail?.hasCollect ? 'collection_fill' : 'collection'"
                    ></svg-icon>
                  </el-icon>
                  <span :class="{ 'text-blue-500': questionDetail?.hasCollect }">{{
                    questionDetail?.collectionCount || 0
                  }}</span>
                </span>
              </div>
            </div>
          </template>
        </el-skeleton>
      </div>

      <!-- 2. 列表控制栏 -->
      <div
        class="bg-white rounded-lg border-b border-slate-100 p-6 flex justify-between items-center shadow-sm"
      >
        <h3 class="font-bold text-slate-800 text-base">{{ total }} 个回答</h3>
        <div class="flex text-sm text-slate-500 bg-slate-50 rounded p-0.5">
          <el-radio-group
            size="small"
            v-model="searchParams.sortType"
            @change="(val) => changeSortType(val as number)"
            fill="#3b82f6"
          >
            <el-radio-button label="最新" :value="2" />
            <el-radio-button label="最多点赞" :value="4" />
            <el-radio-button label="最多评论" :value="1" />
          </el-radio-group>
          <!-- <span
            @click="changeSortType(2)"
            class="px-3 py-0.5 rounded shadow-sm font-medium cursor-pointer"
            :class="{ 'text-slate-800 bg-white': searchParams.sortType === 2 }"
            >最新</span
          >
          <span
            @click="changeSortType(1)"
            class="px-3 py-0.5 rounded hover:text-slate-700 cursor-pointer transition-colors"
            :class="{ 'text-slate-800 bg-white': searchParams.sortType === 1 }"
            >最多评论</span
          >
          <span
            @click="changeSortType(4)"
            class="px-3 py-0.5 rounded hover:text-slate-700 cursor-pointer transition-colors"
            :class="{ 'text-slate-800 bg-white': searchParams.sortType === 4 }"
            >最多点赞</span
          > -->
        </div>
      </div>

      <!-- 3. 回答列表 -->
      <div class="space-y-3">
        <div
          v-for="(answer, index) in list"
          :ref="(el) => (answerRefList[index] = el as HTMLElement)"
          :key="answer.id"
          class="bg-white rounded-lg p-6 shadow-sm border border-slate-100 hover:border-slate-200 transition-colors"
          :class="{ 'top-answer-highlight': highlightCommentId === answer.id }"
        >
          <!-- 用户头 -->
          <div class="flex items-center justify-between gap-3 mb-3">
            <div class="flex items-center gap-3 min-w-0">
              <el-avatar
                :src="answer.avatar"
                :size="36"
                class="flex-shrink-0 cursor-pointer"
                @click="
                  jumpToUserHomePage({ userId: answer.userId, type: ArticleTypeEnum.QUESTION })
                "
              />
              <div class="min-w-0">
                <div class="text-slate-900 text-sm flex items-center gap-2">
                  {{ answer.replyUser }}
                  <span
                    v-if="answer.isTop === 1"
                    class="inline-flex items-center gap-1 px-2 py-0.5 text-13px leading-4 font-medium text-amber-700 bg-amber-50/80 border border-amber-200/70 rounded-full"
                  >
                    <span
                      class="top-badge-dot w-1.5 h-1.5 rounded-full bg-amber-500 shadow-[0_0_0_2px_rgba(245,158,11,0.18)]"
                    ></span>
                    置顶回答
                  </span>
                </div>
              </div>
            </div>
            <button
              v-if="isAuthor"
              type="button"
              class="group cursor-pointer inline-flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-full border transition-all duration-200 active:scale-98 disabled:opacity-55 disabled:cursor-not-allowed"
              :class="
                answer.isTop === 1
                  ? 'text-amber-700 border-amber-300/80 bg-amber-50 hover:bg-amber-100/80'
                  : 'text-slate-600 border-slate-200 bg-white hover:text-indigo-600 hover:border-indigo-200 hover:bg-indigo-50/70'
              "
              :disabled="topCommentPendingId !== null"
              @click="handleTopAnswer(answer)"
            >
              {{ answer.isTop === 1 ? '取消置顶' : '置顶回答' }}
            </button>
          </div>

          <!-- 赞同票数 (微小的灰色文字，增加信息密度) -->
          <div v-if="answer.postPriseCount" class="text-[14px] text-slate-500 mb-2">
            {{ answer.postPriseCount || 0 }} 人赞同了该回答
          </div>

          <!-- 正文 换行 -->
          <div
            class="text-slate-800 leading-7 mb-4 rich-text-content break-all"
            v-html="parseEmoji(answer.content)"
          ></div>
          <!-- 评论图片列表 -->
          <div class="flex flex-wrap gap-3 mb-3">
            <div
              v-for="(img, imgIndex) in answer.imgUrl.split(',').filter(Boolean)"
              :key="imgIndex"
              class="w-24 h-24 rounded-lg overflow-hidden mb-2"
            >
              <el-image
                :src="img"
                :preview-teleported="true"
                class="w-full h-full object-cover"
                :preview-src-list="answer.imgUrl.split(',').filter(Boolean)"
                :initial-index="imgIndex"
                fit="cover"
              />
            </div>
          </div>

          <div class="text-[14px] text-slate-500 mb-3 flex items-center gap-3">
            发布于 {{ dayjs(answer.createTime * 1000).format('YYYY-MM-DD HH:mm') }}
            <span v-if="answer.region">·{{ answer.region }}</span>
          </div>

          <!-- 底 部吸附操作栏 -->
          <div class="flex items-center gap-4 select-none">
            <!-- 核心交互：赞同/反对胶囊 -->
            <div class="flex items-center bg-blue-50/60 rounded-[4px] overflow-hidden">
              <button
                class="flex items-center gap-1 px-3 py-1.5 text-blue-500 hover:bg-blue-100 transition-colors text-sm font-medium cursor-pointer"
                :class="{ '!bg-blue-500 !text-white': answer.hasPraise }"
                @click="handleLikeAnswer(answer)"
              >
                <el-icon><IEpCaretTop /></el-icon>
                <span
                  >{{ answer.hasPraise ? '已赞同' : '赞同' }}
                  {{ answer.postPriseCount || '' }}</span
                >
              </button>
              <!-- <button
                class="px-2 py-1.5 text-blue-600 hover:bg-blue-100 transition-colors border-l border-blue-100/50"
              >
                <el-icon><CaretBottom /></el-icon>
              </button> -->
            </div>

            <button
              class="comment-btn flex items-center gap-1.5 text-slate-500 hover:text-slate-800 transition-colors text-sm cursor-pointer"
              @click="handleComment(answer, index)"
            >
              <el-icon class="text-base"><IEpChatRound /></el-icon>
              <span>
                {{ answer.childrenNum ? `${answer.childrenNum} 条评论` : '回复' }}
              </span>
            </button>
          </div>

          <!-- 内嵌评论区 -->
          <!-- 增加一个边框和浅灰色背景，让它看起来像一个“容器” -->
          <Transition name="fade">
            <div
              v-show="answer.showComment"
              class="mt-4 border border-slate-200 rounded-lg bg-slate-50/50 overflow-hidden"
            >
              <Comment
                :authorId="questionDetail.createUserId"
                :ref="(e) => (commentRefList[index] = e as InstanceType<typeof Comment>)"
                :id="questionId"
                :total="answer.childrenNum"
                :defaultSize="5"
                :type="ArticleTypeEnum.QUESTION"
                :immediate="false"
                :isQuestion="true"
                :commentId="answer.id"
              />
            </div>
          </Transition>
        </div>
      </div>

      <!-- 底部加载更多 -->
      <div class="py-3 px-6 flex justify-end bg-#fff rounded-lg">
        <el-pagination
          v-model:current-page="searchParams.current"
          v-model:page-size="searchParams.size"
          :total="total"
          layout="prev, pager, next,total"
          small
          @current-change="goToPage"
        />
      </div>
    </div>
    <CommentDialog ref="commentDialogRef" @commentSuccess="refresh" />
  </div>
</template>
<script setup lang="ts">
import {
  getArticleDetail,
  getCommentList,
  addOrCanceArticlelLike,
  addOrCanceArticlelCollect,
  addOrCancelCommentLike,
  topOrCancelTopComment,
} from '@/api'
import type { ArticleItemDto, CommentItemDto } from '@/api'
import { usePageSearch } from '@/hooks'
import Comment from '@/components/common/Comment/index.vue'
import CommentDialog from '@/components/common/CommentDialog/index.vue'
import BackButton from '@/components/common/BackButton/index.vue'
import dayjs from 'dayjs'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import { useNavigation, useScrollTop } from '@/hooks'
import { parseEmoji } from '@/utils/emoji'
import { ArticleTypeEnum, BooleanFlag } from '@/constants'
import { push } from 'notivue'
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const { jumpToUserHomePage } = useNavigation()
const route = useRoute()
const router = useRouter()

const questionId = Number(route.params.id)
const commentRefList = ref<InstanceType<typeof Comment>[]>([])
const answerRefList = ref<HTMLElement[]>([])
const questionDetail = ref<ArticleItemDto>({} as ArticleItemDto)
const commentDialogRef = useTemplateRef<typeof CommentDialog>('commentDialogRef')

// 回滚到子评论框
const { handleBackTop: handleBackTopChildren } = useScrollTop(answerRefList)
const loading = computed(() => !questionDetail.value.title)

const isAuthor = computed(() => {
  return questionDetail.value.createUserId === userInfo.value.userId
})
const questionContentRef = useTemplateRef<HTMLElement>('questionContentRef')
const isExpand = ref(false)

// 检测当前是否超过三行 要用到具体的dom
const isOverThreeLine = ref(false)
const checkIsOverThreeLine = () => {
  if (!questionContentRef.value || !questionDetail.value.content) return false

  const lineHeight = parseFloat(getComputedStyle(questionContentRef.value).lineHeight)
  const height = questionContentRef.value!.scrollHeight
  const maxHeight = lineHeight * 3
  return height > maxHeight
}
const getQuestionDetail = async () => {
  const { data } = await getArticleDetail(questionId)
  questionDetail.value = data
  await nextTick()
  isOverThreeLine.value = checkIsOverThreeLine()
}

const { list, total, searchParams, goToPage, refresh } = usePageSearch(getCommentList, {
  // immediate: false,
  defaultParams: {
    articleId: questionId,
    sortType: 2,
  },
  formatList: (list) =>
    list.map((item) => ({
      ...item,
      showComment: false,
      isExpand: false,
    })),
})

const changeSortType = (type: number) => {
  searchParams.value.sortType = type
  refresh()
}

const handleLikeArticle = async () => {
  await addOrCanceArticlelLike(questionId)
  questionDetail.value.hasPraised = !questionDetail.value.hasPraised
  questionDetail.value.praiseCount = questionDetail.value.hasPraised
    ? questionDetail.value.praiseCount + 1
    : questionDetail.value.praiseCount - 1
  push.success(`${questionDetail.value.hasPraised ? '点赞该问题' : '取消点赞该问题'}`)
}

const handleCollectArticle = async () => {
  await addOrCanceArticlelCollect(questionId)
  questionDetail.value.hasCollect = !questionDetail.value.hasCollect
  questionDetail.value.collectionCount = questionDetail.value.hasCollect
    ? questionDetail.value.collectionCount + 1
    : questionDetail.value.collectionCount - 1
  push.success(`${questionDetail.value.hasCollect ? '收藏成功' : '取消收藏成功'}`)
}

const handleLikeAnswer = async (answer: CommentItemDto) => {
  await addOrCancelCommentLike(answer.id)
  answer.hasPraise = answer.hasPraise === BooleanFlag.YES ? BooleanFlag.NO : BooleanFlag.YES
  answer.postPriseCount = answer.hasPraise ? answer.postPriseCount + 1 : answer.postPriseCount - 1
  push.success(`${answer.hasPraise ? '点赞该回答' : '取消点赞该回答'}`)
}

const topCommentPendingId = ref<number | null>(null)
const highlightCommentId = ref<number | null>(null)
const handleTopAnswer = async (answer: CommentItemDto) => {
  if (topCommentPendingId.value !== null) return

  try {
    topCommentPendingId.value = answer.id
    await topOrCancelTopComment(answer.id)
    const isTopNow = answer.isTop === BooleanFlag.YES
    push.success(isTopNow ? '取消置顶成功' : '置顶成功')
    await refresh()

    if (isTopNow) return

    await nextTick()
    const idx = list.value.findIndex((i: CommentItemDto) => i.id === answer.id)
    if (idx !== -1) {
      await handleBackTopChildren(idx)
      highlightCommentId.value = answer.id
      setTimeout(() => {
        if (highlightCommentId.value === answer.id) {
          highlightCommentId.value = null
        }
      }, 2400)
    }
  } catch (error) {
    console.error(error)
  } finally {
    topCommentPendingId.value = null
  }
}

const handleComment = (answer: any, index: number) => {
  commentRefList.value[index]?.search()
  answer.showComment = !answer.showComment
}

const openCommentDialog = () => {
  commentDialogRef.value?.open(questionDetail.value.id)
}

onMounted(() => {
  getQuestionDetail()
})
</script>
<style lang="scss" scoped>
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
  filter: blur(4px);
}
.fade-enter-active,
.fade-leave-active {
  transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
.comment-btn {
  display: inline-flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.5rem 0.75rem;
  font-size: 0.875rem;
  line-height: 1.25rem;
  color: #64748b;
  border-radius: 0.5rem;
  cursor: pointer;
  transition:
    color 0.15s,
    background-color 0.15s;
  &:hover {
    color: #1e293b;
    background-color: #f1f5f9;
  }
}

.top-badge-dot {
  animation: topDotPulse 2.4s ease-in-out infinite;
}

@keyframes topDotPulse {
  0%,
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(245, 158, 11, 0.28);
  }
  50% {
    transform: scale(1.2);
    box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.1);
  }
}

.top-answer-highlight {
  position: relative;
  overflow: hidden;
  border-left: 3px solid rgba(99, 102, 241, 0.65);
  animation: answerFlash 2.4s ease-out;
}

@keyframes answerFlash {
  0% {
    border-left-color: rgba(99, 102, 241, 0.78);
    background-color: rgba(99, 102, 241, 0.12);
  }
  60% {
    border-left-color: rgba(99, 102, 241, 0.52);
    background-color: rgba(99, 102, 241, 0.06);
  }
  100% {
    border-left-color: rgba(99, 102, 241, 0.2);
    background-color: transparent;
  }
}

@keyframes answerBarFlash {
  0% {
    opacity: 0;
    transform: translateY(6px);
  }
  20% {
    opacity: 1;
    transform: translateY(0);
  }
  80% {
    opacity: 1;
    transform: translateY(0);
  }
  100% {
    opacity: 0;
    transform: translateY(-4px);
  }
}
</style>
