<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
        v-if="pageType === 'pagination'"
        class="pagination"
        background
        layout="prev, pager, next,total, jumper"
        :total="count"
        :page-size="rows"
        @current-change="page => load(page)"
      />
      <div
        class="increase"
        v-if="pageType === 'increase' && items.length < count"
        @click="load(params.pageNum + 1)"
      >
        {{ loading ? `${$t(`loading`)}` : `${increaseText || $t("loadMore")}` }}
        <img v-if="loading" src="@assets/throbber.svg" />
        <!-- <img
          :src="require(`@assets/${loading ? `throbber.svg` : `throbber.svg`}`)"
          alt=""
        /> -->
      </div>
    </template>
    <template v-else-if="count === 0 && !hideTip">
      <div class="noneData">
        <img src="@assets/noneData.png" alt="" />
        <br />
        <div>{{ $t("nodata") }}</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({
    type: Object,
    default: () => ({})
  })
  params!: IAny | null;
  @Prop({ default: 10 })
  private readonly rows!: number;
  @Prop(Boolean) private hideTip!: boolean;
  @PropSync("total") totalSync!: number;
  @Prop({ default: "pagination" })
  private readonly pageType!: "none" | "pagination" | "increase";
  @Prop(String)
  private increaseText!: string;
  private count: number | null = null;
  private items: any[] = [];
  private loading = false;
  @Watch("params", { immediate: true, deep: true })
  reload() {
    if (!this.params) return;
    this.items = [];
    return this.load(1);
  }
  @Watch("count")
  totalChange() {
    this.totalSync = this.count || 0;
  }
  @Emit("getItems")
  async load(pageNum: number) {
    if (this.loading) return;
    this.loading = true;
    const [err, { rows = [], total = 0 }] = await this.$post<IPageResult>(
      this.url,
      Object.assign(this.params, {
        pageNum,
        pageSize: this.rows
      })
    );
    this.count = total;
    this.items = [...(this.pageType === "increase" ? this.items : []), ...rows];
    this.loading = false;
    return this.items;
  }
}
</script>
<style lang="scss" scoped>
.loadMore {
  width: 100%;
  overflow: hidden;
  .list {
    overflow: hidden;
  }
  .pagination {
    text-align: right;
    margin-top: 2rem;
  }
  .increase {
    text-align: center;
    cursor: pointer;
  }
  .noneData {
    padding: 5rem;
    text-align: center;
    img {
      width: 15rem;
    }
    div {
      font-size: 1.5rem;
      color: #999;
      margin-top: 1rem;
    }
  }
}
</style>
