<template>
  <div class="k-list">
    <slot name="header" style="width: 100%"> </slot>
    <van-list v-model="isLoading" :finished="isFinished" finished-text @load="next">
      <slot v-for="(data, index) in dataList" :data="data" :index="index"></slot>
    </van-list>
    <van-empty v-if="dataList.length == 0 && !isLoading" description="暂无数据" />
  </div>
</template>
<script>
import { debounce } from 'lodash'

export default {
  components: {},
  data() {
    return {
      isLoading: false,
      isFinished: true,
      page: {
        pageNum: 0,
        pageSize: 10,
      },
      dataList: []
    }
  },
  computed: {},
  watch: {
    params: {
      deep: true,
      handler: debounce(
        function () {
          this.page = { pageNum: 0, pageSize: 10 }
          this.dataList = []
          this.next()
        },
        300,
        { leading: true }
      )
    }
  },
  props: {
    list: {
      type: [Function, Array],
      required: true
    },
    params: {},
    wrap: {
      default() {
        return () => {}
      }
    },
    auto: {
      default: true
    },
    // 是否分页
    pageable: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    //
    async next() {
      this.page.pageNum++
      try {
        this.isLoading = true

        const data = await this.list({
          ...this.params,
          ...this.page
        })
        console.log(data,'data')
        // 工程商列表获取接口/api/service/find/v2/all返回结构为dataList
        const content = data.rows ? data.rows : data.dataList || data
        this.isFinished = content.length < this.page.pageSize
        await this.wrap(content)
        if (this.page.pageNum === 0) {
          this.dataList = content
        } else {
          this.dataList = this.dataList.concat(content)
        }
        // this.dataList.concat(content);
        this.$emit('load', content)
      } catch (e) {
        console.error(e)
        this.isFinished = true
      } finally {
        this.isLoading = false
      }
      //不分页既完成
      if (!this.pageable) {
        this.isFinished = true
      }
    }
  },
  async created() {},
  async mounted() {
    this.auto && this.next()
  }
}
</script>
<style lang="scss">
.k-list {
}
</style>
