app
	.component('appProgramacionviaje',{
		templateUrl: './views/programacionviaje/programacionviaje.view.html',
		controller: CtrlProgramacionviaje
	});

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

	function CtrlProgramacionviaje(scope,api,form,alert,location) 
	{
		
		scope.progviaje = [];
		scope.tausuarios = [];
		scope.clientes = [];
		scope.ruta_o = [];
		scope.ruta_d = [];
		scope.progviajedet= [];

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

			api.list('Programacionviaje/parametros').then(res => {
				scope.tausuarios = res.data.TaUsuarios;
				scope.clientes = res.data.Clientes;
				scope.ruta_o = res.data.Rutas;
				scope.ruta_d = res.data.Rutas;
			})

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

		ListarDetalleIngreso = () => {
			const ruta = "Programacionviaje/detalle/" + scope.modal.model.id_programacion

			scope.spinner = true;
			api.list(ruta).then(res => {
				scope.progviajedet = res.data;
			})
			.finally(fin => scope.spinner = false);
		}

		ListarDetalleGuia = () => {
			const guia = "Programacionviaje/detalle/" + scope.modal.model.id_programacion

			scope.spinner = true;
			api.list(guia).then(res => {
				scope.progviajeguia = res.data;
			})
			.finally(fin => scope.spinner = false);
		}
		
		
		
		scope.openModal = (index,object = {}) => 
		{
			Clean();

			switch(index)
			{
				case 1:
					scope.modal.edit = false;
					scope.modal.title = "Agregar programacion de viaje";
					form.modal('edit');
				break;
				case 2:

					scope.modal.edit = true;
					scope.modal.title = "Generar Guia";

					scope.modal.model = angular.copy(object);
					/*
					scope.modal.model.btn_guia = object.btn_guia
					scope.modal.model.id_programacion = object.id_programacion
					scope.modal.model.id_cliente = object.id_cliente
					scope.modal.model.id_usuario = object.id_usuario
					scope.modal.model.id_vehiculo = object.id_vehiculo
					scope.modal.model.fecha = formatDate(object.fecha)
					*/
					form.modal('genguia');


				break;
				case 3:
					scope.modal.edit = true;
					scope.modal.title = "Registro de Ingresos";
					scope.modal.model = {
						id_programacion: object.id_programacion,
						gasto_detalle: null,
						gasto_moneda: null,
						gasto_monto: null
					}
					form.modal('ingreso');
					ListarDetalleIngreso()
				break;
			}
		}
		
		scope.save = () => 
		{
			scope.modal.spinner = true;
			scope.modal.fails   = {};

			console.log(scope.modal.model);
			const data = {
				id_usuario: scope.modal.model.id_usuario,
				id_cliente: scope.modal.model.id_cliente,
				ruta_origen: scope.modal.model.ruta_origen,
				ruta_destino: scope.modal.model.ruta_destino,
				id_usuario: scope.modal.model.id_usuario,
				fecha:formatDate(scope.modal.model.fecha),
				estado:"0",
				user_crea:"Web",
			}

			
			if(scope.modal.model.id_programacion){
				//Function_cp();
				data.id = scope.modal.model.id_programacion // Para poder setear el ID que usa el servicio "id"
				promise = api.update('Programacionviaje',data);
			}else{
				promise = api.store('Programacionviaje',data);
			}

			promise.then(res => Process(res)).catch(error => ManagerError(error)).finally(fin => scope.modal.spinner = false);
		}

		scope.saveguia = () => 
		{
			console.log(scope.modal.model)

			/*const data = {
				id_programacion: '02',
				id_tipdoc: '09',
				serie: 'EG07',
				documento: '00001087',
				ruc: '20409480587'
			}*/
			/*var data = new FormData();
			data.append('id_tipdoc', '09');
			data.append('serie', 'EG07');
			data.append('documento', '00001087');
			data.append('ruc', '20409480587');
			data.append('id_programacion','02');

			api.post("load_doc_relacionado.php", data).then(res => {
				console.log('res', res)
			})*/
			//scope.modal.spinner = true;
			//scope.modal.fails   = {};

			//console.log(scope.modal.model);
			//promise = api.store('Programacionviajeguia',scope.modal.model);
			//console.log(scope.modal.model)

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

			var formdata = new FormData();
				formdata.append("id_programacion", "2");
				formdata.append("id_tipdoc", "09");
				formdata.append("serie", "EG07");
				formdata.append("documento", "00001087");
				formdata.append("ruc", "20409480587");

			api.post('load_doc_relacionado.php', formdata)
			.then(response => response.text())
			.then(result => console.log(result))
			.catch(error => console.log('error', error));

			api.store('Pa/prueba', {
				param1: 1,
				param2: 31,
				param3: '2024-01-07',
				param4: 1,
				param5: 1
			}).then(res => {
				console.log(res)
			})
		}

		const LlamadaVariosServicios = async () => {

			try {

				var formdata = new FormData();
				formdata.append("guias_client_id", "f8511ad5-ba60-4c04-9552-f55bca5d204f");
				formdata.append("guias_client_secret", "uyog2depfXjQfqPuNZqPbg==");
				formdata.append("ruc", "10035737541");
				formdata.append("usu_secundario_produccion_user", "CARRILLO");
				formdata.append("usu_secundario_produccion_password", "CAfran7541");
				
				var requestOptions = {
				  method: 'POST',
				  body: formdata,
				  redirect: 'follow'
				};
				
				const respuesta1 = await 
				
				fetch("http://157.55.179.51/sisdoc/app_apisunat/1_solicito_token.php", requestOptions)
				  .then(response => response.text())
				  .then(result => console.log(result))
				  .catch(error => console.log('error', error));


			} catch (error) {
				
			}

		}


		scope.saveingreso = () => 
		{
			//console.log('data', scope.modal.model)
			/**
			 * Llamar a backend
			 */
			scope.modal.spinner = true;
			api.store('Programacionviaje/detalle', scope.modal.model).then(res => {
				ListarDetalleIngreso()
			})
			.finally(fin => scope.modal.spinner = false);
		}

		scope.deleteDetalle = (object) => {
			scope.deleted = object
			alert.confirm("¡Se eliminara el detalle con id "+object.id_ingreso+", esta operación es irreversible!",DeleteDetalle);
		}

		const DeleteDetalle = () => {
			scope.spinner_delete = true;

			api.delete('Programacionviaje/detalle',scope.deleted.id_ingreso).then(res => {
				if(!res.data.success) return ManagerError(res.data.message);
				alert.success(res.data.message);
				ListarDetalleIngreso();
			})
			.catch(error => ManagerError(error))
			.finally(fin => scope.spinner_delete = false);
		}
		
		scope.delete = (Programacionviaje) => 
		{
			scope.deleted = Programacionviaje;
			alert.confirm("¡Se eliminara a " + Programacionviaje.vehiculo.placa + "; con fecha:" + Programacionviaje.fecha  + " de la lista de programaciones, esta operación es irreversible!",Delete);
		}

		Delete = (Programacionviaje) => 
		{
			scope.spinner_delete = true;

			api.delete('Programacionviaje',scope.deleted.id_programacion).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);
		}
		
		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);
			Init();
		}

		scope.goToGuia = (guia) => {
			console.log('guia', guia)
			sessionStorage.setItem('guia', JSON.stringify({
				id_programacion: guia.id_programacion,
				id_cliente: guia.id_cliente,
				id_vehiculo: guia.id_vehiculo
			}))
			location.path('guia')
		}

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

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

		Init();
	
	
	}

	function formatDate(date) {
		var d = new Date(date),
			month = '' + (d.getMonth() + 1),
			day = '' + d.getDate(),
			year = d.getFullYear();
	
		if (month.length < 2) 
			month = '0' + month;
		if (day.length < 2) 
			day = '0' + day;
	
		return [year, month, day].join('-');
	}

	