'use strict';

var angular = require('angular'),
  _ = require('jsUtil');
require('../modules');
require('../../info/services/InfosPageLocalStorageService');
require('../../info/services/InfosService');
require('../../info/services/ModelService');

var module = angular.module('infoDisplay.services');

module.factory('InfoDisplayService', function($q, InfosPageLocalStorageService,
  InfosService, ModelService) {

  var service = {};
  var storage = InfosPageLocalStorageService;
  var pageSize = 15.0;

  InfosPageLocalStorageService.setPageSize(pageSize);

  service.getInfoByModelId = function(model, pageNo) {

    var dataList = storage.getDataList(model.id);
    if(_.isEmpty(dataList) || (_.isEmpty(dataList.data)) || pageNo <= dataList.getTotalPages()) {
      return this.refreshStorageInfo(model, pageNo, dataList);
    } else {
      if(pageNo === 0) {
        this.refreshStorageInfo(model, pageNo, dataList);
      }
      return $q.when({
        success: true,
        dataList: dataList.data,
        number: Math.ceil(dataList.data.length / pageSize),//是当前数据的总大页码
        totalNumber: Math.ceil(dataList.totalElements / pageSize)
      });
    }
  };

  service.refreshStorageInfo = function(model, pageNo, dataList) {
    var needReplaceDataList = pageNo == 0;
    var _md5 = storage.getMd5(model.id, 0);
    var storage_md5  = _.isEmpty(_md5) ? '-1' : _md5;
    return InfosService.getInfoList(model.mode, model.id,
      needReplaceDataList? 0 : dataList.getTotalPages(), model.listUrl, storage_md5)
    .then(function(data) {
      if(needReplaceDataList && !_.isEmpty(storage_md5) && storage_md5 != data.md5) {
        dataList.clear();

        dataList.add(data.content, data.totalElements, pageSize);
        storage.saveDataList(model.id, dataList);
        storage.setMd5(model.id, 0, data.md5);
      } else if(!needReplaceDataList){
        dataList.add(data.content, data.totalElements, pageSize);
        storage.saveDataList(model.id, dataList);
        storage.setMd5(model.id, 0, data.md5);
      }
      return {
        success: true,
        dataList: dataList.data,
        number: Math.ceil(dataList.getTotalPages()),//是当前数据的总大页码
        totalNumber: Math.ceil(dataList.totalElements / pageSize)
      };
    }, function() {
      return {
        success: false,
        dataList: dataList.data,
        number: Math.ceil(dataList.getTotalPages()),
        totalNumber: Math.ceil(dataList.totalElements / pageSize)
      };
    });
  };
  return service;
});
