DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`fv_pca`()
BEGIN

DECLARE done INT DEFAULT FALSE;

DECLARE vTicketFk INT;
DECLARE vSaleFk INT;
DECLARE vClonTicket INT DEFAULT 0;

DECLARE cur1 CURSOR FOR 
SELECT s.ticketFk, s.id 
	FROM vn.sale s
		JOIN vn.ticket t ON t.id = s.ticketFk
		JOIN vn.item i ON i.id = s.itemFk
		JOIN vn.itemType it ON it.id = i.typeFk
		WHERE t.shipped BETWEEN '2020-10-18' AND '2020-10-31'
		AND it.code IN ('ANT','ANS','ORQ','TRO')
		and t.warehouseFk = 1;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN cur1;

FETCH cur1 INTO vTicketFk, vSaleFk;

 WHILE done = 0 DO
    
    SELECT t.id INTO vClonTicket
		FROM vn.ticket t
        JOIN (SELECT addressFk, shipped FROM vn.ticket WHERE id = vTicketFk) sub USING(addressFk, shipped)
        WHERE t.warehouseFk = 44
        LIMIT 1;
	
																								SELECT vTicketFk, vClonTicket;
   
	IF vClonTicket = 0 THEN
    
		INSERT INTO ticket (
				clientFk,
				shipped,
				addressFk,
				agencyModeFk,
				nickname,
				warehouseFk,
				companyFk,
				landed,
				zoneFk,
                zonePrice,
                zoneBonus,
                routeFk
		)
		SELECT
				clientFk,
				shipped,
				addressFk,
				agencyModeFk,
				nickname,
				44,
				companyFk,
				landed,
				zoneFk,
                zonePrice,
                zoneBonus,
                routeFk
			
		FROM ticket
		WHERE id = vTicketFk;

		SET vClonTicket = LAST_INSERT_ID();
    
																										SELECT 'lstID', vClonTicket;
        /*
		INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
		SELECT vTicketFk, ao.observationTypeFk, ao.description
			FROM addressObservation ao
				JOIN ticket t ON t.addressFk = ao.addressFk
			WHERE t.id = vClonTicket;
*/
		INSERT INTO ticketLog
		SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert', 
			description = CONCAT('Ha creado el ticket:', ' ', vClonTicket, ' clonando el ', vTicketFk);
      
    END IF;
      
	UPDATE vn.sale
		SET ticketFk = vClonTicket
		WHERE id = vSaleFk;

	SET vClonTicket = 0;
    
    SET done = 0;
    FETCH cur1 INTO vTicketFk, vSaleFk;
    
  END WHILE;

  CLOSE cur1;


END$$
DELIMITER ;