import React, { useEffect, useState } from 'react';
import { AutoComplete , Button , Icon } from 'antd';
import axios from 'axios';

const { Option } = AutoComplete;
function AddGroup({organizeId,getGroupID}){
  const [ id , setID ] = useState(undefined);
  const [ source , setSource ] = useState(undefined);
  const [ searchKey , setSearchKey ] = useState("");
  
  useEffect(()=>{
    getUserList();
  },[searchKey])

  function getUserList(e){
    const url = `/organizations/${organizeId}/teams/search.json`;
    axios.get(url, {
      params: {
        search: searchKey,
      },
    }).then((result) => {
      if (result) {
        sourceOptions(result.data.teams);
      }
    })
    .catch((error) => {
      console.log(error);
    });
  };

  function sourceOptions(userDataSource){
    const s = userDataSource && userDataSource.map((item, key) => {
      return (
        <Option
          key={key}
          value={`${item.id}`}
          name={item.name}
        >
          {item.name}
        </Option>
      );
    });
    setSource(s);
  }

  function changeInputUser(e){
    setSearchKey(e || "");
  };

  // 选择用户
  function selectInputUser(e, option){
    setID(e);
    setSearchKey(option.props.name);
  };

  function addCollaborator(){
    getGroupID && getGroupID(id);
    setID(undefined);
  }

  return(
    <div className="addPanel">
      <AutoComplete
        dataSource={source}
        value={searchKey}
        style={{ width: 300 }}
        onChange={changeInputUser}
        onSelect={selectInputUser}
        placeholder="搜索需要添加的团队..."
        allowClear
      />
      <Button
        type="primary"
        ghost
        onClick={addCollaborator}
        className="ml15"
      >
        <Icon type="plus" size="16"></Icon>
        添加团队
      </Button>
    </div>
  )
}
export default AddGroup;