Source: directives/base-conhecimento/base-conhecimento.js

/**
 * @ngdoc directives
 * @name Base-Conhecimento
 * @module s4c.directives.baseConhecimento.BaseConhecimento
 *
 * @description
 * `baseConhecimentoCtrl` cria ou exibe uma Base de Conhecimento do
 * sistema.
 *
 *@example
 *   <s4c-base-conhecimento>
 *   </s4c-base-conhecimento>
 */
(function () {
    'use strict';

    /**
     * @ngdoc overview
     * @name s4c.components.baseConhecimento
     */
    angular.module('s4c.components.baseConhecimento', ['angular-momentjs', 'angular-toasty'])
        .directive('s4cBaseConhecimento', s4cBaseConhecimento);

    baseConhecimentoCtrl.$inject = [
        '$scope',
        '$rootScope',
        '$mdDialog',
        'BaseConhecimentoService',
        'FileUploader',
        'API_ENDPOINT',
        'PermissoesService',
        'toasty',
        'CamadasService',
        '$http',
        'MainState',
        'AuthService',
        'BotoesManager',
        'BaseConhecimentoManager',
        'PlanejamentoManager',
        'IncidenteEnterManager',
        'CommService',
        '$window',
        'localize'
    ];

    function baseConhecimentoCtrl(
        $scope,
        $rootScope,
        $mdDialog,
        BaseConhecimentoService,
        FileUploader,
        API_ENDPOINT,
        PermissoesService,
        toasty,
        CamadasService,
        $http,
        MainState,
        AuthService,
        BotoesManager,
        BaseConhecimentoManager,
        PlanejamentoManager,
        IncidenteEnterManager,
        CommService,
        $window,
        localize) {


        $scope.res = $rootScope.res;

        var changed = function checkChanges() {
            $('#textLabel').on('change', function () {
                return true;
            });
        }

       /**
        * Obtem as permissões
        *
        * @method getPermissoes
		*        
		*
        */   
        PermissoesService.getPermissoes().then(function (perms) {
            $scope.permissoesVisualizacao = perms.permissoesVisualizacao;
            $scope.permissoesCriacao = perms.permissoesCriacao;
            $scope.permissoesEdicao = perms.permissoesEdicao;
            $scope.permissoesRemocao = perms.permissoesRemocao;
        });

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


       /**
        * Aplica os filtros no arquivo anexado
        *
        * @method push
        *  
        * 
        *
        */
        $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 {
                    var msgFileExceeded = localize.getLocalizedString('COMUM_TAMANHOFILEULTRAPASSADO');
                    var msgFileLimit = localize.getLocalizedString('COMUM_FILELIMIT');
                    $mdDialog
                        .show($mdDialog.alert()
                            .title(msgFileExceeded)
                            .content(msgFileLimit + megaByte)
                            .ok('OK'))
                    return item.size <= 26214400
                }
            }
        });

        CommService.on('base', function (data) {
            CamadasService.reloadBasesConhecimento();
            fecharBaseConhecimento();
        });


        $scope.$botoes = BotoesManager;
        $scope.botoesItems = [{
            title: 'Twitter',
            icon: '/assets/images/Incidentes/ic_social_twitter_color_24px.svg',
            action: function () {

                var geojson = JSON.parse($scope.baseConhecimento.geojson);
                var lat = geojson.coordinates[1];
                var long = geojson.coordinates[0];

                var info = { latitude: lat, longitude: long };

                $scope.$botoes.abrirTwitter(info);
            }
        },
        {
            title: $scope.res('MAIN_MENU_MENSAGERIA'),
            icon: '/assets/images/Incidentes/ic_social_telegram_color_24px.svg',
            action: function () {
                $scope.baseConhecimento.tipoObjeto = 'baseConhecimento';
                $scope.$botoes.abrirMensageria(true, $scope.baseConhecimento);
            }
        }
        ];
        $scope.openShare = false;
        
       /**
        * Abre a opção de compartilhar a base de conhecimento
        *
        * @method openOptionShare
        *  
        * 
        *
        */        
        $scope.openOptionShare = function () {
            $scope.openShare = !$scope.openShare;
        };

       /**
        * Executa uma ação ao terminar o upload do arquivo
        *
        * @method onCompleteItem
        *  
        * @param item {Object} item
        * @param response {Object} response
        *
        */     
        $scope.uploader.onCompleteItem = function (item, response) {
            $scope.baseConhecimento = response;
        };

       /**
        * Executa uma ação após terminar de adicionar o arquivo que será gravado
        *
        * @method onAfterAddingFile
        *  
        * 
        * @param item {Object} item
        * @param evt {Object} evt
        * @param arquivo {Object} arquivo
        *
        */     
        $scope.uploader.onAfterAddingFile = function (item, evt, arquivo) {
            item.novoNome = item.file.name;
            $scope.isUploading = true;

            var hasFile = _.find($scope.baseConhecimento.Arquivos, function (arq) {
                if (arq.nome === item.novoNome) {
                    listaEquals.push(arq);
                }
                return arq.nome === item.novoNome;
            });

            if (hasFile) {
                var msg = localize.getLocalizedString('BASECONHECIMENTO_FILEEXISTE');
                var sim = localize.getLocalizedString('COMUM_SIM');
                var nao = localize.getLocalizedString('COMUM_NAO');
                $mdDialog.show({
                    targetEvent: evt,
                    scope: $scope.$new(),
                    template: '<md-dialog>' +
                        '  <md-content>' + msg + '</md-content>' +
                        '  <div class="md-actions">' +
                        '    <md-button ng-click="enviar()">' + sim + '</md-button>' +
                        '    <md-button ng-click="$api.fecharBaseConhecimento();deleteCancel()">' + nao + '</md-button>' +
                        '  </div>' +
                        '</md-dialog>'
                });

            }

        }
        
       /**
        * Executa uma ação anter do arquivo ser gravado
        *
        * @method onBeforeUploadItem
        *  
        * 
        * @param item {Object} item
        *
        */         
        $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);

        };

       /**
        * Executa uma ação durante o processo de gravação do arquivo
        *
        * @method onProgressItem
        *  
        * 
        * @param fileItem {Object} fileItem
        * @param progress {Object} progress        
        *
        */   
        $scope.uploader.onProgressItem = function (fileItem, progress) {
            console.info('onProgressItem', fileItem, progress);
        };
        
       /**
        * Executa uma ação ao término do processo de gravação do arquivo
        *
        * @method onCompleteAll
        *  
        *
        */        
        $scope.uploader.onCompleteAll = function () {

            _.each(uploadCallbackQueue, function (callback) {
                callback();
            });
            $scope.isUploading = false;
        };

       /**
        * Remove uma base de conhecimento
        *
        * @method deleteBaseConhecimento
        * @param evt {Object} evt
        *  
        *
        */ 
        $scope.deleteBaseConhecimento = function (evt) {
            var msg = localize.getLocalizedString('BASECONHECIMENTO_REMOVER');
            var sim = localize.getLocalizedString('COMUM_SIM');
            var nao = localize.getLocalizedString('COMUM_NAO');
            $mdDialog.show({
                targetEvent: evt,
                scope: $scope.$new(),
                template: '<md-dialog>' +
                    '  <md-content>' + msg + '</md-content>' +
                    '  <div class="md-actions">' +
                    '    <md-button ng-click="deleteConfirm()">' + sim + '</md-button>' +
                    '    <md-button ng-click="deleteCancel()">' + nao + '</md-button>' +
                    '  </div>' +
                    '</md-dialog>'
            });
        };

       /**
        * Cancela a exclusão
        *
        * @method deleteCancel
        * 
        *  
        *
        */ 
        $scope.deleteCancel = function () {
            $mdDialog.hide();
        };

       /**
        * Exibe dialogo para que o usuário confirme ou não a remoção da base de comhecimento
        *
        * @method deleteConfirm
        * 
        *  
        *
        */ 
        $scope.deleteConfirm = function () {
            $mdDialog.hide();
            BaseConhecimentoService.findAndDelete($scope.baseConhecimento.id)
                .then(function (data) {
                    CamadasService.reloadBasesConhecimento();
                    fecharBaseConhecimento();
                    $mdDialog
                        .show($mdDialog.alert()
                            .title($scope.res('COMUM_SUCESSO'))
                            .content($scope.res('BASECONHECIMENTO_EXCLUIDACOMSUCESSO'))
                            .ok($scope.res('COMUM_OK')));
                }, function (err) {
                    $mdDialog
                        .show($mdDialog.alert()
                            .title($scope.res('COMUM_ERRO'))
                            .content($scope.res(err.data.message))
                            .ok($scope.res('COMUM_OK')));
                });
        };

       /**
        * Obtem a extensão do arquivo
        *
        * @method ext
        * @param filename {String} filename
        *  
        *
        */ 
        function ext(filename) {
            var index = _.lastIndexOf(filename, '.');
            return filename.substring(index, filename.length);
        }

       /**
        * Carrega a base de comhecimento
        *
        * @method loadBase
        * @param id {Integer} Id da Base
        *  
        *
        */ 
        function loadBase(id) {
            try {
                BaseConhecimentoService.findById(id)
                    .then(function (data) {
                        //$scope.baseConhecimento = data;
                        if (data != null && data.id != null) {
                            $scope.ativo = true;
                            carregarBaseConhecimento(data);
                        } else {
                            BaseConhecimentoManager.fechar();
                        }
                    });
            } catch (err) {
                console.log('Base de Conhecimento não encontrado no banco de dados');
            }
        }

       /**
        * Abre o detalhamento da Base de conhecimento
        *
        * @method abrirDetalhamento
        * @param base {Object}  Base de Conhecimento
        *  
        *
        */ 
        function abrirDetalhamento(base) {
            $scope.ativo = true;
            carregarBaseConhecimento(base);
        }

       /**
        * Remove um arquivo da lista de arquivos a serem anexados
        *
        * @method removerItem
        * @param item {Object} Arquivo a ser removido 
        *  
        *
        */ 
        function removerItem(item) {
            uploader.removeFromQueue(item);
        }


       /**
        * Converte um objeto Date para Timestamp
        *
        * @method date2timestamp
        * @param dateString {Object} dateString
        *  
        *
        */ 
        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();
        }

       /**
        * Converte um objeto Timestamp para Date 
        *
        * @method timestamp2date
        * @param timestamp {Object} timestamp
        *  
        *
        */ 
        function timestamp2date(timestamp) {

            if (!timestamp) {
                return null;
            }

            var date = moment(parseInt(timestamp, 10)).format('DD/MM/YYYY HH:mm');
            return date;
        }

       /**
        * Remove um arquivo da lista de arquivos anexados na base de conhecimento 
        *
        * @method removerArquivo
        * @param arquivo {Object} Arquivo a ser removido
        *  
        *
        */ 
        function removerArquivo(arquivo) {
            var index = $scope.baseConhecimento.Arquivos.indexOf(arquivo);
            $scope.baseConhecimento.Arquivos.splice(index, 1);
            listaRemocao.push(arquivo);
        }

       /**
        * Abre a opção de anexar arquivo 
        *
        * @method abrirUpload
        * 
        *  
        *
        */ 
        function abrirUpload() {
            $scope.input.click();
        }

        $scope.tentouEnviar = false;
        
       /**
        * Executa as validações antes de salvar a Base 
        *
        * @method validarPermissaoSalvar
        * 
        *  
        *
        */ 
        function validarPermissaoSalvar() {

            $scope.tentouEnviar = true;
            if ($scope.enableButton == false) {
                return;
            }

            if (!$scope.baseConhecimento.nome || $scope.baseConhecimento.nome.length == 0) {
                return;
            }

            if (!$scope.baseConhecimento.tipoId) {
                return;
            }

            $scope.enableButton = false;
            var filtroPermissao = {};
            filtroPermissao.objeto = "CRIAR_BASE_CONHECIMENTO";
            if ($scope.ponto && $scope.ponto.mapa) {
                if ($scope.ponto.mapa === 1) {
                    filtroPermissao.latitude = $scope.ponto.marker.getGeometry().getLatitude();
                    filtroPermissao.longitude = $scope.ponto.marker.getGeometry().getLongitude();
                } else {
                    // Leaflet
                    filtroPermissao.latitude = $scope.ponto.marker.getLatLng().lat;
                    filtroPermissao.longitude = $scope.ponto.marker.getLatLng().lng;
                }
            }

            PermissoesService.verificarPermissaoAreaAtuacao(filtroPermissao)
                .then(function (result) {
                    if (result) {
                        enviar();
                    } else {
                        $mdDialog
                            .show($mdDialog.alert()
                                .title($scope.res('COMUM_AVISO'))
                                .content($scope.res('PERMISSAO_AREAATUACAO_VERIFICACAO'))
                                .ok($scope.res('COMUM_OK')));
                        $scope.enableButton = true;
                        $scope.tentouEnviar = false;
                        return;
                    }
                });
        }

        $scope.enableButton = true;
        

       /**
        * Salva a Base de Conhecimento
        *
        * @method enviar
        * 
        *  
        *
        */         
        function enviar() {

            uploadCallbackQueue = [];
            var baseConhecimento = angular.copy($scope.baseConhecimento);
            $scope.changed = false;

            if ($scope.ponto && $scope.ponto.mapa) {
                if ($scope.ponto.mapa === 1) {
                    baseConhecimento.latitude = $scope.ponto.marker.getGeometry().getLatitude();
                    baseConhecimento.longitude = $scope.ponto.marker.getGeometry().getLongitude();
                } else {
                    // Leaflet
                    baseConhecimento.latitude = $scope.ponto.marker.getLatLng().lat;
                    baseConhecimento.longitude = $scope.ponto.marker.getLatLng().lng;
                }
            }

            baseConhecimento.GruposUsuariosParticipantes = $scope.GruposUsuariosParticipantes;
            baseConhecimento.UsuariosParticipantes = $scope.UsuariosParticipantes;

            if (baseConhecimento.id) {
                baseConhecimento.deleteFiles = listaRemocao;
                baseConhecimento.equalFiles = listaEquals;

                BaseConhecimentoService.updateBaseConhecimento(baseConhecimento)
                    .then(function (_base) {
                        baseConhecimento = _base;
                        $scope.atualizado = true;
                        $scope.enableButton = true;
                        $scope.tentouEnviar = false;

                        uploader.url = '/base_conhecimento/' + _base.id;
                        uploader.uploadAll();

                        if ($scope.ponto) {
                            $scope.ponto.updateOldPosition();
                        }

                        if (!$scope.isUploading) {
                            $mdDialog
                                .show($mdDialog.alert()
                                    .title($scope.res('COMUM_SUCESSO'))
                                    .content($scope.res('BASE_CONHECIMENTO_SALVACOMSUCESSO'))
                                    .ok($scope.res('COMUM_OK')))
                                .then(function () {
                                    fecharBaseConhecimento();
                                });
                        } else {
                            uploadCallbackQueue.push(function () {
                                $mdDialog
                                    .show($mdDialog.alert()
                                        .title($scope.res('COMUM_SUCESSO'))
                                        .content($scope.res('BASE_CONHECIMENTO_SALVACOMSUCESSO'))
                                        .ok($scope.res('COMUM_OK')));
                            });
                            uploadCallbackQueue.push(fecharBaseConhecimento);
                        }
                    }, function (err) {

                        $mdDialog
                            .show($mdDialog.alert()
                                .title($scope.res('COMUM_SUCESSO'))
                                .content(err.data.message)
                                .ok($scope.res('COMUM_OK')));

                        fecharBaseConhecimento();
                    });

            } else {

                BaseConhecimentoService.addBaseConhecimento(baseConhecimento)
                    .then(function (_base) {

                        $scope.tentouEnviar = false;
                        $scope.enableButton = true;
                        baseConhecimento = _base;
                        uploader.url = '/base_conhecimento/' + _base.id;
                        uploader.uploadAll();

                        if (!$scope.isUploading) {
                            $mdDialog
                                .show($mdDialog.alert()
                                    .title($scope.res('COMUM_SUCESSO'))
                                    .content($scope.res('BASE_CONHECIMENTO_SALVACOMSUCESSO'))
                                    .ok($scope.res('COMUM_OK')))
                                .then(function () {
                                    CamadasService.exibirBasesConhecimento();
                                });
                            fecharBaseConhecimento();
                        } else {
                            uploadCallbackQueue.push(function () {
                                $mdDialog
                                    .show($mdDialog.alert()
                                        .title($scope.res('COMUM_SUCESSO'))
                                        .content($scope.res('BASE_CONHECIMENTO_SALVACOMSUCESSO'))
                                        .ok($scope.res('COMUM_OK')))
                                    .then(function () {
                                        BaseConhecimentoManager.reload();
                                        $rootScope.$emit('s4c:reloadBase');
                                    });
                            });
                            fecharBaseConhecimento();
                        }
                    }, function (err) {
                        $mdDialog
                            .show($mdDialog.alert()
                                .title($scope.res('COMUM_ERRO'))
                                .content(err.data.message)
                                .ok($scope.res('COMUM_OK')));
                        fecharBaseConhecimento();
                    });

            }
        }

        $rootScope.$on('baseconhecimento:carregar', function (e, _base, obj) {
            $scope.ponto = obj;
            $scope.ativo = true;
            $scope.ponto.undraggable();
            carregarBaseConhecimento(_base);
        });


       /**
        * Carrega a base de conhecimento de Um Poi
        *
        * @method testeCarregar
		*        
        * @param id {Integer} id
        * @param obj {Object} obj          
        *
        */     
        function testeCarregar(id, obj) {
            $scope.ponto = obj;
            $scope.ativo = true;
            $scope.ponto.undraggable();
            carregarBaseConhecimento({
                id: id
            });
        }

        $scope.tipos;
        BaseConhecimentoService.findAllTypes().then(function (tipos) {

            $scope.tipos = tipos;

        });

       /**
        * Carrega a base de conhecimento
        *
        * @method carregarBaseConhecimento
		*        
        * @param obj {Object} obj          
        *
        */    
        function carregarBaseConhecimento(obj) {
            $scope.acao = 'EDITAR';
            uploader.clearQueue();
            listaRemocao = [];
            //listaEquals = [];
            BaseConhecimentoService.findById(obj.id)
                .then(function (_base) {

                    $scope.baseConhecimento = _base;
                    $scope.baseConhecimento.autor = $scope.baseConhecimento.criador.nome + ' - ' +
                        $scope.baseConhecimento.criador.Departamento.nome;
                    $scope.baseConhecimento.dataHoraCriacao = moment($scope.baseConhecimento.dataHoraCriacao).format(
                        'DD/MM/YYYY - HH:mm'
                    );
                    $scope.baseConhecimento.inicio = timestamp2date($scope.baseConhecimento.inicio);
                    $scope.baseConhecimento.fim = timestamp2date($scope.baseConhecimento.fim);
                    $scope.GruposUsuariosParticipantes = _base.GruposUsuariosParticipantes;
                    $scope.UsuariosParticipantes = _base.UsuariosParticipantes;
                });
            $scope.atualizado = false;
        }

       /**
        * Abre a base de conhecimento
        *
        * @method carregarBaseConhecimento
		*        
        * @param obj {Object} obj          
        * @param evt {Object} evt      
        *
        */    
        function abrirBaseConhecimento(obj, evt) {
            if (PlanejamentoManager.ativo || IncidenteEnterManager.ativo) {
                var msg = localize.getLocalizedString('BASECONHECIMENTO_FECHARMODULOATIVO');
                var sim = localize.getLocalizedString('COMUM_SIM');
                var nao = localize.getLocalizedString('COMUM_NAO');
                $mdDialog.show({
                    targetEvent: evt,
                    scope: $scope.$new(),
                    template: '<md-dialog>' +
                        '  <md-content>' + msg + '</md-content>' +
                        '  <div class="md-actions">' +
                        '    <md-button ng-click="$api.OpenAndClose(obj);deleteCancel();">' + sim + '</md-button>' +
                        '    <md-button ng-click="deleteCancel()">' + nao + '</md-button>' +
                        '  </div>' +
                        '</md-dialog>'
                });

                BaseConhecimentoManager.fechar();
                BaseConhecimentoManager.removeMarker();

            } else {
                uploader.clearQueue();
                $scope.ativo = true;


                $scope.baseConhecimento = {};
                listaRemocao = [];
                listaEquals = [];
                if ($scope.acao === 'NOVO' &&
                    $scope.ponto &&
                    $scope.ponto.marker) {

                    $scope.ponto.destroy();
                }

                $scope.acao = 'NOVO';
                BaseConhecimentoService.findAllTypes().then(function (tipos) {
                    $scope.tipos = tipos;
                });

                if (obj) {
                    $scope.baseConhecimento.latitude = obj.latitude;
                    $scope.baseConhecimento.longitude = obj.longitude;
                    $scope.ponto = obj;
                }

                $scope.atualizado = false;
            }
        }

       /**
        *
        * Fecha o planejamento e incidente e abre a base de conhecimento 
        *
        * @method OpenAndClose
		*        
        * @param obj {Object} obj          
        *
        */    
        function OpenAndClose(obj) {

            if (PlanejamentoManager.ativo || IncidenteEnterManager.ativo) {
                PlanejamentoManager.fechar();
                IncidenteEnterManager.fechar();
            }

            BaseConhecimentoManager.abrir();
        }

       /**
        *
        * Fecha a base de conhecimento 
        *
        * @method fecharBaseConhecimento
		*        
        * @param evt {Object} evt          
        *
        */   
        function fecharBaseConhecimento(evt) {
            var msg = localize.getLocalizedString('BASECONHECIMENTO_MENSAGEMREMOVER');
            var sim = localize.getLocalizedString('COMUM_SIM');
            var nao = localize.getLocalizedString('COMUM_NAO');

            if ($scope.changed) {
                $mdDialog.show({
                    targetEvent: evt,
                    scope: $scope.$new(),
                    template: '<md-dialog>' +
                        '  <md-content>' + msg + '</md-content>' +
                        '  <div class="md-actions">' +
                        '    <md-button ng-click="$api.fecharBase();deleteCancel()">' + sim + '</md-button>' +
                        '    <md-button ng-click="deleteCancel()">' + nao + '</md-button>' +
                        '  </div>' +
                        '</md-dialog>'
                });
                $scope.ativo = true;
                BaseConhecimentoManager.ativo = true;
            } else {



                $scope.openShare = false;

                if ($scope.ponto && $scope.ponto.mapa) {
                    if ($scope.acao === 'NOVO') {
                        $scope.ponto.destroy();
                    } else {
                        $scope.ponto.undraggable();
                    }
                }

                $scope.ativo = false;
                BaseConhecimentoManager.ativo = false;

                if (!$scope.atualizado) {
                    if ($scope.ponto && $scope.ponto.mapa) {
                        if ($scope.ponto.mapa === 1) {
                            $scope.ponto.marker.getGeometry().setLatitude($scope.ponto.oldLat);
                            $scope.ponto.marker.getGeometry().setLongitude($scope.ponto.oldLng);
                        } else {
                            // Leaflet
                            $scope.ponto.marker.setLatLng(new L.LatLng($scope.ponto.oldLat, $scope.ponto.oldLng));
                        }
                    }
                }

                $scope.UsuariosParticipantes = [];
                $scope.GruposUsuariosParticipantes = [];
            }
        }

       /**
        *
        * Fecha a base de conhecimento 
        *
        * @method fecharBase
		*        
        *
        */  
        function fecharBase() {
            $scope.openShare = false;

            if ($scope.ponto && $scope.ponto.mapa) {
                if ($scope.acao === 'NOVO') {
                    $scope.ponto.destroy();
                } else {
                    $scope.ponto.undraggable();
                }
            }

            $scope.ativo = false;
            BaseConhecimentoManager.ativo = false;

            if (!$scope.atualizado) {
                if ($scope.ponto && $scope.ponto.mapa) {
                    if ($scope.ponto.mapa === 1) {
                        $scope.ponto.marker.getGeometry().setLatitude($scope.ponto.oldLat);
                        $scope.ponto.marker.getGeometry().setLongitude($scope.ponto.oldLng);
                    } else {
                        // Leaflet
                        $scope.ponto.marker.setLatLng(new L.LatLng($scope.ponto.oldLat, $scope.ponto.oldLng));
                    }
                }
            }

            $scope.UsuariosParticipantes = [];
            $scope.GruposUsuariosParticipantes = [];
        }

       /**
        *
        * Efetua o doanload de um arquivo 
        *
        * @method download
		*        
        * @param fileId {Object} fileId
		* @param fileName {String} fileName                  
        *
        */   
        function download(fileId, fileName) {

            $http.get('/filemanager/checkexistence/' + fileId)
                .then(function (response) {
                    if (response.data) {

                        BaseConhecimentoService.getAttachedFile(fileId)
                            .then(function (data) {

                                var a = document.createElement("a");
                                document.body.appendChild(a);
                                a.style = "display: none";

                                var file = new Blob([data], { type: 'application/octet-stream' });
                                var fileURL = URL.createObjectURL(file);

                                a.href = fileURL;
                                a.download = fileName;
                                a.click();

                            });
                    }
                    else {
                        $mdDialog
                            .show($mdDialog.alert()
                                .title($scope.res('COMUM_ERRO'))
                                .content(response.data.message)
                                .ok($scope.res('COMUM_OK')));
                    }
                }, function (err) {
                    $mdDialog
                        .show($mdDialog.alert()
                            .title($scope.res('COMUM_ERRO'))
                            .content(err.data.message)
                            .ok($scope.res('COMUM_OK')));
                });

        }

        angular.extend($scope, {
            edicao: true,
            enableButton: true,
            ativo: false,
            baseConhecimento: {},
            atualizado: false,
            isUploading: false,
            acao: '',
            abrirUpload: abrirUpload,
            date2timestamp: date2timestamp,
            enviar: enviar,
            download: download,
            validarPermissaoSalvar: validarPermissaoSalvar,

            $api: {
                testeCarregar: testeCarregar,
                abrirBaseConhecimento: abrirBaseConhecimento,
                fecharBaseConhecimento: fecharBaseConhecimento,
                OpenAndClose: OpenAndClose,
                fecharBase: fecharBase,
                removerItem: removerItem,
                removerArquivo: removerArquivo,
                loadBase: loadBase,
                abrirDetalhamento: abrirDetalhamento,
                carregarBaseConhecimento: carregarBaseConhecimento
            },
            removerArquivo: removerArquivo,
            me: AuthService.user.info,
            UsuariosParticipantes: [],
            GruposUsuariosParticipantes: []
        });

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

        MainState.registerDirective('baseConhecimento', $scope.$api);

        $scope.$on('$destroy', function () {
            MainState.unregisterDirective('baseConhecimento');
        });
    }

    function s4cBaseConhecimento() {

        return {
            restrict: 'EA',
            templateUrl: 'app/directives/base-conhecimento/base-conhecimento.html',
            replace: true,
            scope: {},
            controller: baseConhecimentoCtrl,
            link: function ($scope, $elem) {
                $scope.res = $scope.$root.res;
                var language;
                if ($scope.res("COMUM_LOCALE") == "pt-BR") {
                    language = 'pt-BR';
                } else {
                    language = 'en';
                }

                $scope.bindTo = $elem.parent().parent().parent().parent().parent();

                $scope.timeStep = 30;
                $scope.startDatetimepicker = $elem.find('#startDatetimepicker');
                $scope.startDatetimepicker.datetimepicker({
                    theme: 'dark',
                    format: 'd/m/Y H:i',
                    lang: language,
                    step: $scope.timeStep,
                    onChangeDateTime: function (dp, input) {

                        this.setOptions({
                            maxTime: $scope.baseConhecimento.fim ? (input.val().split(' ')[0] === $scope.baseConhecimento.fim.split(' ')[0] ? $scope.baseConhecimento.fim.split(' ')[1] : false) : false
                        });

                    },
                    onShow: function () {
                        this.setOptions({
                            maxDate: $scope.baseConhecimento.fim ? $scope.baseConhecimento.fim.split(' ')[0] : false,
                            formatDate: 'd.m.Y',
                        });
                    }
                });

                $scope.endDatetimepicker = $elem.find('#endDatetimepicker');
                $scope.endDatetimepicker.datetimepicker({
                    theme: 'dark',
                    format: 'd/m/Y H:i',
                    lang: language,
                    step: $scope.timeStep,
                    onChangeDateTime: function (dp, input) {
                        this.setOptions({
                            minTime: $scope.baseConhecimento.inicio ? (input.val().split(' ')[0] === $scope.baseConhecimento.inicio.split(' ')[0] ? $scope.baseConhecimento.inicio.split(' ')[1] : false) : false
                        });
                    },
                    onShow: function () {
                        this.setOptions({
                            minDate: $scope.baseConhecimento.inicio ? $scope.baseConhecimento.inicio.split(' ')[0] : false,
                            formatDate: 'd.m.Y',
                        });
                    }
                });

                $scope.input = $elem.find('input.uploadArquivo');
            }
        };
    }

}());