import React, { useEffect, useState } from "react";
import { Link } from 'react-router-dom';
import './Index.scss';

import Loadable from "react-loadable";
import Loading from "../../Loading";
import { Route, Switch } from "react-router-dom";

const Notify = Loadable({
  loader: () => import("./Notify"),
  loading: Loading,
});
const UndoEvent = Loadable({
  loader: () => import("./UndoEvent"),
  loading: Loading,
});
function Index(props){
  const username = props.match.params.username;
  const pathname = props.history.location.pathname;
  const user = props.user;
  const undo_messages = props.undo_messages;

  const [ menu , setMenu ] = useState("notify");
  const [ messages , setMessages ] = useState(0);
  const [ transferProjects , setTransferProjects ] = useState(0);

  useEffect(()=>{
    if(user){
      setTransferProjects(user.undo_transfer_projects);
    }
    if(undo_messages){
      setMessages(undo_messages);
    }
  },[user,undo_messages])

  useEffect(()=>{
    if(pathname && username){
      if(pathname === `/users/${username}/notice`){
        setMenu("notify");
      }
      if(pathname === `/users/${username}/notice/undo`){
        setMenu("undo");
      }
    }
  },[pathname])

  function fetchUser(){
    props && props.fetchUser();
  }

  function changeNum(){
    fetchUser();
  }

  return (
    <div>
      <ul className="noticeMenu">
        <li className={menu === "notify" ? "active":""}>
          <Link to={`/users/${username}/notice`} onClick={changeNum}>
            <span>通知</span>
            {messages ? <span className="unNum">{messages}</span>:""}
          </Link>
        </li>
        <li className={menu === "undo" ? "active":""}>
          <Link to={`/users/${username}/notice/undo`}>
            <span>接收仓库</span>
            {transferProjects ? <span className="unNum">{transferProjects}</span>:""}
          </Link>
        </li>
      </ul>
      <Switch>
        <Route
          path="/users/:username/notice/undo"
          render={(p) => {
            return <UndoEvent {...props} {...p} fetchUser={fetchUser}/>;
          }}
        ></Route>
        <Route
          path="/users/:username/notice"
          render={(p) => {
            return <Notify {...props} {...p} fetchUser={fetchUser}/>;
          }}
        ></Route>
      </Switch>
  </div>
  );
}
export default Index;
