import "./index.css";
import "core-js/modules/web.dom.iterable";

/* script */
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
import { createComponentName, componentMixin } from '../_utils/component';
import Icon from '../Icon';
import NomoreTemplets from './NomoreTemplets';
import { isSSR } from '../_utils/constant';

if (!isSSR()) {
  require('intersection-observer');
}

const __vue_script__ = {
  name: createComponentName('loadmore'),
  components: {
    Icon
  },
  NomoreTemplets,
  mixins: [componentMixin],
  props: {
    // 业务方请求
    loadmore: {
      type: Function,
      required: true
    },
    // 是否自动加载更多
    autoLoad: {
      type: Boolean,
      default: true
    },
    // 无数据状态
    isNoMore: {
      type: Boolean,
      default: false
    },
    // 加载失败状态
    isError: {
      type: Boolean,
      default: false
    },
    // 视图窗口展示的百分比 执行数据加载
    threshold: {
      type: Number,
      default: 0.5
    },
    // 距离底部加载的距离
    offset: {
      type: Number,
      default: 0
    }
  },

  data() {
    return {
      pending: false
    };
  },

  watch: {
    isNoMore(v) {
      if (!v) this.tryLoad();
    },

    isError(v) {
      if (!v) this.tryLoad();
    }

  },

  mounted() {
    // 传入fn进来 dom 渲染交给业务  返回promise 来操作页面loading状态
    const onIntersection = observation => {
      observation.forEach(async change => {
        this.intersectionRatio = change.intersectionRatio;
        this.tryLoad();
      });
    };

    this.observer = new IntersectionObserver(onIntersection, {
      threshold: [0, 0.25, 0.5, 0.75, 1],
      rootMargin: `0px 0px ${this.offset}px 0px`
    });
    const bottom = this.$refs.loadmore;
    this.observer.observe(bottom);
  },

  beforeDestroy() {
    if (this.$refs.loadmore && this.observer) {
      this.observer.unobserve(this.$refs.loadmore);
    }
  },

  methods: {
    async tryLoad() {
      if (!this.pending && this.intersectionRatio > this.threshold) {
        // 无数据状态 数据加载失败状态 不触发分页加载
        if (!this.autoLoad || this.isError || this.isNoMore) {
          return;
        }

        await this.load();
      }
    },

    async reload() {
      await this.load();
    },

    async load() {
      this.pending = true;

      try {
        await this.loadmore();
        this.pending = false; // 处理加载更多后，组件仍处于视口，需要再重新重新加载下一页

        setTimeout(() => {
          this.tryLoad();
        }, 0);
      } catch (error) {
        this.pending = false;
        throw error;
      }
    }

  }
};
/* template */

var __vue_render__ = function () {
  var _vm = this;

  var _h = _vm.$createElement;

  var _c = _vm._self._c || _h;

  return _c("div", {
    ref: "loadmore",
    class: _vm.bem()
  }, [_vm.isError ? _c("div", {
    class: [_vm.bem("btn"), _vm.bem("error")],
    on: {
      click: _vm.reload
    }
  }, [_vm._t("error", [_vm._v("加载失败，请重试")])], 2) : _vm.isNoMore ? _c("div", [_c("div", {
    class: _vm.bem("nomore")
  }, [_vm._t("nomore", [_vm._v("\n                没有更多了\n            ")])], 2)]) : [!_vm.autoLoad ? _vm._t("more", [_c("div", {
    class: _vm.bem("btn"),
    on: {
      click: _vm.reload
    }
  }, [_vm.pending ? _c("Icon", {
    attrs: {
      name: "loading"
    }
  }) : _vm._e(), _vm._v("\n                加载更多\n            ")], 1)], {
    reload: _vm.reload,
    isLoading: _vm.pending
  }) : _c("div", {
    class: _vm.bem("loading")
  }, [_vm._t("loading", [_c("span", [_vm._v("玩命加载中...")])])], 2)], _vm._v(" "), _vm._t("footer")], 2);
};

var __vue_staticRenderFns__ = [];
__vue_render__._withStripped = true;
/* style */

const __vue_inject_styles__ = undefined;
/* scoped */

const __vue_scope_id__ = undefined;
/* module identifier */

const __vue_module_identifier__ = undefined;
/* functional template */

const __vue_is_functional_template__ = false;
/* component normalizer */

import __vue_normalize__ from '../_utils/vue-normalize-component.js';
/* style inject */

/* style inject SSR */

export default __vue_normalize__({
  render: __vue_render__,
  staticRenderFns: __vue_staticRenderFns__
}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined);