IF  EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].ufd_calcular_difal_baseunica') AND TYPE IN (N'FN', N'IF', N'TF', N'FS', N'FT'))
    DROP FUNCTION [DBO].ufd_calcular_difal_baseunica
GO 

CREATE FUNCTION dbo.ufd_calcular_difal_baseunica
(
    @VlrBaseIcms DECIMAL(18,4),
    @PercIcmsDestinoDifal DECIMAL(18,4),
    @PercIcmsOrigemDifal DECIMAL(18,4),
    @PercFecop DECIMAL(18,4)
)
RETURNS @Resultado TABLE (
    BaseIcmsDestinoDifal DECIMAL(18,4),
    ValorIcmsDestinoDifal DECIMAL(18,4),
    VlrBaseFecop DECIMAL(18,4),
    VlrFecop DECIMAL(18,4)
)
AS
BEGIN
    DECLARE @AliqIcmsDest DECIMAL(18,4),
            @AliqIcmsOrig DECIMAL(18,4),
            @VlrDifalItem DECIMAL(18,4),
            @PercFecopFuncao DECIMAL(18,4),
            @VlrFecop DECIMAL(18,4);

    -- Convertendo percentuais para fração decimal
    SET @AliqIcmsDest = @PercIcmsDestinoDifal / 100;
    SET @AliqIcmsOrig = @PercIcmsOrigemDifal / 100;
    SET @AliqIcmsDest = @AliqIcmsDest - @AliqIcmsOrig;
    
    -- Cálculo do DIFAL
    SET @VlrDifalItem = @VlrBaseIcms * @AliqIcmsDest;

    -- Cálculo do FECOP
    SET @PercFecopFuncao = @PercFecop / 100;
    SET @VlrFecop = @VlrBaseIcms * @PercFecopFuncao;

    -- Inserindo os valores na tabela de retorno
    INSERT INTO @Resultado (BaseIcmsDestinoDifal, ValorIcmsDestinoDifal, VlrBaseFecop, VlrFecop)
    VALUES (@VlrBaseIcms, @VlrDifalItem, @VlrBaseIcms, @VlrFecop);

    RETURN;
END;
