DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` PROCEDURE `vn`.`item_setGeneric`(vSelf INT)
BEGIN
/**
 * Asigna el código genérico a un item, salvo que sea un código de item genérico.
 * 
 * @param vSelf identificador de vn.item
 */
	DECLARE vGenericFk INT;

	SELECT itemFk INTO vGenericFk
		FROM (
			SELECT itemFk, SUM(matches) = maxMatches `match`
				FROM (
					SELECT ga.id gaid, ga.itemFk,
						CASE 
							WHEN t.code = 'nflowers' THEN
								it.value <=> ga.numFlores
							WHEN t.code = 'origin' THEN
								it.value <=> ga.origin
							WHEN t.code = 'quality' THEN
								it.value <=> ga.quality
							WHEN t.code = 'color' THEN
								it.value <=> ga.color
							WHEN t.code = 'category' THEN
								it.value <=> ga.category
							WHEN t.code = 'producer' THEN
								it.value <=> ga.productor
							ELSE
								0
						END matches,
						(NOT ISNULL(ga.origin))
						+ (NOT ISNULL(ga.color))
						+ (NOT ISNULL(ga.quality))
						+ (NOT ISNULL(ga.numFlores))
						+ (NOT ISNULL(ga.category))
						+ (NOT ISNULL(ga.productor)) maxMatches
				FROM vn.item i
					JOIN vn.itemTag it ON it.itemFk = i.id
					JOIN vn.tag t ON t.id = it.tagFk
					JOIN vn.genericAllocation ga
						ON (i.typeFk = ga.typeFk OR ga.typeFk IS NULL)
						AND (i.longName = ga.longName OR ga.longName IS NULL)
						AND (i.`size` = ga.`size` OR ga.`size` IS NULL)
						AND i.id != ga.itemFk
				WHERE i.id = vSelf
					AND NOT i.isFloramondo) sub 
				GROUP BY gaid
				HAVING `match`) sub2
				LIMIT 1;

	UPDATE vn.item 
		SET genericFk = vGenericFk 
		WHERE id = vSelf;
END$$
DELIMITER ;
