IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_CreateBSK_Direction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_CreateBSK_Direction]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vitacore (с)
-- Create date: 2020-03-30
-- Description: Создание бск направлений
-- =============================================
CREATE PROCEDURE [dbo].[sp_CreateBSK_Direction]
    @ID uniqueidentifier,
    @QueueName varchar(100),
	@User uniqueidentifier = null

AS
BEGIN

    SET NOCOUNT ON;

	declare @newDirId uniqueidentifier, 
			@newBenId uniqueidentifier,
			@PAC_ID int, 
			@Patient uniqueidentifier,
			@DateBeg datetime,
			@DateEnd datetime,
			@Diagnosis varchar(255),
			@Old bit = 0,
			@DRegistrationDate datetime,
			@CloseDate datetime
	select @newDirId = newid(), @newBenId = newid()
	select @Patient = Patient from AKUZ.T_BSK_REGISTER_RECORDS where BskRegisterRecordsID = @ID
	
	select top 1 
	@PAC_ID = d.PAC_ID, @CloseDate  = br.CloseDate, @DRegistrationDate = br.DRegistrationDate
	from AKUZ.T_BSK_REGISTER_RECORDS br
		join AKUZ.T_PATIENT_BENEFITS_DIRECTION d on d.Patient = br.Patient
		join AKUZ.T_BSK_BENEFITS_DIRECTION bb on bb.PatientBenefitsDirectionID = d.PatientBenefitsDirectionID
	where d.PAC_ID is not null and br.BskRegisterRecordsID = @ID

	if(exists(select * from AKUZ.T_BSK_REGISTER_RECORDS br where br.Patient = @Patient and br.BskRegisterRecordsID <> @ID))
	begin
		set @Old = 1
	end
	else
	begin
		set @Old = 0
	end

	if(@PAC_ID is not null and @Old = 0 and @CloseDate is null and @DRegistrationDate is null)
            raiserror('Ошибка создания направления из терапии! Обратитесь к администратору', 16, 0)

	INSERT INTO [AKUZ].[T_PATIENT_BENEFITS_DIRECTION]
           ([Date]
           ,[ChangeType]
           ,[PatientBenefitsDirectionID]
           ,[EnterDate]
           ,[LastName]
           ,[FirstName]
           ,[FatherName]
           ,[Birthday]
           ,[Kod]
           ,[DocSeries]
           ,[DocNumber]
           ,[Users]
           ,[Sex]
           ,[SNILS]
           ,[DocType]
           ,[LpuMain]
           ,[PAC_ID]
           ,[Patient]
           ,[type_])
	select getdate()
		,case when br.DRegistrationDate is not null or br.CloseDate is not null or @Old = 1 then 2 else 1 end
		,@newDirId
		,getdate()
		,p.LastName
		,p.FirstName
		,p.FatherName
		,p.Birthday
		,(select top 1 ac.Number from AKUZ.T_AMBULANCE_CARD ac where ac.Patient = p.PatientID and ac.CardLpu = br.LpuMain)
		,p.DocSeries
		,p.DocNumber
		,@User
		,p.Sex
		,p.SNILS
		,p.DocType
		,br.LpuMain
		,@PAC_ID
		,p.PatientID
		,(select top 1 e.EntityID from VCLib.T_ENTITIES e where e.EntName = 'BSK_BENEFITS_DIRECTION')
	from AKUZ.T_BSK_REGISTER_RECORDS br
		join AKUZ.T_PATIENT p on br.Patient = p.PatientID
	where br.BskRegisterRecordsID = @ID

	INSERT INTO [AKUZ].[T_BSK_BENEFITS_DIRECTION]
           ([PatientBenefitsDirectionID]
           ,[ExcludeReason]
		   ,[BskRegisterRecords])
	select @newDirId, null, @ID

	INSERT INTO [AKUZ].[T_PATIENT_BENEFITS_DIRECTION_DATA]
           ([PatientBenefitsDirectionDataID]
           ,[DiagDate]
           ,[Document]
           ,[DocumentDate]
           ,[PatientBenefitsDirection]
           ,[Benefits]
           ,[Doctor]
           ,[Mkb]
           ,[BenefitViews]
           ,[ChangeType]
           ,[type_])
	select @newBenId
		,br.DateBegin
		,null
		,null
		,@newDirId
		,br.Benefits
		,br.Post
		,br.Mkb
		,4
		,(case when br.CloseDate is not null and  br.ExclusionReason is not null and br.ExclusionReason <> 0 then 3
				when br.DRegistrationDate is not null and br.Place = 0 then 2
				else 1 
			   end)
		,(select top 1 e.EntityID from VCLib.T_ENTITIES e where e.EntName = 'BSK_BENEFITS_DIRECTION_DATA')
	from AKUZ.T_BSK_REGISTER_RECORDS br
		join AKUZ.T_PATIENT p on br.Patient = p.PatientID
	where br.BskRegisterRecordsID = @ID

	INSERT INTO [AKUZ].[T_BSK_BENEFITS_DIRECTION_DATA]
           ([PatientBenefitsDirectionDataID]
           ,[MedicalService]
           ,[DateBegin]
           ,[DateEnd]
           ,[ExclusionReason]
           ,[EstimatedDDate]
           ,[DRegistrationDate]
           ,[Place]
           ,[LpuMainTo]
		   ,[CloseDate])
	select @newBenId
		,br.MedicalService
		,br.DateBegin
		,br.DateEnd
		,br.ExclusionReason
		,br.EstimatedDDate
		,br.DRegistrationDate
		,br.Place
		,br.LpuMainTo
		,br.CloseDate
	from AKUZ.T_BSK_REGISTER_RECORDS br
		join AKUZ.T_PATIENT p on br.Patient = p.PatientID
	where br.BskRegisterRecordsID = @ID

	update compl
	set compl.BskBenefitsDirectionData = @newBenId 
	from AKUZ.T_BSK_REGISTER_COMPLICATION_LINK compl
	where compl.BskRegisterRecords = @ID

	INSERT INTO [AKUZ].[T_BSK_BENEFITS_DIRECTION_MEDICAMENTS]
           ([BskBenefitsDirectionMedicamentsID]
           ,[BskBenefitsDirectionData]
           ,[CMnn]
           ,[DateStart]
           ,[EndDate]
           ,[MedicationForms]
           ,[Regiment]
           ,[Dose]
           ,[MeasureUnit]
           ,[Prepid]
           ,[DayliCoeff]
		   ,[DoseView]
		   ,[SingleDose]
		   ,[Multiplicity])
	select newid()
		,@newBenId
		,mnn.CMnn
		,mnn.DateStart
		,mnn.EndDate
		,mnn.MedicationForms
		,mnn.Regiment
		,mnn.Dose
		,mnn.MeasureUnit
        ,mnn.Prepid
        ,mnn.DayliCoeff
        ,mnn.DoseView
        ,mnn.SingleDose
        ,mnn.Multiplicity
	from AKUZ.T_BSK_REGISTER_LINK_MNN mnn 
		join AKUZ.T_BSK_REGISTER_RECORDS br on br.BskRegisterRecordsID = mnn.BskRegisterRecords
	where mnn.BskRegisterRecords = @ID

	exec [dbo].[sp_BSK_Register_Direction] null, @newDirId, @QueueName

	select @DateBeg = br.DateBegin
	, @DateEnd = isnull(br.CloseDate, br.DateEnd)
	, @Diagnosis = left(br.Diagnosis, 255)
	from AKUZ.T_BSK_REGISTER_RECORDS br
		join AKUZ.T_PATIENT p on br.Patient = p.PatientID
	where br.BskRegisterRecordsID = @ID

	exec [dbo].[sp_CreatePulmo_Notification] @Patient, @DateBeg, @DateEnd, @Diagnosis

END
GO