Source: directives/minhas-tarefas/minhas-tarefas.js

/**
 * @ngdoc directives
 * @name Tarefas
 * @module s4c.directives.minha-tarefa.Tarefas
 *
 * @description
 * `Tarefas` Gerenciamento do módulo de tarefas  
 * 
 */
(function () {
    'use strict';

    tarefasCtrl.$inject = [
        '$scope',
        '$http',
        '$mdDialog',
        'API_ENDPOINT',
        '$q',
        'TarefaService',
        'MainState',
        'CommService',
        'AuthService',
        'TarefaManager',
        'localize'
    ];

    function tarefasCtrl($scope, $http, $mdDialog,
        API_ENDPOINT, $q, TarefaService, MainState, CommService, AuthService, TarefaManager, localize) {

        $scope.res = $scope.$root.res;

        $scope.getMatches = function (query) {
            var deferred = $q.defer();
            $http.get(API_ENDPOINT + 'usuarios/find/' + query)
                .then(function (res) {
                    if (_.isEmpty(res.data)) {
                        deferred.resolve([]);
                    } else {
                        deferred.resolve(res.data);
                    }
                });
            return deferred.promise;
        };

        CommService.on('tarefas:update', function (tarefa) {
            var tarefaAntiga = _.find($scope.tarefasAbertas.concat($scope.tarefasConcluidas), { id: tarefa.id });

            tarefaAntiga.concluida = tarefa.concluida;

            $scope.$apply();
        });

        /**
         * @method getTarefas
         */
        function getTarefas() {
            $scope.tarefasAbertas = _.chain(res.data)
                .reject(function (d) { return d.estado == 'CONCLUIDA' })
                .sortBy('id')
                .value();

        }

        /**
         * @method atualizarTarefas
         */
        function atualizarTarefas() {
            $http.get(API_ENDPOINT + 'tarefas/usuario/' + AuthService.user.info.id)
                .then(function (res) {
                    $scope.tarefasConcluidas = _.chain(res.data)
                        .filter(function (d) { return d.estado == 'CONCLUIDA' })
                        .map(function (d) { d.concluida = true; return d; })
                        .sortBy('id')
                        .value();

                    $scope.tarefasAbertas = _.chain(res.data)
                        .reject(function (d) { return d.estado == 'CONCLUIDA' })
                        .sortBy('id')
                        .value();
                    if ($scope.tarefasAbertas.length > 0) {
                        TarefaManager.unreadMessages = true;
                    }




                });

            $http.get(API_ENDPOINT + 'tarefas/from/usuario/' + AuthService.user.info.id)
                .then(function (res) {

                    $scope.tarefasDelegadasConcluidas = _.chain(res.data)
                        .filter(function (d) { return d.estado == 'CONCLUIDA' })
                        .sortBy('id')
                        .value();

                    $scope.tarefasDelegadasAbertas = _.chain(res.data)
                        .reject(function (d) { return d.estado == 'CONCLUIDA' })
                        .sortBy('id')
                        .value();


                });
        }

        /**
         * @method atualizarTarefa
         * @param {*} tarefa 
         */
        function atualizarTarefa(tarefa) {
            if (tarefa.owner.id !== AuthService.user.info.id) {
                return;
            }

            var _tarefa = _.clone(tarefa);
            _tarefa.owner = _tarefa.owner.id;
            delete _tarefa.Usuario;
            $http.put(API_ENDPOINT + 'tarefas/' + _tarefa.id, _tarefa)
                .then(function (res) {
                    atualizarTarefas();
                    $scope.valTarefasConcluidas = $scope.tarefasConcluidas.length == 1 ? true : false;
                    $scope.valTarefasAbertas = $scope.tarefasAbertas.length == 1 ? true : false;
                    $scope.valTarefasDelegadasConcluidas = $scope.tarefasDelegadasConcluidas.length == 1 ? true : false;
                    $scope.valTarefasDelegadasAbertas = $scope.tarefasDelegadasAbertas.length == 1 ? true : false;
                });
        }

        /**
         * @method deletarTarefa
         * @param {*} tarefa 
         */
        function deletarTarefa(tarefa) {
            $http.delete(API_ENDPOINT + 'tarefas/' + tarefa.id)
                .then(function (res) {
                    atualizarTarefas();
                });
        }

        /**
         * @method buscar
         * @param {*} query 
         */
        function buscar(query) {
            $http.get(API_ENDPOINT + 'usuarios/find/' + query)
                .then(function (res) {
                    if (_.isEmpty(res.data)) {
                        $scope.usuarios = [];
                        return;
                    }

                    $scope.usuarios = res.data;
                });
        }

        /**
         * @method selecionarUsuario
         * @param {*} usuario 
         */
        function selecionarUsuario(usuario) {
            if (usuario && !_.find($scope.usuariosSelecionados, { 'nome': usuario.nome })) {
                $scope.usuariosSelecionados.push(usuario);
            }

            $scope.searchText = '';
        }

        /**
         * @method removerUsuario
         * @param {*} usuario 
         */
        function removerUsuario(usuario) {
            var index = _.findIndex($scope.usuariosSelecionados, usuario);
            $scope.usuariosSelecionados.splice(index, 1);
        }

        /**
         * Definição de funções:
         */


         /**
          * @method date2timestamp
          */
        function date2timestamp(dateString) {

            if (!dateString || dateString.length === 0) {
                return null;
            }

            var dateParts = dateString.split(' ');
            var timeParts = dateParts[1].split(':');
            var date;

            dateParts = dateParts[0].split('/');
            date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);

            return date.getTime();
        }

        /**
         * @method salvar
         */
        function salvar() {
            if ($scope.data.selectedIndex === 0 || $scope.data.selectedIndex === 1) {
                atualizarTarefas();
            } else {
                if ($scope.tarefa.id) {

                } else {
                    var errors = [];

                    if ($scope.usuariosSelecionados.length <= 0) {
                        errors.push($scope.res('FAVOR_ESCOLHER_USUARIO'));
                    }

                    if (!$scope.tarefa.hasOwnProperty('nome')) {
                        errors.push($scope.res('FAVOR_NOME_TAREFA'));
                    }

                    if (!$scope.tarefa.hasOwnProperty('email') && !$scope.tarefa.hasOwnProperty('mensageria')) {
                        errors.push($scope.res('FAVOR_ESCOLHER_ENVIO'));
                    }

                    if (errors.length > 0) {
                        $mdDialog.show({
                            template: '<md-dialog>' +
                                '  <md-content>' +
                                errors.join('<br>') +
                                '</md-content>' +
                                '  <div class="md-actions">' +
                                '    <md-button ng-click="closeDialog()">' +
                                '      ' + $scope.res('COMUM_OK') +
                                '    </md-button>' +
                                '  </div>' +
                                '</md-dialog>',
                            controller: ['$scope', '$mdDialog', function ($scope, $mdDialog) {
                                $scope.closeDialog = function () {
                                    $mdDialog.hide();
                                };
                            }]
                        });
                        return;
                    }

                    var date = new Date();
                    $scope.tarefa.dataInicio = date.getTime();
                    $scope.tarefa.usuarios = [];

                    var erroUsuarioSelecionado = false;


                    for (var index in $scope.usuariosSelecionados) {
                        var usuario = $scope.usuariosSelecionados[index];
                        $scope.tarefa.usuarios.push(usuario.id);
                        if (usuario.id == AuthService.user.info.id) {
                            erroUsuarioSelecionado = true;
                        }
                    }

                    if (erroUsuarioSelecionado) {
                        var confirm = $mdDialog.confirm()
                            .title($scope.res('COMUM_AVISO'))
                            .content($scope.res('TAREFA_USUARIO_ERRO'))
                            .ok($scope.res('COMUM_SIM'))
                            .cancel($scope.res('COMUM_CANCELAR'));
                        $mdDialog.show(confirm)
                            .then(function () {
                                TarefaService.addTarefa($scope.tarefa)
                                    .then(function () {
                                        $mdDialog
                                            .show($mdDialog.alert()
                                                .title($scope.res('COMUM_SUCESSO'))
                                                .content($scope.res('TAREFA_SALVA_SUCESSO'))
                                                .ok($scope.res('COMUM_OK')));
                                        $scope.usuariosSelecionados = [];

                                        fecharTarefa();
                                        atualizarTarefas();
                                    });
                            }, function () {
                                console.log('cancel');
                            });
                    } else {
                        TarefaService.addTarefa($scope.tarefa)
                            .then(function () {
                                $mdDialog
                                    .show($mdDialog.alert()
                                        .title($scope.res('COMUM_SUCESSO'))
                                        .content($scope.res('TAREFA_SALVA_SUCESSO'))
                                        .ok($scope.res('COMUM_OK')));
                                $scope.usuariosSelecionados = [];

                                fecharTarefa();
                                atualizarTarefas();
                            });
                    }
                }
            }
        }

        /**
         * @method abrirTarefa
         */
        function abrirTarefa() {
            $scope.ativo = true;
            $scope.tarefa = {
                nome: null,
                descricao: null,
                UsuarioId: null
            };
        }

        /**
         * @method fecharTarefa
         */
        function fecharTarefa() {
            $scope.ativo = false;
            $scope.tarefa = {};
            TarefaManager.fechar();
        }

        $scope.edicao = true;
        $scope.ativo = false;
        $scope.tarefa = {};
        $scope.usuarios = [];
        $scope.usuariosSelecionados = [];
        $scope.atualizado = false;
        $scope.acao = '';
        $scope.data = {
            selectedIndex: 0
        };
        $scope.selecionarUsuario = selecionarUsuario;
        $scope.atualizarTarefa = atualizarTarefa;
        $scope.deletarTarefa = deletarTarefa;
        $scope.date2timestamp = date2timestamp;
        $scope.atualizar = atualizarTarefas;
        $scope.salvar = salvar;
        $scope.buscar = buscar;
        $scope.removerUsuario = removerUsuario;
        $scope.$api = {
            abrirTarefa: abrirTarefa,
            fecharTarefa: fecharTarefa
        };

        atualizarTarefas();
        MainState.registerDirective('minhas-tarefas', $scope.$api);

        $scope.$on('$destroy', function () {
            MainState.unregisterDirective('minhas-tarefas');
        });
    }

    /**
     * @ngdoc directive
     * @name s4c.components.tarefas.s4cMinhasTarefas
     * @module s4c.components.tarefas
     *
     * @description
     * `<s4c-minhas-tarefas>` exibe tarefas de um usuário autenticado.
     *
     *@example
     *   <s4c-minhas-tarefas>
     *   </s4c-minhas-tarefas>
     */
    function s4cMinhasTarefas() {
        return {
            restrict: 'EA',
            templateUrl: 'app/directives/minhas-tarefas/minhas-tarefas.html',
            replace: true,
            scope: {},
            controller: tarefasCtrl
        };
    }

    /**
     * @ngdoc overview
     * @name s4c.components.tarefas
     */
    angular.module('s4c.components.tarefas', [])
        .directive('s4cMinhasTarefas', s4cMinhasTarefas);

}());