<template>
  <div ref="commentRef" class="bg-white rounded-3 shadow-sm border border-gray-100">
    <!-- 评论筛选 -->
    <div class="p-4 border-b border-gray-100">
      <div class="flex items-center gap-4 justify-between">
        <span class="text-lg font-semibold text-gray-800">评论 ({{ total }})</span>
        <div class="flex items-center gap-2">
          <button
            class="cursor-pointer px-3 py-1.5 text-sm transition-all relative"
            @click="((searchParams.sortType = CommentSortTypeEnum.MOST_LIKE), refresh())"
            :class="{
              'text-indigo-600 font-medium':
                searchParams.sortType === CommentSortTypeEnum.MOST_LIKE,
              'text-gray-600 hover:text-gray-900':
                searchParams.sortType !== CommentSortTypeEnum.MOST_LIKE,
            }"
          >
            最高点赞
            <span
              v-if="searchParams.sortType === CommentSortTypeEnum.MOST_LIKE"
              class="absolute bottom-0 left-0 right-0 h-0.5 bg-indigo-600"
            ></span>
          </button>
          <button
            class="cursor-pointer px-3 py-1.5 text-sm transition-all relative"
            @click="((searchParams.sortType = CommentSortTypeEnum.MOST_COMMENT), refresh())"
            :class="{
              'text-indigo-600 font-medium':
                searchParams.sortType === CommentSortTypeEnum.MOST_COMMENT,
              'text-gray-600 hover:text-gray-900':
                searchParams.sortType !== CommentSortTypeEnum.MOST_COMMENT,
            }"
          >
            最多评论
            <span
              v-if="searchParams.sortType === CommentSortTypeEnum.MOST_COMMENT"
              class="absolute bottom-0 left-0 right-0 h-0.5 bg-indigo-600"
            ></span>
          </button>
          <button
            class="cursor-pointer px-3 py-1.5 text-sm transition-all relative"
            @click="((searchParams.sortType = CommentSortTypeEnum.EARLIEST_PUBLISH), refresh())"
            :class="{
              'text-indigo-600 font-medium':
                searchParams.sortType === CommentSortTypeEnum.EARLIEST_PUBLISH,
              'text-gray-600 hover:text-gray-900':
                searchParams.sortType !== CommentSortTypeEnum.EARLIEST_PUBLISH,
            }"
          >
            最早发布
            <span
              v-if="searchParams.sortType === CommentSortTypeEnum.EARLIEST_PUBLISH"
              class="absolute bottom-0 left-0 right-0 h-0.5 bg-indigo-600"
            ></span>
          </button>
          <button
            class="cursor-pointer px-3 py-1.5 text-sm transition-all relative"
            @click="((searchParams.sortType = CommentSortTypeEnum.NEWEST_PUBLISH), refresh())"
            :class="{
              'text-indigo-600 font-medium':
                searchParams.sortType === CommentSortTypeEnum.NEWEST_PUBLISH,
              'text-gray-600 hover:text-gray-900':
                searchParams.sortType !== CommentSortTypeEnum.NEWEST_PUBLISH,
            }"
          >
            最新发布
            <span
              v-if="searchParams.sortType === CommentSortTypeEnum.NEWEST_PUBLISH"
              class="absolute bottom-0 left-0 right-0 h-0.5 bg-indigo-600"
            ></span>
          </button>

          <!-- <Tabs v-model="searchParams.sortType" :tabs="tabs" /> -->
        </div>
      </div>
    </div>

    <div>
      <!-- 发表评论 -->
      <div class="px-5 py-4 border-b border-gray-100">
        <div class="flex gap-3">
          <img
            :src="userAvatar"
            alt=""
            class="w-10 h-10 rounded-full object-cover cursor-pointer ring-2 ring-slate-100"
            @click="jumpToUserHomePage({ userId: userInfo.userId, type })"
          />
          <CommentBox
            v-model:inputText="myComment"
            v-model:inputImg="myCommentImgStr"
            class="flex-1"
            ref="myCommentBoxRef"
          >
            <template #submit>
              <button
                type="button"
                class="comment-publish-btn cursor-pointer disabled:opacity-50 px-6 py-2 text-white rounded-full text-sm hover:shadow-lg transition-all"
                :disabled="!myComment?.trim() || loading"
                @click="handleMyComment"
              >
                <div v-show="myCommentLoading" class="flex items-center gap-2">
                  <el-icon><IEpLoading /></el-icon>
                  <span>发表中...</span>
                </div>
                <div v-show="!myCommentLoading">发表</div>
              </button>
            </template>
          </CommentBox>
        </div>
      </div>
      <!-- 分割线 -->

      <!-- 评论列表 -->
      <div v-loading="loading" class="divide-y divide-gray-100">
        <div v-show="list.length">
          <div
            v-for="(item, index) in list"
            :key="item.id"
            :ref="(el) => (commentItemRefList[index] = el as HTMLElement)"
          >
            <div
              class="px-5 py-4"
              :class="{ 'top-comment-highlight': highlightCommentId === item.id }"
            >
              <div class="flex gap-3">
                <img
                  @click="jumpToUserHomePage({ userId: item.userId, type })"
                  :src="isReal ? item.avatar : item.hiddenAvatar"
                  alt=""
                  class="w-10 h-10 rounded-full object-cover cursor-pointer ring-2 ring-slate-100"
                />
                <div class="flex-1">
                  <div class="flex items-center justify-between mb-2">
                    <div class="flex items-center gap-2">
                      <span class="font-semibold text-gray-800">{{
                        isReal ? item.replyUser : item.hiddenName
                      }}</span>
                      <span
                        v-if="item.isTop === BooleanFlag.YES"
                        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>
                      <span
                        v-if="!isQuestion"
                        class="inline-flex items-center rounded-full border border-gray-200 bg-gray-50 px-1.5 py-0.5 text-xs leading-none text-gray-500"
                      >
                        {{ item.floorNumber || '顶' }}楼
                      </span>
                    </div>
                    <!-- 作者有权利置顶 并且不是问吧（问吧是获取的二级评论列表） -->
                    <button
                      v-if="isAuthor && !isQuestion"
                      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="
                        item.isTop === BooleanFlag.YES
                          ? '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="handleTopComment(item)"
                    >
                      <span class="tracking-[0.2px]">{{
                        item.isTop === BooleanFlag.YES ? '取消置顶' : '置顶评论'
                      }}</span>
                    </button>
                    <!-- <span
                    class="px-2 py-0.5 text-xs bg-gradient-to-r from-purple-100 to-blue-100 text-purple-600 rounded-full"
                  >
                    技术专家
                  </span> -->
                    <!-- <span class="px-2 py-0.5 text-xs bg-red-100 text-red-600 rounded-full">置顶</span> -->
                  </div>
                  <!-- 换行 -->
                  <p
                    class="text-gray-800 my-2 break-all whitespace-pre-wrap"
                    v-html="parseEmoji(item.contentHtml || item.content)"
                    v-parse-comment
                  ></p>
                  <!-- 评论图片列表 -->
                  <div class="flex flex-wrap gap-2">
                    <div
                      v-for="(img, imgIndex) in item.imgUrl.split(',').filter(Boolean)"
                      :key="imgIndex"
                      class="w-20 h-20 rounded-lg overflow-hidden mb-2 cursor-pointer"
                    >
                      <el-image
                        :src="img"
                        :preview-teleported="true"
                        class="w-full h-full object-cover"
                        :preview-src-list="item.imgUrl.split(',').filter(Boolean)"
                        :initial-index="imgIndex"
                        fit="cover"
                      />
                    </div>
                  </div>
                  <div class="flex items-center">
                    <div class="flex items-center gap-5 text-gray-500">
                      <span class="flex items-center gap-2 text-[14px]">
                        <span
                          >{{ dayjs(item.createTime * 1000).format('YYYY-MM-DD HH:mm:ss') }}
                        </span>
                        <span>·</span>
                        <span class="text-gray-500">{{ item.region }}</span>
                      </span>
                      <div class="flex gap-2 items-center hover:text-blue-500 transition-colors">
                        <div
                          class="flex items-center gap-1 cursor-pointer"
                          @click="handleLickComment(item)"
                        >
                          <el-icon :size="16">
                            <svg-icon :name="item.hasPraise ? 'praise_fill' : 'praise'"></svg-icon>
                          </el-icon>
                          <span>{{ item.postPriseCount }}</span>
                        </div>
                      </div>
                      <button
                        class="cursor-pointer hover:text-blue-500 transition-colors text-[14px]"
                        @click="handleReply(item, index)"
                      >
                        回复
                      </button>
                    </div>
                  </div>
                  <!-- 回复列表 -->
                  <!-- 问吧 和 其他 做区分 -->
                  <template v-if="!isQuestion">
                    <div v-if="item.children?.length" class="mt-3 ml-4 space-y-3">
                      <!-- 回复评论的内容 里面可能是 展示全部的 也有可能是展示5条之内容 -->
                      <div
                        v-for="child in getCurrentChildrenList(item)"
                        v-loading="item.loadingChildren"
                        :key="child.id"
                        class="flex gap-2 p-3 rounded-lg"
                      >
                        <img
                          @click="jumpToUserHomePage({ userId: child.userId, type })"
                          :src="child.avatar"
                          alt=""
                          class="w-8 h-8 rounded-full object-cover cursor-pointer ring-1 ring-slate-200"
                        />
                        <div class="flex-1">
                          <div class="flex items-center gap-1">
                            <span class="font-semibold text-gray-600 text-base">{{
                              child.replyUser
                            }}</span>
                            <!-- v-if="item.replyName && item.replyName !== parentComment?.replyUser" -->
                            <span class="text-gray-500 text-sm flex items-center gap-1">
                              <el-icon class="mx-1"><IEpCaretRight /></el-icon>
                              {{ child.replyName }}
                            </span>
                          </div>
                          <p
                            class="text-gray-800 my-2 break-all whitespace-pre-wrap text-[16px]"
                            v-html="parseEmoji(child.contentHtml || child.content)"
                            v-parse-comment
                          ></p>
                          <!-- 评论图片列表 -->
                          <div class="flex flex-wrap gap-2">
                            <div
                              v-for="(img, imgIndex) in child.imgUrl.split(',').filter(Boolean)"
                              :key="imgIndex"
                              class="w-20 h-20 rounded-lg overflow-hidden mb-2"
                            >
                              <el-image
                                :src="img"
                                :preview-teleported="true"
                                class="w-full h-full object-cover"
                                :preview-src-list="child.imgUrl.split(',').filter(Boolean)"
                                :initial-index="imgIndex"
                                fit="cover"
                              />
                            </div>
                          </div>
                          <div class="flex items-center justify-between">
                            <div class="flex items-center gap-6 text-gray-500 text-[14px]">
                              <span class="flex items-center gap-2">
                                <span
                                  >{{
                                    dayjs(child.createTime * 1000).format('YYYY-MM-DD HH:mm:ss')
                                  }}
                                </span>
                                <span>·</span>
                                <span class="text-gray-500">{{ child.region }}</span>
                              </span>
                              <div class="flex gap-2 items-center hover:text-blue-500">
                                <div
                                  class="flex items-center gap-1 cursor-pointer"
                                  @click="handleLickComment(child)"
                                >
                                  <el-icon :size="16">
                                    <svg-icon
                                      :name="child.hasPraise ? 'praise_fill' : 'praise'"
                                    ></svg-icon>
                                  </el-icon>
                                  <span>{{ child.postPriseCount }}</span>
                                </div>
                              </div>
                              <button
                                @click="handleReply(child, index)"
                                class="cursor-pointer hover:text-blue-500 transition-colors"
                              >
                                回复
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                  <!-- 问吧  如果有 子评论 直接变成 查看更多 -->
                  <template v-else>
                    <div v-if="item.childNum">
                      <button
                        class="cursor-pointer text-sm text-gray-500 mt-2"
                        @click="handleOpenCommentDialog(item)"
                      >
                        查看全部{{ item.childNum }} 条回复>
                      </button>
                    </div>
                  </template>
                  <!-- 只有大于5 才会显示这个 -->
                  <div class="ml-4" v-show="item.childrenNum > 5 && !isQuestion">
                    <!-- 展示 展开回复 -->
                    <button
                      v-show="!item.showChildrenPage"
                      class="cursor-pointer text-sm text-gray-500"
                      @click="handleExpandReply(item)"
                    >
                      还有{{ item.childrenNum - 5 }}条回复,<span
                        class="hover:text-blue-500 transition-colors"
                        >点击查看</span
                      >
                    </button>
                    <!-- 展示 收起回复 以及分页 -->
                    <div class="flex items-center gap-2" v-show="item.showChildrenPage">
                      <span class="text-sm text-gray-500"
                        >共{{ Math.ceil(item.childrenNum / 10) }}页</span
                      >
                      <el-pagination
                        :pager-count="5"
                        layout="pager"
                        v-show="item.showChildrenPage"
                        :current-page="item.childrenPageCurrent"
                        :total="item.childrenNum"
                        @current-change="handleChildrenCurrentChange($event, item, index)"
                      />
                      <button
                        class="cursor-pointer hover:text-blue-500 transition-colors text-sm text-gray-500"
                        @click="handleCollapseReply(item, index)"
                      >
                        收起回复
                      </button>
                    </div>
                  </div>
                  <!-- 展示 回复评论的输入框 -->
                  <transition name="fadeToComment">
                    <div v-show="showCommentBox(item)" class="flex gap-3 mt-4">
                      <img
                        :src="userAvatar"
                        alt=""
                        class="w-10 h-10 rounded-full object-cover cursor-pointer"
                        @click="jumpToUserHomePage({ userId: userInfo.userId, type })"
                      />
                      <CommentBox
                        v-model:inputText="commentToOther"
                        v-model:inputImg="commentToOtherImgStr"
                        class="flex-1"
                        :ref="
                          (ins) =>
                            (replyToOtherBoxRefList[index] = ins as InstanceType<typeof CommentBox>)
                        "
                      >
                        <template #submit>
                          <button
                            type="button"
                            class="comment-publish-btn cursor-pointer disabled:opacity-50 px-6 py-2 text-white rounded-full text-sm hover:shadow-lg transition-all"
                            :disabled="!commentToOther.trim() || commentToOtherLoading"
                            @click="handleComment(index)"
                          >
                            发表
                          </button>
                        </template>
                      </CommentBox>
                    </div>
                  </transition>
                </div>
              </div>
            </div>
            <div class="px-5">
              <el-divider class="my-1.5! border-slate-100!" />
            </div>
          </div>
          <!-- 底部分页 -->
          <!-- 靠右侧 -->
          <div class="flex justify-end">
            <div class="w-fit p-4">
              <el-pagination
                v-model:current-page="searchParams.current"
                v-model:page-size="searchParams.size"
                :total="firstComentTotal"
                @current-change="handleCurrentChange"
                @size-change="changePageSize"
                layout="prev, pager, next, slot"
              >
                <div>共 {{ total }} 条</div>
              </el-pagination>
            </div>
          </div>
        </div>
        <div v-show="!list.length">
          <div class="flex items-center justify-center">
            <el-empty :image-size="100" description="暂无评论" />
          </div>
        </div>
      </div>
    </div>
    <CommentListDialog ref="commentListDialogRef" :articleId="id" :pid="currentDialogCommentPid" />
  </div>
</template>
<script setup lang="ts">
import {
  getCommentList,
  addOrCancelCommentLike,
  addComment,
  getCommentChildren,
  getSecondCommentList,
  topOrCancelTopComment,
} from '@/api'
import { usePageSearch, useScrollTop } from '@/hooks'
import { ArticleTypeEnum, BooleanFlag } from '@/constants'
import type { CommentItemDto } from '@/api'
import { useUserStore } from '@/stores'
import { storeToRefs } from 'pinia'
import CommentListDialog from '../CommentListDialog/index.vue'
import { useNavigation } from '@/hooks'
import { parseEmoji } from '@/utils/emoji'
import CommentBox from '../CommentBox/index.vue'
import dayjs from 'dayjs'
import { push } from 'notivue'
import { IS_REAL_KEY_COMMENT, CommentSortTypeEnum } from '@/constants'

const { jumpToUserHomePage } = useNavigation()
const {
  authorId = '',
  id,
  defaultSize = 10,
  immediate = true,
  isQuestion = false,
  commentId = 0,
  type,
} = defineProps<{
  authorId?: string // 文章作者id
  id: number // 文章ID
  defaultSize?: number
  isQuestion?: boolean // 如果是问题的话 展示有点不一样
  immediate?: boolean
  commentId?: number // 如果是问题的话 需要传入评论id
  type: ArticleTypeEnum
}>()

const emit = defineEmits<{
  (e: 'commentSuccess'): void
}>()

const total = defineModel<number>('total', { required: true, default: 0 })

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const isReal = computed<BooleanFlag>(
  () =>
    +(
      type === ArticleTypeEnum.PRACTICE ||
      type === ArticleTypeEnum.INTERVIEW ||
      type === ArticleTypeEnum.QUESTION
    ),
)
provide(IS_REAL_KEY_COMMENT, isReal)
const userAvatar = computed(() => {
  return isReal.value ? userInfo.value.avatar : userInfo.value.hiddenAvatar
})
const isAuthor = computed(() => {
  return authorId === userInfo.value.userId
})
const commentRef = useTemplateRef<HTMLElement | null>('commentRef')
const commentListDialogRef = useTemplateRef<typeof CommentListDialog>('commentListDialogRef')
const replyToOtherBoxRefList = ref<InstanceType<typeof CommentBox>[]>([])
const commentItemRefList = ref<HTMLElement[]>([])
// 回滚到评论框
const { handleBackTop } = useScrollTop(commentRef)
// 回滚到子评论框
const { handleBackTop: handleBackTopChildren } = useScrollTop(commentItemRefList)

const {
  list,
  searchParams,
  goToPage,
  loading,
  changePageSize,
  refresh,
  search,
  total: firstComentTotal,
} = usePageSearch(isQuestion ? getSecondCommentList : getCommentList, {
  defaultParams: {
    ...(commentId
      ? { pid: commentId, sortType: CommentSortTypeEnum.MOST_LIKE }
      : {
          articleId: id,
          sortType: CommentSortTypeEnum.MOST_LIKE,
        }),
  },
  defaultSize,
  formatList(list: CommentItemDto[]) {
    return list.map((item) => {
      // 初始化的时候 添加新的字段 是否展示分页子评论 默认是false 当前子评论分页current 以及子评论分页列表 loading效果

      const obj: CommentItemDto = { ...item }
      // if (obj.showChildrenPage == undefined) {
      obj.showChildrenPage = false
      // }
      // if (obj.childrenPageCurrent == undefined) {
      obj.childrenPageCurrent = 1
      // }
      // if (obj.childrenPageList == undefined) {
      obj.childrenPageList = []
      // }
      // if (obj.loadingChildren == undefined) {
      obj.loadingChildren = false
      // }

      return obj
    })
  },
  immediate,
})
const handleCurrentChange = async (e: number) => {
  await goToPage(e)
  handleBackTop()
}

// 自己发出的评论
const myComment = ref('')
const myCommentLoading = ref(false)
// 回复别人的
const commentToOther = ref('')
const commentToOtherLoading = ref(false)
// 回复别人placeholder
const replyPlaceholder = ref('回复@')
// 自己发出的评论图片
const myCommentImgStr = ref('')
// 回复别人的图片
const commentToOtherImgStr = ref('')
const currentCommentId = ref(-1)
const myCommentBoxRef = useTemplateRef<InstanceType<typeof CommentBox>>('myCommentBoxRef')

const handleLickComment = async (item: CommentItemDto) => {
  await addOrCancelCommentLike(item.id)
  if (item.hasPraise === BooleanFlag.YES) {
    push.success('取消点赞成功')
    item.postPriseCount--
    item.hasPraise = BooleanFlag.NO
  } else {
    push.success('点赞成功')
    item.postPriseCount++
    item.hasPraise = BooleanFlag.YES
  }
}

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

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

    if (isTopNow) return

    await nextTick()
    const idx = list.value.findIndex((i: CommentItemDto) => i.id === item.id)

    if (idx !== -1) {
      await handleBackTopChildren(idx)
      highlightCommentId.value = item.id

      setTimeout(() => {
        if (highlightCommentId.value === item.id) {
          highlightCommentId.value = null
        }
      }, 2400)
    }
  } catch (error) {
    console.error(error)
  } finally {
    topCommentPendingId.value = null
  }
}

const handleReply = (item: CommentItemDto, index: number) => {
  replyPlaceholder.value = `回复@${item.replyUser}：`
  commentToOther.value = ''
  currentCommentId.value = item.id
  replyToOtherBoxRefList.value[index]?.focus()
}

// 是否展示子评论回复框
const showCommentBox = (item: CommentItemDto) => {
  return (
    currentCommentId.value === item.id ||
    getCurrentChildrenList(item)?.some((i) => i.id === currentCommentId.value)
  )
}

const handleMyComment = async () => {
  try {
    myCommentLoading.value = true
    await addComment({
      articleId: id,
      content: myComment.value,
      ...(commentId ? { pid: commentId } : {}),
      imgUrl: myCommentImgStr.value,
      mentionUserIdList: myCommentBoxRef.value?.getMentionFns()?.getMentionUserIds?.()?.join?.(','),
      contentHtml: myCommentBoxRef.value?.getAnswerHtml(),
    })
    push.success('发表评论成功')
    refresh()
    myComment.value = ''
    myCommentImgStr.value = ''
    total.value++
    emit('commentSuccess')
  } catch (error) {
    console.error(error)
  } finally {
    myCommentLoading.value = false
  }
}

const handleComment = async (index: number) => {
  try {
    commentToOtherLoading.value = true
    await addComment({
      articleId: id,
      content: commentToOther.value,
      ...(currentCommentId.value ? { pid: currentCommentId.value } : {}),
      imgUrl: commentToOtherImgStr.value,
      mentionUserIdList:
        replyToOtherBoxRefList.value[index]
          ?.getMentionFns?.()
          ?.getMentionUserIds?.()
          ?.join?.(',') || '',
      contentHtml: replyToOtherBoxRefList.value[index]?.getAnswerHtml(),
    })
    push.success('发表评论成功')
    commentToOther.value = ''
    commentToOtherImgStr.value = ''
    total.value++
    handleBackTopChildren(index)
    // 只需要刷新当前的评论
    search()
    emit('commentSuccess')
  } catch (error) {
    console.error(error)
  } finally {
    commentToOtherLoading.value = false
  }
}

// 展开回复 获取子评论列表
const handleExpandReply = async (item: CommentItemDto) => {
  item.loadingChildren = true
  try {
    // 获取子评论
    await getCommentChildrenList(item)
  } catch (error) {
    console.error(error)
  } finally {
    item.loadingChildren = false
  }

  item.showChildrenPage = true
}
// 收起回复
const handleCollapseReply = (item: CommentItemDto, index: number) => {
  item.showChildrenPage = false

  handleBackTopChildren(index)
}

// 改变子评论的当前页数
const handleChildrenCurrentChange = (e: number, item: CommentItemDto, index: number) => {
  item.childrenPageCurrent = e
  getCommentChildrenList(item)
  handleBackTopChildren(index)
}

// 根据页数获取子评论列表
const getCommentChildrenList = async (item: CommentItemDto) => {
  const { data } = await getCommentChildren({
    pid: item.id,
    articleId: id,
    current: item.childrenPageCurrent,
    size: 10,
  })
  item.childrenPageList = data.list
}

// 获取当前要渲染的子列表
const getCurrentChildrenList = (item: CommentItemDto) => {
  if (item.showChildrenPage) {
    return item.childrenPageList
  } else {
    return item.children
  }
}

const currentDialogCommentPid = ref(0)
const handleOpenCommentDialog = (item: CommentItemDto) => {
  currentDialogCommentPid.value = item.id
  commentListDialogRef.value?.open()
}

defineExpose({
  scrollToCommentBox: () => handleBackTop(),
  search: () => search(),
})
</script>
<style scoped lang="scss">
/**
 * 发表按钮：不用纯 Uno 渐变工具类。
 * 旧版内核 / 部分企业微信 WebView 对「依赖 CSS 变量的 linear-gradient」解析失败时，
 * 背景会变成透明或无效，原生 button 呈白底，易出现「只剩阴影、几乎看不见按钮」。
 * 这里用实色 background-color 作兜底，并写死 hex + -webkit- 前缀渐变。
 */
.comment-publish-btn {
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
  border: 1px solid rgba(255, 255, 255, 0.35);
  /* 与 Tailwind blue-500 / purple-500 接近的实色兜底 */
  background-color: #6366f1;
  background-image: -webkit-linear-gradient(left, #3b82f6, #a855f7);
  background-image: linear-gradient(to right, #3b82f6, #a855f7);
  color: #ffffff;
}

.comment-publish-btn:disabled {
  cursor: not-allowed;
}

/* 进入 & 离开公共属性 */
.fadeToComment-enter-active,
.fadeToComment-leave-active {
  transition:
    opacity 0.25s ease,
    transform 0.25s cubic-bezier(0.22, 1, 0.36, 1);
  will-change: opacity, transform;
}

/* 进入前 & 离开后 */
.fadeToComment-enter-from,
.fadeToComment-leave-to {
  opacity: 0;
  transform: translateY(8px);
}

/* 进入后 & 离开前 */
.fadeToComment-enter-to,
.fadeToComment-leave-from {
  opacity: 1;
  transform: translateY(0);
}

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

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

.top-comment-highlight {
  position: relative;
  overflow: hidden;
  animation: commentFlash 2.4s ease-out;
}

.top-comment-highlight::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0%;
  width: 3px;
  height: 100%;
  border-radius: 999px;
  background: linear-gradient(180deg, rgba(99, 102, 241, 0.95), rgba(129, 140, 248, 0.55));
  box-shadow: 0 0 0 1px rgba(99, 102, 241, 0.08);
  animation: commentBarFlash 2.4s ease-out;
}

@keyframes commentFlash {
  0% {
    background-color: rgba(99, 102, 241, 0.16);
  }
  100% {
    background-color: transparent;
  }
}

@keyframes commentBarFlash {
  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>
