import { useRef,useState, useEffect } from 'react';
import {ShowPageLoading} from '@/components/Page/PageLoading';

const useLoading=(props={})=>{
  const {canTouch=false} = props;
  const [name] = useState(props?.name||'loading')
  const [count,setCount] = useState(props?.loading?1:0);
  const refPageLoading = useRef();

  const setLoading=(state)=>{
    if(state){
      setCount(v=>v+1);
    }else{
      setCount(v=>v-1);
    }
  }
  const reset=()=>{
    setCount(v=>0);
  }
  useEffect(()=>{
    if(count > 0 ){
      if(!refPageLoading.current){
        refPageLoading.current = ShowPageLoading({canTouch:canTouch});
      }
    }else{
      if(refPageLoading.current){
        refPageLoading.current();//销毁
        refPageLoading.current=null;
      }
    }
  },[count])

  
  return {
    name,
    reset,
    setLoading,
    loading:count
  }
}

export default useLoading;
