<template>
  <div class="loadMore">
    <template v-if="count">
      <div class="list">
        <slot v-for="(item, index) in items" :index="index" :item="item" />
      </div>
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next,total, jumper"
        :total="count"
        :page-size="rows"
        @current-change="currentChange"
      />
    </template>
    <template v-else-if="count === 0 && !hideTip">
      <div class="noneData">
        <img src="@assets/noneData.png" alt="" />
        <br />
        <div>暂无数据</div>
      </div>
    </template>
  </div>
</template>
<script lang="ts">
import {
  Component,
  Vue,
  Prop,
  PropSync,
  Watch,
  Emit
} from "vue-property-decorator";
interface IPageResult {
  rows: any[];
  total: number;
}
@Component
export default class extends Vue {
  @Prop({ required: true })
  private readonly url!: string;
  @Prop(Object)
  params: object | undefined;
  @Prop({ default: 10 })
  private readonly rows!: number;
  @Prop(Boolean) private hideTip!: boolean;
  @PropSync("total") totalSync!: number;

  private count: number | null = null;
  private page = 0;
  private items: any[] = [];
  @Watch("params", { immediate: true, deep: true })
  reload() {
    if (this.page === 1) return this.load();
    this.page = 1;
  }
  @Watch("count", { immediate: true })
  totalChange() {
    this.totalSync = this.count || 0;
  }
  @Watch("page", { immediate: true })
  async load() {
    const [err, { rows = [], total = 0 }] = await this.$post<IPageResult>(
      this.url,
      Object.assign({}, this.params, {
        pageNum: this.page,
        pageSize: this.rows
      })
    );
    if (err) console.error("列表加载失败");
    // if (err) this.$message.error("列表加载失败"); //throw Error("loadMore fail");
    this.count = total;
    this.setItems(rows);
  }
  currentChange(page: number) {
    this.page = page;
  }
  @Emit("getItems")
  private setItems(items: any[]) {
    return (this.items = items);
  }
}
</script>
<style lang="scss" scoped>
.loadMore {
  width: 100%;
  overflow: hidden;
  .list {
    overflow: hidden;
  }
  .pagination {
    text-align: right;
  }
  .noneData {
    padding-top: 5rem;
    text-align: center;
    img {
      width: 15rem;
    }
    div {
      font-size: 1.5rem;
      color: #999;
      margin-top: 1rem;
    }
  }
}
</style>
