import { useRequest } from '@umijs/max';
import { useEffect, useRef, useState } from 'react';
import {fetchImageLowRes} from "@/services/file/api";

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

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

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

  return {imageUrl, loading};
};
export default useFetchImageUrl;
