<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 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"
          :key="answer.id"
          class="bg-white rounded-lg p-6 shadow-sm border border-slate-100 hover:border-slate-200 transition-colors"
        >
          <!-- 用户头 -->
          <div class="flex items-center gap-3 mb-3">
            <el-avatar
              :src="answer.avatar"
              :size="36"
              class="flex-shrink-0 cursor-pointer"
              @click="jumpToUserHomePage({ userId: answer.userId, type: ArticleTypeEnum.QUESTION })"
            />
            <div>
              <div class="text-slate-900 text-sm flex items-center gap-2">
                {{ answer.replyUser }}
                <!-- 徽章示例 -->
                <!-- <span
                  v-if="index === 0"
                  class="px-1.5 py-0.5 bg-yellow-50 text-yellow-600 text-[10px] rounded scale-90 origin-left"
                  >优秀回答</span
                > -->
              </div>
              <!-- <div class="text-xs text-slate-500 mt-0.5 max-w-md truncate">
                {{ answer.description || '暂无简介' }}
              </div> -->
            </div>
          </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') }} ·
            {{ answer.region }}
          </div>

          <!-- 底 部吸附操作栏 -->
          <div class="flex items-center gap-4 select-none sticky bottom-0 bg-white">
            <!-- 核心交互：赞同/反对胶囊 -->
            <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
                :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,
} from '@/api'
import type { ArticleItemDto } 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 } from '@/hooks'
import { parseEmoji } from '@/utils/emoji'
import { ArticleTypeEnum } 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 questionDetail = ref<ArticleItemDto>({} as ArticleItemDto)
const commentDialogRef = useTemplateRef<typeof CommentDialog>('commentDialogRef')

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: any) => {
  await addOrCancelCommentLike(answer.id)
  answer.hasPraise = !answer.hasPraise
  answer.postPriseCount = answer.hasPraise ? answer.postPriseCount + 1 : answer.postPriseCount - 1
  push.success(`${answer.hasPraise ? '点赞该回答' : '取消点赞该回答'}`)
}

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;
  }
}
</style>
