import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import styled from 'styled-components';
import { HomeAPI } from '@/api';
import { InterListType } from '@/api/interface';
import { ForumListType } from '@/api/interface/home';
import ForumItemView from '@/components/forumItem';
import HomeTopicView from '@/components/home-comp/home-topic';
import { RootState } from '@/store';
import { setGlobalData } from '@/store/module/globalData';
import { SystemState } from '@/store/module/system';

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

const HomeForumView = () => {
  // store
  const dispatch = useDispatch();
  // system
  const system = useSelector((state: RootState) => state.system) as SystemState;
  // 论坛列表
  const [forumList, setForumList] = useState<ListType>([]);
  // 获取论坛列表
  const getForumList = async () => {
    const res = await HomeAPI.getForumList({
      pageNo: 5,
      pageSize: 10,
    });
    if (res && res.code === '200') {
      setForumList(res.result?.list || []);
      // console.log('论坛列表 --->', res.result?.list);
    }
  };
  // 页面挂载
  useEffect(() => {
    if (!system?.token) {
      dispatch(setGlobalData({ loginModalVisible: true }));
    } else {
      getForumList().then();
    }
  }, [system]);
  return (
    <HomeForumWrap>
      <div className="forum-list">
        {forumList.map((i, j) => (
          <ForumItemView key={j} detail={i} />
        ))}
      </div>
      <HomeTopicView />
    </HomeForumWrap>
  );
};

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;
  }
`;
