'use strict';

var angular = require('angular'),
  _ = require('jsUtil');
require('../modules');

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

module.directive('sinoInfoCard', function() {
  return {
    restrict: 'E',
    templateUrl: 'views/info/infoCcdt.tpl.html',
    replace: true,
    controller: 'sinoInfoCardCtrl',
    controllerAs: 'infoCardCtrl'
  };
})
.controller('sinoInfoCardCtrl', function($scope, listService,
  $attrs, $state, $q, $timeout) {

  var modelId = $scope.$eval($attrs.modelId),
    refreshing = false,
    ctrl = this;

  ctrl.loadingState = 1;

  $scope.$watch('modelId', function() {
    ctrl.loadData();
  });

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

  ctrl.refresh = function() {
    init(0)['finally'](function() {
      $scope.$broadcast('scroll.refreshComplete');
      $scope.$broadcast('scroll.resize');
    });
  };

  function init(number) {
    refreshing = true;
    return listService.getListData(number).then(function(data) {
      if($scope.dataList && number > 0) {
        $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() {
        refreshing = false;
      }, 1000);//等待下拉刷新完成。
    });
  }

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

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