  'use strict';

  var angular = require('angular');
  require('../modules');
  require('../services/LoginService');
  require('../../../commons/services/AppConfig');

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

  /**
  * 跳转到登录页面，如果需要退出的，添加退出的属性
  * <to-login-page></to-login-page> 或者<div to-login-page></div>
  *
  * @param {String} needLoginout
  */
  module.directive('toLoginPage', function($state, LoginService, $q, $ionicActionSheet,
  AppConfig) {
    return {
      restict: 'EA',
      scope: {
        needLogout: '='
      },
      replace: true,
      template: '<button class="bind-bt" ng-click="toLogin()">重新登录</button>',
      link: function(scope) {

        /**
        * 跳转到登录页面
        */
        scope.toLogin = function() {
          return actionSheet().then(function(value) {
            return value ? LoginService.logout() : true;
          }).then(function() {
            if(!AppConfig.getCustomResult('passwordLoginEnable')) {
              $state.go('calogin');
            } else {
              $state.go('login'); // 定制是否显示密码登录页面
            }
          });
        };

        function actionSheet() {
          var deferred = $q.defer();

          if (scope.needLogout) {
            $ionicActionSheet.show({
              buttons: [{
                text: '<i class="icon ion-log-out sino-logout-icon"></i>退出登录'
              }],
              cancelText: '取消',
              cancel: function() {
                deferred.reject('取消登录');
                return true;
              },
              buttonClicked: function() {
                deferred.resolve(true);
                return true;
              }
            });
          } else {
            deferred.resolve(false);
          }
          return deferred.promise;
        }
      }
    };
  });
