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

function Contributors({contributors,owner,projectsId}){
  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 setMenusFunc(data){
    if(data){
      let ele = (
        <Spin spinning={isSpin}>
          <FlexAJ>
            <AlignCenter>
              <Link to={`/users/${data.login}`}><img src={getImageUrl(`/${data.image_url}`)} alt="" className="radius" width="38px" height="38px"/></Link>
              <Link to={`/users/${data.login}`} className="ml10">{data.name}</Link>
            </AlignCenter>
            {
              data.is_watch ? <a className="color-grey-9" onClick={()=>FocusFunc(false,data.login)}>取消关注</a>:<a className="color-blue" onClick={()=>FocusFunc(true,data.login)}>关注</a>
            }
          </FlexAJ>
          <AlignCenter className="menuinfos">
            <a href={data.projects_url}>
              <span>{data.projects_count}</span>
              <span>项目数</span>
            </a>
            <a href={data.followers_url}>
              <span>{data.followers_count}</span>
              <span>粉丝数</span>
            </a>
            <a href={data.following_url}>
              <span>{data.following_count}</span>
              <span>关注数</span>
            </a>
          </AlignCenter>
          {
            data.organizations && data.organizations.length > 0 ?
            <AlignCenter className="font-12 pt4 pb4">
              <span>所属组织：</span>
              <div className="task-hide flex1">
                {renderArray(data.organizations)}
              </div>
            </AlignCenter>
            :""
          }
          {
            data.location && <AlignCenter className="font-12 pt4 pb4"><span>所在地址:</span><span className="ml5">{data.location}</span></AlignCenter>
          }
        </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">
      <FlexAJ>
        <AlignCenter><span className="font-16 color-grey-6">贡献者</span>{ contributors && contributors.total_count > 0 && <span className="infoCount">{contributors.total_count}</span>}</AlignCenter>
        <Link className="font-12 color-grey-9" to={`/projects/${owner}/${projectsId}/contribute`}>全部</Link>
      </FlexAJ>
      <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={`/users/${item.login}`}>
                  <img src={getImageUrl(`/${item.image_url}`)} alt="" onMouseOver={()=>setVisibleFunc(true,item.login,key)}/>
                </Link>
              </Popover>
            )
          })
          :""
        }
      </div>
    </div>
  )
}
export default Contributors;