import React,{useState, useEffect, useRef, useImperativeHandle,forwardRef} from 'react';
import { Dropdown } from 'antd';
import { findDOMNode } from 'react-dom';

function Drop({overlay , children , placement, overlayClassName},ref){
  const [ visible , setVisible ] = useState(false);
  const refFa = useRef(null);
  const refBox = useRef(null);

  useImperativeHandle(ref, () => ({
    clearVisible: (v) => {
      // 父组件按钮：清除筛选条件，将dropmenu里的choose字段全部改为0
      setVisible(v);
    }
  }))

  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);
      }
    }
  }
  return(
    <Dropdown 
      placement={placement} 
      visible={visible} 
      overlay={<div ref={refFa}>{overlay}</div>} 
      trigger={['click']}
      overlayClassName={overlayClassName}
    >
      <span className="dropspan" ref={refBox} onClick={()=>setVisible(visible ? false : true)}>
        {children}
      </span>
    </Dropdown>
  )
}
export default forwardRef(Drop);