'use strict';

var angular = require('angular');

require('../modules');
require('../services/DeviceLoginRecordsService');
require('../../login/services/LoginService');

var module = angular.module('devicemanager.controller');

module.filter('normalTime', function() {
  var filterfun = function(timeStr) {
    var str = timeStr || '';
    return str.slice(0,str.length-5).replace('T',' ');
  };
  return filterfun;
});

module.controller('DeviceManagerCtrl', function($rootScope, $scope, DeviceLoginRecordsService,
  LinkerService, LoginService, $state) {

  $scope.refreshState = {
    begin: false,
    done: false
  };

  $scope.device = window.device;


  //页面上的返回按钮
  $scope.goBack = function() {
    $state.go('devicemanager.accountProtect');
  };

  $scope.showUserLoginRecordsOnDevice = function() {
    $state.go('devicemanager.devicerecord');
  };

  //回到设置页面
  $scope.goBackSetting = function() {
    $state.go('core-setting');
  };

  $scope.getLoginHistory = function() {
    $state.go('devicemanager.showLoginHistory');
  };

  $scope.onRefresh = function() {
    $scope.refreshState.begin = true;
    $scope.refreshState.done = false;
    $scope.showLoginHistory().then(function() {
      $scope.$broadcast('scroll.refreshComplete');
    })['finally'](function() {
      $scope.refreshState.done = true;
    });
  };

  $scope.loadingState = 1;
  //获取用户登录历史记录
  function showLoginHistory() {
    var userId = LinkerService.currentUserId;
    return DeviceLoginRecordsService.getLoginHistory(userId).then(function(data) {
      $scope.loginHistorys = data;
      $scope.loadingState = data.length > 0 ? 2 : 4;
      return $scope.loginHistorys;
    }, function() {
      $scope.loadingState = 3;
    });
  }
  showLoginHistory();
  $scope.showLoginHistory = showLoginHistory;

  $scope._deviceStatus = JSON.parse(localStorage.getItem('deviceStatus'));
});
