import React , { useState , useEffect } from 'react';
import { AutoComplete } from 'antd';
import { getImageUrl } from "educoder";
import axios from 'axios';
const Option = AutoComplete.Option;

export default ({ getUser })=>{
  const [ searchKey , setSearchKey ] = useState(undefined);
  const [ userDataSource , setUserDataSource ] = useState(undefined);

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

  function selectInputUser(id, option){
    setSearchKey(option.props.searchValue);
    getUserList(option.props.searchValue);
    getUser && getUser(id);
  }
  const source =
    userDataSource && userDataSource.map((item, key) => {
      return (
        <Option
          key={key}
          value={`${item.user_id}`}
          searchValue={`${item.username}`}
        >
          <img
            className="user_img radius"
            width="28"
            height="28"
            src={getImageUrl(`images/${item && item.image_url}`)}
            alt=""
          />
          <span className="ml10" style={{ "vertical-align": "middle" }}>
            {item.username}
            <span className="color-grey ml10">({item.login})</span>
          </span>
        </Option>
      );
    });
  return(
    <AutoComplete
      dataSource={source}
      value={searchKey}
      style={{ width: 300 }}
      onChange={changeInputUser}
      onSelect={selectInputUser}
      placeholder="搜索需要添加的用户..."
    />
  )
}