import React, { Component } from "react";
import { Link } from "react-router-dom";
import { Button, Spin , Menu } from "antd";
import FocusButton from "../UsersList/focus_button";

import axios from "axios";
import { getImageUrl } from "educoder";
import { Route, Switch } from "react-router-dom";

import "./new_user.css";
import "../css/index.scss";
import './Index.scss';

import Loadable from "react-loadable";
import Loading from "../../Loading";

const UpdateInfo = Loadable({
  loader: () => import("./Material/Index"),
  loading: Loading,
});
const InfosDevOps = Loadable({
  loader: () => import("./devOpsCI"),
  loading: Loading,
});
const InfosDevOpsCD = Loadable({
  loader: () => import("./devOpsCD"),
  loading: Loading,
});

const Statistics = Loadable({
  loader: () => import("./Statistics/Index"),
  loading: Loading,
}); 
const GeneralView = Loadable({
  loader: () => import("./GeneralView/Index"),
  loading: Loading,
}); 
const InfosUser = Loadable({
  loader: () => import("./InfosUser"),
  loading: Loading,
});
const Organize = Loadable({
  loader: () => import("./Team"),
  loading: Loading,
});

const WatchsUser = Loadable({
  loader: () => import("./watch_users"),
  loading: Loading,
})
const FanUser = Loadable({
  loader: () => import("./fan_users"),
  loading: Loading,
})

const Notice = Loadable({
  loader: () => import("../Notice/Index"),
  loading: Loading,
})
class Infos extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isSpin: false,
      user: undefined,
      project_type: undefined,
      route_type: undefined,
      undo_events:0,
      menuKey:"0"
    };
  }

  renderPath=(pathname)=>{
    const { username } = this.props.match.params;
    if(pathname === `/users/${username}`){
      this.setState({menuKey:"0",route_type:undefined});
    }else if(pathname === `/users/${username}/statistics`){
      this.setState({menuKey:"1",route_type:undefined});
    }else if(pathname.indexOf(`/users/${username}/projects`)>-1){
      this.setState({menuKey:"2",route_type:undefined});
    }else if(pathname.indexOf(`/users/${username}/notice`)>-1){
      this.setState({menuKey:"3",route_type:undefined});
    }else if(pathname.indexOf(`/users/${username}/devops`)>-1){
      this.setState({menuKey:"4",route_type:undefined});
    }else if(pathname === `/users/${username}/organizes`){
      this.setState({menuKey:"5",route_type:undefined});
    }else if(pathname === `/users/${username}/watchers`){
      this.setState({menuKey:undefined,route_type:"watchers"});
    }else if(pathname === `/users/${username}/fan_users`){
      this.setState({menuKey:undefined,route_type:"fan_users"});
    }else{
      this.setState({menuKey:undefined,route_type:undefined});
    }
  }

  componentDidMount = () => {
    this.fetchUser();
    const { pathname } = this.props.location;
    this.renderPath(pathname);
  };

  componentDidUpdate=(prevProps)=>{
    const { username } = this.props.match.params;
    const prevUser = prevProps.match.params.username;
    if(prevUser && username && prevUser !== username){
      this.fetchUser();
    }
    const { pathname } = this.props.location;
    const prevPath = prevProps.location.pathname;
    if(prevPath && pathname && prevPath !== pathname){
      this.renderPath(pathname);
    }
    this.props.history.listen(()=>{
      if (document.body.scrollTop || document.documentElement.scrollTop > 0) {
        window.scrollTo(0, 0)
      }
    })
  }

  fetchUser = () => {
    this.setState({
      isSpin: true,
    });
    const { current_user } = this.props;
    const { username } = this.props.match.params;

    let url = `/users/${username || (current_user && current_user.login)}.json`;
    axios.get(url).then((result) => {
      let e = result.data && result.data.undo_events;
      this.setState({
        user: result.data,
        isSpin: false,
        undo_events:e
      });
    })
    .catch((error) => {
      this.setState({
        isSpin: false,
      });
    });
  };

  change_devops_type=(type)=>{
    const {user} = this.state;
    this.setState({
      project_type: type ,
      route_type: undefined
    })
    this.props.history.push(`/users/${user && user.login}/devops/${type}`);
  }

  undo_link = () => {
    const {user } = this.state;
    this.setState({
      route_type: undefined,
      project_type:"notice",
    },()=>{
      this.props.history.push(`/users/${user && user.login}/notice`);
      this.fetchUser();
    })
  }

  route_link = (type) => {
    this.setState({
      route_type: type
    })
  }

  organize_link = () => {
    const {user} = this.state
    this.setState({
      route_type: undefined,
      project_type:"organizes"
    })
    this.props.history.push(`/users/${user && user.login}/organizes`)
  }

  resetUser=()=>{
    const { resetUserInfo } = this.props;

    this.fetchUser();
    resetUserInfo && resetUserInfo();
  }

  // 修改待办事项右侧的数量
  deleteUndoEvent=(count)=>{
    let { undo_events } = this.state;
    let undo = undo_events - count;
    this.setState({
      undo_events:undo
    })
  }

  render() {
    const { current_user } = this.props;
    const { username } = this.props.match.params;
    const { user, isSpin, route_type , undo_events , menuKey } = this.state;
    return (
      <div className="newMain clearfix">
        <Spin spinning={isSpin}>
          <div className="new-content-flex">
            <div className="list-left" style={{border:"none"}}>
              <div className="bgcF">
                <div className="list-l-Menu text-center" style={{padding:"20px 25px"}}>
                  <span className="headimg">
                    <img src={getImageUrl(`/${user && user.image_url}`)} alt=""/>
                    <span>
                      {
                        user && user.gender===1?
                        <i className="iconfont icon-nan1"></i>
                        :
                        <i className="iconfont icon-nv1"></i>
                      }
                    </span>
                  </span>
                  
                  <div className="text-center mt15 font-24 task-hide" title={user && user.username}>
                    {user && user.username}
                  </div>
                  <div className="userDescription">
                    {user && user.description}
                  </div>
                  <div>
                    {user && current_user && user.login === current_user.login && (
                      <div className="user-info-star-button ">
                        <Button
                          block
                          className="text-button-grey"
                          onClick={()=>this.props.history.push(`/users/${user.login}/info`)}
                          type="primary"
                        >
                          {" "}
                          <i className="iconfont icon-shezhi4 font-15 mr5"></i>
                          修改资料
                        </Button>
                      </div>
                    )}
                    {current_user && user && user.login !== current_user.login && (
                      <div className="user-info-star-button ">
                        <FocusButton
                          is_block={true}
                          is_watch={user.is_watch}
                          id={user.login}
                          fontClass={"font-14 ml5"}
                          starText={"关注TA"}
                        />
                      </div>
                    )}
                  </div>
                  <div className="focusBox">
                    <Link
                      to={`/users/${user && user.login}/watchers`}
                      className={`with50 text-center pull-left ${route_type === "watchers" ? "text-primary" : ""}`}
                      onClick={() =>this.route_link("watchers")}
                    >
                      <div>{current_user && user && user.login === current_user.login ? "我关注的" : "TA关注的"}</div>
                      <span>{user && user.watching_count}</span>
                    </Link>
                    <Link
                      to={`/users/${user && user.login}/fan_users`}
                      onClick={() =>this.route_link("fan_users")}
                      className={`with50 text-center pull-left ${route_type === "fan_users" ? "text-primary" : ""}`}
                    >
                      <div>{current_user && user && user.login === current_user.login ? "关注我的" : "关注TA的"}</div>
                      <span>{user && user.watched_count}</span>
                    </Link>
                  </div>
                  {
                    user && (user.province || user.custom_department || user.email) ?
                    <div className="infoBox">
                      { user.province && <div><i className="iconfont icon-weizhi"></i><span>{user.province}</span><span title={user.city}>{user.city}</span></div> }
                      { user.custom_department && <div><i className="iconfont icon-danwei"></i><span title={user.custom_department}>{user.custom_department}</span></div> }
                      { user.email && <div><i className="iconfont icon-youxiangrenzheng"></i><span title={user.email}>{user.email}</span></div> }
                    </div>
                    :""
                  }
                </div>
              </div>
            </div>
            <div className="list-right">
              { !route_type && menuKey &&
                <Menu selectedKeys={[menuKey]} mode={`horizontal`} className="infosRightMenu">
                  <Menu.Item key="0"><Link to={`/users/${user && user.login}`}><i className="iconfont icon-gailan"></i>概览</Link></Menu.Item>
                  <Menu.Item key="1"><Link to={`/users/${user && user.login}/statistics`}><i className="iconfont icon-shujutongji"></i>数据统计</Link></Menu.Item>
                  <Menu.Item key="2"><Link to={`/users/${user && user.login}/projects/common`}><i className="iconfont icon-xiangmu"></i>项目</Link></Menu.Item>
                  {
                    current_user && user && user.login === current_user.login ?
                    <Menu.Item key="3">
                      <Link to={`/users/${user && user.login}/notice`}>
                        <i className="iconfont icon-daibanshixiang"></i>待办事项
                        {undo_events && undo_events >0 ? <span className="menuNum">({undo_events})</span>:""}</Link>
                      </Menu.Item>
                    :""
                  }
                  {
                    current_user && current_user.login && current_user.login === username ?
                    <Menu.Item key="4"><Link to={`/users/${user && user.login}/devops/CIService`}><i className="iconfont icon-gongzuoliu1"></i>DevOps工作流</Link></Menu.Item>
                    :""
                  }
                  <Menu.Item key="5">
                    <Link to={`/users/${user && user.login}/organizes`}>
                      <i className="iconfont icon-zuzhi"></i>组织
                      { user && user.user_org_count && user.user_org_count > 0 ? <span className="menuNum">({user.user_org_count})</span>:""}
                    </Link>
                  </Menu.Item>
                </Menu>
              }
              {user && (
              <Switch {...this.props}>
                <Route
                    path="/users/:username/watchers"
                    render={() => {
                      return <WatchsUser {...this.props} {...this.state} userType="watchers" fetchUser={this.fetchUser}/>;
                    }}
                  ></Route>
                  <Route
                    path="/users/:username/notice"
                    render={() => {
                      return <Notice {...this.props} {...this.state} deleteUndoEvent={this.deleteUndoEvent}/>;
                    }}
                  ></Route>
                  <Route
                    path="/users/:username/fan_users"
                    render={() => {
                      return <FanUser {...this.props} {...this.state} userType="fan_users" fetchUser={this.fetchUser}/>;
                    }}
                  ></Route>
                  <Route
                    path="/users/:username/devops/CDService"
                    render={() => {
                      return <InfosDevOpsCD {...this.props} {...this.state} />;
                    }}
                  ></Route>
                  <Route
                    path="/users/:username/devops/CIService"
                    render={() => {
                      return <InfosDevOps {...this.props} {...this.state} />;
                    }}
                  ></Route>
                  <Route
                    path="/users/:username/projects/:project_type"
                    render={() => {
                      return <InfosUser {...this.props} {...this.state} />;
                    }}
                  ></Route>
                  <Route
                    path="/users/:username/organizes"
                    render={() => {
                      return <Organize {...this.props} {...this.state} />;
                    }}
                  ></Route>
                  <Route
                    path="/users/:username/info"
                    render={() => {
                      return <UpdateInfo {...this.props} {...this.state} resetUser={this.resetUser}/>;
                    }}
                  ></Route>
                  <Route
                    path="/users/:username/password"
                    render={() => {
                      return <UpdateInfo {...this.props} {...this.state}/>;
                    }}
                  ></Route>

                  <Route
                    path="/users/:username/statistics"
                    render={(props) => {
                      return <Statistics {...this.props} {...this.state} />;
                    }}
                  ></Route>
                  <Route
                    path="/users/:username"
                    render={(props) => {
                      return <GeneralView {...this.props} {...this.state} />;
                    }}
                  ></Route>
                  <Route
                    path="/"
                    render={(props) => {
                      return <GeneralView {...this.props} {...this.state} />;
                    }}
                  ></Route>
                </Switch>
              )}
            </div>
          </div>
        </Spin>
      </div>
    );
  }
}
export default Infos;
