// src/components/Hooks/useFetchHighResImageUrl.ts
import { useRequest } from '@umijs/max';
import { useEffect, useRef, useState } from 'react';
import { fetchImage } from '@/services/file/api';

// 简单内存缓存，避免重复请求同一张图片
const highResImageUrlCache = new Map<string, string>();

const useFetchHighResImageUrl = (imageInstanceId: string) => {
  const [imageUrl, setImageUrl] = useState<string | null>(null);
  const retryRef = useRef(0);
  const { run, loading } = useRequest(
    () => fetchImage(imageInstanceId),
    {
      manual: true,
      onSuccess: (data) => {
        if (data) {
          const objectUrl = URL.createObjectURL(data);
          highResImageUrlCache.set(imageInstanceId, objectUrl);
          setImageUrl(objectUrl);
        } else {
          setImageUrl(null);
        }
        retryRef.current = 0;
      },
      onError: () => {
        if (retryRef.current < 2) {
          retryRef.current += 1;
          run();
        } else {
          setImageUrl(null);
          highResImageUrlCache.set(imageInstanceId, "error");
          retryRef.current = 0;
        }
      },
    },
  );

  useEffect(() => {
    if (imageInstanceId) {
      retryRef.current = 0;
      const cached = highResImageUrlCache.get(imageInstanceId);
      if (cached && cached !== "error") {
        setImageUrl(cached);
      } else if (cached !== "error") {
        run();
      }
    } else {
      setImageUrl(null);
    }
  }, [imageInstanceId, run]);

  return { imageUrl, loading };
};

export default useFetchHighResImageUrl;