var angular = require('angular');
require('../modules');
'use strict';

/**
 * 信息发布Detail页面 缓存服务
 */
var module = angular.module('info.services');

function SmallPage() {
  this.items = [];
}

SmallPage.prototype = {
  isFull: function() {
    return this.items.length == 1?
      !_.isEmpty(this.items[0].imageFilePath) :
      this.items.length >= 2;
  },

  add: function(item) {
    this.items.push(item);
  }
};

/**
 * 整个的数据列表
 *
 * @param {Array} data
 * @param {Number} totalElements
 */
function DataList(data, totalElements, size) {
  this.data = data || [];
  this.totalElements = totalElements;
  this.pages = this.generatePages();
  this.size = size;
}

DataList.prototype = {

  generatePages: function() {
    var currentNotFullPage, page, pages = [];

    for (var i = 0, len = this.data.length; i < len; i++) {
      var value = this.data[i];
      value.imageFilePath = value.img? value.img.src : null;
      if (_.isEmpty(value.imageFilePath)) {
        if (!currentNotFullPage) {
          currentNotFullPage = new SmallPage();
          pages.push(currentNotFullPage);
        }
        currentNotFullPage.add(value);
        if (currentNotFullPage.isFull()) {
          currentNotFullPage = null;
        }
      } else {
        page = new SmallPage();
        page.idx = i;
        page.add(value);
        pages.push(page);
      }
    }
    this._handleIdx(pages);
    return pages;
  },

  _handleIdx: function(pages) {
    var num = 0, page;
    for (var i = 0, len = pages.length; i < len; i++) {
      page = pages[i];
      num += page.items.length;
      page.idx = num - 1;
    }
  },

  add: function(data, totalElements, size) {
    this.data = this.data.concat(data || []);
    this.totalElements = totalElements;
    this.pages = this.generatePages();
    this.size = size;//一大页的数据量（36/15）
  },

  clear: function() {
    this.data = [];
    this.totalElements = 0;
    this.pages = this.generatePages();
  },

  getPage: function(i) {
    return this.pages[i - 1];
  },

  getPageSize: function() {
    return this.pages.length;
  },

  needGetData: function(pageNo) {
    var notEnough = this.getPageSize() < pageNo,
      lastNotFullPage = this.getPageSize() == pageNo && !this.getPage(pageNo).isFull();
    return notEnough || lastNotFullPage;
  },

  isEnd: function(smallPageNo) {
    return this.getPage(smallPageNo).idx == this.totalElements - 1;
  },

  getTotalPages: function() {
    return Math.ceil(this.data.length / this.size);
  },

  getTotalElements: function() {
    return this.totalElements;
  },

  getInfoByInfoId: function(infoId) {
    var info;
    for (var i = 0, len = this.data.length; i < len; i++) {
      info = this.data[i];
      if (info.infoId === infoId || info.id === infoId) {//公文中只有ID没有infoID
        return info;
      }
    }
    return null;
  }
};

module.factory('InfosPageLocalStorageService', function() {
  var dataListCache = {};
  var size = 15;

  var service = {
    setPageSize: function(pageSize) {
      size = pageSize;
    },
    getDataList: function(modelId) {
      if (!dataListCache[modelId]) {
        var infos = this.getInfos(modelId),
        totalElements = this.getTotalElements(modelId);
        if (infos && infos.length > 0 && totalElements == 0) {
          totalElements = 10000; //设置为大值，解决缓存中没有totalElement的bug。
        }
        dataListCache[modelId] = new DataList(infos, totalElements, size);
      }
      return dataListCache[modelId];
    },

    saveDataList: function(modelId, dataList) {
      this.setInfos(modelId, dataList.data);
      this.setTotalElements(modelId, dataList.totalElements);
    },

    /**
     * 按照模块缓存信息列表
     * @param {[type]} modelId 模块ID
     * @param {[type]} infos   信息列表
     */
    setInfos: function(modelId, infos) {
      var jsonInfos = JSON.stringify(infos);
      localStorage.setItem(modelId + 'infoList', jsonInfos);
    },
    getInfos: function(modelId) {
      return JSON.parse(localStorage.getItem(modelId + 'infoList'));
    },

    setMd5: function(modelId, pageNo, md5) {
      localStorage.setItem(modelId + 'infosmd5' + pageNo, md5);
    },

    getMd5: function(modelId, pageNo) {
      var _md5 = localStorage.getItem(modelId + 'infosmd5' + pageNo);
      if(_.isEmpty(_md5)) {
        _md5 = null;
      }
      return _md5;
    },

    /**
     * 缓存总个数
     */
    setTotalElements: function(modelId, totalElements) {
      localStorage.setItem('$$totalElements_' + modelId, JSON.stringify(totalElements));
    },

    /**
     * 获取总个数
     * @param  {String} modelId
     */
    getTotalElements: function(modelId) {
      var totalElements = localStorage.getItem('$$totalElements_' + modelId);
      if(_.isEmpty(totalElements)) {
        totalElements = 0;
      } else {
        totalElements = parseInt(totalElements);
      }
      return totalElements;
    }

  };

  return service;
});
