import React, { useEffect, useState } from 'react';
import { App, Skeleton } from 'antd';
import { useSelector } from 'react-redux';
import styled from 'styled-components';
import { HomeAPI } from '@/api';
import { InterListType, PaginationProps } from '@/api/interface';
import { ForumListType } from '@/api/interface/home';
import ForumItemView from '@/components/forumItem';
import HomeFlyerView from '@/components/home-comp/home-flyer';
import HomeTopicView from '@/components/home-comp/home-topic';
import InfiniteScrollList from '@/components/InfiniteScrollList';
import { RootState } from '@/store';
import { SystemState } from '@/store/module/system';

// 列表类型
type ListType = InterListType<ForumListType>;

const HomeForumView = () => {
  // store
  const { message } = App.useApp();
  // system
  const system = useSelector((state: RootState) => state.system) as SystemState;
  // 翻页数据
  const [pagination, setPagination] = useState<
    { totalPage: number } & PaginationProps
  >({
    pageNo: 1,
    pageSize: 10,
    totalPage: 0,
  });
  // 论坛列表
  const [forumList, setForumList] = useState<ListType>([]);
  // 获取论坛列表
  const getForumList = async () => {
    const res = await HomeAPI[system?.token ? 'getForumList' : 'getForumList1'](
      {
        pageNo: pagination.pageNo,
        pageSize: pagination.pageSize,
      },
    );
    if (res && res.code === '200') {
      const { list, totalPage, pageNo, pageSize } = res.result || {};
      setForumList((prevList) => [...prevList, ...(list || [])]);
      pagination.totalPage = totalPage;
      setPagination({ pageNo, pageSize, totalPage });
    }
  };
  // 添加 handleReachBottom 函数
  const handleReachBottom = async () => {
    if (pagination.pageNo < pagination.totalPage) {
      pagination.pageNo += 1;
      await getForumList();
    } else {
      message.success('没有更多数据了');
    }
  };
  // 页面挂载
  useEffect(() => {
    getForumList().then();
  }, []);
  return (
    <InfiniteScrollList bottomDistance={300} onReachBottom={handleReachBottom}>
      <HomeForumWrap>
        <div className="forum-list">
          {forumList
            ?.slice(0, 1)
            ?.map((i, j) => <ForumItemView key={j} detail={i} />)}
          <HomeFlyerView />
          {forumList
            ?.slice(1)
            ?.map((i, j) => <ForumItemView key={j} detail={i} />)}
          <Skeleton active avatar />
        </div>
        <HomeTopicView />
      </HomeForumWrap>
    </InfiniteScrollList>
  );
};

export default HomeForumView;
// 样式
const HomeForumWrap = styled.div`
  position: relative;
  width: 100%;
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  flex-wrap: nowrap;
  .forum-list {
    position: relative;
    width: calc(100% - 20rem - 10rem);
    margin-right: 10rem;
    box-sizing: border-box;
  }
`;
