import React, { Component } from "react";
import { Link } from "react-router-dom";
import { 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 Avatar from './Avatar/Index';

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,
})
const Personal = Loadable({
  loader: () => import("./Personal/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:"6",
      avatarVisible:false
    };
  }

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

  componentDidMount = () => {
    this.fetchUser();
    document.title = "个人中心";
  };

  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;
    const { pathname } = this.props.location;
    const { notice } = this.state;

    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
      });
      const { pathname } = this.props.location;
      this.renderPath(pathname,result.data);
    })
  }

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

  undo_link = () => {
    const {user } = this.state;
    this.setState({
      route_type: undefined,
      project_type:"notice",
    },()=>{
      this.props.history.push(`/${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(`/${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
    })
  }

  onCancelAvatar=(reset)=>{
    this.setState({
      avatarVisible:false
    })
    if(reset){
      const { menuKey } = this.state;
      if(menuKey === "2" || menuKey === "3"){
        window.location.reload();
      }else{
        this.fetchUser();
        const { resetUserInfo } = this.props;
        resetUserInfo && resetUserInfo();
      }
    }
  }

  chooseTab =(key)=>{
    this.setState({
      menuKey:key
    })
  }

  aboutDescFunc =(flag)=>{
    const { user } = this.state;
    const url = `/users/${user && user.login}.json`;
    const params={
      user: {
        user_extension_attributes: {
          show_super_description:flag
        }
      }
    }
    axios.put(url,params).then(result=>{
      if(result && result.data){
        this.fetchUser();
      }
    })
  }

  render() {
    const { current_user } = this.props;
    const { username } = this.props.match.params;
    const { user, isSpin, route_type , undo_events , menuKey , avatarVisible } = this.state;
    return (
      <div className="newMain clearfix">
        {
          avatarVisible && 
          <Avatar 
            onCancel={this.onCancelAvatar}
            avatarImg={getImageUrl(`/${user && user.image_url}`)}
            login={current_user && current_user.login}
          />
        }
        <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"}}>
                  <div className="headimg-div">
                    <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>
                    {
                      current_user && current_user.login && current_user.login === username ?
                      <span className="updateAvatar" onClick={()=>{this.setState({avatarVisible:true})}}>修改头像</span>
                      :""
                    }
                  </div>
                  <div className="text-center mt15 font-24 task-hide" title={user && user.username}>
                    {user && user.username}
                  </div>
                  <div className="userDescription">
                    {user && user.description}
                  </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(`/${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"}
                        notReset={true}
                      />
                    </div>
                  )}
                  {
                    current_user && user && user.login === current_user.login &&
                    <div className="usersDesc">
                      <p>想全方位展示自己？试试点击下方按钮定制化您的专属个人简介吧！</p>
                      {
                        user.show_super_description ? <a className="emptyBtn" onClick={()=>this.aboutDescFunc(false)}>隐藏个人简介</a> : <a className="fullBtn" onClick={()=>this.aboutDescFunc(true)}>展示个人简介</a>
                      }
                    </div>
                  }   
                  <div className="focusBox">
                    <Link
                      to={`/${user && user.login}/following`}
                      className={`with50 text-center pull-left ${route_type === "following" ? "text-primary" : ""}`}
                      onClick={() =>this.route_link("following")}
                    >
                      <div>{current_user && user && user.login === current_user.login ? "我关注的" : "TA关注的"}</div>
                      <span>{user && user.watching_count}</span>
                    </Link>
                    <Link
                      to={`/${user && user.login}/followers`}
                      onClick={() =>this.route_link("followers")}
                      className={`with50 text-center pull-left ${route_type === "followers" ? "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>
              {/* {current_user && user && user.login === current_user.login ? (
                <div className="bgcF">
                  <div className="list-l-Menu">
                    <li className={project_type && project_type === "notice" ? "active" : ""}>
                      <p onClick={() => this.undo_link()}>
                        <span className="font-16 color-grey-3">
                          <i className="iconfont icon-dahuizhongzuo3x font-15 mr5"></i>
                          待办事项
                        </span>
                        <span className="text-yellow font-16">
                          {user.undo_events}
                        </span>
                      </p>
                    </li>
                  </div>
                </div>
              ):""}
              
              <div className="bgcF">
                <ul className="list-l-Menu">
                  <li className="MenuTitle" onClick={() => this.change_project_type(undefined)}>
                    <i className="iconfont icon-xiangmuleixing font-15 mr5"></i>
                    项目类型
                    <i className="iconfont icon-youjiantou font-15 mr20 color-grey-9 pull-right"></i>
                  </li>
                  <li className={project_type && project_type === "common" ? "active" : ""}  onClick={() => this.change_project_type("common")}>
                    <p>
                      <span className="font-16">开源托管项目</span>
                      <span className="color-blue">
                        {user && user.common_projects_count}
                      </span>
                    </p>
                  </li>
                  <li className={project_type && project_type === "mirror" ? "active" : ""}  onClick={() => this.change_project_type("mirror")}>
                    <p>
                      <span className="font-16">开源镜像项目</span>
                      <span className="color-blue">
                        {user && user.mirror_projects_count}
                      </span>
                    </p>
                  </li>
                  <li className={project_type && project_type === "sync_mirror" ? "active" : ""}  onClick={() => this.change_project_type("sync_mirror")}>
                    <p>
                      <span className="font-16">镜像托管项目</span>
                      <span className="color-blue">
                        {user && user.sync_mirror_projects_count}
                      </span>
                    </p>
                  </li>
                </ul>
              </div>
              {
                current_user && current_user.login && current_user.login === username &&
                <div className="bgcF">
                  <ul className="list-l-Menu">
                    <li className="MenuTitle">
                      <i className="iconfont icon-gongzuoliu font-15 mr5"></i>
                      DevOps工作流
                      <i className="iconfont icon-youjiantou font-15 mr20 color-grey-9 pull-right"></i>
                    </li>
                    <li className={project_type && project_type === "CIService" ? "active" : ""}  onClick={() => this.change_devops_type("CIService")}>
                      <p>
                        <span className="font-16 color-grey-3">CI服务</span>
                      </p>
                    </li>
                  </ul>
                </div>
              }
              <div className="bgcF">
                <div className="list-l-Menu">
                  <li className={project_type && project_type === "organizes" ? "active" : ""}>
                    <p onClick={() => this.organize_link()} >
                      <span className="font-16 color-grey-3">
                        <i className="iconfont icon-itsm-liuchengguanli font-15 mr5"></i>
                        组织
                      </span>
                      <span className="color-blue font-16">
                        {user && user.user_org_count}
                      </span>
                    </p>
                  </li>
                </div>
              </div> */}
            </div>
            <div className="list-right">
              { !route_type && menuKey &&
                <Menu selectedKeys={[menuKey]} mode={`horizontal`} className="infosRightMenu">
                  {
                    user && user.show_super_description &&
                    <Menu.Item key="6"><Link to={`/${user && user.login}`} onClick={()=>this.chooseTab("6")}><i className="iconfont icon-personal-center font-20"></i>个人简介</Link></Menu.Item>
                  }
                  <Menu.Item key="0"><Link to={`/${user && user.login}`} onClick={()=>this.chooseTab("0")}><i className="iconfont icon-gailan"></i>活动概览</Link></Menu.Item>
                  <Menu.Item key="1"><Link to={`/${user && user.login}/statistics`}><i className="iconfont icon-shujutongji"></i>数据统计</Link></Menu.Item>
                  <Menu.Item key="2"><Link to={`/${user && user.login}/projects`}><i className="iconfont icon-xiangmu"></i>参与项目</Link></Menu.Item>
                  {
                    current_user && user && user.login === current_user.login ?
                    <Menu.Item key="3">
                      <Link to={`/${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={`/${user && user.login}/devops/CIService`}><i className="iconfont icon-gongzuoliu1"></i>DevOps引擎</Link></Menu.Item>
                    :""
                  }
                  <Menu.Item key="5">
                    <Link to={`/${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="/:username/following"
                    render={() => {
                      return <WatchsUser {...this.props} {...this.state} userType="watchers" fetchUser={this.fetchUser}/>;
                    }}
                  ></Route>
                  <Route
                    path="/:username/notice"
                    render={() => {
                      return <Notice {...this.props} {...this.state} deleteUndoEvent={this.deleteUndoEvent}/>;
                    }}
                  ></Route>
                  <Route
                    path="/:username/followers"
                    render={() => {
                      return <FanUser {...this.props} {...this.state} userType="fan_users" fetchUser={this.fetchUser}/>;
                    }}
                  ></Route>
                  <Route
                    path="/:username/devops/CDService"
                    render={() => {
                      return <InfosDevOpsCD {...this.props} {...this.state} />;
                    }}
                  ></Route>
                  <Route
                    path="/:username/devops/CIService"
                    render={() => {
                      return <InfosDevOps {...this.props} {...this.state} />;
                    }}
                  ></Route>
                  <Route
                    path="/:username/projects"    // /:project_type
                    render={() => {
                      return <InfosUser {...this.props} {...this.state} />;
                    }}
                  ></Route>
                  <Route
                    path="/:username/organizes"
                    render={() => {
                      return <Organize {...this.props} {...this.state} />;
                    }}
                  ></Route>
                  {/* <Route
                    path="/:username/info"
                    render={() => {
                      return <UpdateInfo {...this.props} {...this.state} resetUser={this.resetUser}/>;
                    }}
                  ></Route> */}
                  {/* <Route
                    path="/:username/password"
                    render={() => {
                      return <UpdateInfo {...this.props} {...this.state}/>;
                    }}
                  ></Route> */}

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