DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`previousSticker_get`(
	vSaleGroupFk INT
)
BEGIN
/**
 * Devuelve los campos a imprimir en una etiqueta de preparación previa.
 * Actualiza el valor de saleGroup.parkingFk en el caso de que exista un
 * saleGroup del mismo ticket con parking, del mismo sector, para que todos se
 * pongan juntos.
 *
 * @param vSaleGroupFk Identificador de saleGroup
 */
	DECLARE vTicketFk INT;
	DECLARE vParkingFk INT;
	DECLARE vSectorFk INT;
	DECLARE vTicketLines INT;

	WITH ticketData AS(
		SELECT s.ticketFk 
			FROM vn.saleGroupDetail sgd
				JOIN vn.sale s ON s.id = sgd.saleFk
			WHERE sgd.saleGroupFk = vSaleGroupFk
	)
	SELECT COUNT(*), s.ticketFk INTO vTicketLines, vTicketFk 
		FROM vn.sale s 
			JOIN ticketData td ON td.ticketFk = s.ticketFk;

	SELECT sg.parkingFk, sc.sectorFk
		INTO vParkingFk, vSectorFk
		FROM saleGroup sg
			JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id
			JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk
			JOIN saleGroupDetail sgd ON sgd.saleGroupFk = sg.id
			JOIN sale s ON s.id = sgd.saleFk
		WHERE s.ticketFk = vTicketFk
			AND sg.parkingFk IS NOT NULL
		LIMIT 1;

	UPDATE saleGroup sg
		SET sg.parkingFk = vParkingFk
		WHERE sg.id = vSaleGroupFk
			AND sg.sectorFk = vSectorFk;

	SELECT sgd.saleGroupFk,
			t.id ticketFk,
			COUNT(*) previousLines,
			IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) shippingHour,
			IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) shippingMinute ,
			IFNULL(MAX(i.itemPackingTypeFk),'H') itemPackingTypeFk ,
			vTicketLines ticketLines,
			p.code `location`,
			sc.description sector
		FROM sale s
			JOIN item i ON i.id = s.itemFk
			JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
			JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
			JOIN sector sc ON sc.id = sg.sectorFk
			JOIN ticket t ON t.id = s.ticketFk
			LEFT JOIN parking p ON p.id = sg.parkingFk
			LEFT JOIN `zone` z ON z.id = t.zoneFk
		WHERE sgd.saleGroupFk = vSaleGroupFk;
END$$
DELIMITER ;
