<script setup lang="ts">
import type { ExperimentDiscussType } from '../types'
import { Loading } from '@element-plus/icons-vue'
import { useInfiniteScroll } from '@vueuse/core'
import DiscussItem from './DiscussItem.vue'
import { getExperimentDiscussList } from '../api'

const DiscussPublish = defineAsyncComponent(() => import('./DiscussPublish.vue'))
interface Props {
  competition_id: string
}
const props = defineProps<Props>()
const params = reactive({ tag: 1, page: 1, 'per-page': 10 })
let list = $ref<ExperimentDiscussType[]>([])
let hasMore = $ref(false)
let isLoading = $ref(false)
function fetchInfo(isForce = false) {
  if (!props.competition_id) return
  if (isForce) {
    params.page = 1
  }
  isLoading = true
  getExperimentDiscussList({ ...params, competition_id: props.competition_id })
    .then(res => {
      list = isForce ? res.data.list : [...list, ...res.data.list]
      hasMore = !!res.data.list.length
    })
    .finally(() => {
      isLoading = false
    })
}
watch(
  () => props.competition_id,
  () => {
    fetchInfo(true)
  },
  { immediate: true }
)

const isEmpty = $computed(() => {
  return !props.competition_id || !list.length
})

// 滚动加载
const scrollRef = ref<HTMLElement>()
useInfiniteScroll(
  scrollRef,
  () => {
    if (!hasMore || isLoading) return
    params.page++
    fetchInfo()
  },
  { distance: 10 }
)
</script>

<template>
  <div class="discuss">
    <el-radio-group size="small" v-model="params.tag" @change="fetchInfo(true)">
      <el-radio :label="1">我的话题</el-radio>
      <!-- <el-radio :label="2">我回复的</el-radio>
      <el-radio :label="3">我的小组</el-radio>
      <el-radio :label="4">我的班级</el-radio> -->
    </el-radio-group>
    <!-- 发表新话题 -->
    <DiscussPublish :competition_id="competition_id" @update="fetchInfo(true)" v-if="competition_id"></DiscussPublish>
    <el-empty description="暂无数据" v-if="isEmpty" />
    <template v-else>
      <div class="discuss-scroll" ref="scrollRef">
        <DiscussItem v-for="item in list" :key="item.id" :data="item" @update="fetchInfo(true)"></DiscussItem>
        <div class="tips" v-if="isLoading">
          <el-icon class="is-loading">
            <Loading />
          </el-icon>
          加载中...
        </div>
        <div class="tips" v-if="!hasMore">没有更多了</div>
      </div>
    </template>
  </div>
</template>

<style lang="scss" scoped>
.discuss {
  display: flex;
  height: 100%;
  flex-direction: column;
  .el-radio {
    margin-right: 12px;
  }
}
.discuss-scroll {
  flex: 1;
  overflow-y: auto;
}
.tips {
  padding: 40px;
  color: #555;
  text-align: center;
}
.el-icon.is-loading {
  animation: rotating 2s linear infinite;
}
</style>
