<template>
  <div>
    <el-table
      v-bind="$attrs"
      v-on="$listeners"
      ref="tables"
      v-loading="loading"
      :data="list"
    >
      <slot></slot>
    </el-table>
    <pagination
      v-show="pagingQuery.total > 0"
      :total="pagingQuery.total"
      :page.sync="pagingQuery.page"
      :limit.sync="pagingQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>
<script>
export default {
  name: "PagingTable",
  props: {
    fetch: {
      type: Function,
      default: () => {
        // 返回一个 Promise，模拟异步操作
        return new Promise((resolve) => {
          setTimeout(() => {
            resolve({ list: [], total: 0 });
          }, 1000);
        });
      },
    },
    formatResponse: {
      type: Function,
      default: (res) => ({ list: res.list, total: res.total }),
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      pagingQuery: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  mounted() {
    this.getList(); // 组件创建时自动调用一次获取数据的函数
  },
  methods: {
    async getList() {
      this.loading = true;
      try {
        // 使用传递给组件的 `fetch` 函数，或默认的异步函数
        const result = await this.fetch(this.pagingQuery);
        const { list = [], total = 0 } = this.formatResponse(result);
        this.list = list || [];
        this.pagingQuery.total = total || 0;
      } catch (error) {
        console.error(error);
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>
