import React , { useEffect, useState } from 'react';
import SelectBranch from '../Branch/Select';
import Title from '../Component/Title';
import styled from 'styled-components';
import { AlignCenter , WhiteBack , FlexAJ } from '../Component/layout';
import axios from 'axios';
import { Button, Select , Pagination } from 'antd';
import { getBranch } from '../GetData/getData';

const Div = styled.div`{
  padding:20px 30px;
  min-height:500px;
}`

export default ((props)=>{
  const LIMIT = 15;
  const [ branch , setBranch ] = useState("master");
  const [ branchList , setBranchList ] = useState(undefined);
  const [ protectBranch , setProtectBranch ] = useState("master");
  const [ protectBranchList , setProtectBranchList ] = useState(undefined);

  const [ count , setCount ] = useState(0);
  const [ page , setPage ] = useState(1);
  let defaultBranch = props.defaultBranch;


  useEffect(()=>{
    if(defaultBranch){
      setBranch(defaultBranch);
      setProtectBranch(defaultBranch);
    }
  },[defaultBranch]);
  
  const { projectsId , owner } = props.match.params;
  const projectDetail = props.projectDetail;

  useEffect(()=>{
    if(defaultBranch){
      setBranch(defaultBranch);
    }
  },[defaultBranch]);

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

  // 获取已经设置过分支保护的分支列表
  function getProtectBranchList(owner,repo){
    const url = `/${owner}/${repo}/protected_branches.json`;
    axios.get(url,{
      params:{
        page,limit:LIMIT
      }
    }).then(result=>{
      if(result){
        setCount(result.data.total_count);
        setProtectBranchList(result.data.protected_branches);
      }
    }).catch(error=>{})
  }

  // 获取分支列表（下拉、过滤掉已经设置过分支保护的分支）
  async function getBranchs(id,owner){
    let re = await getBranch(id,owner);
    setBranchList(re);
  }

  // 设为默认分支
  function resetSetting(){
    const url = `/${owner}/${projectsId}.json`;
    axios.put(url, {
      default_branch:branch
    })
    .then((result) => {
      if (result) {
        props.showNotification(`分支设置成功！`);
        const { getDetail } = props;
        getDetail && getDetail();
      }
    })
    .catch((error) => {
      console.log(error);
    });
  }

  // 跳转
  function settingRule(protectBranch){
    props.history.push(`/${owner}/${projectsId}/settings/branches/${protectBranch}`);
  }

  // 翻页
  function changePageNum(page){
    setPage(page);
  }

  return(
    <WhiteBack>
      <Title><span className="font-18">分支设置</span></Title>
      <Div>
        <div className="pb20" style={{borderBottom:"1px dashed #eee"}}>
          <p className="color-grey-3 mb10 font-18">默认分支</p>
          <p className="mb10">默认分支被视作为代码库中的基本分支，是所有克隆、代码提交、合并请求的目标分支</p>
          <AlignCenter>
            <SelectBranch 
            branch={branch}
            repo_id={ projectDetail && projectDetail.repo_id}
            projectsId={projectsId} 
            changeBranch={setBranch}
            owner={owner}
            history={props.history}
            branchList = {branchList}
            tagflag={false}
            />
            <a className="color-blue ml20" onClick={()=>resetSetting()}>设为默认分支</a>
          </AlignCenter>
        </div>
        <div className="mt10">
          <p className="color-grey-3 mb10 font-18">分支保护</p>
          <AlignCenter>
            <SelectBranch 
            branch={protectBranch}
            repo_id={ projectDetail && projectDetail.repo_id}
            projectsId={projectsId} 
            changeBranch={setProtectBranch}
            owner={owner}
            history={props.history}
            branchList = {branchList}
            tagflag={false}
            />
            <a className={ protectBranchList && protectBranchList.length > 0?"color-blue ml20":"color-grey ml20"} onClick={()=>settingRule(protectBranch)}>设置分支保护</a>
          </AlignCenter>
          {
            protectBranchList && protectBranchList.length > 0 && 
            <div className="protectBranchList">
              {
                protectBranchList.map((item,key)=>{
                  return(
                    <FlexAJ>
                      <span>{item.branch_name}</span>
                      <Button onClick={()=>settingRule(item.branch_name)}>编辑</Button>
                    </FlexAJ>
                  )
                })
              }
            </div>
          }
          {
            count > LIMIT && 
            <div className="mt15 mb20" style={{textAlign:"center"}}>
              <Pagination simple current={page} pageSize={LIMIT} total={count} onChange={changePageNum}></Pagination>
            </div>
          }
        </div>
      </Div>
    </WhiteBack>
  )
})