'use strict';

var angular = require('angular');
require('../modules');
require('../services/InfoDisplayService');
require('../../info/services/ModelService');
require('jsUtil');

var module = angular.module('infoDisplay.directives');
module.directive('sinoInfoCggs', function() {
  return {
    restrict: 'E',
    templateUrl: 'views/infoDisplay/sinoInfoCggs.tpl.html',
    replace: true,
    controller: 'sinoInfoCggsCtrl',
    controllerAs: 'infoCggsCtrl'
  };
})
.controller('sinoInfoCggsCtrl', function(InfoDisplayService, Timer,
  $attrs, $scope, $ionicScrollDelegate, $timeout, $state, ModelService) {
  var service = InfoDisplayService;
  var modelId = $scope.$eval($attrs.modelId);
  var ctrl = this;

  ctrl.init = init;
  ctrl.refresher = refresher;
  ctrl.moreDataCanBeLoaded = moreDataCanBeLoaded;
  ctrl.loadMore = loadMore;
  ctrl.toDetail = toDetail;

  $scope.$watch('modelId', function() {

    ModelService.getModelOfId(modelId).then(function(data) {
      ctrl.model = data;
    }).then(function() {
      init();
    });;
  });

  function init() {
    ctrl.loadingState = 1;
    getInfo(0).then(function(data) {
      ctrl.loadingState = 2;
    }, function() {
      ctrl.loadingState = 3;
    });
  }

  /**
   * 根据modelId获取该模块下的所有信息
   * @param  {[String]} modelId 模块ID
   * @return {[array]} 信息列表
   */
  function getInfo(pageNo) {
    return service.getInfoByModelId(ctrl.model, pageNo).then(function(data) {
      ctrl.infos = data.dataList;
      ctrl.number = data.number;
      ctrl.totalNumber = data.totalNumber;
      return data;
    });
  }


  function toDetail(item) {
    $state.go('info-infoDetailCggs', {
      modelId: item.modelId,
      infoId: item.infoId
    });
  }

  /**
   * 下滑刷新
   */
  function refresher() {
    Timer.delay(function() {
      getInfo(0).then(function() {
        $scope.$broadcast('scroll.refreshComplete');
      });
    }, 800);
  }


  function moreDataCanBeLoaded() {
    return ctrl.number >= 0 && ctrl.number < ctrl.totalNumber;
  }

  ctrl.loading = true;
  function loadMore() {
    //ctrl.number是当前的页码数，从1开始，而pageNo是从0开始
    if(ctrl.loading) {
      ctrl.loading = !ctrl.loading;
      getInfo(ctrl.number).then(function() {
        ctrl.loading = !ctrl.loading;
        $scope.$broadcast('scroll.infiniteScrollComplete');
        $scope.$broadcast('scroll.resize');
      });
    }

  }


});

