<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">
          <div
            v-for="(item, index) in list"
            :key="item.id"
            class="relative group bg-white rounded-lg p-5 cursor-pointer transition-all duration-300 hover:shadow-lg hover:shadow-gray-100 border border-gray-100 hover:border-gray-200 mb-3 sm:mb-4"
          >
            <!-- 推荐标签 -->
            <div v-if="item.isRecommend" class="absolute left-0 top-5">
              <div
                class="h-5.5 pl-2 pr-2.5 flex items-center gap-1 bg-gradient-to-r from-#6366f1 to-#818cf8 rounded-r-full text-white text-11px font-medium shadow-sm"
              >
                <svg viewBox="0 0 16 16" class="w-3 h-3 fill-current">
                  <path
                    d="M8 1.3l2 4.1 4.5.7-3.2 3.1.8 4.5L8 11.5l-4.1 2.2.8-4.5L1.5 6.1l4.5-.7z"
                  />
                </svg>
                推荐
              </div>
            </div>

            <h2
              class="text-xl line-clamp-1 font-semibold text-gray-900 mb-3 leading-tight hover:text-blue-600 transition-colors"
              :class="{ 'pl-14': item.isRecommend }"
              @click="openNewPage(`/questionDetail/${item.id}`)"
            >
              {{ item.title }}
            </h2>

            <div class="mb-3">
              <p
                :ref="(e) => (contentRefList[index] = e as HTMLElement)"
                class="text-gray-600 text-sm sm:text-base leading-relaxed transition-all duration-300"
                :class="{ 'line-clamp-3': !item.isExpand }"
              >
                <template
                  v-if="
                    item.cultureCommentListVo?.replyName || item.cultureCommentListVo?.hiddenName
                  "
                >
                  {{
                    item.cultureCommentListVo?.replyName || item.cultureCommentListVo?.hiddenName
                  }}：
                  <span v-html="parseEmoji(item.cultureCommentListVo?.content)"></span>
                </template>
                <template v-else>
                  <span v-html="parseEmoji(item.content)"></span>
                </template>
              </p>
              <div class="flex justify-end" v-if="isOverThreeLine(index)">
                <el-button @click.stop="handleExpand(item)" type="primary" text size="small">
                  {{ item.isExpand ? '收起' : '阅读全文' }}
                  <el-icon class="ml-1" :class="{ 'rotate-180': item.isExpand }">
                    <IEpArrowDown />
                  </el-icon>
                </el-button>
              </div>
            </div>

            <div class="flex items-center justify-between pt-3 border-t border-gray-100/80">
              <div class="flex items-center gap-2 xl:gap-3 flex-wrap">
                <div class="flex items-center gap-2">
                  <el-avatar :size="22" :src="item.showAvatar" />
                  <span class="text-sm text-gray-600">{{ item.showName }}</span>
                </div>
                <span class="text-xs text-gray-400 hidden sm:inline">{{
                  dayjs(item.createTime * 1000).format('YYYY-MM-DD HH:mm')
                }}</span>
                <div class="hidden sm:block w-1 h-1 bg-gray-300 rounded-full mx--1"></div>
                <!-- 地区 -->
                <span class="text-xs text-gray-400 hidden sm:inline">{{ item.region }}</span>
                <div class="hidden sm:block w-1 h-1 bg-gray-300 rounded-full mx--1"></div>
                <!-- 阅读量 -->
                <span class="text-xs text-gray-400 hidden sm:inline">{{ item.viewCount }}阅读</span>

                <div class="flex items-center gap-1">
                  <el-button
                    size="small"
                    plain
                    class="rounded-lg"
                    :class="{
                      '!text-blue-500 !border-blue-200 !bg-blue-50': item.hasAddQuestion,
                    }"
                    @click.stop="handleAddQuestion(item)"
                  >
                    <el-icon class="mr-0.5">
                      <IEpCircleCheckFilled v-show="item.hasAddQuestion" />
                      <IEpPlus v-show="!item.hasAddQuestion" />
                    </el-icon>
                    {{ item.hasAddQuestion ? '已添加' : '添加' }}
                  </el-button>

                  <el-button
                    size="small"
                    plain
                    class="rounded-lg"
                    :class="{ '!text-amber-500 !border-amber-200 !bg-amber-50': item.hasCollect }"
                    @click.stop="handleCollect(item)"
                  >
                    <el-icon class="mr-0.5">
                      <IEpStarFilled v-show="item.hasCollect" />
                      <IEpStar v-show="!item.hasCollect" />
                    </el-icon>
                    {{ item.hasCollect ? '已关注' : '关注' }}
                  </el-button>

                  <el-button
                    size="small"
                    plain
                    class="rounded-lg"
                    @click.stop="handleComment(item, index)"
                  >
                    <el-icon class="mr-0.5"><IEpEdit /></el-icon>
                    <template v-if="item.cultureCommentListVo?.childNum">
                      {{ item.cultureCommentListVo?.childNum }}条评论
                    </template>
                    <template v-else>写评论</template>
                  </el-button>

                  <ActionMore class="ml-1" :articleDetail="item" />
                </div>
              </div>
            </div>
            <Transition name="fadeCommentBox" mode="out-in">
              <Comment
                v-show="item.showComment"
                :authorId="item.createUserId"
                :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>
          </div>
        </div>
        <!-- 底部分页 -->
        <div class="bottom-pagination 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>
    <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'
import { push } from 'notivue'
import { useTourStore } from '@/stores'
import { storeToRefs } from 'pinia'

const { fetchUserQestionNum } = useQuestionStore()
const tourStore = useTourStore()
const { shouldShowAskTabTour } = storeToRefs(tourStore)
const router = useRouter()
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
  push.success(item.hasCollect ? '收藏成功' : '取消收藏')
}

// 一个是直接写这个问题的首评论 一个是直接给最热评论写评论
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()
  push.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) => {
  router.push(path)
}

onActivated(async () => {
  if (shouldShowAskTabTour.value) {
    await handleBackTop()
    tourStore.hitAskTabTour()
  }
  refresh()
})
</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>
