import React , { useState , useEffect , useRef } from 'react';
import { Dropdown} from 'antd';
import './branch.scss';
import SelectOverlay from './SelectOverlay';
import { findDOMNode } from 'react-dom';

export default (({ projectsId , branch , owner , changeBranch , branchList , tagflag = true })=>{
  const [ showValue , setShowValue ] = useState(branch);
  const [ visible , setVisible ] = useState(false);

  const refFa = useRef(null);
  const refBox = useRef(null);

  useEffect(() => {
    document.addEventListener('click', clickMe , false);
  }, [])

  const clickMe = ({ target }) => {
    // 查找父组件
    const faComponent = findDOMNode(refFa.current);
    const boxComponent = findDOMNode(refBox.current);

    if (faComponent && boxComponent) {
      const isChild = faComponent.contains(target);
      const isBox = boxComponent.contains(target);
      if(!isChild && !isBox){
        setVisible(false);
      }
    }
  }

  useEffect(()=>{
    setShowValue(branch);
  },[branch])

  function ChangeB(params) {
    setVisible(false);
    changeBranch(params);
  }

  const menu = (
    <div ref={refFa}>
      <SelectOverlay 
        visible={visible}
        changeBranch={ChangeB} 
        tagflag={tagflag} 
        projectsId={projectsId}
        owner={owner}
        branchList={branchList}
      />
    </div>
  );
  return(
    <Dropdown placement='bottomLeft' visible={visible} overlay={menu} overlayClassName="branch-tagBox-list" trigger={['click']} >
      <div className="branch-tagBox" ref={refBox} onClick={()=>setVisible(visible ? false : true)}>
        {/* {nav === 0 ?"分支":"标签"} */}
        <span className="color-grey-9 mr3 ml8"><i className="iconfont icon-fenzhi2 font-18"></i></span>
        <span className="ant-dropdown-link task-hide" style={{fontWeight:"500",minWidth:"45px",maxWidth:"270px"}}>
          {showValue}
        </span>
        <i className="showtag iconfont icon-sanjiaoxing-down font-15 color-grey-9 mr5 ml5 mt1" />
      </div>
    </Dropdown>
  )
})