import { Select } from "antd";
import { useEffect } from "react";

/**
 * 基础下拉组件
 */
function BasicSelect(props) {
  const {
    onGetData,
    onChange,
    onGetLabel,
    onGetOption,
    placeholder = "",
    data = [],
    nameKey = "name",
    idKey = "id",
    labelRender,
    ...restProps
  } = props;

  const handleChange = (event, option) => {
    if (onGetLabel || onGetOption) {
      if (Array.isArray(event)) {
        if (event.length > 0) {
          const findItems = [];
          const names = [];
          event.forEach((item) => {
            const findItem = data.find(dataItem => dataItem[idKey] === item);
            if (findItem) {
              findItems.push(findItem);
              names.push(findItem[nameKey]);
            }
          });
          onGetLabel?.(names);
          onGetOption?.(findItems);
        }
        else {
          onGetLabel?.([]);
          onGetOption?.([]);
        }
      }
      else {
        if (event) {
          const findItem = data.find(item => item[idKey] === event);
          onGetLabel?.(findItem[nameKey]);
          onGetOption?.(findItem);
        }
        else {
          onGetLabel?.("");
          onGetOption?.({});
        }
      }
    }
    onChange?.(event, option);
  };

  useEffect(() => {
    onGetData?.(data);
  }, [data]);

  return (
    <Select placeholder={`请选择${placeholder}`} showSearch allowClear optionFilterProp="children" onChange={handleChange} {...restProps}>
      {data.map((item) => {
        const value = item[idKey];
        const label = labelRender ? labelRender(item) : item[nameKey];
        return (
          <Select.Option key={value} value={value}>
            {label}
          </Select.Option>
        );
      })}
    </Select>
  );
}

BasicSelect.displayName = "BasicSelect";

export default BasicSelect;
