IF EXISTS (
		SELECT *
		FROM sys.objects
		WHERE object_id = OBJECT_ID(N'[dbo].[P_LOJA_NOVA_PRODUTOS]')
			AND type IN (N'P', N'PC')
		)
	DROP PROCEDURE [dbo].[P_LOJA_NOVA_PRODUTOS]
GO

--EXEC P_LOJA_NOVA_PRODUTOS  1,35
--Procedure para replicar cadastro complementar de produtos
CREATE PROCEDURE [dbo].[P_LOJA_NOVA_PRODUTOS] (
	@IN_CD_FILIAL_BASE INT = 1
	,@IN_CD_FILIAL_DESTINO INT = 1
	)
AS
SET DEADLOCK_PRIORITY HIGH;
SET NOCOUNT ON;

--Replicando produtos complemento
ALTER TABLE DBO.EST_PROD_CPL DISABLE CHANGE_TRACKING;

INSERT INTO EST_PROD_CPL (
	CD_EMP
	,CD_FILIAL
	,CD_PROD
	,QT_EST
	,QT_EST_FLUT
	,PRAT
	,GAV
	,VLR_CUSTO_MD
	,VLR_CUSTO
	,QT_IMP
	,DT_IMP
	,SLD_INI
	,VLR_CUSTO_INI
	,CD_USU
	,DT_ULT_ATU
	,VLR_CONS
	,VLR_REV
	,PERC_IPI
	,IPI_NF_SAIDA
	,TP_PROD
	,STS_PROD
	,DT_CAD
	,VLR_CUSTO_ANT
	,VLR_CUSTO_TAB
	,DT_ULT_ENTR_COMPRA
	,VLR_COMPRA
	,DT_ULT_ENTR_TRANSF
	,VLR_TRANSF
	,QTDE_PONTO_FIDEL
	,EMAX
	,ESEG
	,CD_SIGLA
	,QT_EST_EM_TERC
	,QT_EST_DE_TERC
	,QT_EST_GAV
	,QTDE_FINANCIADO
	,QTDE_LIMITADOR
	,QTDE_FACEAMENTO
	,MEDIAF
	,QT_VD_MES1
	,QT_VD_MES2
	,QT_VD_MES3
	,PERC_DESC_FIDEL
	,PERC_DESC_FIDEL_MAX
	,PERC_COMISSAO_SERVICO
	,QT_EST_DEPOSITOS
	,QTDE_MES_VENDA_FECHADO
	,PERC_COMIS
	,FLAG_VERBA_DESCON
	,PERC_DESC_LIMITE
	,VLR_FABRICA
	,DT_ATUALIZA_PARAM
	)
SELECT P.CD_EMP
	,@IN_CD_FILIAL_DESTINO AS CD_FILIAL
	,P.CD_PROD
	,0 AS QT_EST
	,0 AS QT_EST_FLUT
	,P.PRAT
	,P.GAV
	,0 AS VLR_CUSTO_MD
	,0 AS VLR_CUSTO
	,0 AS QT_IMP
	,NULL AS DT_IMP
	,0 AS SLD_INI
	,0 AS VLR_CUSTO_INI
	,1 AS CD_USU
	,NULL AS DT_ULT_ATU
	,0 AS VLR_CONS
	,0 AS VLR_REV
	,P.PERC_IPI
	,P.IPI_NF_SAIDA
	,P.TP_PROD
	,P.STS_PROD
	,GETDATE() AS DT_CAD
	,0 AS VLR_CUSTO_ANT
	,0 AS VLR_CUSTO_TAB
	,NULL AS DT_ULT_ENTR_COMPRA
	,0 AS VLR_COMPRA
	,NULL AS DT_ULT_ENTR_TRANSF
	,0 AS VLR_TRANSF
	,P.QTDE_PONTO_FIDEL
	,P.EMAX
	,P.ESEG
	,0 AS CD_SIGLA
	,0 AS QT_EST_EM_TERC
	,0 AS QT_EST_DE_TERC
	,0 AS QT_EST_GAV
	,0 AS QTDE_FINANCIADO
	,0 AS QTDE_LIMITADOR
	,0 AS QTDE_FACEAMENTO
	,0 AS MEDIAF
	,0 AS QT_VD_MES1
	,0 AS QT_VD_MES2
	,0 AS QT_VD_MES3
	,P.PERC_DESC_FIDEL
	,P.PERC_DESC_FIDEL_MAX
	,P.PERC_COMISSAO_SERVICO
	,0 AS QT_EST_DEPOSITOS
	,0 AS QTDE_MES_VENDA_FECHADO
	,P.PERC_COMIS
	,P.FLAG_VERBA_DESCON
	,P.PERC_DESC_LIMITE
	,P.VLR_FABRICA
	,NULL
FROM EST_PROD_CPL P WITH (NOLOCK)
LEFT OUTER JOIN EST_PROD_CPL CPL WITH (NOLOCK) ON P.CD_EMP = CPL.CD_EMP
	AND @IN_CD_FILIAL_DESTINO = CPL.CD_FILIAL
	AND P.CD_PROD = CPL.CD_PROD
WHERE P.CD_EMP = 1
	AND P.CD_FILIAL = @IN_CD_FILIAL_BASE
	AND CPL.CD_PROD IS NULL;

ALTER TABLE DBO.EST_PROD_CPL ENABLE CHANGE_TRACKING
	WITH (TRACK_COLUMNS_UPDATED = ON);


