import React, { useEffect, useState } from "react";
import axios from "axios";
import { PagenationDiv } from "../css/projects";
import { Spin, Empty, Pagination } from "antd";
import ForumSections from "./SelectTitle";
import { SelectSection } from "../css/layout";
import ListItem from "../../forums/Component/ListItem";
import RepliesMemos from "./Replies";

function memos(props) {
  const user_login = props.match.params.login;
  const [is_current_uesr, setIsCurrentUser] = useState(false);
  const [memos, getMemos] = useState([]);
  const [memosSize, setMemosSize] = useState(0);
  const [page, setListPage] = useState(1);
  const [memo_type, setMemoType] = useState(null);
  const [limit, setLimitType] = useState(15);
  const [isSpin, setSpinType] = useState(false);
  const [common_select, setCommonSelect] = useState(null);
  useEffect(() => {
    let memos_type = props.location.pathname.split("/")
    setMemoType(memos_type.pop());
  }, [props.location]);

  useEffect(() => {
    if(memo_type){
      init();
    }
  }, [memo_type, common_select, page]);

  async function init() {
    setSpinType(true);

    let url = `/my_memos/${user_login}/memos.json`;
    axios.get(url, {
      params: {
        ...common_select,
        limit,
        memo_type,
        page,
      },
    }).then((result) => {
      if (result) {
        getMemos(result.data.memos);
        setMemosSize(result.data.memos_count);
        setIsCurrentUser(result.data.is_current_user);
      }
      setSpinType(false);
    })
    .catch((e) => {
      setSpinType(false);
      console.log(e);
    });
  }

  function select_memos(target_params) {
    setCommonSelect(target_params);
  }
  const handleChangePage = (page) => {
    setListPage(page);
  };

  return (
    <div>
      {is_current_uesr && (
        <div>
          <ForumSections select_memos={select_memos}></ForumSections>
          <div className="color-grey font-12 mt15">共{memosSize}个帖子</div>
        </div>
      )}
      <SelectSection>
        <Spin spinning={isSpin}>
          {memos && memos.length > 0 ? (
            <div>
               {memo_type === "replies" ? 
               <RepliesMemos memos={memos}></RepliesMemos> : 
               <ListItem memos={memos} calbackFunc={init} confirm={props.confirm} current_user={props.current_user}></ListItem>}
            </div>
          ) : (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              className="pd100"
            ></Empty>
          )}
        </Spin>
      </SelectSection>
      {memosSize > limit && (
        <PagenationDiv>
          <Pagination
            showQuickJumper
            current={page}
            onChange={handleChangePage}
            total={memosSize}
            pageSize={limit}
          />
        </PagenationDiv>
      )}
    </div>
  );
}
export default memos;
