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

const { Option } = AutoComplete;
function AddMember({getID,login,showNotification}){
  const [ id , setID ] = useState(undefined);
  const [ source , setSource ] = useState(undefined);
  const [ searchKey , setSearchKey ] = useState(undefined);
  
  useEffect(()=>{
    getUserList();
  },[searchKey])

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

  function sourceOptions(userDataSource){
    const s = userDataSource && userDataSource.map((item, key) => {
      return (
        <Option
          key={key}
          value={`${item.user_id}`}
          login={`${item.login}`}
          name={item.username}
        >
          <img
            className="user_img radius"
            width="28"
            height="28"
            src={getImageUrl(`/${item && item.image_url}`)}
            alt=""
          />
          <span className="ml10" style={{ verticalAlign: "middle" }}>
            {item.username}
            <span className="color-grey ml10">({item.login})</span>
          </span>
        </Option>
      );
    });
    setSource(s);
  }

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

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

  function addCollaborator(){
    if(source && source.length>0){
      getID && getID(id);
      setSearchKey(undefined);
    }else{
      showNotification("请选择存在的用户!");
    }
  }

  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 AddMember;