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

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculate`(
    vDate DATE,
    vAddress INT,
    vAgencyMode INT)
proc: BEGIN
/**
 * Calcula los articulos disponibles y sus precios
 * 
 * @param vDate Fecha de recepcion de mercancia
 * @param vAddress Id del consignatario
 * @param vAgencyMode Id de la agencia
 * @return tmp.ticketCalculateItem, tmp.ticketComponentPrice
 **/
 
    DECLARE vAvailableCalc INT;
    DECLARE vShipment DATE;
    DECLARE vAgencyId INT;
    DECLARE vClient INT;
    DECLARE vWarehouseFk SMALLINT;
    DECLARE vDone BOOL;
    DECLARE cTravelTree CURSOR FOR
        SELECT warehouseFk, shipped FROM tmp.agencyHourGetShipped;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
    
    -- Establece los almacenes y las fechas que van a entrar al disponible

    SELECT agencyFk INTO vAgencyId
        FROM agencyMode WHERE id = vAgencyMode;

    SELECT clientFk INTO vClient
        FROM address WHERE id = vAddress;

    CALL vn.agencyHourGetShipped(vDate, vAddress, vAgencyId);

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot(
      `warehouseFk` smallint(5) unsigned NOT NULL,
      `itemFk` int(11) NOT NULL,
      `available` double DEFAULT NULL,
      `buyFk` int(11) DEFAULT NULL,
      `fix` tinyint(3) unsigned DEFAULT '0',
      KEY `itemFk` (`itemFk`),
      KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH
    ) ENGINE=MEMORY DEFAULT CHARSET=utf8;

    OPEN cTravelTree;

    l: LOOP
        SET vDone = FALSE;
        FETCH cTravelTree INTO  vWarehouseFk, vShipment;

        IF vDone THEN
            LEAVE l;
        END IF;

        CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipment);
        CALL buyUltimate (vWarehouseFk, vShipment);

        INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk)
			SELECT
					vWarehouseFk,
					i.item_id,
					IFNULL(i.available, 0),
					bu.buyFk
				FROM `cache`.available i
					JOIN tmp.item br ON br.itemFk = i.item_id
					LEFT JOIN item it ON it.id = i.item_id
					LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id
				WHERE i.calc_id = vAvailableCalc
					AND it.id != 100    
					AND i.available > 0;
        
        DROP TEMPORARY TABLE tmp.buyUltimate;
    END LOOP;

    CLOSE cTravelTree;

    CALL vn.ticketComponentCalculate(vAddress, vAgencyMode);

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem;
    CREATE TEMPORARY TABLE tmp.ticketCalculateItem
    ENGINE = MEMORY
		SELECT 
				b.itemFk, 
				SUM(b.available) available,
				p.name producer, 
				i.name item, 
				i.size size,  
				i.stems,  
				i.category, 
				i.inkFk,  
				i.image,
				o.code origin, bl.price
			FROM tmp.ticketLot b
				JOIN item i ON b.itemFk = i.id
				LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible
				JOIN origin o ON o.id = i.originFk
				JOIN (
					SELECT MIN(price) price, itemFk
						FROM tmp.ticketComponentPrice
						GROUP BY itemFk
				) bl ON bl.itemFk = b.itemFk
			GROUP BY b.itemFk;
        
	DROP TEMPORARY TABLE 
		tmp.ticketComponent,
		tmp.ticketLot;
END$$

DELIMITER ;

