var angular = require('angular');
require('../modules');
require('../services/LoginService');
require('../LoginModal');
'use strict';

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

module.controller('LoginCtrl', function($scope, LoginService,
  $ionicModal, $rootScope, $timeout, $state, $toast, CommonService,
  $ionicLoading, $window, $ionicPopup, CoreAppConfig, LoginModal, Timer) {

  $scope.data = {
    serverUrl: CoreAppConfig.serverUrl
  };
  $scope.user = {};
  $scope.showLoading = function() {
    $ionicLoading.show({
      content: '登录中..',
      animation: 'fade-in',
      showBackdrop: true
    });
  };

  var user = LoginService.getLastLoginUser();
  $scope.lastLoginUser = user;
  $scope.user.userName = user ? (user.loginName || user.userName) : '';

  $scope.showLoginModal = function() {
    LoginModal.show();
  };
  $scope.showLoginModalOnly =function() {
    $scope.tishi2 = true;
    $scope.tishici = '切换用户';
    Timer.delay(function() {
      $scope.showLoginModal();
      $scope.tishi2 = false;
    }, 1000);
  };
  /**
   * scope作用域销毁时将登录弹层移除。
   */
  $scope.$on('$destroy', function() {
    if ($scope.settingModal) {
      $scope.settingModal.remove();
    }
  });

  $scope.loginNormal = function() {
    $scope.login($scope.user);
  };

  $scope.login = function(user, successFn) {
    if(user.userName.toLocaleLowerCase() === 'admin'){
      $toast.showLongCenter('管理员权限暂没开放！');
      return;
    }
    $scope.showLoading();
    return LoginService.login(user, successFn).then(function(data) {
      if (!data.success) {
        $toast.showLongCenter(data.msg);
      } else if (data.mask) {
        $toast.showLongCenter('当前登录用户被屏蔽掉，请联系管理员在黑白名单设置中查找原因！');
      }
    }, function() {
      $toast.showLongCenter('网络无法连接，请您查看本地网络是否连通或联系管理员查看');
    })['finally'](function() {
      $ionicLoading.hide();
    });
  };


  $scope.showSettingModalOnly =function() {
    $scope.tishi3 = true;
    $scope.tishici = '设置';
    Timer.delay(function() {
      $scope.showSettingModal();
      $scope.tishi3 = false;
    }, 1000);
  };

  $scope.toCA = function() {
    $state.go('calogin');
  };
  $scope.tishi1 = false;
  $scope.toCAOnly = function() {
    $scope.tishi1 = true;
    $scope.tishici = '证书登录';
    Timer.delay(function() {
      $state.go('calogin');
      $scope.tishi1 = false;
    }, 1000);
  };

});
