import { queryApp } from '../server';
import { Select } from 'antd';
import { debounce } from 'lodash';
import { memo, useCallback, useMemo, useState } from 'react';
import { useIntl } from 'umi';

interface AppSelectProps {
  value?: any;
  onChange?: (value: any) => void;
  /**
   * @description 可以选择单选还是多选，multiple是多选。
   */
  mode?: 'multiple' | 'tags' | undefined;
  placeholder?: string;
}
const AppSelect = ({ value, onChange, placeholder, mode }: AppSelectProps) => {
  const { formatMessage } = useIntl();
  const [options, setOptions] = useState<any[]>([]);
  const [selectUserMap, setSelectUserMap] = useState<any>({});
  const handleChange = useCallback(
    (val) => {
      onChange?.(mode ? val?.map((item) => selectUserMap[item] || { id: item }) : val);
    },
    [onChange, selectUserMap, mode],
  );
  const searchChange = useMemo(
    () =>
      debounce(async (val) => {
        if (!val) return;
        const {
          data: { list },
        } = await queryApp(val.trim());
        const newUserMap = {};
        const res = list?.map((item) => {
          newUserMap[item.id] = item;
          return {
            label: `${item.name}（${item.domain}）`,
            key: item.id,
            value: item.id,
          };
        });
        setOptions(res);
        setSelectUserMap({ ...selectUserMap, ...newUserMap });
      }, 200),
    [selectUserMap],
  );

  return (
    <Select
      mode={mode}
      filterOption={false}
      showSearch={true}
      style={{ width: '100%' }}
      options={options}
      placeholder={placeholder || formatMessage({ id: 'component.UserSelect.placeholder' })}
      allowClear={true}
      onSearch={searchChange}
      value={mode ? value?.map((item) => item?.id) : value}
      onChange={handleChange}
    />
  );
};
export default memo(AppSelect);
