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

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

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

  useEffect(() => {
    if (snap.computingResource.length > 0) {
      setResourceStandardList(snap.computingResource as ComputingResource[]);
    } else {
      getComputingResource();
    }
  }, []);

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

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

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

  return [resourceStandardList, filterResourceStandard, getDescription] as const;
}
