<script setup>
const props = defineProps({
  url: {
    type: String,
    required: true,
  },
  d: {
    type: Object,
    required: false,
  },
  loop: {
    type: Boolean,
    required: false,
    default: false,
  },
})

let page = 1

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

let list = $ref([])

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

// 将一个数组的元素分割成指定长度的数组
function chunk(arr, size) {
  const result = []
  for (let i = 0; i < arr.length; i += size) {
    result.push(arr.slice(i, i + size))
  }
  return result
}


function onLoad() {
  loading = true
  request({
    url: props.url,
    data: {
      page,
      limit: 20,
      ...props.d
    },
  }).then(res => {
    if (res.code === '1') {
      // if (refreshing || refreshloop) {
      //   list = [];
      //   refreshing = false;
      //   refreshloop = false;

      // }
      list = chunk(res.data.page_data, 2)
      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
  onLoad()
}

let timer;

// if (props.loop) {
//   timer = setTimeout(async () => {
//     refreshloop = true;
//     await onRefresh();
//   }, 60 * 1000);
// }

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

watch(
  () => props.d.keyword,
  async (val, oldVal) => {
    if (oldVal === '搜索') return;
    // refreshloop = true;
    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>
      <div v-for="items in list" class="flex justify-between mb-2">
        <div class="w-49/100" v-for="item in items">
          <slot :row="item"></slot>
        </div>
      </div>
    </van-list>
  </van-pull-refresh>
</template>
