<script setup lang="ts">
import planetBg from '@/assets/img/planetBg.png'
import { NConfigProvider, NImage, NMessageProvider } from 'naive-ui'
import { ref, watch } from 'vue'

const userStore = useUserStore()
definePageMeta({
  layout: 'planet',
})
const isShow = ref('publish')
const listParams = ref({
  communityTag: null as string | null,
  pageNum: 1,
  pageSize: 100,
  userId: userStore.userInfo?.userId,
  isMyCreate: 1,
})
interface CommunityItem {
  imageUrl: string
  publishNum: number
  communityName: string
  avatar: string
  createBy: string
  createDay: number
  description: string
  price: number | null
}
const listFinish = ref(false)
const loading = ref(false)
const communityList = ref<CommunityItem[]>([])
const tabList = [
  { key: 0, label: '发布的帖子' },
  { key: 1, label: '我的问答' },
  { key: 2, label: '我的收藏' },
]
const commentParams = ref({
  communityId: null as string | null,
  pageNum: 1,
  pageSize: 10,
  tenantId: null as string | null,
  type: 0,
  isMy: 1,
})
// function refresh() {
//   listParams.value.pageNum = 1
//   getList()
// }

// 获取星球列表
async function getCommunityList() {
  try {
    if (listFinish.value || loading.value) // 添加loading检查,避免重复请求
      return
    loading.value = listParams.value.pageNum === 1 // 只在第一页显示loading
    const res = await request.post<ApiResponse<CommunityItem>>(`/community/myJoin`, listParams.value)
    if (res.code === 200) {
      if (res.rows.length !== 0) {
        const { id, tenantId } = res.rows[0]
        commentParams.value.tenantId = tenantId
        commentParams.value.communityId = id
        getCommentList()
      }
      if (listParams.value.pageNum === 1) {
        communityList.value = res.rows
      }
      else {
        communityList.value = [...communityList.value, ...res.rows]
      }

      if (communityList.value.length >= res.total) {
        listFinish.value = true
      }
      listParams.value.pageNum++
    }
  }
  catch (error) {
    communityList.value = []
    listFinish.value = true
    console.error(error)
  }
  finally {
    loading.value = false
  }
}
getCommunityList()

// 获取评论列表
const commentList = ref([])
const commentFinish = ref(false)
const commentLoading = ref(false)
async function getCommentList() {
  try {
    if (commentFinish.value || commentLoading.value) // 添加loading检查,避免重复请求
      return
    commentLoading.value = commentParams.value.pageNum === 1 // 只在第一页显示loading personHome/getPersonHomeLis
    const res = await request.post<ApiResponse<CommunityItem>>(`/personHome/getPersonHomeList`, commentParams.value)
    if (res.code === 200) {
      if (listParams.value.pageNum === 1) {
        commentList.value = res.rows
      }
      else {
        commentList.value = [...commentList.value, ...res.rows]
      }

      if (commentList.value.length >= res.total) {
        commentFinish.value = true
      }
      listParams.value.pageNum++
    }
  }
  catch (error) {
    commentList.value = []
    commentFinish.value = true
    console.error(error)
  }
  finally {
    commentLoading.value = false
  }
}

// 刷新
function refresh() {
  commentFinish.value = false
  commentLoading.value = false
  commentParams.value.pageNum = 1
  getCommentList()
}

// const userInfo = ref({
//   avatar: userStore.userInfo?.avatar,
//   nickname: userStore.userInfo?.nickName,
//   createdCount: 14456,
//   followCount: 145,
//   collectCount: 46464,
// })

// 切换星球
function changeCommunity(item: any) {
  commentParams.value.tenantId = item.tenantId
  commentParams.value.communityId = item.id
  refresh()
}

// 切换类型
function changeTab(key: number) {
  if (key !== 1) {
    isShow.value = 'publish'
  }
  else {
    isShow.value = 'question'
  }
  commentParams.value.type = key
  refresh()
}
// 获取用户点赞/粉丝/关注数量
interface SelectUserInfo {
  likeCount: number
  bean: number
  download: number
  attention: number
}
const selectUserInfo = ref<SelectUserInfo>({
  likeCount: 0,
  bean: 0,
  download: 0,
  attention: 0,
})

// 获取关注
async function getAttention() {
  try {
    const res = await request.get('/attention/selectUserInfo')
    if (res.code === 200) {
      selectUserInfo.value = res.data
    }
  }
  catch (err) {
    console.log(err)
  }
}
getAttention()
</script>

<template>
  <div class="min-h-screen bg-[#F7F8FA]">
    <div class="relative">
      <!-- 背景图片区域 -->
      <div class="h-[300px] w-full bg-[#E8F3FF]">
        <img :src="planetBg" alt="背景图片" class="w-full h-full object-cover">
      </div>

      <!-- 主要内容区域 -->
      <div class="absolute inset-x-0 top-[80px]">
        <div class="max-w-[1140px] mx-auto">
          <!-- 用户基本信息 -->
          <client-only>
            <div class="flex items-center gap-4 mb-6">
              <img :src="userStore.userInfo?.avatar" class="w-20 h-20 rounded-full" alt="头像">
              <div>
                <div class="text-lg font-medium text-[#1f2329]">
                  {{ userStore.userInfo?.nickName }}
                </div>
                <div class="flex items-center gap-6 mt-2 text-[#86909C]">
                  <div>{{ selectUserInfo.bean || 0 }} 粉丝</div>
                  <div>{{ selectUserInfo.attention || 0 }} 关注</div>
                </div>
              </div>
            </div>
          </client-only>

          <!-- 内容区域（白色背景） -->
          <div class="bg-white rounded-lg min-h-[500px] mt-8">
            <!-- 导航标签 -->
            <div class="flex border-b border-[#E5E6EB]">
              <div
                v-for="(item, index) in tabList"
                :key="index"
                class="px-6 py-3 text-[#1f2329] font-medium cursor-pointer"
                :class="{ 'text-[#3f7ef7] border-b-2 border-[#3f7ef7]': commentParams.type === item.key }"
                @click="changeTab(item.key)"
              >
                {{ item.label }}
              </div>
            </div>

            <!-- 星球分类标签 -->
            <div class="flex items-center gap-2 p-3">
              <div
                v-for="item in communityList"
                :key="item.id"
                class="px-3 py-1 text-sm rounded-lg cursor-pointer"
                :class="[
                  commentParams.communityId === item.id
                    ? 'text-white bg-[#1f2329]'
                    : 'text-[#1f2329] hover:text-white hover:bg-[#1f2329]',
                ]"
                @click="changeCommunity(item)"
              >
                {{ item.communityName }}
              </div>
            </div>
            <div v-if="isShow === 'publish'">
              <NConfigProvider>
                <NMessageProvider>
                  <PlanetComment
                    :publish-list-params="commentParams"
                  />
                </NMessageProvider>
              </NConfigProvider>
            </div>
            <div v-if="isShow === 'question'">
              <NConfigProvider>
                <NMessageProvider>
                  <PlanetQuestionComment
                    :publish-list-params="commentParams"
                  />
                </NMessageProvider>
              </NConfigProvider>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
