DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientGreugeSpray`(
	IN vClientFk INT, 
	IN vIsOnlyForHisOwner BOOL, 
	IN vDepartmentCode VARCHAR(45), 
	IN vWithMana BOOLEAN
)
BEGIN
	DECLARE vGreuge DECIMAL(10,2);
	DECLARE vOwner INT;
	DECLARE vTotalSale INT;
	DECLARE vGreugeTypeFk INT DEFAULT 5; -- HERENCIA
	DECLARE vGreugeTypeMana INT DEFAULT 3;-- Maná
	DECLARE vMana DECIMAL(10,2);

	SELECT clientGetMana(vClientFk) INTO vMana;

	IF vWithMana AND vMana THEN
		INSERT INTO greuge 
			SET clientFk = vClientFk,
				description = 'Desasignación',
				amount = - vMana,
				shipped = util.VN_CURDATE(),
				greugeTypeFk = vGreugeTypeMana;
	END IF;

	SELECT SUM(amount) INTO vGreuge
		FROM greuge
		WHERE clientFk = vClientFk;

	IF vGreuge THEN
		IF LENGTH(vDepartmentCode) THEN
			SELECT salesDepartmentFk INTO vOwner
				FROM client
				WHERE id = vClientFk;
		ELSE
			SELECT id INTO vOwner
				FROM department
				WHERE code = vDepartmentCode;
		END IF;
		
		IF vOwner IS NULL THEN 
			CALL util.throw('The department is incorrect');
		END IF;
		
		INSERT INTO greuge(clientFk, description, amount, shipped, greugeTypeFk)
			WITH greuges AS(	
			SELECT DISTINCT t.clientFk, FLOOR(cr.yearSale / 12) monthSale
				FROM vn.ticket t
					JOIN vn.client c ON c.id = t.clientFk
					JOIN vn.departmentMana dm ON dm.salesDepartmentFk = c.salesDepartmentFk
					JOIN vn.claimRatio cr ON cr.clientFk = c.id
				WHERE dm.salesDepartmentFk = IF(vIsOnlyForHisOwner, vOwner, dm.salesDepartmentFk)
					AND t.shipped >= util.VN_CURDATE() - INTERVAL 1 MONTH
					AND c.id <> vClientFk
				HAVING monthSale > 100
			), totalGreuge AS(
			SELECT SUM(monthSale) totalSale FROM greuges
			)SELECT g.clientFk, 
						CONCAT('Cliente: ', vClientFk), 
						vGreuge * g.monthSale / tgtotalSale, 
						util.VN_CURDATE(), 
						vGreugeTypeFk
					FROM greuges g
						JOIN totalGreuge tg
			UNION ALL
			SELECT vClientFk, 
					'Reparto greuge', 
					-vGreuge, 
					util.VN_CURDATE(), 
					vGreugeTypeFk;
	END IF;
END$$
DELIMITER ;
