/*
 * @Author: 赵伟
 * @Date: 2024-04-16 08:42:57
 * @Description: 参数下拉选择组件，支持资源规格、数据集、模型、服务
 */

import { PipelineNodeModelParameter } from '@/types';
import { to } from '@/utils/promise';
import { Select } from 'antd';
import { useEffect, useState } from 'react';
import { paramSelectConfig } from './config';

type ParameterSelectProps = {
  value?: PipelineNodeModelParameter;
  onChange?: (value: PipelineNodeModelParameter) => void;
  disabled?: boolean;
};

function ParameterSelect({ value, onChange, disabled = false }: ParameterSelectProps) {
  const [options, setOptions] = useState([]);
  const valueNonNullable = value ?? ({} as PipelineNodeModelParameter);
  const { item_type } = valueNonNullable;
  const propsConfig = paramSelectConfig[item_type];

  useEffect(() => {
    getSelectOptions();
  }, []);

  const hangleChange = (e: string) => {
    onChange?.({
      ...valueNonNullable,
      value: e,
    });
  };

  // 获取下拉数据
  const getSelectOptions = async () => {
    if (!propsConfig) {
      return;
    }
    const getOptions = propsConfig.getOptions;
    const [res] = await to(getOptions());
    if (res) {
      setOptions(res);
    }
  };

  return (
    <Select
      placeholder={valueNonNullable.placeholder}
      filterOption={propsConfig?.filterOption}
      options={options}
      fieldNames={propsConfig?.fieldNames}
      value={valueNonNullable.value}
      optionFilterProp={propsConfig.optionFilterProp}
      onChange={hangleChange}
      disabled={disabled}
      showSearch
      allowClear
    />
  );
}

export default ParameterSelect;
