import React, { useEffect, useState } from 'react';
import { FlexAJ , AlignCenter } from '../../Component/layout';
import { Link } from 'react-router-dom';
import axios from 'axios';
import Box from './ConcentrateBox';

function ConcentrateProject({userLogin,current,showCompeleteDialog,completeProfile}) {
  const [ list , setList ] = useState(undefined);
  const [ visible , setVisible ] = useState(false);
  const [ value , setValue ] = useState([]);

  useEffect(()=>{
    getList();
  },[])

  function getList() {
    const url = `/users/${userLogin}/is_pinned_projects.json`;
    axios.get(url).then(result=>{
      if(result && result.data){
        let p = result.data.projects;
        setList(p);
        if(p && p.length > 0){
          let array = p.map(i=>{
            return i.project_id
          })
          setValue(array);
        }
      }
    }).catch(erroer=>{})
  }

  function onSure(is_pinned_project_ids) {
    if(is_pinned_project_ids && is_pinned_project_ids.length===0){
      setValue([]);
    }
    const url = `/users/${userLogin}/is_pinned_projects/pin.json`;
    axios.post(url,{
      is_pinned_project_ids
    }).then(result=>{
      if(result && result.data){
        setVisible(false);
        getList();
      }
    }).catch(error=>{})
  }
  return(
    <React.Fragment>
      <Box 
        visible={visible} 
        onCancel={()=>setVisible(false)} 
        onSure={onSure} 
        username={userLogin} 
        choosed={value}
        completeProfile={completeProfile}
        showCompeleteDialog={showCompeleteDialog}
      />
      {
        list && list.length>0 &&
        <div className="concentrate">
          <FlexAJ>
            <span className="font-18">精选项目</span>
            { current && <a className="color-blue" onClick={()=>setVisible(true)}>自定义精选项目</a> }
          </FlexAJ>
          <div>
            <ul className="concentrateUl">
              {
                list.map((i,k)=>{
                  return(
                    <li key={i.id}>
                      <Link to={`/${i.author && i.author.login}/${i.identifier}`} className="name">{i.name}</Link>
                      <p className="task-hide desc">{i.description}</p>
                      <AlignCenter>
                        { i.category && <span className="tagName">{i.category.name}</span> }
                        <span className="pariseCount"><i className="iconfont icon-guanzhu"></i>{i.watchers_count}</span>
                        <span className="forkCount"><i className="iconfont icon-fork"></i>{i.forked_count}</span>
                      </AlignCenter>
                    </li>
                  )
                })
              }
            </ul>
          </div>
        </div>
      }
      {
        list && list.length === 0 && current && <div className="ConcentrateTip"><i className="iconfont icon-tishi2"></i>你还没有设置精选项目，<a onClick={()=>setVisible(true)}>点击设置</a></div>
      }
    </React.Fragment>
  )
}
export default ConcentrateProject;