DROP function IF EXISTS `vn`.`bionicCalcReverse`;

DELIMITER $$
CREATE DEFINER=`root`@`%` FUNCTION `vn`.`bionicCalcReverse`(vWarehouse INT,
    vMargin DECIMAL(10,3),
    vRetailedPrice DECIMAL(10,3),
    vM3 DECIMAL(10,3),
    vAddress INT,
    vAgencyMode INT) RETURNS decimal(10,3)
    DETERMINISTIC
BEGIN
	DECLARE vGeneralInflationCoeficient INT;
    DECLARE vVerdnaturaVolumeBox BIGINT;
    DECLARE vClientFk INT;
    DECLARE vComponentRecovery VARCHAR(50) DEFAULT 'debtCollection';
	DECLARE vComponentMana VARCHAR(50) DEFAULT 'autoMana';
	DECLARE vComponentPort VARCHAR(50) DEFAULT 'delivery';
	DECLARE vComponentMargin VARCHAR(50) DEFAULT 'margin';
	DECLARE vComponentCost VARCHAR(50) DEFAULT 'purchaseValue';
    DECLARE vComponentCostValue DECIMAL(10,2);
	DECLARE vItem INT DEFAULT 98;
    DECLARE vItemCarryBox INT;
	
    SELECT generalInflationCoeFicient, verdnaturaVolumeBox, itemCarryBox
			INTO vGeneralInflationCoeficient, vVerdnaturaVolumeBox, vItemCarryBox
		FROM bionicConfig;
    
    SELECT clientFk INTO vClientFk FROM address WHERE id = vAddress;

	-- Creamos la tabla tmp.bionicComponent
    DROP TEMPORARY TABLE IF EXISTS tmp.bionicComponent;
    CREATE TEMPORARY TABLE tmp.bionicComponent(
		`warehouseFk` smallint(5) unsigned NOT NULL,
		`itemFk` int(11) NOT NULL,
		`componentFk` int(10) unsigned NOT NULL,
		`value` decimal(10,4) NOT NULL,
		UNIQUE KEY `itemWarehouseComponent` (`itemFk`,`warehouseFk`,`componentFk`) USING HASH,
		KEY `itemWarehouse` (`itemFk`,`warehouseFk`) USING BTREE
	) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

   -- Margin
	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, id, vMargin
			FROM component
			WHERE code = vComponentMargin;

   -- Recobro
	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, c.id, ROUND(LEAST(cr.recobro,0.25), 3) 
			FROM bi.claims_ratio cr
				JOIN component c ON c.code = vComponentRecovery
				WHERE cr.Id_Cliente = vClientFk AND cr.recobro > 0.009;
                            
	-- Componente de maná automático, en función del maná acumulado por el comercial.
	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, co.id, ROUND(ms.prices_modifier_rate, 3)
			FROM client c 
				JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador
                JOIN component co ON co.code = vComponentMana
			WHERE ms.prices_modifier_activated AND c.id = vClientFk LIMIT 1;
 
	-- Reparto
	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, co.id, vGeneralInflationCoeficient
				* ROUND(
						vM3
						* az.price
						* az.inflation
						/ vVerdnaturaVolumeBox, 4
						)
			FROM agencyMode ag
				JOIN address a ON a.id = vAddress AND ag.id = vAgencyMode
				JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk 
					AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk
				JOIN agencyModeZone az ON az.agencyModeFk = vAgencyMode 
					AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse
				JOIN component co ON co.code = vComponentPort;
    
    -- Coste
	SELECT vRetailedPrice - SUM(`value`) INTO vComponentCostValue
		FROM tmp.bionicComponent;

	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, id,vComponentCostValue
			FROM component 
            WHERE code = vComponentCost;
        
    RETURN vComponentCostValue;
END$$

DELIMITER ;

