import React , { useState , useEffect } from 'react';
import { Input , Spin , Menu } from 'antd';
import { getBranch , getTag } from '../GetData/getData';

function SelectOverlay({ changeBranch , tagflag , projectsId , owner , visible }) {
  const [ inputValue , setInputValue] = useState(undefined);
  const [ nav , setNav ] = useState(0);
  const [ isSpin , setIsSpin ] = useState(true);

  const [ data , setData ] = useState(undefined);
  const [ datas , setDatas ] = useState(undefined);
  const [ keys ,setKeys] = useState("branch");

  useEffect(()=>{
    if(visible){
      setKeys("branch");
      getBranchs(projectsId,owner);
      setIsSpin(true);
    }
  },[visible])

  async function getBranchs(id,owner){
    let result = await getBranch(id,owner);
    setData(result);
    setDatas(result);
    setIsSpin(false);
  }
  async function getTags(id,owner){
    let result = await getTag(id,owner);
    setData(result);
    setDatas(result && result.tags);
    setIsSpin(false);
  }
  function chooseitem(value){
    changeBranch(value);
  }
  function changeInputValue(e){
    setInputValue(e.target.value);
    let filter = e.target.value ? data && data.length>0 && data.filter(item=>item.name.indexOf(e.target.value)>-1) : data;
    setDatas(filter);
  }

  function changeNav(e){
    setKeys(e.key);
    setIsSpin(true);
    if(e.key === "branch"){
      getBranchs(projectsId,owner);
      setNav(0);
    }else{
      getTags(projectsId,owner);
      setNav(1);
    }
  }

  return(
    <div className="overlayBranch">
      <div className="padding15" style={{paddingBottom:"0px"}}>
        <Input 
          prefix={<i className="iconfont icon-sousuo_icon1 font-14"></i>}
          placeholder={`请输入分支${tagflag ? "或标签" :""}名称搜索`}
          autocomplete="off" className="OptionsInput" 
          value={inputValue} 
          onChange={changeInputValue}
        />
      </div>
      <Menu mode="horizontal" className="navUl" selectedKeys={[keys]} onClick={changeNav}>
        <Menu.Item key={"branch"}>分支</Menu.Item>
        { tagflag && <Menu.Item key={"tag"}>标签</Menu.Item> }
      </Menu>
      <Spin spinning={isSpin}>
        <ul className="OptionsUl" id="ul-btn">
          {
            datas && datas.length>0 &&
            datas.map((item,key)=>{
              return(
                <li key={key} onClick={()=>chooseitem(item.name)}><a className="task-hide ulALink">{item.name}</a></li>
              )
            })
           
          }
          {
            datas && datas.length === 0 &&
            <p className="listTips">暂无{inputValue}{nav === 0 ?"分支":"标签"}~</p>
          }
        </ul>
      </Spin>
    </div>
  )
}
export default SelectOverlay;