Source: components/admin/controllers/editar_usuario.controller.js

/**
 * @ngdoc controllers
 * @name editarUsuario
 * @module s4c.components.admin.controllers.editarUsuario
 *
 * @description
 * `UsuarioCtrl` Controller da tela de Usuários do módulo de administração
 * 
 * 
 */
(function () {
    'use strict';

    function UsuarioCtrl($scope, $stateParams, $mdDialog, $state, Usuario, Departamento, AuthService, FileUploader, CommService, MainService, Base) {
        var id = $stateParams.id;

        var originalState;
        var base64img;

        Departamento.getAgencias()
            .then(function (departamentos) {
                $scope.departamentos = departamentos;
            });

        Usuario.obterPorId(id)
            .then(function (usuario) {
                originalState = angular.copy(usuario);
                $scope.editarUsuario = usuario;
                $scope.gruposUsuario = _.map(usuario.GrupoUsuarios, 'nome').join(', ');
                AuthService.user.info.id == usuario.id ? $scope.usuarioLogado = true : $scope.usuarioLogado = false;
            });

        /**
         * @method isLdapLogin
         */
        function isLdapLogin() {
            Base.obter('ldap/authenticatedUser').then(function (response) {
                if (response.ldapAuthenticatedUser != null && response.ldapAuthenticatedUser) {
                    $scope.isLdapAuthenticatedUser = true;
                } else {
                    $scope.isLdapAuthenticatedUser = false;
                }
            });
        }

        /**
         * @method toBlob
         */
        function toBlob() {
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            canvas.height = document.getElementById('editarHeight').value;
            canvas.width = document.getElementById('editarWidth').value;
            ctx.drawImage(document.getElementById('image'), document.getElementById('editarX').value, document.getElementById('editarY').value, canvas.width, canvas.height, 10, 10, canvas.width, canvas.height);

            if (canvas.toBlob) {
                canvas.toBlob(function (blob) {
                    var formData = new FormData();

                    var token = window.sessionStorage.getItem('s4cToken');
                    var tokenObj = JSON.parse(token);

                    formData.append('arquivo', blob, "avatar.png");
                    $.ajax('/usuarios/' + $scope.editarUsuario.id, {
                        method: "POST",
                        data: formData,
                        processData: false,
                        contentType: false,
                        headers: {
                            'Authorization': 'Bearer ' + tokenObj.access_token
                        },
                        success: function (data) {
                            var usuarioIdSessao = $.parseJSON(sessionStorage.s4cToken).usuario.id;
                            if ($scope.editarUsuario.id == usuarioIdSessao) {
                                $('.imagem-usuario').attr("src", data.imgUrl);
                                AuthService.getUserInfo().then(function (usuario) {
                                    usuario.urlImagem = data.imgUrl;
                                });
                            }
                        },
                        error: function () {
                            console.log('Upload error');
                        }
                    });
                });
            }
        }

        /**
         * @method resetarSenha
         * @param {*} usuario 
         */
        function resetarSenha(usuario) {
            $mdDialog.show({
                controller: function ($scope, $mdDialog) {
                    $scope.res = $scope.$root.res;
                    $scope.salvar = function (senha) {
                        if ($scope.resetarSenha.$valid) {
                            $mdDialog.hide(senha);
                        }
                    };

                    $scope.cancelar = function () {
                        $mdDialog.hide();
                    }
                },
                templateUrl: 'app/components/admin/modulos/usuarios/Usuario/nova_senha.html'
            })
                .then(function (password) {
                    AuthService.resetUserPassword(usuario.id, password)
                        .then(function (usuario) {
                            $mdDialog.hide();
                            var dialog = $mdDialog;
                            dialog
                                .show(dialog.alert()
                                    .title($scope.res('COMUM_SUCESSO'))
                                    .content($scope.res('RESET_SENHA'))
                                    .ok($scope.res('COMUM_OK')))
                                .then(function () {
                                    dialog.hide();
                                    $state.go('admin.usuarios_agencias_perfis');
                                });
                        }, function (err) {
                            $mdDialog.hide();
                        });
                }, function () { });
        }

        /**
         * @method salvarUsuario
         */
        function salvarUsuario() {
            var confirm = $mdDialog.confirm()
                .title($scope.res('CERTEZA_SALVAR_USUARIO'))
                .content($scope.res('MENSAGEM_MUDANCAS_IRREVERSIVEIS'))
                .ariaLabel($scope.res('SALVAR_USUARIO'))
                .ok($scope.res('COMUM_SIM'))
                .cancel($scope.res('COMUM_CANCELAR'));

            $mdDialog.show(confirm)
                .then(function () {
                    Usuario.atualizar($scope.editarUsuario.id, $scope.editarUsuario)
                        .then(function () {
                            if ($("#image").length > 0) {
                                toBlob();
                            }
                            if (_.has(originalState, 'DepartamentoId') &&
                                originalState.DepartamentoId !== $scope.editarUsuario.DepartamentoId) {

                                var confirm = $mdDialog.confirm()
                                    .title($scope.res('COMUM_ATENCAO'))
                                    .content($scope.res('USUARIO_TER_ACESSO_PERFIL'))
                                    .ariaLabel($scope.res('COMUM_ATENCAO'))
                                    .ok($scope.res('COMUM_OK'));

                                $mdDialog.show(confirm)
                                    .then(function () {
                                        $state.go('admin.usuarios_agencias_perfis');
                                    }, function () {
                                        $state.go('admin.usuarios_agencias_perfis');
                                    });
                            } else {
                                $state.go('admin.usuarios_agencias_perfis');
                            }
                        });
                });
        }

        /**
         * @method excluirUsuario
         */
        function excluirUsuario() {
            var confirm = $mdDialog.confirm()
                .title($scope.res('CERTEZA_DELETAR_USUARIO'))
                .content($scope.res('MENSAGEM_MUDANCAS_IRREVERSIVEIS'))
                .ariaLabel($scope.res('DELETAR_USUARIO'))
                .ok($scope.res('COMUM_SIM'))
                .cancel($scope.res('COMUM_CANCELAR'));

            $mdDialog.show(confirm)
                .then(function () {
                    Usuario.remover($scope.editarUsuario.id)
                        .then(function () {
                            $state.go('admin.usuarios_agencias_perfis');
                        });
                });
        }
        $scope.input = angular.element('input.uploadArquivo');
        function abrirUpload() {
            $scope.input.click();
        }

        var uploader = $scope.uploader = new FileUploader(),
            uploadCallbackQueue = [];

        uploader.clearQueue();

        $scope.uploader.filters.push({
            'name': 'enforceMaxFileSize',
            'fn': function (item, evt) {
                var megaByte = parseInt(item.size / 1000000) + "MB";
                if (item.size <= 26214400) {
                    return item.size <= 26214400
                } else {
                    $mdDialog
                        .show($mdDialog.alert()
                            .title($scope.res('COMUM_TAMANHOFILEULTRAPASSADO'))
                            .content($scope.res('LIMITE_ARQUIVO_ULTRAPASSADO', megaByte))
                            .ok($scope.res('COMUM_OK')))
                    return item.size <= 26214400
                }
            }
        });

        $scope.uploader.onCompleteItem = function (item, response) {
            $scope.mensagem = response;
        };

        $scope.uploader.onAfterAddingFile = function (item, evt, arquivo) {
            item.novoNome = item.file.name;
            enviarArquivo();
        }

        function ext(filename) {
            var index = _.lastIndexOf(filename, '.');
            return filename.substring(index, filename.length);
        }

        $scope.uploader.onBeforeUploadItem = function (item) {
            item.url = uploader.url;
            var token = window.sessionStorage.getItem('s4cToken');
            var tokenObj = JSON.parse(token);
            item.headers = {
                'Authorization': 'Bearer ' + tokenObj.access_token
            };
            item.file.name = item.novoNome + ext(item.file.name);
        };

        $scope.uploader.onProgressItem = function (fileItem, progress) {
            console.info('onProgressItem', fileItem, progress);
            //listaEquals = [];
        };

        $scope.uploader.onCompleteAll = function (result) {
            _.each(uploadCallbackQueue, function (callback) {
                callback();
            });
        };


        $scope.mostrarImagem = function () {
            $('#arquivo').each(function (index) {
                if ($('#arquivo').eq(index).val() != "") {
                    $scope.readURL(this);
                }
            });
        }


        $scope.readURL = function (input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $("#renderCropper").empty();
                    var img = $('<img />',
                        {
                            id: 'image',
                            src: e.target.result,
                            style: 'width: 100%'
                        }).appendTo($('#renderCropper'));
                    var cropper = new Cropper(img[0], {
                        aspectRatio: 1,
                        crop: function (e) {
                            document.getElementById('editarX').value = e.detail.x;
                            document.getElementById('editarY').value = e.detail.y;
                            document.getElementById('editarWidth').value = e.detail.width;
                            document.getElementById('editarHeight').value = e.detail.height;
                        },
                        zoomable: true,
                        scalable: true,
                        movable: true,
                        background: false,
                        viewMode: 1
                    });
                };
                reader.readAsDataURL(input.files[0]);
            }
        }



        function enviarArquivo() {
            $scope.mostrarImagem();
        }

        $scope.uploader.alias = 'arquivo';
        $scope.uploader.removeAfterUpload = true;

        angular.extend($scope, {
            salvarUsuario: salvarUsuario,
            excluirUsuario: excluirUsuario,
            resetarSenha: resetarSenha,
            abrirUpload: abrirUpload
        });

        isLdapLogin();

    }

    angular.module('s4c.controllers.UsuarioCtrl', [
        'ngMaterial',
        's4c.services.Usuario',
        's4c.services.Departamento'
    ])
        .controller('UsuarioCtrl', UsuarioCtrl);

    UsuarioCtrl.$inject = [
        '$scope',
        '$stateParams',
        '$mdDialog',
        '$state',
        'Usuario',
        'Departamento',
        'AuthService',
        'FileUploader',
        'CommService',
        'MainService',
        'Base'
    ];

}());