<template>
  <van-pull-refresh v-model="refreshing" @refresh="refresh" class="flow-y-dhc flex-1-dhc" :style="{ width: dWidth + 'px' }">
    <van-list ref="list" v-model="loading" :finished="finished" :error="error" :offset="offset" :loading-text="loadingText" :finished-text="finishedText" :error-text="errorText" :immediate-check="immediateCheck" :direction="direction" @load="onLoad">
      <slot></slot>
      <slot :name="loading"></slot>
      <slot :name="finished"></slot>
      <slot :name="error"></slot>
    </van-list>
  </van-pull-refresh>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
/**
 * @Description 列表封装，实现下拉刷新
 * @Author lbb
 * @Date 2021年12月15日15:47:15
 */
@Component({
  name: "BaseList",
})
export default class BaseList extends Vue {
  @Prop({ default: () => [] }) data: any[] | undefined; // 列表数据
  @Prop({ default: 100 }) offset: number | undefined; // 滚动条与底部距离小于 offset 时触发load事件
  @Prop({ default: "" }) loadingText: string | undefined; // 加载过程中的提示文案
  @Prop({ default: "" }) finishedText: string | undefined; // 加载完成后的提示文案
  @Prop({ default: "" }) errorText: string | undefined; // 加载失败后的提示文案
  @Prop({ default: false }) immediateCheck: boolean | undefined; // 是否在初始化时立即执行滚动位置检查
  @Prop({ default: "down" }) direction: string | undefined; // 滚动触发加载的方向，可选值为up
  @Prop({ default: 10 }) pageLines: number | undefined; // 分页查询数据的条数，默认10条数据,需要和传递给服务端的条数保持一致
  @Prop({ default: "" }) dWidth: string | undefined; // 横向滚动行宽 - 适配表格横向滚动

  @Watch("data")
  onData(value: any) {
    if (this.pageLines ? value.length <= this.pageLines : false) {
      this.finished = false;
    }
  }
  recordsLen = 0;
  loading = false;
  finished = false;
  error = false;
  refreshing = false;
  /**
   * 加载更多函数，滚动条与底部距离小于 offset 时触发
   */
  onLoad() {
    let pageNo = this.data && this.pageLines ? Math.round(this.data.length / this.pageLines) + 1 : 1; //当前页数
    this.recordsLen = this.data ? this.data.length : 0;
    this.loading = true;
    this.$emit("onLoad", pageNo, this);
  }
  /**
   * 数据加载时调用
   */
  onStoreLoad(data = this.data) {
    let count = data?.length,
      len = this.pageLines ? (this.recordsLen || 0) + this.pageLines : 1;
    this.finished = false; // 重置加载完成
    if (count === this.recordsLen) {
      //count(当前的数据) == this.recordsLen(之前的数据，就是没加10条数据时)
      this.finished = true;
    } else if (count && count < len) {
      this.finished = true;
    }
    this.loading = false;
  }
  //刷新
  refresh() {
    this.$emit("refresh", this);
  }
}
</script>

<style lang="scss" scoped></style>
