<template>
  <div class="list">
    <van-list
      v-model="loading"
      :finished="finished"
      @load="onLoad"
      v-if="list.length"
    >
      <group-item
        v-for="(item, index) in list"
        :data="item"
        :index="index"
        :show-index="showIndex"
        :key="item.id"
      ></group-item>
    </van-list>
    <template v-else>
      <slot name="empty">
        <div class="empty">暂时没有内容哦，去别处看看吧～</div>
      </slot>
    </template>
  </div>
</template>

<script>
import * as api from '@/api/index'
import GroupItem from '@/components/GroupItem'
export default {
  components: { GroupItem },
  props: {
    params: {
      type: Object,
      default() {
        return {}
      }
    },
    showIndex: { type: Boolean, default: false }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      requestParams: { offset: 0, limit: 20 }
    }
  },
  watch: {
    params: {
      immediate: true,
      handler(value) {
        this.requestParams = Object.assign({}, this.requestParams, value)
      }
    }
  },
  methods: {
    getList() {
      this.loading = true
      api
        .getGroupList(this.requestParams)
        .then(response => {
          if (response.length) {
            this.list = this.list.concat(response)
          }
          this.loading = false
          this.finished = response.length < this.requestParams.limit
        })
        .catch(() => {
          this.loading = false
          this.finished = true
        })
    },
    onLoad() {
      this.requestParams.offset =
        this.requestParams.offset + this.requestParams.limit
      this.getList()
    },
    // 刷新
    refresh() {
      this.requestParams.offset = 0
      this.list = []
      this.getList()
    }
  },
  beforeMount() {
    this.getList()
  }
}
</script>
