import React, { useEffect, useState } from 'react';
import { AlignCenter , FlexAJ  } from '../Component/layout';
import { Link } from 'react-router-dom';
import { Popover , Spin , Button } from 'antd';
import { getImageUrl } from 'educoder';
import './Component.scss';
import { getUser } from '../GetData/getData';
import axios from 'axios';

function Contributors({contributors,owner,projectsId,currentLogin}){
  const [ menuList ,setMenuList ]= useState([]);
  const [ list , setList ]= useState(undefined);
  const [ total , setTotal ]= useState(0);
  const [ menu , setMenu ] = useState("");
  const [ login , setLogin ] = useState(undefined);
  const [ isSpin , setIsSpin ] = useState(false);

  useEffect(()=>{
    if(contributors && contributors.total_count>0){
      setTotal(contributors.total_count);
      setList(contributors.list);
    }
  },[contributors])

  useEffect(()=>{
    if(login){
      getUsers(login);
    }else{
      setMenu(undefined);
    }
  },[login])

  async function getUsers(login){
    setIsSpin(true);
    let a = menuList && menuList.filter(i=>i.login === login);
    if(a.length === 0){
      let result = await getUser(login);
      let arr = menuList;
      arr.push({...result});
      setMenuList(arr);
      setMenusFunc(result);
      setIsSpin(false);
    }else{
      setMenusFunc(a[0]);
      setIsSpin(false);
    }
  }

  function renderOrganize(list) {
    let str = "";
    list.map(i=>{
      str = str+i.name + "、";
    })
    return str && str.substr(0,str.length - 1);
  }

  function setMenusFunc(data){
    if(data){
      let ele = (
        <Spin spinning={isSpin}>
          <FlexAJ className="menuMaininfos">
            <AlignCenter>
              <Link to={`/${data.login}`}><img src={getImageUrl(`/${data.image_url}`)} alt="" className="radius" width="38px" height="38px"/></Link>
             
              <div className="ml10">
                <Link to={`/${data.login}`}>{data.name}</Link>
                { data.location && <span className="leftline">{data.location}</span> }
                {
                  data.organizations && data.organizations.length>0&&
                  <p className="task-hide" style={{maxWidth:"215px"}}>
                    所属组织：{renderOrganize(data.organizations)}
                  </p>
                }
              </div>
            </AlignCenter>
          </FlexAJ>
          <AlignCenter className="menuinfos">
            <Link to={`/${data.login}/projects`}>
              <span>{data.projects_count}</span>
              <span>项目数</span>
            </Link>
            <Link to={`/${data.login}/followers`}>
              <span>{data.followers_count}</span>
              <span>粉丝数</span>
            </Link>
            <Link to={`/${data.login}/following`}>
              <span>{data.following_count}</span>
              <span>关注数</span>
            </Link>
          </AlignCenter>
          <div className={"pb20"} style={{display:"flex",justifyContent:'center'}}>
            {
              currentLogin && (currentLogin === data.login)
              ?
              <Button className="currentBtn">当前用户</Button>
              :
              data.is_watch ? 
              <Button type={"default"} onClick={()=>FocusFunc(false,data.login)}>已关注</Button>
              :
              <Button type={"primary"} onClick={()=>FocusFunc(true,data.login)}>关注TA</Button>
            }
          </div>
        </Spin>
      )
      setMenu(ele);
    }
  }

  function FocusFunc(flag,login){
    axios({
      method: flag ? 'post' : 'delete',
      url: `/watchers/${flag ? 'follow' : 'unfollow'}.json`,
      params: {target_type: "user",id:login}
    }).then(result => {
      if (result && (result.data.status === 0 || result.data.status === 2)) {
        let a = menuList && menuList.filter(i=>i.login === login);
        if(a){
          a[0].is_watch = flag;
        }
        setMenusFunc(a[0]);
      }
    })
    .catch(error => {
      console.log(error);
    });
  }

  function renderArray(array){
    let str = "";
    for(var i = 0;i<array.length;i++){
      str += array[i].name +"、";
    }
    let substr = str.substr(0,str.length-1);
    return (<span title={substr}>{substr}</span>)
  }

  function setVisibleFunc(flag,l,index){
    if(l !== login){
      setLogin(l);
    }
    var lx = list.concat();
    lx.map(i=>i.visible =false);
    if(flag){
      lx[index].visible = flag;
    }
    lx.splice();
    setList(lx);
  }

  return(
    <div className="halfs">
      <Link to={`/${owner}/${projectsId}/contribute`} className="font-16 color-ooo hoverA">
        <span>贡献者</span>
        { contributors && contributors.total_count > 0 && <span className="infoCount">{contributors.total_count}</span>}
      </Link>
      <div className="attrPerson" onMouseLeave={()=>setVisibleFunc(false)}>
        {
          total > 0 ?
          list.map((item,key)=>{
            return(
              <Popover content={menu} visible={item.visible} overlayClassName="menuPanels" placement="top">
                <Link key={key} to={`/${item.login}`}>
                  <img src={getImageUrl(`/${item.image_url}`)} alt="" onMouseOver={()=>setVisibleFunc(true,item.login,key)}/>
                </Link>
              </Popover>
            )
          })
          :""
        }
      </div>
    </div>
  )
}
export default Contributors;