import React ,{ useState , useEffect , useRef , forwardRef } from 'react';
import { findDOMNode } from 'react-dom';
import { Dropdown , Menu , Input , Button, Form , Tooltip } from 'antd';
import { getImageUrl } from 'educoder';
import AddTagsBox from './addTagsBox';

const { Search } = Input;
/**
 * 
 * @param {placeholder} placeholder:默认显示内容（为空时） 
 * @param {editFlag} editFlag:是否有编辑权限
 * @param {searchFlag} searchFlag:是否显示搜索框
 * @param {selectValueList} selectValueList:将选中的list保存
 * @param {searchFunc} searchFunc:搜索方法
 * @param {onAdd} onAdd:标记管理
 * @param {headImg} headImg:是否显示头像
 * @param {menus} menus:下拉列表
 * @param {chooseFunc} chooseFunc:选择下拉列表
 * @param {double} double:undefined为单选，有值就是最多选的数量
 * @param {colorFlag} colorFlag:选中值需根据颜色显示背景
 * @param {mustFlag} mustFlag:必须选择一个
 * @param {removeFlag} removeFlag:移除按钮
 * @returns 
 */
function ChooseMenu({
  placeholder ="未设置",
  editFlag,
  searchFlag,
  selectValueList,
  searchFunc,
  onAdd,
  headImg,
  menus,
  auto,
  chooseFunc,double,colorFlag,mustFlag,removeFlag,owner,projectsId
}){
  const [ visible , setVisible ] = useState(false);
  const [ searchValue , setSearchValue ]= useState(undefined);
  const [ valuesId , setValuesId ] = useState([]);
  const [ count , setCount ] = useState(double);
  const [ content , setContent ] = useState(false);

  const [ saveList , setSaveList ] = useState(undefined);

  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);
      const arr = ["removeicon","iconfont icon-guanbi font-12 color-white","iconfont icon-guanbi font-12 color-blue","icon-a-bianji12","color-blue font-15 tagManage","iconfont icon-xiangzuojiantou font-15 color-grey mr5 cursor","cover","ant-btn cancelTags"];
      const pointer = arr.includes(target.className);
      if(!isChild && !isBox && !pointer){
        setVisible(false);
        setContent(false);
      }
    }
  }

  // 根据选中的列表循环出id数组
  useEffect(()=>{
    if(selectValueList && selectValueList.length > 0 && visible ){
      renderSelectList(selectValueList);
      setSaveList(selectValueList);
      setCount(selectValueList.length);
    }else{
      setValuesId([]);
      setCount(0);
      setSaveList(undefined);
    }
    if(!visible){
      setSearchValue(undefined);
      searchFunc(undefined);
    }
  },[selectValueList,visible])

  function renderSelectList(list){
    let a = list && list.length > 0 && list.map((i,k)=>{
      return i.id ? i.id.toString() : i.name
    })
    setValuesId(a);
  }

  // 搜索
  function changeSearchvalue(e){
    setSearchValue(e.target.value);
    searchFunc(e.target.value);
  }
  function renderNames(nameArrs){
    return <React.Fragment>
      {
        nameArrs && nameArrs.length>0?
          nameArrs.map((i,k)=>{
            return(
              <p style={{display:"flex",alignItems:"center"}} className={removeFlag?"removeFlag":''}>
                {i.image_url && <img src={getImageUrl(i.image_url)} alt="" width="28px" height="28px" style={{borderRadius:"50%",marginTop:"5px"}} className="mr5"/>}
                {
                  colorFlag ?
                  (
                    colorFlag === "2" ?
                    <span className={"colorsquare task-hide"} style={{backgroundColor:`${i.color || "#000"}`,paddingRight:"18px"}}>
                      {i.name}
                    </span>
                    :
                    <span className={"colorsborder task-hide"} style={{borderColor:`${i.color}`,color:`${i.color}`}}>{i.name}</span>
                  )
                  :
                  <span className={"task-hide"}>{i.name}</span>
                }
                { !colorFlag && removeFlag && <a className="removeicon" onClick={()=>removeValueFunc(i.id)}><i className="iconfont icon-shanchu8 font-14"></i></a>}
                { colorFlag && removeFlag && <a className="removeicon" onClick={()=>removeValueFunc(i.id)} style={{display:'block',right:"19px",position:"absolute"}}><i className="iconfont icon-guanbi font-12 color-white"></i></a>}
              </p>
            )
          })
        :<span>{placeholder}</span>
      }
    </React.Fragment>
  }

  // 选择项
  function chooseMenu(i){
    let list =  saveList && saveList.length > 0 ? [...saveList]:[] ;
    let relist = [];
    relist = list && list.length > 0 ? list:[];
    let filter = [];
    if(i.id){
      filter = list.filter(j=>j.id === i.id);
    }else{
      filter = list.filter(j=>j.name === i.name);
    }
    if(filter && filter.length > 0){
      if(i.id){
        relist = list.filter(j=>j.id !== i.id);
      }else{
        relist = list.filter(j=>j.name !== i.name);
      }
    }else{
      if(double && (saveList && saveList.length >= double)){
        setCount(-1);
        return;
      }
      if(double){
        relist.push(i);
      }else{
        relist = [i];
      }
    }
    renderSelectList(relist);
    setSaveList(relist);
    setCount(relist ? relist.length :0);
    if(!double){
      setVisible(false);
      setContent(false);
      chooseFunc(relist);
    }
  }

  // 确认按钮
  function onSureFunc(){
    setVisible(false);
    setContent(false);
    chooseFunc(saveList);
  }
  // 移除选择的项
  function removeSaveFunc(id){
    let list = [...saveList];
    let filter = list.filter(j=>j.id !== id);
    setSaveList(filter);
    renderSelectList(filter);
    setCount(filter ? filter.length :0);
  }

  // 移除后保存
  function removeValueFunc(id){
    let list = [...selectValueList];
    let filter = list.filter(j=>j.id !== id);
    setSaveList(filter);
    renderSelectList(filter);
    setCount(filter ? filter.length :0);
    chooseFunc(filter);
  }

  function onSuccess(){
    setContent(false);
    onAdd();
  }
  return(
    <li>
      <span>
        {placeholder}
        {
          !editFlag && 
          <Dropdown 
          visible={visible} 
          overlayClassName={"overlayChooseStyle"} 
          placement="bottomRight" 
          trigger={['click']} 
          overlay={
            <div ref={refFa}>
              {
                !content ? 
                <div>
                {
                  double && saveList && saveList.length>0?
                  <ul className="choosedul">
                    {
                      saveList.map((i,k)=>{
                        return(
                          <li style={{backgroundColor:`${i.color}` || "#eff2ff",borderColor:`${i.color}` || "#466aff",color:`${colorFlag?"#FFF":"#466aff"}`}}>
                            <span className="task-hide">{i.name}</span>
                            <span className="removeicon" onClick={()=>removeSaveFunc(i.id)}><i className={`iconfont icon-guanbi font-12 ${colorFlag? "color-white":"color-blue"}`}></i></span>
                          </li>
                        )
                      })
                    }
                  </ul>
                  :""
                }
                { searchFunc && 
                  <div className="searchbox">
                    <Search   
                      placeholder={`请输入${placeholder}名称进行搜索`} 
                      value={searchValue} 
                      onChange={changeSearchvalue} 
                      style={{marginRight:"18px"}}
                    />
                  </div>
                }
                {
                  menus && menus.length >0?
                  <Menu className={auto && "piecemenu"} selectedKeys={valuesId}>
                    {
                      menus.map((i,k)=>{
                        return(
                          <Menu.Item key={i.id || i.name} className={colorFlag ?"colorli":"commonli"} style={{backgroundColor:colorFlag?`${i.color || "#000"}`:"#f4f6fe"}} onClick={()=>chooseMenu(i)}>
                            {
                              auto ? <span><span className="task-hide">{i.name}</span></span>
                              :
                              <Tooltip display={auto?false:true} placement={"bottom"} title={i.name}><span><span className="task-hide">{i.name}</span></span></Tooltip>
                            }
                          </Menu.Item>
                        )
                      })
                    }
                  </Menu>
                  :
                  <div className="menusEmpty">
                    <p>{searchValue ?  <span>暂无{placeholder}“{searchValue}”</span>: `暂无${placeholder}`}</p>
                  </div>
                }
                <div className="counttips">
                  <div>
                    { onAdd && 
                      <a className="color-blue font-15 tagManage" onClick={()=>{setContent(true)}}>
                      <i className="iconfont icon-a-bianji12 font-14 mr5"></i>创建标记</a>
                    }
                  </div>
                  {
                    double && (count<0 ?
                    <p className="color-red font-13">最多添加{double}个{placeholder}！</p>
                    :
                    <p className="font-13" style={{color:"#898d9d"}}>还可添加{double - count}个{placeholder}！</p>
                    )
                  }
                </div>
                {
                  double && 
                  <div style={{textAlign:'center'}}>
                    <Button style={{width:"80px"}} onClick={()=>setVisible(false)}>取消</Button>
                    <Button style={{width:"80px"}} className="ml20" type="primary" onClick={onSureFunc}>确认</Button>
                  </div>
                }
                </div>
                :
                <AddTagsBox
                  owner={owner} 
                  projectsId={projectsId} 
                  visible={visible} 
                  onCancel={()=>setContent(false)} 
                  onSuccess={onSuccess}  />
              }
            </div>
          }>
            <a ref={refBox} onClick={()=>setVisible(visible ? false : true)}>
              <i className="iconfont icon-a-bianji12 font-13" style={{color:"#898d9d"}}></i>
            </a>
          </Dropdown>
        }
      </span>
      <div className={selectValueList && selectValueList.length > 0 ? "operatevalue color-grey-3":"operatevalue"} style={{display:colorFlag?"flex":"block"}}>{renderNames(selectValueList)}</div>
    </li>
  )
}
export default Form.create()(forwardRef(ChooseMenu));