require('angular');
require('../modules');
require('../../info/services/listService');
'use strict';

var module = angular.module('infoRelease');

module.controller('InfoReleaseCcdtCtrl', function($scope, listService,
  $state, $q, $timeout) {
  $scope.subject = '出差动态';
  $scope.refreshing = false;
  var ctrl = this;
  ctrl.loadingState = 1;

  $scope.$on('$ionicView.beforeEnter', function() {
    $scope.refresh();
  });

  $scope.refresh = function() {
    ctrl.loadingState = 1;
    init(0).then(function(data) {
      ctrl.loadingState = !_.isEmpty(data) ? 2 : 4;
    }, function() {
      ctrl.loadingState = 3;
    });
  };

  function init(number) {
    $scope.refreshing = true;
    return listService.getListData(number).then(function(data) {
      if($scope.dataList) {
        $scope.dataList.list = $scope.dataList.list.concat(data.list);
        $scope.dataList.number = data.number;
        $scope.dataList.totalPages = data.totalPages;

      } else {
        $scope.dataList = data;
      }
      return data.list;
    }, function() {
      return $q.when(false);
    }).finally(function() {
      $timeout(function() {
        $scope.refreshing = false;
      }, 1000);//等待下拉刷新完成。
    });
  }

  $scope.moreDataCanBeLoaded = function() {
    if(_.isEmpty($scope.dataList)) {return false;}
    return !$scope.refreshing && $scope.dataList.number >= 0 && $scope.dataList.number < $scope.dataList.totalPages;
  };

  $scope.loadMore = function() {
    var number = $scope.dataList.number + 1;
    init(number).finally(function() {
      $scope.$broadcast('scroll.infiniteScrollComplete');
      $scope.$broadcast('scroll.resize');
    });
  };
});
