/**
* @ngdoc controllers
* @name PontoMovel
* @module s4c.components.admin.controllers.PontoMovel
*
* @description
* `AdminPontoMovelCtrl` Controller da tela de Ponto Móvel do módulo de administração
*
*
*/
(function () {
'use strict';
AdminPontoMovelCtrl.$inject = [
'$scope',
'$http',
'$mdDialog',
'API_ENDPOINT',
'ngFileReader',
'$rootScope',
'MainState',
'FileUploader'
];
angular.module('s4c.controllers.AdminPontoMovelCtrl', [
's4c.directives.ngFileReader'
])
.controller('AdminPontoMovelCtrl', AdminPontoMovelCtrl)
.directive('focusOn', function () {
return function (scope, elem, attr) {
scope.$on(attr.focusOn, function (e) {
elem[0].focus();
});
};
});
function AdminPontoMovelCtrl($scope, $http, $mdDialog, API_ENDPOINT,
ngFileReader, $rootScope, MainState, FileUploader) {
$scope.res = $rootScope.res;
$scope.selectedRows = [];
$scope.editar = false;
$scope.flagEditarPontoMovel = false;
$scope.pontosMoveis = [];
$scope.tiposElementoRastreavel = [];
$scope.msgSalvandoHidden = true;
$scope.icones = [];
$scope.bytesIcone = null;
$scope.nomeIcone = null;
carregarTiposPontoMovel();
carregarTiposElementoRastreavel();
/**
* @instance basicColumns
* @memberof AdminPontoMovelCtrl
*/
var basicColumns = [{
headerName: '',
width: 70,
checkboxSelection: true,
suppressSorting: true,
suppressMenu: true
}, {
headerName: $scope.res('COMUM_NOME'),
width: 150,
field: "nome",
editable: true,
volatile: true
}, {
headerName: $scope.res('COMUM_DESCRICAO'),
width: 300,
field: "descricao",
editable: true,
volatile: true
}];
var defaultColumns = angular.copy(basicColumns);
/**
* @instance gridOptions
* @memberof AdminPontoMovelCtrl
*/
$scope.gridOptions = {
rowSelection: 'multiple',
rowDeselection: true,
enableSorting: true,
columnDefs: basicColumns,
rowData: [],
angularCompileHeaders: true,
headerCellRenderer: headerCellRendererFunction,
pinnedColumnCount: 1,
enableColResize: true
};
/**
* @method headerCellRendererFunction
* @param {*} params
*/
function headerCellRendererFunction(params) {
var eHeader = document.createElement('span');
var eTitle = document.createTextNode(params.colDef.headerName);
eHeader.appendChild(eTitle);
if (params.colDef.headerName == '') {
eHeader.style.textAlign = 'center';
eHeader.style.verticalAlign = 'center';
} else {
var eEdit = document.createElement('md-icon');
eEdit.setAttribute('class', 'menu-icon');
eEdit.setAttribute('style', 'float: right');
eEdit.setAttribute('md-svg-icon', 'menu:edit');
eEdit.setAttribute('alt', 'editar');
eEdit.setAttribute('ng-click', 'definirValorDaColuna($event, this,"' + params.colDef.field + '")');
eHeader.appendChild(eEdit);
}
return eHeader.outerHTML;
}
/**
* @method salvar
*/
function salvar() {
if ($scope.tipoPontoMovel.nome == '') {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_ERRO'))
.content($scope.res('TIPO_PONTO_MOVEL_INFORMAR_NOME'))
.ok($scope.res('COMUM_OK')));
return;
}
var tipoPontoMovel = $scope.tipoPontoMovel;
tipoPontoMovel.pontosMoveis = $scope.gridOptions.rowData;
_.map(tipoPontoMovel.pontosMoveis, function (pontoMovel) {
var valorExtras = [];
_.each($scope.tipoPontoMovel.extras, function (extra) {
valorExtras.push({ nome: extra, valor: pontoMovel[extra] });
delete pontoMovel[extra];
});
pontoMovel.valorExtras = valorExtras;
return pontoMovel;
});
$scope.msgSalvandoHidden = false;
if ($scope.bytesIcone != null) {
var formData = new FormData();
if ($scope.bytesIcone['tipo'] != undefined) {
formData.append('arquivo', $scope.bytesIcone['tipo'], tipoPontoMovel.urlIcone);
tipoPontoMovel.temArquivo = true;
}
_.map(tipoPontoMovel.iconesDispositivo, function (iconeDispositivo) {
if ($scope.bytesIcone[iconeDispositivo.nome] != undefined) {
formData.append('arquivo', $scope.bytesIcone[iconeDispositivo.nome], iconeDispositivo.urlIcone);
iconeDispositivo.temArquivo = true;
}
return iconeDispositivo;
});
formData.append('tipoPontoMovel', encodeURI(angular.toJson(tipoPontoMovel, true)));
$http.post("/tipo_ponto_movel/file", formData, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
})
.then(function (data) {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_SUCESSO'))
.content($scope.res('MENSAGEM_SUCESSO_ATUALIZACAO_TIPO_PONTO_MOVEL'))
.ok($scope.res('COMUM_OK')));
$scope.editar = false;
carregarTiposPontoMovel();
$scope.msgSalvandoHidden = true;
}, function (err) {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_ERRO'))
.content(err.data.message)
.ok($scope.res('COMUM_OK')));
$scope.msgSalvandoHidden = true;
});
}
else {
$http.post("/tipo_ponto_movel", tipoPontoMovel)
.then(function (data) {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_SUCESSO'))
.content($scope.res('MENSAGEM_SUCESSO_ATUALIZACAO_TIPO_PONTO_MOVEL'))
.ok($scope.res('COMUM_OK')));
$scope.editar = false;
carregarTiposPontoMovel();
$scope.msgSalvandoHidden = true;
}, function (err) {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_ERRO'))
.content(err.data.message)
.ok($scope.res('COMUM_OK')));
$scope.msgSalvandoHidden = true;
});
}
}
/**
* @method criarNovoPontoMovel
*/
function criarNovoPontoMovel() {
$scope.gridOptions.rowData.unshift({
_id: _.uniqueId(), nome: '', descricao: '', idElementoRastreavel: null, extras: []
});
$scope.gridOptions.api.onNewRows();
$scope.gridOptions.api.setSortModel($scope.gridOptions.api.getSortModel());
$scope.$broadcast('newItemAdded');
}
/**
* @method abrirModalAdicionarExtraPontoMovel
*/
function abrirModalAdicionarExtraPontoMovel() {
$mdDialog.show({
scope: $scope.$new(),
template: '<md-dialog draggable style="width: 200px;">' +
'<md-title style="padding: 20px 0px 0px 20px;">' + $scope.res('PONTO_MOVEL_ADICIONAR_EXTRA') + '</md-title>' +
'<br>' +
'<div flex>' +
' <div style="height: 80px;" class="ag-fresh">' +
' <md-input-container class="md-accent">' +
' <label class="md-accent">' + $scope.res('PONTO_MOVEL_NOME_EXTRA') + '</label>' +
' <input class="md-accent" ng-model="nome">' +
' </md-input-container>' +
' </div>' +
' <div class="md-actions">' +
' <md-button ng-click="fechar()">' + $scope.res('COMUM_CANCELAR') + '</md-button>' +
' <md-button ng-click="adicionar()">' + $scope.res('COMUM_OK') + '</md-button>' +
' </div>' +
' </div>' +
'</md-dialog>',
controller: function ($scope, $mdDialog) {
$scope.fechar = function () {
$mdDialog.hide();
}
$scope.adicionar = function () {
var campoExiste = false;
_.each($scope.tipoPontoMovel.extras, function (extra) {
if (extra.toUpperCase() == $scope.nome.toUpperCase()) {
campoExiste = true;
}
});
if (campoExiste) {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_ERRO'))
.content($scope.res('PONTO_MOVEL_EXTRA_EXISTENTE'))
.ok($scope.res('COMUM_OK')));
return;
}
else {
adicionarExtraPontoMovel($scope.nome);
$scope.fechar();
}
}
}
});
}
/**
* @method adicionarExtraPontoMovel
* @param {*} nome
*/
function adicionarExtraPontoMovel(nome) {
if ($scope.tipoPontoMovel.extras == undefined) {
$scope.tipoPontoMovel.extras = [];
}
$scope.tipoPontoMovel.extras.push(nome);
adicionarColunaExtra(nome);
}
/**
* @method adicionarColunaExtra
* @param {*} nome
*/
function adicionarColunaExtra(nome) {
var columnDefs = $scope.gridOptions.columnDefs;
columnDefs.push({
headerName: nome,
field: nome,
width: 100,
editable: true,
volatile: true
});
$scope.gridOptions.api.columnDefs = columnDefs;
$scope.gridOptions.api.onNewCols();
}
/**
* @method setDefaultColumns
*/
function setDefaultColumns() {
var columnDefs = $scope.gridOptions.api.columnDefs;
_.each(columnDefs, function (columnDef) {
var encontrou = false;
_.each(defaultColumns, function (defaultColumn) {
if (columnDef.headerName == defaultColumn.headerName) {
encontrou = true;
}
});
if (!encontrou) {
removerColunaExtra(columnDef.headerName);
}
});
}
/**
* @method removerExtraPontoMovel
* @param {*} nome
*/
function removerExtraPontoMovel(nome) {
var index = 0;
var indexDelete = -1;
_.each($scope.tipoPontoMovel.extras, function (extra) {
if (extra == nome) {
indexDelete = index;
}
index++;
});
if (indexDelete > -1) {
$scope.tipoPontoMovel.extras.splice(indexDelete, 1);
}
removerColunaExtra(nome);
}
/**
* @method removerColunaExtra
* @param {*} nome
*/
function removerColunaExtra(nome) {
var columnDefs = $scope.gridOptions.columnDefs;
var index = 0;
var indexDelete = -1;
_.each(columnDefs, function (columnDef) {
if (columnDef.headerName == nome) {
indexDelete = index;
}
index++;
});
if (indexDelete > -1) {
columnDefs.splice(indexDelete, 1);
}
$scope.gridOptions.api.columnDefs = columnDefs;
$scope.gridOptions.api.onNewCols();
}
/**
* @method editarPontoMovel
* @param {*} pontoMovel
*/
function editarPontoMovel(pontoMovel) {
$scope.pontoMovel = pontoMovel;
$scope.flagEditarPontoMovel = true;
//selecionarElementoRastreavel();
}
/**
* @method deletePontoMovel
*/
function deletePontoMovel() {
var selecionados = _.map($scope.gridOptions.api.getSelectedNodes(), 'data.nome');
//$scope.rowsDeleted.push(_.map($scope.gridOptions.api.getSelectedNodes(), 'data'));
_.remove($scope.gridOptions.rowData, function (row) {
return _.includes(selecionados, row.nome)
});
$scope.tipoPontoMovel.pontosMoveis = $scope.gridOptions.rowData;
$scope.gridOptions.api.onNewRows();
}
/**
* @method criarNovoTipo
*/
function criarNovoTipo() {
$scope.editar = true;
setDefaultColumns();
$scope.flagEditarPontoMovel = false;
$scope.tipoPontoMovel = { _id: _.uniqueId(), nome: '', urlIcone: null, descricao: '', iconesDispositivo: [], idTipoElementoRastreavel: null };
$scope.pontosMoveis = [];
$scope.icones = [];
$scope.bytesIcone = [];
$scope.gridOptions.rowData = [];
$scope.gridOptions.api.onNewRows();
}
/**
* @method deletarTipoPontoMovel
*/
function deletarTipoPontoMovel() {
var index = 0;
_.each($scope.tiposPontoMovel, function (tipoPontoMovel) {
if ($scope.tipoPontoMovel._id == tipoPontoMovel._id) {
$scope.tiposPontoMovel.splice(index, 1);
}
index++;
});
if ($scope.tipoPontoMovel.id != undefined && $scope.tipoPontoMovel.id != null) {
$http.post("/tipo_ponto_movel/" + $scope.tipoPontoMovel.id)
.then(function (data) {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_SUCESSO'))
.content($scope.res('MENSAGEM_SUCESSO_EXCLUSAO_TIPO_PONTO_MOVEL'))
.ok($scope.res('COMUM_OK')));
carregarTiposPontoMovel();
}, function (err) {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_ERRO'))
.content(err.data.message)
.ok($scope.res('COMUM_OK')));
});
}
$scope.editar = false;
$scope.tipoPontoMovel = null;
}
/**
* @method editarTipoPontoMovel
*/
function editarTipoPontoMovel() {
$scope.editar = !$scope.editar;
}
/**
* @method ativarTipoPontoMovel
* @param {*} element
*/
function ativarTipoPontoMovel(element) {
if (typeof $scope.tipoPontoMovel === 'string' || $scope.tipoPontoMovel instanceof String) {
$scope.tipoPontoMovel = JSON.parse($scope.tipoPontoMovel);
}
$scope.bytesIcone = null;
$http.get(API_ENDPOINT + "tipo_ponto_movel/" + $scope.tipoPontoMovel.id)
.then(function (result) {
$scope.tipoPontoMovel = result.data;
if (typeof $scope.tipoPontoMovel === 'string' || $scope.tipoPontoMovel instanceof String) {
$scope.tipoPontoMovel = JSON.parse($scope.tipoPontoMovel);
}
$scope.icones['tipo'] = $scope.tipoPontoMovel.urlIcone;
_.each($scope.tipoPontoMovel.iconesDispositivo, function (iconeDispositivo) {
$scope.icones[iconeDispositivo.nome] = iconeDispositivo.urlIcone;
});
setDefaultColumns();
_.each($scope.tipoPontoMovel.extras, function (extra) {
adicionarColunaExtra(extra);
});
carregarValorExtraPontosMoveis();
$scope.pontosMoveis = $scope.tipoPontoMovel.pontosMoveis;
$scope.gridOptions.api.sizeColumnsToFit();
$scope.gridOptions.rowData = $scope.pontosMoveis;
$scope.gridOptions.api.onNewRows();
$scope.gridOptions.api.setSortModel([{
field: 'nome',
sort: 'asc'
}]);
$scope.flagEditarPontoMovel = false;
}, function (err) {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_ERRO'))
.content(err.data.message)
.ok($scope.res('COMUM_OK')));
});
}
//Faz o merge da lista de pontos moveis existente com a lista importada do SR
/**
* @method mergedPontosMoveis
* @param {*} pontosMoveis
*/
function mergePontosMoveis(pontosMoveis) {
var existe;
var mergedPontosMoveis = [];
_.each(pontosMoveis, function (pontoMovel) {
existe = false;
//pontoMovel.valorExtras = getValorExtras(pontoMovel.nome);
_.each($scope.tipoPontoMovel.pontosMoveis, function (pontoMovelAtual) {
if (pontoMovelAtual.nome == pontoMovel.nome) {
existe = true;
mergedPontosMoveis.push(pontoMovelAtual);
}
});
if (!existe) {
mergedPontosMoveis.push(pontoMovel);
}
});
return mergedPontosMoveis;
}
/**
* @method carregarValorExtraPontosMoveis
*/
function carregarValorExtraPontosMoveis() {
_.map($scope.tipoPontoMovel.pontosMoveis, function (pontoMovel) {
_.each(pontoMovel.valorExtras, function (valorExtra) {
pontoMovel[valorExtra.nome] = valorExtra.valor;
});
return pontoMovel;
});
}
/**
* @method carregarTiposPontoMovel
*/
function carregarTiposPontoMovel() {
$http.get(API_ENDPOINT + "tipo_ponto_movel")
.then(function (result) {
$scope.tiposPontoMovel = result.data;
_.each($scope.tiposPontoMovel, function (tipoPontoMovel) {
tipoPontoMovel._id = _.uniqueId();
});
}, function (err) {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_ERRO'))
.content(err.data.message)
.ok($scope.res('COMUM_OK')));
});
}
/**
* @method carregarElementosRastreaveis
*/
function carregarElementosRastreaveis() {
$http.post(API_ENDPOINT + "obterERs")
.then(function (result) {
var elementosRastreaveis = result.data;
var pontosMoveis = [];
_.each(elementosRastreaveis, function (elementoRastreavel) {
pontosMoveis.push({ _id: _.uniqueId(), nome: elementoRastreavel.nome, descricao: elementoRastreavel.nome, idElementoRastreavel: elementoRastreavel.id });
});
$scope.pontosMoveis = mergePontosMoveis(pontosMoveis);
$scope.gridOptions.api.sizeColumnsToFit();
$scope.gridOptions.rowData = $scope.pontosMoveis;
$scope.gridOptions.api.onNewRows();
$scope.gridOptions.api.setSortModel([{
field: 'nome',
sort: 'asc'
}]);
}, function (err) {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_ERRO'))
.content(err.data.message)
.ok($scope.res('COMUM_OK')));
});
}
/**
* @method carregarTiposElementoRastreavel
*/
function carregarTiposElementoRastreavel() {
$http.post(API_ENDPOINT + "obterTiposER")
.then(function (result) {
$scope.tiposElementoRastreavel = result.data;
}, function (err) {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_ERRO'))
.content(err.data.message)
.ok($scope.res('COMUM_OK')));
});
}
/**
* @method carregarTiposDispositivo
*/
function carregarTiposDispositivo() {
$http.post(API_ENDPOINT + "obterTiposDispositivo", $scope.tipoPontoMovel.idTipoElementoRastreavel)
.then(function (result) {
$scope.tipoPontoMovel.iconesDispositivo = [];
_.each(result.data, function (tipoDispositivo) {
var iconeDispositivo = { nome: tipoDispositivo.nome, idDispositivo: tipoDispositivo.id };
$scope.tipoPontoMovel.iconesDispositivo.push(iconeDispositivo);
});
}, function (err) {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_ERRO'))
.content(err.data.message)
.ok($scope.res('COMUM_OK')));
});
}
/**
* @method selecionarTipoElementoRastreavel
*/
function selecionarTipoElementoRastreavel() {
carregarTiposDispositivo();
}
function abrirUpload(nome) {
$scope.nomeIcone = nome;
$scope.input = angular.element('input.uploadArquivo_' + nome);
$scope.input.click();
}
var uploader = $scope.uploader = new FileUploader();
uploader.filters.push({
name: 'customFilter',
fn: function (item) {
if (item.type == 'image/png' || item.type == 'image/jpeg' || item.type == 'image/gif') {
return true;
} else {
$mdDialog
.show($mdDialog.alert()
.title($scope.res('COMUM_ERRO'))
.content('Tipo de arquivo incorreto')
.ok($scope.res('COMUM_OK')));
return false;
}
}
});
$scope.uploader.onCompleteItem = function (item, response) {
$scope.mensagem = response;
};
$scope.uploader.onAfterAddingFile = function (item, evt, arquivo) {
//item.novoNome = item.file.name;
enviarArquivo();
}
function enviarArquivo() {
$scope.mostrarImagem();
}
$scope.mostrarImagem = function () {
$('#arquivo_' + $scope.nomeIcone).each(function (index) {
if ($('#arquivo_' + $scope.nomeIcone).eq(index).val() != "") {
$scope.readURL(this);
}
});
}
$scope.readURL = function (input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onloadend = function () {
$scope.icones[$scope.nomeIcone] = reader.result;
$scope.$apply();
};
reader.readAsDataURL(input.files[0]);
if ($scope.nomeIcone == 'tipo') {
$scope.tipoPontoMovel.urlIcone = input.files[0].name;
}
else {
$scope.tipoPontoMovel.iconesDispositivo = _.map($scope.tipoPontoMovel.iconesDispositivo, function (iconeDispositivo) {
if (iconeDispositivo.nome == $scope.nomeIcone) {
iconeDispositivo.urlIcone = input.files[0].name;
}
return iconeDispositivo;
});
}
if ($scope.bytesIcone == null) {
$scope.bytesIcone = [];
}
$scope.bytesIcone[$scope.nomeIcone] = input.files[0];
}
}
angular.extend($scope, {
criarNovoTipo: criarNovoTipo,
abrirModalAdicionarExtraPontoMovel: abrirModalAdicionarExtraPontoMovel,
removerExtraPontoMovel: removerExtraPontoMovel,
ativarTipoPontoMovel: ativarTipoPontoMovel,
salvar: salvar,
editarPontoMovel: editarPontoMovel,
deletePontoMovel: deletePontoMovel,
editarTipoPontoMovel: editarTipoPontoMovel,
deletarTipoPontoMovel: deletarTipoPontoMovel,
abrirUpload: abrirUpload,
selecionarTipoElementoRastreavel: selecionarTipoElementoRastreavel,
carregarElementosRastreaveis: carregarElementosRastreaveis
});
}
}());