app
	.component('appGuiatrans', {
		templateUrl: './views/guiatrans/guiatrans.view.html',
		controller: CtrlGuiatrans
	});

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



function CtrlGuiatrans(scope, api, form, alert) {

	scope.guiatrans = [];


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

		api.list('Guiatrans/lista').then(res => {
			scope.guiatrans = res.data;
		})
			.finally(fin => scope.spinner = false);
	}

	scope.dowloadfile = (guiatrans) => {
		//console.log(cerchofe.documento);
		window.open(guiatrans.file_attached, '_blank');
	}

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

		switch (index) {
			case 1:
				scope.ventas = [];
				scope.modal.spinnertwo = true;

				api.list('Guiatrans/listaventas').then(res => {
					scope.ventas = res.data;
				})
					.finally(fin => scope.modal.spinnertwo = false);
				scope.modal.title = "Asociar venta (Factura)";
				scope.modal.model = angular.copy(object);
				scope.modal.tab = 1;
				form.modal('edit');
				break;

			case 2:
				//scope.ventas = [];
				scope.modal.spinnertwo = true;

				api.list('Guiatrans/listaventas').then(res => {
					scope.ventas = res.data;
				})
					.finally(fin => scope.modal.spinnertwo = false);
				scope.modal.title = "Sincronizar SUNAT - GUIAS";
				form.modal('editsinsunat');
				break;

		}
	}


	scope.savesinsunat = () => {
		scope.modal.spinner = true;
		scope.modal.fails = {};
		let promise;

		promise = api.list('Guiatrans/getguia');
		promise.then(res => Process(res)).catch(error => ManagerError(error)).finally(fin => scope.modal.spinner = false);

	}


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

		let id_venta = null;

		switch (scope.modal.tab) {
			case 1:
				id_venta = scope.modal.model.id_venta;
				break;
			case 2:
				if (scope.modal.venta_encontrada != null){
					id_venta = scope.modal.venta_encontrada.id;
					/*** Reasignar valor id_venta*/
					scope.modal.model.id_venta = id_venta;
				}
				break;
		}

		
		if (id_venta > 0 ) {
			promise = api.update('Guiatrans', scope.modal.model);
			promise.then(res => Process(res)).catch(error => ManagerError(error)).finally(fin => scope.modal.spinner = false);
		} else {
			scope.modal.spinner = false;
			return alert.warning("Seleccione un documento para asociar!");
		}
	}



	scope.findVenta = () => {
		const search = scope.modal.model.venta_filtro;
		//console.log(search)
		api.list('Guiatrans/buscarventa/' + search).then(res => {
			scope.modal.venta_encontrada = res.data;
		})
	}

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

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

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

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

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

	Init();
}

