IF EXISTS(SELECT * FROM SYS.procedures WHERE NAME = 'P_PDV_VD_IT_REC_SNGPC' )
    BEGIN 
		DROP PROCEDURE P_PDV_VD_IT_REC_SNGPC;
    END;
GO
CREATE PROCEDURE P_PDV_VD_IT_REC_SNGPC @CD_EMP    INT = 0 , @CD_FILIAL INT = 0 , @CD_VD     INT = 0
AS
     
	INSERT INTO PDV_VD_IT_REC(
					CD_EMP
				  , CD_FILIAL
				  , CD_VD
				  , CD_IT
				  , CD_MEDICO_REC
				  , NR_RECEITA
				  , DT_RECEITA
				  , COMPRADOR_NOME
				  , COMPRADOR_DOC_NUMERO
				  , COMPRADOR_DOC_TIPO
				  , COMPRADOR_DOC_EXPEDIDOR
				  , COMPRADOR_DOC_UF
				  , PACIENTE_NOME
				  , PACIENTE_IDADE
				  , PACIENTE_TP_IDADE
				  , PACIENTE_SEXO
				  , PACIENTE_CID
				  , MEDICAMENTO_NUMERO_LOTE
				  , MEDICAMENTO_RECEITA_TIPO
				  , MEDICAMENTO_NUMERO_NOTIFICACAO
				  , MEDICAMENTO_DATA_PRESCRICAO
				  , MEDICANENTO_DATA_VENDA
				  , STS_IMPORT
				  , ORIGEM_REC
		)
		SELECT DISTINCT
		   IT.CD_EMP
		 , IT.CD_FILIAL
		 , IT.CD_VD
		 , IT.CD_IT
		 , MED.CD_CTR AS CD_MEDICO_REC
		 , CRM.NR_RECEITA  AS NR_RECEITA
		 , VD.DT_VD AS DT_RECEITA
		 , ISNULL(CRM.NM_COMPRADOR, '') AS COMPRADOR_NOME
		 , CRM.NR_DOC_CLI AS COMPRADOR_DOC_NUMERO
		 , CRM.TIPO_DOCUMENTO AS COMPRADOR_DOC_TIPO
		 , '' AS COMPRADOR_DOC_EXPEDIDOR
		 , CRM.UF AS COMPRADOR_DOC_UF
		 , CRM.NM_PACIENTE AS PACIENTE_NOME
		 , CRM.IDADE AS PACIENTE_IDADE
		 , CRM.TP_IDADE AS PACIENTE_TP_IDADE
		 , 0 AS PACIENTE_SEXO
		 , CRM.CID AS PACIENTE_CID
		 , '' AS MEDICAMENTO_NUMERO_LOTE
		 , 0 AS MEDICAMENTO_RECEITA_TIPO
		 , '' AS MEDICAMENTO_NUMERO_NOTIFICACAO
		 , NULL AS MEDICAMENTO_DATA_PRESCRICAO
		 , VD.DT_VD AS MEDICANENTO_DATA_VENDA
		 , 0 AS STS_IMPORT
		 , 1 AS ORIGEM_REC
	FROM
		 PDV_VD VD
		 INNER JOIN PDV_VD_IT IT ON VD.CD_EMP = IT.CD_EMP
									AND VD.CD_FILIAL = IT.CD_FILIAL
									AND VD.CD_VD = IT.CD_VD
									AND VD.DT_VD = IT.DT_VD
		 INNER JOIN EST_ORC ORC ON VD.CD_EMP = ORC.CD_EMP
								   AND VD.CD_FILIAL = ORC.CD_FILIAL
								   AND VD.NR_ORC = ORC.CD_ORC
		 INNER JOIN EST_ORC_GLB_MEDICO CRM ON ORC.CD_EMP = CRM.CD_EMP
											  AND ORC.CD_FILIAL = CRM.CD_FILIAL
											  AND ORC.CD_ORC = CRM.NR_ORC
		 INNER JOIN GLB_MEDICOS MED ON CRM.CD_EMP = MED.CD_EMP
									   AND CRM.CD_MEDICO_REC = MED.CD_CTR
		 LEFT OUTER JOIN PDV_VD_IT_REC ON IT.CD_EMP = PDV_VD_IT_REC.CD_EMP
										  AND IT.CD_FILIAL = PDV_VD_IT_REC.CD_FILIAL
										  AND IT.CD_VD = PDV_VD_IT_REC.CD_VD
										  AND IT.CD_IT = PDV_VD_IT_REC.CD_IT
	WHERE IT.CD_EMP = @CD_EMP
		  AND IT.CD_FILIAL = CRM.CD_FILIAL
		  AND IT.CD_PROD = CRM.CD_PROD
		  AND IT.ST_IT = 1
		  AND VD.ST_VD = 0
		  AND IT.CD_FILIAL  = @CD_FILIAL
		  AND IT.CD_VD		= @CD_VD
		  AND PDV_VD_IT_REC.CD_IT IS NULL;