<template>
  <!-- 当mescroll-body写在子组件时,父页面需引入useMescrollComp.js -->
  <mescroll-body
    :height="`${scrollHeight}px`"
    @init="mescrollInit"
    @down="downCallback"
    @up="upCallback"
  >
    <slot :list="list"></slot>
  </mescroll-body>
</template>

<script setup>
import { sys } from '@climblee/uv-ui/libs/function'
import { ref, computed, nextTick } from 'vue'
import useMescroll from '@/uni_modules/mescroll-uni/hooks/useMescroll.js'
import { http } from '@/utils/request'
const props = defineProps({
  top: {
    type: Number,
    default: 44,
  },
  apiUrl: {
    type: String,
    default: '',
  },
  params: {
    type: Object,
    default: () => {},
  },
})
const scrollHeight = computed(() => {
  return sys().screenHeight - props.top
})
const list = ref([]) // 数据列表

// 子组件的mescroll-body无需传入onPageScroll, onReachBottom
const { mescrollInit, downCallback, getMescroll } = useMescroll() // 调用mescroll的hook

// 使父组件可以通过ref调用到getMescroll方法 (必须)
defineExpose({ getMescroll })

// 上拉加载的回调: 其中num:当前页 从1开始, size:每页数据条数,默认10
const upCallback = async (mescroll) => {
  await nextTick()
  if (!props.apiUrl) return
  http
    .get(props.apiUrl, {
      params: {
        per_page: mescroll.size,
        page: mescroll.num,
        ...props.params,
      },
    })
    .then((res) => {
      const curPageData = res.data || [] // 当前页数据
      if (mescroll.num == 1) list.value = [] // 第一页需手动制空列表
      list.value = list.value.concat(curPageData) // 追加新数据
      mescroll.endSuccess(curPageData.length) // 隐藏加载进度
    })
    .catch(() => {
      mescroll.endErr() // 隐藏加载进度
    })
}


</script>
