<template>
  <div class="article-list">
    <article-list-item v-for="(item, index) in dataList" :data="item" v-bind="$attrs" :key="index"></article-list-item>
    <el-pagination
      class="article-list-pagination"
      layout="prev, pager, next"
      :page-size="page.size"
      :total="page.total"
      :current-page.sync="page.currentPage"
      @current-change="fetchList"
      :hide-on-single-page="true"
    >
    </el-pagination>
  </div>
</template>

<script>
import ArticleListItem from './ArticleListItem.vue'
export default {
  name: 'ArticleList',
  components: { ArticleListItem },
  inheritAttrs: false,
  props: {
    remote: { type: Object, default: () => ({}) },
    // 是否含有翻页
    hasPagination: { type: Boolean, default: true },
    // 每页多少条数据
    limit: { type: Number, default: 20 }
  },
  data() {
    return {
      loading: false,
      params: this.remote.params || {},
      dataList: this.data,
      page: { total: 0, size: this.limit, currentPage: 1 }
    }
  },
  watch: {
    'remote.params': {
      immediate: true,
      handler(data) {
        this.params = data || {}
      }
    }
  },
  async fetch() {
    await this.fetchList()
  },
  methods: {
    fetchList() {
      /**
       * @param function httpRequest api接口
       * @param function beforeRequest 接口请求之前
       * @param function callback 接口请求成功回调
       */
      const { httpRequest, beforeRequest, callback } = this.remote
      if (!httpRequest) {
        return
      }
      // 参数设置
      let params = this.params
      // 翻页参数设置
      if (this.hasPagination) {
        params.page = this.page.currentPage
        params.limit = this.page.size
      }
      // 接口请求之前
      if (beforeRequest) {
        params = beforeRequest(params)
      }
      for (const key in params) {
        if (params[key] === '' || params[key] === undefined || params[key] === undefined) {
          delete params[key]
        }
      }
      this.loading = true
      return httpRequest(params)
        .then(res => {
          const { data = [], total = 0 } = res.data || {}
          this.page.total = total
          this.dataList = callback ? callback(data) : data
        })
        .catch(() => {
          this.page.total = 0
          this.dataList = []
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style lang="scss">
.article-list {
  overflow: hidden;
}
.article-list-pagination {
  padding: 20px;
  text-align: center;
}
.is-h5 {
  .article-list {
    background: #eee;
    margin: -0.2rem -0.15rem;
  }
}
</style>
