import { useState,useRef } from 'react';


const DEFAULT_PAGE_SIZE=20;
const DEFAULT_PAGE_CURRENT=1;

const useNextPage=(props)=>{
  const [search,setSearch] = useState(props.initSearch||{});
  const [service] = useState(()=>props.service);
  const [beforeService] = useState(()=>props.beforeService);
  const [pagination,setPagination] = useState(()=>{
    let temp = {
      current:DEFAULT_PAGE_CURRENT,
      pageSize:DEFAULT_PAGE_SIZE,
      total:0,
      startIdx:0,
      more:false,
      ...props.pagination
    };
    temp.startIdx = (temp.current-1)*temp.pageSize;
    return temp;
  });
  const resetCount = useRef(0);
  const [data,setData] = useState([]);
  
  const reset= async ()=>{
    resetCount.current++;
    let page = {...pagination};
    page.current =1;
    return refresh({pageValue:page})
  }
  const nextPage= async ()=>{
    if(!pagination.more){
      return false;
    }
    let page = {...pagination};
    page.current= +page.current+1;
    return refresh({pageValue:page})
  }
  const refresh= async ({searchValue,pageValue}={})=>{
    searchValue = searchValue || search;
    pageValue = pageValue || pagination;
    searchValue = {...search,...searchValue};
    pageValue = {...pagination,...pageValue};

    const {current,pageSize} = pageValue;
    let params = {...searchValue,current:current,pageSize:pageSize};
    if(beforeService)params=beforeService(params);
    if(!params)return;

    setSearch(searchValue);

    let ret = await service(params);
    if(ret?.code==0){
      const {page} = ret.data;
      const current= +(page.pageNum||DEFAULT_PAGE_CURRENT);
      const pageSize= +(page.pageSize||DEFAULT_PAGE_SIZE);
      const total= +page.total;
      const startIdx= (current-1)*pageSize;
      const more = current*pageSize<total;
      setPagination({
        current,pageSize,total,startIdx,more
      })
      if(ret.data.list){
        ret.data.list.map(item=>{
          item.resetCount = resetCount.current;
        })
        let newData = current==1?[]:data;
        newData[current-1] = ret.data.list;
        setData([...newData])
      }
    }
    return ret;
  }


  return {
    pagination,
    search,
    setSearch,
    refresh,
    reset,
    nextPage,
    data,
  };

}

export default useNextPage;
