const wx2my = require('../wx2my');
const Behavior = require('../Behavior');
class RenderPage {
  constructor() {
    this.pagingPoint = []; // 需要被渲染的节点段

    this.previousPoint = 0; // 已渲染数据的索引

    this.groupTabsIndex = -1;
    this.previousRenderData = []; // 已渲染的数据
  }

  initPaging(pagingPoint) {
    if (toString.call(pagingPoint) !== '[object Array]') {
      throw new Error('pagingPoint is not array');
    }

    this.pagingPoint = pagingPoint;
    this.previousPoint = 0;
    this.hiddenGroupsTab = [];
    this.groupTabsIndex = -1;
    return this;
  }

  initRenderData(data) {
    if (toString.call(data) !== '[object Array]') {
      throw new Error('data is not Array');
    }

    this.renderData = data;
    return this;
  }
  /**
     * 获取比index大的缓存数据
     * @param index
     * @returns {*|Array}
     */


  getCacheDataByGroupTabsIndex(index) {
    if (index > -1) {
      this.groupTabsIndex = index;
      const res = this.previousRenderData.reduce((total, item) => {
        total.count += item.length;

        if (total.count > index) {
          total.temp = total.temp.concat(item.map(it => {
            return {
              hidden: true,
              ...it
            };
          }));
        }

        return { ...total
        };
      }, {
        count: 0,
        temp: []
      });
      this.hiddenGroupsTab = res.temp;
      return res.temp;
    } else {
      throw new Error('setGroupTabsIndex index is invalidate');
    }
  }
  /**
   * 获取下一个节点的数据
   */


  next() {
    const pagingPoint = this.pagingPoint;
    let res = {
      done: true,
      value: []
    };
    let renderPoint = [];
    const showRes = this.showHiddenRes();

    if (showRes.length) {
      this.hiddenGroupsTab = [];
      const index = this.groupTabsIndex;
      res = {
        done: true,
        value: showRes,
        type: 'showResult',
        index
      };
      return res;
    }

    if (pagingPoint.length) {
      const item = this.pagingPoint.shift();
      renderPoint = this.renderData.slice(this.previousPoint, item.index + 1);
      res = {
        value: renderPoint,
        done: false
      };
      this.previousPoint = item.index + 1;
    } else {
      renderPoint = this.renderData.slice(this.previousPoint);
      res = {
        value: renderPoint,
        done: true
      };
    }

    this.cacheRenderData(renderPoint);
    return res;
  }

  showHiddenRes() {
    return this.hiddenGroupsTab.map(item => {
      return { ...item,
        hidden: false
      };
    });
  }
  /**
     * 缓存分页的数据
     * @param index
     * @param renderData
     */


  cacheRenderData(renderData) {
    this.previousRenderData.push(renderData);
  }

}

module.exports = {
  renderPage: new RenderPage(),
  getRenderPage: () => new RenderPage()
};