/*
 * @Author: 赵伟
 * @Date: 2024-10-10 08:51:41
 * @Description: 资源规格 hook
 */

import { getComputingResourceReq } from '@/services/pipeline';
import { ComputingResource } from '@/types';
import { to } from '@/utils/promise';
import { type SelectProps } from 'antd';
import { useCallback, useEffect, useState } from 'react';

const computingResource: ComputingResource[] = [];

/** 过滤资源规格 */
export const filterResourceStandard: SelectProps<string, ComputingResource>['filterOption'] = (
  input: string,
  option?: ComputingResource,
) => {
  return (
    option?.computing_resource?.toLocaleLowerCase()?.includes(input.toLocaleLowerCase()) ?? false
  );
};

/** 资源规格字段 */
export const resourceFieldNames = {
  label: 'description',
  value: 'id',
};

/** 获取资源规格 */
export function useComputingResource() {
  const [resourceStandardList, setResourceStandardList] = useState<ComputingResource[]>([]);

  useEffect(() => {
    // 获取资源规格列表数据
    const getComputingResource = async () => {
      const params = {
        page: 0,
        size: 1000,
        resource_type: '',
      };
      const [res] = await to(getComputingResourceReq(params));
      if (res && res.data && Array.isArray(res.data.content)) {
        setResourceStandardList(res.data.content);
        computingResource.splice(0, computingResource.length, ...res.data.content);
      }
    };

    if (computingResource.length > 0) {
      setResourceStandardList(computingResource);
    } else {
      getComputingResource();
    }
  }, []);

  // 根据 standard 获取 description
  const getDescription = useCallback(
    (id?: string | number) => {
      if (!id) {
        return undefined;
      }
      return resourceStandardList.find((item) => Number(item.id) === Number(id))?.description;
    },
    [resourceStandardList],
  );

  return [resourceStandardList, getDescription] as const;
}
