app
	.directive("fileReader", fileReader)
	.component('appVentasdetra', {
		templateUrl: './views/ventasdetra/ventasdetra.view.html',
		controller: CtrlVentasdetra
	});

CtrlVentasdetra.$inject = ['$scope', 'api.service', 'form.service', 'alert.service'];

function CtrlVentasdetra(scope, api, form, alert) {
	
	scope.fileContent = null;
	scope.retenciones = [];

	Init = () => {
		scope.spinner = true;

		api.list('ventas/listaretenciones').then(res => {
			scope.retenciones = res.data;
		})

		.finally(fin => scope.spinner = false);
	}

	scope.delete = (detraccion) => 
		{
			scope.deleted = detraccion;
			alert.confirm("¡Se eliminara la detracción " +  detraccion.iddetraccion+ " ,esta operación es irreversible!",Delete);		
		}
	
	Delete = (detraccion) => 
	{
		
		scope.spinner_delete = true;

		
		api.delete('detraccion',scope.deleted.id).then(res => {
			if(!res.data.success) return ManagerError(res.data.message);
			alert.success(res.data.message);
			Init();
		})
		.catch(error => ManagerError(error))
		.finally(fin => scope.spinner_delete = false);
		
	}

	
	scope.openModal = (index, object = {}) => {
		Clean();

		switch (index) {
			case 1:
				scope.modal.edit = true;
				scope.modal.title = "Importar Detracciones";
				scope.modal.model = angular.copy(object);
				form.modal('edit');
			break;
		}
	}

	scope.save = () => {
	
		scope.modal.spinner = true;
		let promise;

		if (!scope.fileContent) return;

		const data = scope.fileContent.split("\r\n")

		const list = []; // Enviar a backend

		data.forEach(element => {
			list.push(element.split(","))
		});

		/*
		api.store('detraccion', {detracciones: list}).then(res => {
			console.log(res)
		})
		*/
		promise = api.store('detraccion',{detracciones: list});
		promise.then(res => Process(res)).catch(error => ManagerError(error)).finally(fin => scope.modal.spinner = false);

	}


	Process = (res) => {
		if (res.data.fails)
			return scope.modal.fails = res.data.fails;

		if (!res.data.success)
			return alert.warning(res.data.message);

		//alert(res.data.message);
		alert.successimport(res.data.message);
		form.modal('edit', false);
		Init();
	}

	ManagerError = (error) => {
		alert.warning(error);
	}

	Clean = () => {
		scope.modal = { model: {}, fails: {} };
	}

	Init();
}


function fileReader() {
	return {
	  scope: {
		fileReader:"="
	  },
	  link: function(scope, element) {
		$(element).on('change', function(changeEvent) {
		  var files = changeEvent.target.files;
		  if (files.length) {
			var r = new FileReader();
			r.onload = function(e) {
				var contents = e.target.result;
				scope.$apply(function () {
				  scope.fileReader = contents;
				});
			};
			
			r.readAsText(files[0]);
		  }
		});
	  }
	};
}
  