// src/components/Hooks/useAuthImageUrls.ts
import { useEffect, useState } from 'react';
import { fetchImage } from '@/services/file/api';
import { get } from 'lodash';
import { getAuthization } from '@/utils/userUtils';

const useAuthImageUrls = (imageIds: string[]) => {
  const [imageUrls, setImageUrls] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState<Record<string, boolean>>({});

  useEffect(() => {
    const fetchImageUrls = async () => {
      const newImageUrls: Record<string, string> = {};
      const newLoading: Record<string, boolean> = { ...loading };
      
      const promises = imageIds
        .filter(id => !imageUrls[id] && !loading[id]) // 只获取尚未加载或正在加载的图片
        .map(async (id) => {
            if(!id) return;
          newLoading[id] = true;
          
          try {
            const {data: response} = await fetchImage(id);
            if (response) {
              const objectUrl = URL.createObjectURL(response);
              newImageUrls[id] = objectUrl;
            }
          } catch (error) {
            console.error(`Failed to fetch image ${id}:`, error);
            // 如果认证请求失败，使用原始URL作为备选
            newImageUrls[id] = `/file/image-low-res/${id}?Authorization=${getAuthization()}`;
          } finally {
            newLoading[id] = false;
          }
        });
      
      if (promises.length > 0) {
        setLoading({ ...newLoading });
        await Promise.all(promises);
        setImageUrls(prev => ({ ...prev, ...newImageUrls }));
        setLoading(prev => {
          const updatedLoading = { ...prev };
          Object.keys(newImageUrls).forEach(key => {
            delete updatedLoading[key];
          });
          return updatedLoading;
        });
      }
    };

    fetchImageUrls();
  }, [imageIds, imageUrls, loading]);

  // 组件卸载时清理Object URLs以避免内存泄漏
  useEffect(() => {
    return () => {
      Object.values(imageUrls).forEach(url => {
        if (url.startsWith('blob:')) {
          URL.revokeObjectURL(url);
        }
      });
    };
  }, [imageUrls]);

  return { imageUrls, loading };
};

export default useAuthImageUrls;