import React, { useState, useEffect } from 'react';
import { Button , Popconfirm, Empty , Pagination } from 'antd';
import styled from 'styled-components';
import { Box, Short, Long, Gap, WhiteBack, AlignCenterBetween } from '../../Component/layout';
import Tabs from '../../Component/Tabs';

import Memberlist from './GroupDetailMember';
import Grouplist from './GroupDetailProject';
import axios from 'axios';
const Leave = styled.a`{
  display:block;
  border-radius:5px;
  border:1px solid rgba(40,189,108,1);
  color:rgba(40,189,108,1);  
  padding:0px 14px;
  height:30px;
  line-height:30px;
}`;
const limit = 15;
export default ((props) => {
  const [nav, setNav] = useState('0');
  const [ page , setPage ] = useState(1);
  const [ total , setTotal ] = useState(0);
  const [ projects , setProjects ] = useState(undefined);
  const [ members , setMembers ] = useState(undefined);
  const [ group , setGroup ] = useState(undefined);
  const { OIdentifier, groupId } = props.match.params;
  const { current_user } = props;

  useEffect(()=>{
    if(groupId){
      getInit();
    }
  },[groupId]);

  function getInit(){
    const url = `/organizations/${OIdentifier}/teams/${groupId}.json`;
    axios.get(url).then(result=>{
      if(result && result.data){
        setGroup(result.data);
      }
    }).catch(error=>{})
  }

  useEffect(()=>{
    if(nav === "0"){
      getMember(OIdentifier, groupId,page);
    }else{
      get_project(OIdentifier, groupId,page);
    }
  },[nav,page])

  // 获取团队成员
  function getMember( OIdentifier, groupId, page ) {
    const url = `/organizations/${OIdentifier}/teams/${groupId}/team_users.json`;
    axios.get(url, {
      params: {
        page,
        limit
      },
    })
    .then((result) => {
      if (result && result.data) {
        setMembers(result.data.team_users);
        setTotal(result.data.total_count);
      }
    }).catch((error) => { });
  };

  // 获取团队项目
  function get_project(OIdentifier,groupId,page) {
    const url = `/organizations/${OIdentifier}/teams/${groupId}/team_projects.json`;
    axios.get(url, {
      params: {
        page,limit
      },
    }).then((result) => {
      if (result && result.data && result.data.team_projects.length > 0) {
        setProjects(result.data.team_projects);
        setTotal(result.data.total_count);
      }
    }).catch((error) => { });
  }

  // 移除成员
  function removeUser(username) {
    if (username) {
      const url = `/organizations/${OIdentifier}/teams/${groupId}/team_users/quit.json`;
      axios.delete(url).then((result) => {
        if (result && result.message==='success') {
          props.showNotification(`已成功退出团队！`); 
          props.history.push(`/${username}`);
        }
      }).catch((error) => { });
    }
  }

  return (
    <Box className="GroupSubLevel">
      <Short className="g-sub-left">
        {
          group ?
            <div>
              <AlignCenterBetween>
                <span className="color-grey-3 task-hide">{group.nickname}</span>
                {group.is_member && !group.is_admin ?
                  <Popconfirm
                    title="确认离开团队吗？"
                    onConfirm={() => removeUser(current_user.login)}
                    okText="确认"
                    cancelText="取消"
                  >
                    <Leave>离开团队</Leave>
                  </Popconfirm>
                  : ""
                }
              </AlignCenterBetween>
              <div className="g-desc">{group.description ? group.description : "暂无描述"}</div>
              <div className="g-tip">
                <p>管理员团队对 <span>所有仓库</span> 具有操作权限，且对组织具有 <span>管理员权限</span>。 </p>
                <p>此外，该团队拥有了 <span>创建仓库</span>  的权限：成员可以在组织中创建新的仓库。 </p>
                {group.is_admin ? <Button type="primary" onClick={()=>props.history.push(`/${OIdentifier}/teams/${groupId}/setting`)}><span className="color-white">团队设置</span></Button> : ""}
              </div>
            </div>
            :
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        }
      </Short>
      <Long>
        <Gap>
          <WhiteBack>
            <Tabs nav={['团队成员', '团队项目']} index={nav} onChange={setNav}>
              {
                nav === "0" ? <Memberlist data={members} current_user={props.current_user} successFunc={()=>getMember( OIdentifier, groupId, page )}/> : <Grouplist projects={projects}/>
              }
            </Tabs>
            {
              total > limit && 
              <div className="mt20 pb20 edu-txt-center">
                <Pagination simple current={page} total={total} pageSize={limit} onChange={(page)=>setPage(page)}/>
              </div>
            }
          </WhiteBack>
        </Gap>
      </Long>
    </Box>
  )
})