import React, { useEffect,useState,useMemo,useRef,useCallback } from 'react';

const usePreload=(files)=>{
  const [list] = useState(files);
  const [count,setCount] = useState(files.length);
  const [state,setState]=useState('');

  const load=useCallback((options)=>{
    return new Promise(resolve=>{
      if(count <= 0 ){
        resolve(true);
        return;
      }
      if(state=='loading'){
        resolve(false);
        return;
      }
      setState('loading');
      let per = files.length;
      list.forEach((item, idx) => {
        if (typeof item === 'string') {
          let img = new Image();
          img.onload = () => {
            console.log('加载成功')
            per--;
            if(per<=0){
              setCount(0);
              if(options?.delay){
                setTimeout(resolve, options.delay);
                return;
              }
              resolve(true);
            }
          };
          img.onerror = () => {
            per--;
            if(per<=0){
              setCount(0);
              resolve(true);
            }
            console.log(`图片预加载失败`,item);
          };
          img.src = item;
        } else {
          console.log(`图片预加载失败异常图片`,item);
          per--;
          if(per<=0){
            setCount(0);
            resolve(true);
          }
        }
      });
    })
    
  },[state,setState,count]);

  const actions=useMemo(()=>{
    return {
      count,
      load,
    };
  },[count]);
  return actions;
}

export default usePreload;
