import { shallowReactive,reactive, ref,onActivated,nextTick } from "vue";
// import { useRoute } from 'vue-router'
export function useInfiniteScroll(callback,needReactive) {
  const list = needReactive?reactive([]):shallowReactive([]);
  const scrollRef = ref(null);
  let currentPage = 1;
  // const route = useRoute()
  // let fullpath = ''
  // onActivated(()=>{
  //   if(fullpath!= route.fullPath){
  //     // 需要重置页面里的各种查询条件，所以这里貌似没有统一处理的必要
  //     nextTick(refresh)
  //   }
  // })
  function refresh(){
    setTimeout(()=>{
      list.splice(0, list.length);
      scrollRef.value?.refresh();
    },0 );
  }
  return {
    list,
    scrollRef,
    refresh,
    reloadCurrentPage(){
      // scrollRef.value?.reload();
      return callback(currentPage).then(res=>{
        if(!res.total && !res.per_page){
          // 不分页的清空
          // 直接替换所有数据
          res.data.forEach((item,i)=>{
            list[i] = item
          })
          if(list.length > res.data.length){
            list.splice(res.data.length,list.length-res.data.length)
          }
        }else{
          let startI = (currentPage-1)*res.per_page
          res.data.forEach((item,i)=>{
            list[startI + i] = item
          })
        }
      })
    },
    load(page) {
      currentPage = page ||1
      return callback(page||1).then((res) => {
        if (!page || page == 1) {
          list.splice(0, list.length);
        }
        if (!res.data) {
          return true;
        }
        Array.prototype.push.apply(list, res.data);
        return !res.total || res.total / res.per_page <= res.current_page;
      });
    },
  };
}
