USE `vn`;
DROP procedure IF EXISTS `ticket_componentPreview`;

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentPreview`(
	vTicketFk INT,
    vLanded DATE, 
    vAddressFk INT,
    vZoneFk INT,
    vWarehouseFk SMALLINT)
BEGIN
/**
 * Calcula los componentes de los articulos de un ticket
 *
 * @param vTicketFk id del ticket
 * @param vLanded nueva fecha de entrega
 * @param vAddressFk nuevo consignatario
 * @param vZoneFk nueva zona
 * @param vWarehouseFk nuevo warehouse
 *
 * @return tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
 */
	DECLARE vShipped DATE;
	DECLARE vBuyOrderItem INT DEFAULT 100;

    DECLARE vHasDataChanged BOOL DEFAULT FALSE;    
    DECLARE vHasAddressChanged BOOL;
    DECLARE vHasZoneChanged BOOL DEFAULT FALSE;
    DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE;
    
	DECLARE vAddressTypeRateFk INT DEFAULT NULL;
	DECLARE vAgencyModeTypeRateFk INT DEFAULT NULL;
    
    DECLARE vHasChangeAll BOOL DEFAULT FALSE;
  
	SELECT DATE(landed) <> vLanded, 
			addressFk <> vAddressFk, 
			zoneFk <> vZoneFk,
            warehouseFk <> vWarehouseFk
		INTO
			vHasDataChanged,
            vHasAddressChanged,
            vHasZoneChanged,
            vHasWarehouseChanged
		FROM vn.ticket t
        WHERE t.id = vTicketFk;

    IF vHasDataChanged OR vHasWarehouseChanged THEN
		SET vHasChangeAll = TRUE;
	END IF;
    
	IF vHasAddressChanged THEN
		SET vAddressTypeRateFk = 5;
    END IF;
    
	IF vHasZoneChanged THEN
		SET vAgencyModeTypeRateFk = 6;
    END IF;

	SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped 
		FROM zone
		WHERE id = vZoneFk;
        
	CALL buyUltimate(vWarehouseFk, vShipped);
        
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( 
	SELECT 
			vWarehouseFk AS warehouseFk,
			NULL AS available,
			s.itemFk,
			bu.buyFk
		FROM sale s
			LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
		WHERE s.ticketFk = vTicketFk
			AND s.itemFk != vBuyOrderItem
		GROUP BY bu.warehouseFk, bu.itemFk);

	CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);

	REPLACE INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
		SELECT t.warehouseFk, s.itemFk, sc.componentFk, sc.value
			FROM saleComponent sc
				JOIN sale s ON s.id = sc.saleFk
				JOIN ticket t ON t.id = s.ticketFk
				JOIN componentRate cr ON cr.id = sc.componentFk
			WHERE s.ticketFk = vTicketFk 
				AND (cr.isRenewable = FALSE 
					OR 
					(NOT vHasChangeAll
						AND (NOT (cr.componentTypeRate <=> vAddressTypeRateFk
                        OR cr.componentTypeRate <=> vAgencyModeTypeRateFk))));

    SET @shipped = vShipped;

	DROP TEMPORARY TABLE
        tmp.buyUltimate,
		tmp.ticketLot;

	IF vShipped IS NULL THEN
		CALL util.throw('NO_ZONE_AVAILABLE');
    END IF;
    
	IF vShipped < CURDATE() THEN
		CALL util.throw('ERROR_PAST_SHIPMENT');
    END IF;
END$$

DELIMITER ;

