<script setup lang="ts">
const props = defineProps({
  url: {
    type: String,
    required: true,
  },
  d: {
    type: Object,
    required: false,
  },
})

let page = 1

let loading = $ref(false)
let error = $ref(false)
let finished = $ref(false)
let refreshing = $ref(false)

const list = ref<Array<any>>([])

// request({
//   url: props.url,
//   data: {
//     page,
//     ...props.d
//   },
// })

function onLoad() {
  loading = true
  request({
    url: props.url,
    data: {
      page,
      limit: 20,
      ...props.d,
    },
  }).then((res) => {
    if (res.code === '1') {
      if (refreshing) {
        list.value = []
        refreshing = false
      }
      list.value = list.value.concat(res.data.page_data)
      loading = false
      page++
      if (res.data.page_now === res.data.total_page)
        finished = true
    }
    else {
      error = true
    }
  }).catch((err) => {
    console.log(err)
  })
}

function onRefresh() {
  finished = false
  page = 1
  refreshing = true
  onLoad()
}

let timer: NodeJS.Timeout

onBeforeUnmount(() => {
  timer && clearInterval(timer)
})

function debounce(fn: () => void, delay: number) {
  return () => {
    timer && clearInterval(timer)
    timer = setTimeout(() => {
      fn()
    }, delay)
  }
}

watch(
  () => props.d,
  debounce(() => {
    page = 1
    refreshing = true
    onLoad()
  }, 400),
  {
    deep: true,
  },
)

defineExpose({
  refresh: () => {
    onRefresh()
  },
})
</script>

<template>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model:loading="loading" v-model:error="error" error-text="请求失败，点击重新加载" :finished="finished"
      finished-text="没有更多了" @load="onLoad" @click.stop
    >
      <slot :rows="list" />
    </van-list>
  </van-pull-refresh>
</template>
