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

import { useComputingResource } from '@/hooks/useComputingResource';
import { to } from '@/utils/promise';
import { Select, type SelectProps } from 'antd';
import { useEffect, useState } from 'react';
import FormInfo from '../FormInfo';
import { paramSelectConfig } from './config';

export type ParameterSelectObject = {
  value: any;
  [key: string]: any;
};

export type ParameterSelectDataType = 'dataset' | 'model' | 'service' | 'resource';

export interface ParameterSelectProps extends SelectProps {
  /** 类型 */
  dataType: ParameterSelectDataType;
  /** 是否只是展示信息 */
  display?: boolean;
  /** 值，支持对象，对象必须包含 value */
  value?: string | ParameterSelectObject;
  /** 用于流水线, 流水线资源规格要求 id 为字符串 */
  isPipeline?: boolean;
  /** 修改后回调 */
  onChange?: (value: string | ParameterSelectObject) => void;
}

/** 参数选择器，支持资源规格、数据集、模型、服务 */
function ParameterSelect({
  dataType,
  display = false,
  value,
  isPipeline = false,
  onChange,
  ...rest
}: ParameterSelectProps) {
  const [options, setOptions] = useState<SelectProps['options']>([]);
  const propsConfig = paramSelectConfig[dataType];
  const valueText = typeof value === 'object' && value !== null ? value.value : value;
  const [resourceStandardList] = useComputingResource();
  const computingResource = isPipeline
    ? resourceStandardList.map((v) => ({
        ...v,
        id: String(v.id),
      }))
    : resourceStandardList;

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

    getSelectOptions();
  }, [propsConfig]);

  const selectOptions = dataType === 'resource' ? computingResource : options;

  const handleChange = (text: string) => {
    if (typeof value === 'object' && value !== null) {
      onChange?.({
        ...value,
        value: text,
      });
    } else {
      onChange?.(text);
    }
  };

  // 只用于展示，FormInfo 组件带有 Tooltip
  if (display) {
    return (
      <FormInfo
        select
        value={valueText}
        options={selectOptions}
        fieldNames={propsConfig?.fieldNames}
      ></FormInfo>
    );
  }

  return (
    <Select
      {...rest}
      filterOption={propsConfig?.filterOption}
      options={selectOptions}
      fieldNames={propsConfig?.fieldNames}
      optionFilterProp={propsConfig?.optionFilterProp}
      value={valueText}
      onChange={handleChange}
      showSearch
      allowClear
    />
  );
}

export default ParameterSelect;
