SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_DirectDispancerRDSUpdate]') and xtype = N'P')
DROP PROCEDURE  [dbo].[sp_DirectDispancerRDSUpdate]
GO
-- =============================================
-- Author:      Vitacore (с)
-- Create date: 2017-10-24
-- Description: Внести исправление из амбулаторной карты пациента в его данные по диспансеризации
-- =============================================
CREATE PROCEDURE [dbo].[sp_DirectDispancerRDSUpdate]
	 @AmbulanceCardID uniqueidentifier
	,@RDSDirectPatientID uniqueidentifier	
	
AS
BEGIN
	SET NOCOUNT ON;

declare
	@p60 [datetime]


set @p60 = CONVERT (datetime, GETDATE())

update dpt set
	 dpt.FAM = p.LastName
	,dpt.IM = p.FirstName
	,dpt.OT = p.FatherName
	,dpt.DR = p.Birthday
	,dpt.SPOLIS = lastpol.Serial	
	,dpt.NPOLIS = lastpol.Number	
	,dpt.VPOLIS = lastpol.PolicyForm	
	,dpt.DOCTYPE = t24.Alias
	,dpt.DOCSER = p.DocSeries
	,dpt.DOCNUM = p.DocNumber
	,dpt.SNILS = p.SNILS
	,dpt.TEL =	 LEFT(STUFF((SELECT ',' + Number + case when PhoneType = 1 then ' (дом.)' 
														when PhoneType = 2 then ' (раб.)'
														when PhoneType = 3 then ' (моб.)' 
														when PhoneType = 4 then ' (email)' 
														when PhoneType = 5 then ' (прочее)' else '' end   
							FROM  AKUZ.T_PHONE_NUMBER pn1 where pn1.Patient =  p.PatientID FOR XML PATH ('')), 1, 1, ''),128) 
	,dpt.MR = p.PlaceOfBirth	
	
	--,dpt.MonthDISP = DATEPART(m,p.Birthday) --  Не восстанавливать из АК.  Месяц в dpt  можно менять по усмотрению врача
		
	,dpt.PODR = lastreg.Code
	,dpt.UCH = lastreg.StateNumber

	from AKUZ.T_RDS_DISP_PATIENT dpt
	left join  AKUZ.T_AMBULANCE_CARD ak ON ak.AmbulanceCardID = dpt.AmbulanceCard   and ak.AmbulanceCardID = @AmbulanceCardID 
	left join  AKUZ.T_LPU_MAIN lm ON ak.CardLpu = lm.LpuID
	left join  AKUZ.T_PATIENT p on p.PatientID = ak.Patient
	left join AKUZ.T_PATIENT_CONTINGENT pc  ON pc.Patient = p.PatientID   
	left join AKUZ.T_CONTINGENT  con ON con.ContingentID = pc.Contingent -- категории граждан
	left join VCLib.T_ENUMS t24 ON t24.EnumID = p.DocType

	cross apply
	(
		select top 1 pol.PolicyID, pol.ValidThrough, pol.Number, pol.Serial, pol.PolicyForm
		from AKUZ.T_POLICY pol 
		where pol.Patient = p.PatientID and pol.type_ in (536) and GETDATE() >= pol.issuedate
		order by pol.issuedate desc, isnull(pol.validthrough, dateadd(year, 100, pol.issuedate)) desc
	) lastpol
	cross apply
	(
		select Top 1 r.RegistrationID , r.Patient, r.[Status], r.RegistrationDate, r.LpuMain ,st.StateNumber, dv.Code 
		from [AKUZ].T_REGISTRATION r 
		left join [AKUZ].T_STATE st on st.StateID = r.State 
		left join [AKUZ].T_DIVISION dv on dv.DivisionID = st.Division
		where r.Patient = p.PatientID
		order by r.RegistrationDate Desc, r.[Status]
	) lastreg


	LEFT JOIN VCLib.T_ENUMS t31 ON t31.EnumID = p.Sex
where dpt.RdsDispPatientID = @RDSDirectPatientID  

END

GO
