import React , { useState, useEffect } from 'react';
import { Link } from "react-router-dom";
import { Dropdown , Menu , Icon , Tooltip , Spin } from 'antd';
import { truncateCommitId } from '../common/util';
import { getBranch } from '../GetData/getData';

import './list.css';

export default ((props)=>{
  const [ data , setData ] =useState(undefined);
  const [ isSpin , setIsSpin ] =useState(true);

  const { projectsId , owner } = props.match.params;

  useEffect(()=>{
    getBranchs(projectsId, owner);
  },[projectsId])

  async function getBranchs(id,owner){
    let result = await getBranch(id,owner);
    setData(result);
    setIsSpin(false);
  }

  const list =()=>{
    if(data && data.length>0){
      return(
        <React.Fragment>
        <ul className="branchUl">
          {
            data.map((item,key)=>{
              return(
                <li key={key}>
                  <div>
                    <Link to={`/projects/${owner}/${projectsId}?branch=${item.name}`} className="color-blue font-15" style={{"maxWidth":"100px"}}>{item.name}</Link>
                    <p className="f-wrap-alignCenter mt15">
                      <span className="mr5 commitKey" style={{marginLeft:0}}>{item.last_commit && truncateCommitId(item.last_commit.sha)}</span>
                      <span className="color-grey-3 hide-1 messages leftPoint">{item.last_commit && item.last_commit.message}</span>
                      <span className="color-grey-8 ml30">最后更新于{item.last_commit && item.last_commit.time_from_now}</span>
                    </p>
                  </div>
                  <span>
                    <Link to={`/projects/${owner}/${projectsId}/pulls/new`} className="mr20 color-blue mr30">创建合并请求</Link>
                    <Dropdown overlay={menu(item.zip_url,item.tar_url)} trigger={['click']} placement="bottomRight" className="color-green-file">
                      <a className="ant-dropdown-link">
                        <Tooltip title={`下载分支${item.name}`}><Icon type="cloud-download" className="font-18"/></Tooltip>
                      </a>
                    </Dropdown>
                  </span>
                </li>
              )
            })
          }
        </ul>
        </React.Fragment>
      )
    }
  }
  const menu =(zip_url,tar_url)=> (
    <Menu>
      <Menu.Item key={'0'}><a href={zip_url}>ZIP</a></Menu.Item>
      <Menu.Item key={'1'}><a href={tar_url}>TAR.GZ</a></Menu.Item>
    </Menu>
  )
  return(
    <React.Fragment>
      <div className="main">
        <Spin spinning={isSpin}>
          <div className="branchTable">
            <p className="branchTitle bor-bottom-greyE">分支列表</p>
            {list()}
          </div>
        </Spin>
      </div>
    </React.Fragment>
  )
})


    
