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 Apply = Loadable({
  loader: () => import("./Apply"),
  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("undo");
  const [ messagesCount , setMessagesCount ] = useState(0);
  const [ transferCount , setTransferCount ] = useState(0);
  const [ applyCount , setApplyCount ] = useState(0);

  const [ flag , setFlag ] = useState(true);
  const { current_user } = props;

  useEffect(()=>{
    if((username && current_user && (current_user.login !== username))){
      props.history.push(`/${username}`);
    }
  },[current_user,username])

  useEffect(()=>{
    if(user){
      setTransferCount(user.undo_transfer_projects);
      setApplyCount(user.undo_join_projects);
      setMessagesCount(user.undo_messages);
    }
  },[user])

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

  function changeNum(){
    if(flag){
      messagesCount && props.deleteUndoEvent(messagesCount);
      setFlag(false);
    }
  }

  function deleteEvent(type,count) {
    let c = count;
    if(type==="apply"){
      setApplyCount(applyCount-count);
    }else if(type==="undo"){
      setTransferCount(transferCount-count);
    }else{
      setMessagesCount(0);
      c = messagesCount;
    }
    (c || c===0) && props.deleteUndoEvent(c);
  }

  return (
    <div>
      <ul className="noticeMenu">
        <li className={menu === "undo" ? "active":""}>
          <Link to={`/${username}/notice`}>
            <span>接收仓库</span>
            {transferCount ? <span className="unNum">{transferCount}</span>:""}
          </Link>
        </li>
        <li className={menu === "apply" ? "active":""}>
          <Link to={`/${username}/notice/apply`}>
            <span>成员申请</span>
            {applyCount ? <span className="unNum">{applyCount}</span>:""}
          </Link>
        </li>
      </ul>
      <Switch>
        <Route
          path="/:username/notice/apply"
          render={(p) => {
            return <Apply {...props} {...p} deleteEvent={deleteEvent}/>;
          }}
        ></Route>
        <Route
          path="/:username/notice"
          render={(p) => {
            return <UndoEvent {...props} {...p} deleteEvent={deleteEvent}/>;
          }}
        ></Route>
      </Switch>
  </div>
  );
}
export default Index;
