<template>
  <div>
    <!-- 头部Tabs -->
    <div class="flex gap-3 items-center">
      <Tabs v-model="activeTab" :tabs="tabs" @change="(e) => handleTabChange(e as string)" />
      <el-icon
        size="15"
        class="cursor-pointer hover:rotate-180 transition-all duration-300"
        @click="handleRefresh"
        ><IEpRefresh
      /></el-icon>
    </div>

    <!-- 主要内容区域 -->
    <div class="mx-auto pt-6">
      <PublishBox :type="ArticleTypeEnum.QUESTION" ref="publishBoxRef" />
      <div v-loading="loading" v-if="list.length">
        <!-- 问题列表 -->
        <div class="space-y-4">
          <el-card
            v-for="(item, index) in list"
            :key="item.id"
            class="question-card !rounded-lg mb-4 transition-all duration-300 relative"
            shadow="hover"
          >
            <div
              v-if="item.isRecommend"
              class="absolute top-0 left-0 w-13 h-6 bg-#FFF9B9 flex items-center justify-center border-2px border-solid border-#f4f0eb rounded-tl-lg rounded-br-lg"
            >
              <img class="w-6" src="@/assets/img/culture/recommend.png" alt="" />
              <div class="text-12px text-#000 line-height-12px">推荐</div>
            </div>
            <!-- 问题标题 -->
            <h2
              class="text-xl line-clamp-1 font-semibold text-gray-900 mb-2 leading-relaxed cursor-pointer hover:text-blue-600 transition-colors"
              @click="openNewPage(`/questionDetail/${item.id}`)"
            >
              {{ item.title }}
            </h2>
            <div class="flex gap-4 mb-2">
              <!-- 问吧暂时先不展示图片 -->
              <!-- <el-image
                v-if="item.faceUrl && !item.cultureCommentListVo?.hiddenName"
                :src="item.faceUrl"
                fit="cover"
                class="w-50 h-25 rounded-lg"
              /> -->
              <!-- 问题内容 -->
              <div>
                <p
                  :ref="(e) => (contentRefList[index] = e as HTMLElement)"
                  class="text-gray-600 text-base leading-relaxed transition-all duration-300"
                  :class="{ 'line-clamp-3': !item.isExpand }"
                >
                  <!-- 如果有评论的话 就展示 最热的 没有的话 说明没有评论  就展示内容 -->
                  <template v-if="item.cultureCommentListVo?.hiddenName">
                    {{ item.cultureCommentListVo?.hiddenName }}：
                    <span v-html="parseEmoji(item.cultureCommentListVo?.content)"></span>
                  </template>
                  <template v-else>
                    <p v-html="parseEmoji(item.content)"></p>
                  </template>
                </p>
                <!-- 展开/收起按钮 靠右边布局 -->
                <div class="flex justify-end">
                  <el-button
                    v-if="isOverThreeLine(index)"
                    @click.stop="handleExpand(item)"
                    type="primary"
                    text
                    size="small"
                    class="text-blue-500"
                  >
                    {{ item.isExpand ? '收起' : '阅读全文' }}
                    <el-icon class="ml-1" :class="{ 'rotate-180': item.isExpand }">
                      <IEpArrowDown />
                    </el-icon>
                  </el-button>
                </div>
              </div>
            </div>
            <!-- 底部信息栏 -->
            <div class="flex items-center justify-between border-t border-gray-100">
              <!-- 左侧：发布人信息 -->
              <div class="flex items-center gap-2 lg:gap-4">
                <div class="flex items-center gap-2">
                  <span class="text-orange-500 text-sm font-medium hidden lg:block">发布人</span>
                  <div class="flex items-center gap-2">
                    <el-avatar :size="20" :src="item.showAvatar"> </el-avatar>
                    <span class="text-sm text-gray-700 font-medium">{{ item.showName }}</span>
                  </div>
                </div>

                <span class="text-xs text-gray-400">{{
                  dayjs(item.createTime * 1000).format('YYYY-MM-DD HH:mm')
                }}</span>

                <!-- 操作按钮组 -->
                <div class="flex items-center">
                  <el-button
                    size="small"
                    plain
                    :class="{ 'opacity-50': item.hasAddQuestion }"
                    @click.stop="handleAddQuestion(item)"
                  >
                    <el-icon>
                      <IEpCircleCheckFilled v-show="item.hasAddQuestion" />
                      <IEpPlus v-show="!item.hasAddQuestion" />
                    </el-icon>
                    {{ item.hasAddQuestion ? '已添加' : '添加' }}
                  </el-button>

                  <el-button
                    size="small"
                    plain
                    :class="{ 'opacity-50': item.hasCollect }"
                    @click.stop="handleCollect(item)"
                  >
                    <el-icon>
                      <IEpStarFilled v-show="item.hasCollect" />
                      <IEpStar v-show="!item.hasCollect" />
                    </el-icon>
                    {{ item.hasCollect ? '已关注' : '关注' }}
                  </el-button>

                  <!-- 回答按钮保持不变 -->
                  <!-- 当前最热评论的评论有几条 -->
                  <el-button size="small" plain @click.stop="handleComment(item, index)">
                    <el-icon><IEpEdit /></el-icon>
                    <template v-if="item.cultureCommentListVo?.childNum">
                      {{ item.cultureCommentListVo?.childNum }}条评论
                    </template>
                    <template v-else>
                      <span>写评论</span>
                    </template>
                  </el-button>

                  <ActionMore class="ml-4" :articleDetail="item" />
                </div>
              </div>

              <!-- 右侧：统计信息 -->
              <div class="flex items-center">
                <!-- 浏览量 -->
                <!-- <el-button text class="flex items-center gap-2 text-gray-500">
                  <el-icon><IEpView /></el-icon>
                  <span class="text-sm">{{ item.viewCount || 0 }}</span>
                </el-button> -->

                <!-- 收藏 -->
                <!-- <el-button
                  text
                  class="flex items-center gap-2 text-gray-500 transition-colors"
                  @click.stop="handleCollect(item)"
                >
                  <el-icon :color="item.hasCollect ? '#409EFF' : '#999'"><IEpStar /></el-icon>
                  <span class="text-sm" :class="{ 'text-blue-500': item.hasCollect }">{{
                    item.collectionCount || 0
                  }}</span>
                </el-button> -->

                <!-- 评论 -->
                <!-- <el-button
                  text
                  class="flex items-center gap-2 text-gray-500 transition-colors"
                  @click.stop="handleComment(item, index)"
                >
                  <el-icon><IEpChatDotRound /></el-icon>
                  <span class="text-sm">{{ item.cultureCommentListVo?.childNum || 0 }}</span>
                </el-button> -->
              </div>
            </div>
            <Transition name="fadeCommentBox" mode="out-in">
              <Comment
                v-if="item.showComment"
                :ref="(e) => (commentRefList[index] = e as InstanceType<typeof Comment>)"
                :id="item.id"
                :total="item.cultureCommentListVo?.childNum || 0"
                :defaultSize="5"
                :type="ArticleTypeEnum.QUESTION"
                :immediate="false"
                :isQuestion="true"
                :commentId="item.cultureCommentListVo?.id"
                @commentSuccess="() => handleCommentSuccess(item)"
              />
            </Transition>
          </el-card>
        </div>
        <!-- 底部分页 -->
        <div class="bottom-pagination backdrop-blur-8 border-t border-gray-200">
          <div class="max-w-7xl mx-auto py-4">
            <div class="flex items-center justify-between">
              <!-- 左侧：回到顶部按钮 -->
              <div class="left">
                <ScrollTopComp />
              </div>

              <!-- 右侧：分页器 -->
              <div class="right">
                <div
                  class="pagination-wrapper bg-white rounded-lg shadow-sm border border-gray-100 p-2"
                >
                  <el-pagination
                    v-model:current-page="searchParams.current"
                    v-model:page-size="searchParams.size"
                    @current-change="
                      async (e) => {
                        await goToPage(e)
                        handleBackTop()
                      }
                    "
                    @size-change="changePageSize"
                    :page-sizes="[15, 30, 45, 60]"
                    layout="prev, pager, next, jumper, total"
                    :total="total"
                    class="custom-pagination"
                    :pager-count="5"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template v-else>
        <div class="flex items-center justify-center h-full">
          <el-empty description="暂无数据" />
        </div>
      </template>
    </div>

    <el-tour v-model="open">
      <el-tour-step :target="publishBoxRef?.$el" placement="right">
        <div>在这里发布你的问题</div>
      </el-tour-step>
      <template #indicators></template>
    </el-tour>
    <CommentDialog ref="commentDialogRef" @commentSuccess="search" />
  </div>
</template>

<script setup lang="ts">
import Tabs from '@/components/common/Tabs'
import Comment from '@/components/common/Comment/index.vue'
import { useScrollTop, usePageSearch } from '@/hooks'
import { TABS_REF_KEY } from '@/constants'
import PublishBox from '@/components/common/PublishBox/index.vue'
import { ArticleTypeEnum } from '@/constants'
import dayjs from 'dayjs'
import { getArticleList, addOrCanceArticlelCollect, addOrCancelToAnswerList } from '@/api'
import type { ArticleItemDto } from '@/api/article/types'
import { useQuestionStore } from '@/stores/question'
import ActionMore from '@/components/common/ActionMore/index.vue'
import CommentDialog from '@/components/common/CommentDialog/index.vue'
import { parseEmoji } from '@/utils/emoji'

const { fetchUserQestionNum } = useQuestionStore()

const route = useRoute()
const open = ref(false)
const publishBoxRef = useTemplateRef('publishBoxRef')
const commentDialogRef = useTemplateRef<typeof CommentDialog>('commentDialogRef')

const activeTab = ref('最新')
const tabs = [
  { label: '最新', value: '最新' },
  { label: '热问', value: '热问' },
  { label: '关注', value: '关注' },
]

const { list, total, searchParams, loading, refresh, goToPage, changePageSize, search } =
  usePageSearch(getArticleList, {
    immediate: false,
    defaultParams: {
      type: ArticleTypeEnum.QUESTION,
      sortLogic: 1,
    },
    formatList: (list) =>
      list.map((item) => ({
        ...item,
        showComment: false,
        isExpand: false,
      })),
  })

const tabsRef = inject(TABS_REF_KEY)

const { ScrollTopComp, handleBackTop } = useScrollTop(tabsRef!)

const handleCollect = async (item: ArticleItemDto) => {
  await addOrCanceArticlelCollect(item.id)
  item.hasCollect = !item.hasCollect
  item.collectionCount = item.hasCollect ? item.collectionCount + 1 : item.collectionCount - 1
  ElMessage.success(item.hasCollect ? '收藏成功' : '取消收藏')
  refresh()
}

// 一个是直接写这个问题的首评论 一个是直接给最热评论写评论
const handleComment = async (item: ArticleItemDto, index: number) => {
  if (item.cultureCommentListVo?.hiddenName) {
    item.showComment = !item.showComment
    await nextTick()

    if (item.showComment) {
      commentRefList.value[index]?.search()
    }
  } else {
    // 直接让他写评论
    commentDialogRef.value?.open(item.id)
  }
}

const handleCommentSuccess = (item: ArticleItemDto) => {
  item.cultureCommentListVo.childNum++
  // 同时更新下
  // 如果已经添加了回答 则改为未添加 并且更新问题数量
  if (item.hasAddQuestion) {
    item.hasAddQuestion = false
    fetchUserQestionNum()
  }
}

const handleAddQuestion = async (item: ArticleItemDto) => {
  await addOrCancelToAnswerList({ articleId: item.id })
  item.hasAddQuestion = !item.hasAddQuestion
  fetchUserQestionNum()
  ElMessage.success(item.hasAddQuestion ? '添加成功' : '取消添加')
}

const handleRefresh = () => {
  refresh()
}

const handleTabChange = (val: string) => {
  if (val === '热问') {
    searchParams.value.sortLogic = 0
    searchParams.value.questionFocus = undefined
  } else if (val === '关注') {
    searchParams.value.sortLogic = undefined
    searchParams.value.questionFocus = 1
  } else if (val === '最新') {
    searchParams.value.questionFocus = undefined
    searchParams.value.sortLogic = 1
  }
  handleRefresh()
}

const contentRefList = ref<HTMLElement[]>([])
const commentRefList = ref<InstanceType<typeof Comment>[]>([])

// 检测当前是否超过三行 要用到具体的dom
const isOverThreeLine = (index: number) => {
  if (!contentRefList.value[index]) return false

  const lineHeight = parseFloat(getComputedStyle(contentRefList.value[index]).lineHeight)
  const height = contentRefList.value[index]!.scrollHeight
  const maxHeight = lineHeight * 3

  return height > maxHeight
}

const handleExpand = (item: ArticleItemDto) => {
  item.isExpand = !item.isExpand
}

const openNewPage = (path: string) => {
  window.open(path)
}

// 是否打开漫游
watch(
  () => route.fullPath,
  async (newVal) => {
    // 处理在当前页面跳转到当前页面的情况 onActivated 不会触发
    if (newVal.includes('#tabsRef') && newVal.includes('?t')) {
      await handleBackTop()
      open.value = true
    }
  },
)
onActivated(async () => {
  if (route.fullPath.includes('#tabsRef')) {
    await handleBackTop()
    open.value = true
  }
  refresh()
})

onMounted(() => {
  console.log('父组件onmounted')
})
</script>
<style lang="scss" scoped>
.fadeCommentBox-enter-from {
  opacity: 0;
  transform: translateY(-10px);
  filter: blur(4px);
}

.fadeCommentBox-enter-to {
  opacity: 1;
  transform: translateY(0);
  filter: blur(0);
}

.fadeCommentBox-leave-from {
  opacity: 1;
  transform: translateY(0);
  filter: blur(0);
}

.fadeCommentBox-leave-to {
  opacity: 0;
  transform: translateY(-10px);
  filter: blur(4px);
}

.fadeCommentBox-enter-active,
.fadeCommentBox-leave-active {
  transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
</style>
