DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`add_awb_component`(IN vAwbFk SMALLINT)
BEGIN

	DECLARE vShipped DATE;
	DECLARE vHasStems BOOLEAN;

	SELECT tr.shipped, IF(a.stems, TRUE, FALSE)  
			INTO vShipped, vHasStems
		FROM vn.travel tr
			JOIN vn.entry e ON e.travelFk = tr.id
			JOIN vn.duaEntry de ON de.entryFk = e.id
			JOIN vn.dua d ON d.id = de.duaFk
			JOIN vn.awb a ON a.id = d.awbFk
		WHERE awbFk = vAwbFk 
		LIMIT 1;

	INSERT IGNORE INTO awb_component (awb_id,Id_Proveedor,awb_component_type_id,awb_role_id,awb_unit_id,value,Id_Moneda) 
		SELECT id, Id_Proveedor, awb_component_type_id, awb_role_id,awb_unit_id, LEAST(GREATEST(value1, IFNULL(min_value, value1)), IFNULL(max_value, value1)), Id_Moneda
			FROM (
				SELECT a.id,
						IFNULL(act.carguera_id,
							CASE awb_role_id 
								WHEN 1 THEN a.carguera_id 
								WHEN 2 THEN a.transitario_id 
								WHEN 3 THEN f.airline_id 
							END
						) Id_Proveedor, 
						act.awb_component_type_id,
						act.awb_role_id,
						act.awb_unit_id, 
						value *
							CASE awb_unit_id
								WHEN '1000Tj-20' THEN ((CAST(stems AS SIGNED) - 20000)/1000) + (min_value / value)
								WHEN '1000Tj-10' THEN ((CAST(stems AS SIGNED) - 10000)/1000) + (min_value / value)
								WHEN '100GW' THEN peso/100 
								WHEN 'AWB' THEN 1 -- No action
								WHEN 'FB' THEN hb/2
								WHEN 'GW' THEN peso
								WHEN 'TW' THEN GREATEST(peso,volume_weight)
								WHEN 'PN' THEN LEAST(90, value + a.propertyNumber * 10)
							END value1, 
						value,
						act.Id_Moneda, 
						act.min_value, 
						act.max_value
					FROM awb a 
						JOIN flight f ON f.flight_id = a.flight_id 
						LEFT JOIN awb_component_template act ON 
							((IFNULL(act.carguera_id, a.carguera_id) = a.carguera_id AND awb_role_id = 1) 
								OR (IFNULL(act.carguera_id, a.transitario_id) = a.transitario_id AND awb_role_id = 2)
								OR (IFNULL(act.airline_id, f.airline_id) = f.airline_id AND awb_role_id = 3)
								OR (awb_role_id = 4))
							AND IFNULL(act.airport_out, f.airport_out) = f.airport_out 
							AND IFNULL(act.airport_in, f.airport_in) = f.airport_in 
							AND IFNULL(act.airline_id, f.airline_id) = f.airline_id 
							AND INSTR(IFNULL(act.days, WEEKDAY(vShipped) + 1),WEEKDAY(vShipped) + 1)
						JOIN awb_component_type acty ON acty.awb_component_type_id = act.awb_component_type_id 
					WHERE a.id = vAwbFk AND Fecha <= vShipped 
						AND (vHasStems = TRUE OR acty.hasStems)
					ORDER BY Fecha DESC, act.days DESC LIMIT 10000000000000000000
				) t;
END$$
DELIMITER ;
