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 , placeholder, width ,value })=>{
  const [ source , setSource ] = useState(undefined);
  const [ searchKey , setSearchKey ] = useState(undefined);

  useEffect(()=>{
    if(!value){
      setSearchKey(undefined);
    }
  },[value])
  
  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={{ "vertical-align": "middle" }}>
            {item.username}
            <span className="color-grey ml10">({item.login})</span>
          </span>
        </Option>
      );
    });
    setSource(s);
  }

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

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

  return(
    <div className="addPanel">
      <AutoComplete
        getPopupContainer={trigger => trigger.parentNode}
        dataSource={source}
        value={searchKey}
        style={{ width: width || 300 }}
        onChange={changeInputUser}
        onSelect={selectInputUser}
        placeholder={placeholder || "搜索需要添加的用户..."}
        allowClear
      />
    </div>
  )
}