DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketParking_findSkipped`(vTicketFk INT, vItemPackingTypeFk VARCHAR(1))
BEGIN

/**
 * Averigua los tickets que se han saltado por un error en el proceso encajado
 * @param vTicketFk Ticket
 * @param vItemPackingTypeFk Modo de encajado
 * @return un select con los tickets afectados
 */

   	DECLARE vParkingFk INT;
    DECLARE vParked DATETIME;
    DECLARE vLevel INT;
    DECLARE vWagon INT;
    DECLARE vCollectionFk INT;

    SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0)
		INTO vLevel, vWagon, vCollectionFk
		FROM vn.ticketCollection tc
			JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk
        WHERE ticketFk = vTicketFk
        ORDER BY c.id DESC
        LIMIT 1;

	SELECT created, parkingFk
		INTO vParked, vParkingFk
		FROM vn.ticketParking tp
			JOIN vn.parking p ON p.id = tp.parkingFk
			JOIN vn.sector s ON s.id = p.sectorFk
        WHERE ticketFk = vTicketFk
       		AND s.itemPackingTypeFk = vItemPackingTypeFk
       		AND s.isPackagingArea ;

    SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia
		FROM vn.ticketParking tp
			JOIN vn.parking p ON p.id = tp.parkingFk
			JOIN vn.sector sc ON sc.id = p.sectorFk
			LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk
			JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk
			JOIN vn.ticket t ON t.id = tp.ticketFk
			JOIN vn.zone z ON z.id = t.zoneFk
			JOIN vn.agencyMode am ON am.id = z.agencyModeFk
			JOIN vn.state s ON s.id = tst.state
			JOIN vn.alertLevel alPacked ON alPacked.code = 'PACKED'
			JOIN vn.alertLevel alOnPreparation ON alOnPreparation.code = 'ON_PREPARATION'
        WHERE (s.alertLevel < alPacked.id
				AND tp.parkingFk = vParkingFk
	            AND sc.isPackagingArea
	            AND 	(
						( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked )
					OR
						( tc.collectionFk = vCollectionFk
							AND (LEFT(tc.wagon,1) < LEFT(vWagon,1)
							OR  (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1)))
						)
					)
				) -- Etiquetas que no se han escaneado y ya estamos con una posterior
				OR
	            (s.alertLevel > alOnPreparation.id
					AND tp.parkingFk = vParkingFk
	                AND sc.isPackagingArea
	                AND tp.created < vParked
	                AND t.packages <=> 0);
END$$
DELIMITER ;
