<template>
  <div v-if="list.length||loading">
    <van-pull-refresh v-model="refreshing" success-text="刷新成功" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        v-model:error="error"
        :finished="finished"
        finished-text="没有更多了"
        :immediate-check="false"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <slot v-for="item in list" :key="item" name="listItem" :row="item" />
      </van-list>
    </van-pull-refresh>
  </div>
  <van-empty v-else  description="没有数据" />
</template>

<script setup lang="ts">
import { showNotify } from 'vant'
import { ref } from 'vue'
const list = ref<any[]>([])
const refreshing = ref(false)
const loading = ref(false)
const error = ref(false)
const finished = ref(false)
const total = ref(0)
// eslint-disable-next-line no-undef
const props = defineProps<{
    param:any,
    pagination:any,
    request:(params:any)=>any
}>()
// eslint-disable-next-line no-undef
const emit = defineEmits(['resetPage', 'pagePlus', 'noData'])
const paginationCopy = ref()
const paramCopy = ref()
// paginationCopy.value = Object.assign({}, (props.pagination ? props.pagination : { page: 1, per_page: 15 }))

const onLoad = async(flag?:any, pa?:any) => {
  loading.value = true
  // 是否从第1页加载
  if (flag) {
    emit('resetPage')
    list.value = []
    finished.value = false
  }
  paginationCopy.value = props.pagination ? props.pagination : { page: 1, per_page: 15 }
  // console.log(props.param)

  paramCopy.value = pa || { ...(props.param ? props.param : {}) }
  await props.request({ ...paramCopy.value, ...paginationCopy.value }).then((res:any) => {
    console.log('列表res', res.data)
    if (res.data.data.total === 0) {
      finished.value = true
    }
    console.log(typeof res.data.data.total)

    total.value = typeof res.data.data.total === 'number' ? res.data.data.total : res.data.data.total.total
    list.value = list.value.concat(res.data.data.lists ? res.data.data.lists : [])
    // list.value = [...list.value, ...(res.data.data ? res.data.data : [])]
    console.log('list', list.value)
    if (!list.value.length) emit('noData')
  }).catch((err:any) => {
    console.log(err)
    // showNotify({ type: 'danger', message: err.data.msg })
    finished.value = true
    error.value = true
  })
  loading.value = false
  const pageAttr = Object.keys(paginationCopy.value)
  if (paginationCopy.value[pageAttr[0]] * paginationCopy.value[pageAttr[1]] > total.value) {
    finished.value = true
  } else {
    emit('pagePlus')
  }
}

const onRefresh = async() => {
  // 清空列表数据
  finished.value = false

  // 重新加载数据
  // 将 loading 设置为 true，表示处于加载状态
  loading.value = true
  await onLoad(1)
  refreshing.value = false
}
// eslint-disable-next-line no-undef
defineExpose({
  onLoad,
  list
})
</script>

<style lang="scss" scoped>

</style>
