IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_RC_CLI_CONV_PBM_CONTROLE_CENTRALIZADO]') 
					AND type in (N'P', N'PC'))
BEGIN
	DROP PROCEDURE [DBO].[P_RC_CLI_CONV_PBM_CONTROLE_CENTRALIZADO]
END
GO
--P_RC_CLI_CONV_PBM_CONTROLE_CENTRALIZADO 1,12,13174
 CREATE PROCEDURE P_RC_CLI_CONV_PBM_CONTROLE_CENTRALIZADO @CD_EMP_PAR INT=1, @CD_DEPOSITO INT=0, @CD_NF_PAR INT=0
 AS
SET NOCOUNT ON;

DECLARE @CD_EMP INT
DECLARE @CD_FILIAL INT
DECLARE @CD_NF INT
DECLARE @CD_CTR_CENTRALIZADO INT

IF @CD_NF_PAR=0
BEGIN
	DECLARE ProcPBMCentral CURSOR FAST_FORWARD
	FOR SELECT
		EST_NF_ENT.CD_EMP,
		EST_NF_ENT.CD_FILIAL,
		EST_NF_ENT.CD_NF	
	FROM
		 EST_NF_ENT INNER JOIN V_PRC_FILIAL_RELACAO_DEPOSITOS ON
		 EST_NF_ENT.CD_EMP = V_PRC_FILIAL_RELACAO_DEPOSITOS.CD_EMP AND
		 EST_NF_ENT.CD_FILIAL = V_PRC_FILIAL_RELACAO_DEPOSITOS.CD_FILIAL
		 LEFT OUTER JOIN RC_CLI_CONV_PBM_CENTRALIZADO ON
		 EST_NF_ENT.CD_EMP = RC_CLI_CONV_PBM_CENTRALIZADO.CD_EMP AND
		 EST_NF_ENT.CD_FILIAL = RC_CLI_CONV_PBM_CENTRALIZADO.CD_FILIAL AND
		 EST_NF_ENT.CD_NF = RC_CLI_CONV_PBM_CENTRALIZADO.CD_NF 
	WHERE
		EST_NF_ENT.DT_ENT >=GETDATE()-10
		AND EST_NF_ENT.FLAG_REPOSICAO_PBM=1
		AND RC_CLI_CONV_PBM_CENTRALIZADO.CD_NF IS NULL
END
ELSE
BEGIN
	DECLARE ProcPBMCentral CURSOR FAST_FORWARD
	FOR SELECT
		EST_NF_ENT.CD_EMP,
		EST_NF_ENT.CD_FILIAL,
		EST_NF_ENT.CD_NF	
	FROM
		 EST_NF_ENT
	WHERE
		EST_NF_ENT.CD_EMP = @CD_EMP_PAR
		AND EST_NF_ENT.CD_FILIAL = @CD_DEPOSITO
		AND EST_NF_ENT.FLAG_REPOSICAO_PBM=1
		AND EST_NF_ENT.CD_NF =@CD_NF_PAR
END
SET @CD_CTR_CENTRALIZADO=0
OPEN ProcPBMCentral;
FETCH NEXT FROM ProcPBMCentral INTO @CD_EMP,
								 @CD_FILIAL,
								 @CD_NF;
WHILE @@FETCH_STATUS = 0
	BEGIN
		PRINT 'Filial '+CONVERT(VARCHAR(10), @CD_FILIAL)+CONVERT(VARCHAR(10), @CD_NF)+' '+CONVERT(VARCHAR, GETDATE(), 108);
		IF @CD_NF_PAR=0
		BEGIN
			INSERT INTO RC_CLI_CONV_PBM_CENTRALIZADO
			(CD_EMP,
			CD_FILIAL,
			CD_NF,
			DT_CAD)
			SELECT
				@CD_EMP,
				@CD_FILIAL,
				@CD_NF,
				GETDATE()

			SET @CD_CTR_CENTRALIZADO = SCOPE_IDENTITY()	
		END
		
		EXEC P_RC_CLI_CONV_PBM_CONTROLE_CENTRALIZADO_NOTA_FISCAL @CD_EMP,@CD_FILIAL,@CD_NF,@CD_CTR_CENTRALIZADO

		SET @CD_CTR_CENTRALIZADO=0
		FETCH NEXT FROM ProcPBMCentral INTO @CD_EMP,
											@CD_FILIAL,
											@CD_NF;
	END;
PRINT 'Concluido.';
CLOSE ProcPBMCentral;
DEALLOCATE ProcPBMCentral;