import React, { useEffect, useState } from "react";
import { Select } from "easy-design";
import { getOptionsList } from "../../_util/remoteReq";

export default function EasySelect(props) {
  const { allowInput, value, options = [], onChange, api, localOptionsVar, ...rest } = props;
  const [search, setSearch] = useState("");
  const [optionList, setOptionList] = useState(() => {
    if (localOptionsVar) {
      return JSON.parse(localStorage.getItem(localOptionsVar) || "[]");
    } else {
      return options;
    }
  });

  useEffect(() => {
    if (api) {
      let isSubscribed = true;
      getOptionsList(api)
        .then((res) => {
          if (!isSubscribed) return;
          if (res && Array.isArray(res)) {
            setOptionList(
              res.map((d) => ({ label: d.name, value: d.value, disabled: d.disabled })),
            );
          }
        })
        .catch(() => {
          // 忽略请求错误，避免在卸载后抛错
        });
      return () => {
        isSubscribed = false;
      };
    }
  }, [api, options]);

  useEffect(() => {
    if (!localOptionsVar) {
      const res = options.map((d) => ({ label: d.name, value: d.value, disabled: d.disabled }));
      setOptionList(res);
    }
  }, [options]);

  const handleSearch = (value) => {
    setSearch(value);
  };

  const handleChange = (value) => {
    onChange(value);
    setSearch("");
  };

  const handleDropdownVisibleChange = (open) => {
    if (!open) {
      setSearch("");
    }
  };

  // 注意：这里如果没有配置allowInput并且options长度大于10则自动开启搜索\如果配置了allowInput并且存在输入值则采用输入值
  const showSearch = allowInput ? true : optionList.length > 5;
  const searchResult = search
    ? optionList.filter((item) => String(item.label).includes(search))
    : [];
  const resultOptions =
    allowInput && search ? [{ label: search, value: search }, ...searchResult] : optionList;

  return (
    <Select
      showSearch={showSearch}
      value={value}
      filterOption={allowInput ? false : true}
      options={resultOptions}
      optionFilterProp={allowInput ? false : "label"}
      virtual={false}
      onSearch={showSearch && handleSearch}
      onChange={handleChange}
      onDropdownVisibleChange={handleDropdownVisibleChange}
      {...rest}
    />
  );
}
