/**
 ****--@date 2024-06-07 09:47:03
 ****--@author yizhiyang
 ****--@description  list mixin 主要处理上拉加载和分页
 **/
module.exports = {
  data() {
    return {
      total: 0,
      listData: [],
      // loadmore(加载前) loading（加载中） nomore（没有更多数据）
      loadmoreStatus: 'loadmore',
      page: {
        pageNum: 1,
        pageSize: 10,
      },
      queryData: {},
    };
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.loadData();
  },
  // 触底刷新
  onReachBottom() {
    let { pageNum, pageSize } = this.page;
    if (pageNum * pageSize > this.total) return;
    this.page.pageNum++;
    this.initDataList(this.queryData, true);
  },

  methods: {
    // 分页初始化数据isUp是否为上拉加载，默认false
    initDataList(searchData = {}, isUp = true) {
      this.isListLoading = true;

      uni.showLoading({
        title: '加载中',
        mask: true,
      });

      /* 参数的处理 */
      this.queryData = Object.assign(
        {},
        { ...searchData },
        {
          paging: `${this.page.pageNum},${this.page.pageSize}`,
        },
      );
      if (!isUp) this.page.pageNum = 1;

      this.listApiName({ ...this.queryData })
        .then(res => {
          if (isUp) {
            this.listData = this.listData.concat(res.data.records);
          } else {
            this.listData = res.data.records;
          }
          this.total = res.data.total;

          if (this.listData.length < this.total) {
            this.loadmoreStatus = 'loadmore';
          } else {
            this.loadmoreStatus = 'nomore';
          }
        })
        .finally(() => {
          this.isListLoading = false;
          setTimeout(() => {
            uni.hideLoading();
          }, 1000);
        });
    },

    loadData() {
      this.page.pageNum = 1;
      this.initList = [];
      this.initDataList(this.queryData);
      this.loadmoreStatus = 'nomore';

      setTimeout(function () {
        uni.stopPullDownRefresh();
      }, 2000);
    },
  },
};
