IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_GetSetRDSOrphRegister]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_GetSetRDSOrphRegister]
/****** Object:  StoredProcedure [dbo].[sp_GetSetRDSOrphRegister]    Script Date: 18.11.2015 22:00:23 ******/

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO

-- =============================================
-- Author:      Vitacore (с)
-- Create date: 2020-09-01
-- Description: Загрузка льготников по орфанным заболеваниям
-- =============================================
create PROCEDURE [dbo].[sp_GetSetRDSOrphRegister]
    @Xml xml = null,
    @ID uniqueidentifier = null,
    @IsNew bit = 1,
    @QueueName varchar(100) = 'RDSSync',
    @dateTime datetime = null,
    @User uniqueidentifier = null
AS
BEGIN

    SET NOCOUNT ON;

    declare @Result varchar(max)
           ,@ContentEncoding varchar(255)
           ,@Type varchar(255)
           ,@OperationType varchar(255)
           ,@OwnerID uniqueidentifier
            -- Operation types
           ,@INSERT varchar(6)
           ,@UPDATE varchar(6)
           ,@DELETE varchar(6)
           ,@FTLOAD varchar(6)

    select @dateTime = ISNULL(@dateTime, GETDATE())
            -- Operation types
          ,@INSERT = 'Insert'
          ,@UPDATE = 'Update'
          ,@DELETE = 'Delete'
          ,@FTLOAD = 'FTLoad'

    IF (@Xml is not null)
    BEGIN
         -- Получаем тип операции
        select @OperationType = t.c.value('./header[1]/TYPE[1]', 'varchar(36)')
              ,@OwnerID = t.c.value('./header[1]/ID[1]', 'uniqueidentifier')
              ,@Result = cast(@Xml as varchar(max))
        from @Xml.nodes('ORPHAN_REGISTER') T(c)

		if (@OperationType = @FTLOAD)
        BEGIN
            -- Generate table #ORPHAN_REGISTERS
            SELECT t.c.value('./ID[1]', 'uniqueidentifier')                                AS ID,
                   CONVERT(DATETIME, t.c.value('./DATE_BEGIN[1]', 'varchar(10)'), 104)     AS DateBegin,
                   CONVERT(DATETIME, t.c.value('./DATE_END[1]', 'varchar(10)'), 104)       AS DateEnd,
                   t.c.value('./FIRST_NAME[1]', 'varchar(60)')                             AS FirstName,
                   t.c.value('./LAST_MANE[1]', 'varchar(60)')                              AS LastName,
                   t.c.value('./BIRTH_LAST_MANE[1]', 'varchar(60)')                        AS BirthLastName,
                   t.c.value('./FATHER_NAME[1]', 'varchar(60)')                            AS FatherName,
                   CONVERT(DATETIME, t.c.value('./BIRTHDAY[1]', 'varchar(10)'), 104)       AS Birthday,
                   t.c.value('./SEX[1]', 'int')                                            AS Sex,
                   t.c.value('./SNILS[1]', 'varchar(14)')                                  AS SNILS,
                   t.c.value('./DIASBILITY[1]', 'int')                                     AS Disability,
                   t.c.value('./ADRESS[1]', 'varchar(1000)')                               AS Adress,
                   t.c.value('./OKATO[1]', 'varchar(256)')                                 AS OKATO,
                   t.c.value('./FEDERAL[1]', 'bit')                                        AS Federal,
                   CONVERT(DATETIME, t.c.value('./DOC_ISSUE_DATE[1]', 'varchar(10)'), 104) AS DocIssueDate,
                   t.c.value('./DOC_ISSUE_ORG[1]', 'varchar(256)')                         AS DocIssueOrg,
                   t.c.value('./DOC_TYPE[1]', 'int')                                       AS DocType,
                   t.c.value('./DOC_SERIES[1]', 'varchar(30)')                             AS DocSeries,
                   t.c.value('./DOC_NUMBER[1]', 'varchar(30)')                             AS DocNumber,
                   t.c.value('./SMO[1]', 'varchar(5)')                                     AS F002Smo,
                   t.c.value('./OMS_SERIAL[1]', 'varchar(12)')                             AS OmsSerial,
                   t.c.value('./OMS_NUMBER[1]', 'varchar(32)')                             AS OmsNumber,
                   t.c.value('./MKB[1]', 'varchar(10)')                                    AS Mkb,
                   t.c.value('./DIAGNOSIS[1]', 'varchar(4096)')                            AS Diagnosis,
                   t.c.value('./MKB_DOP[1]', 'varchar(10)')                                AS MkbDop,
                   t.c.value('./DIAGNOSIS_DOP[1]', 'varchar(4096)')                        AS DiagnosisDop,
                   t.c.value('./LPU_MAIN_FIRST[1]', 'varchar(6)')                          AS LpuMainFirst,
                   t.c.value('./LPU_MAIN[1]', 'varchar(6)')                                AS LpuMain,
                   t.c.value('./POST_FIO[1]', 'varchar(255)')                              AS PostFio,
                   t.c.value('./REGISTER_ID[1]', 'int')                                    AS RegisterId
            INTO #ORPHAN_REGISTERS
            FROM @Xml.nodes('ORPHAN_REGISTER/body/ORPHAN_REGISTERS/ORPHAN_REGISTER_ITEM') T(c)

            ALTER TABLE #ORPHAN_REGISTERS ADD [Patient] uniqueidentifier

            -- Поиск по СНИЛС + ДР
            UPDATE orph
            SET orph.Patient = p.PatientID
            FROM #ORPHAN_REGISTERS orph
            JOIN AKUZ.T_PATIENT p ON p.SNILS = orph.SNILS AND p.Birthday = orph.Birthday
            WHERE
                  orph.Patient IS NULL
              AND orph.SNILS IS NOT NULL
              AND orph.Birthday IS NOT NULL

            -- Поиск по серии и номеру документа
            UPDATE orph
            SET orph.Patient = p.PatientID
            FROM #ORPHAN_REGISTERS orph
            JOIN AKUZ.T_PATIENT p ON LEFT(p.DocSeries, 8) = orph.DocSeries AND LEFT(p.DocNumber, 8) = orph.DocNumber AND
                                     p.Birthday = orph.Birthday
            WHERE
                  orph.Patient IS NULL
              AND orph.DocSeries IS NOT NULL
              AND orph.DocNumber IS NOT NULL
              AND orph.Birthday IS NOT NULL

            -- Поиск по ФИО + ДР
            UPDATE orph
            SET orph.Patient = p.PatientID
            FROM #ORPHAN_REGISTERS orph
            JOIN AKUZ.T_PATIENT p ON p.LastName = orph.LastName AND p.FirstName = orph.FirstName AND
                                     (p.FatherName = orph.FatherName OR
                                      p.FatherName IS NULL AND orph.FatherName IS NULL) AND p.Birthday = orph.Birthday
            WHERE orph.Patient IS NULL

			delete pd
			from [AKUZ].T_PATIENT_BENEFITS pd
				join [AKUZ].T_BENEFITS b on b.BenefitsID = pd.Benefits
			where b.BenefitViews = 19011 and CreateType = 2

			INSERT INTO [AKUZ].[T_PATIENT_BENEFITS]
		           ([PatientBenefitsID]
		           ,[Patient]
		           ,[Benefits]
		           ,[BenefitDocument]
		           ,[BenefitDocumentNumber]
		           ,[BeginDate]
		           ,[EndDate]
		           ,[Mkb]
		           ,[Active]
		           ,[Deleted]
		           ,[CreateType]
		           ,[PAC_ID]
		           ,[LPU_INF]
		           ,[SOST_R]
		           ,[ReasonRegistration]
		           ,[ReasonDeregistration]
		           ,[BenefitDocumentSeries]
		           ,[BenefitDocType]
		           ,[RegDate])
		     SELECT
		           newid()
		           ,orph.[Patient]
		           ,(select TOP 1 b.BenefitsID from [AKUZ].T_BENEFITS b where b.BenefitViews = 19011)
		           ,null
		           ,null
		           ,orph.DateBegin
		           ,orph.DateEnd
		           ,orph.Mkb
		           ,1
		           ,0
		           ,2
		           ,orph.[RegisterId]
		           ,orph.LpuMain
		           ,null
		           ,null
		           ,null
		           ,null
		           ,null
		           ,orph.DateBegin
				   FROM #ORPHAN_REGISTERS orph
				   where orph.[Patient] is not null
        END
        ELSE
        BEGIN
            -- Generate table #ORPHAN_REGISTER
            SELECT t.c.value('./body[1]/ID[1]', 'uniqueidentifier')                                AS ID,
                   CONVERT(DATETIME, t.c.value('./body[1]/DATE_BEGIN[1]', 'varchar(10)'), 104)     AS DateBegin,
                   CONVERT(DATETIME, t.c.value('./body[1]/DATE_END[1]', 'varchar(10)'), 104)       AS DateEnd,
                   t.c.value('./body[1]/FIRST_NAME[1]', 'varchar(60)')                             AS FirstName,
                   t.c.value('./body[1]/LAST_MANE[1]', 'varchar(60)')                              AS LastName,
                   t.c.value('./body[1]/BIRTH_LAST_MANE[1]', 'varchar(60)')                        AS BirthLastName,
                   t.c.value('./body[1]/FATHER_NAME[1]', 'varchar(60)')                            AS FatherName,
                   CONVERT(DATETIME, t.c.value('./body[1]/BIRTHDAY[1]', 'varchar(10)'), 104)       AS Birthday,
                   t.c.value('./body[1]/SEX[1]', 'int')                                            AS Sex,
                   t.c.value('./body[1]/SNILS[1]', 'varchar(14)')                                  AS SNILS,
                   t.c.value('./body[1]/DIASBILITY[1]', 'int')                                     AS Disability,
                   t.c.value('./body[1]/ADRESS[1]', 'varchar(1000)')                               AS Adress,
                   t.c.value('./body[1]/OKATO[1]', 'varchar(256)')                                 AS OKATO,
                   t.c.value('./body[1]/FEDERAL[1]', 'bit')                                        AS Federal,
                   CONVERT(DATETIME, t.c.value('./body[1]/DOC_ISSUE_DATE[1]', 'varchar(10)'), 104) AS DocIssueDate,
                   t.c.value('./body[1]/DOC_ISSUE_ORG[1]', 'varchar(256)')                         AS DocIssueOrg,
                   t.c.value('./body[1]/DOC_TYPE[1]', 'int')                                       AS DocType,
                   t.c.value('./body[1]/DOC_SERIES[1]', 'varchar(30)')                             AS DocSeries,
                   t.c.value('./body[1]/DOC_NUMBER[1]', 'varchar(30)')                             AS DocNumber,
                   t.c.value('./body[1]/SMO[1]', 'varchar(5)')                                     AS F002Smo,
                   t.c.value('./body[1]/OMS_SERIAL[1]', 'varchar(12)')                             AS OmsSerial,
                   t.c.value('./body[1]/OMS_NUMBER[1]', 'varchar(32)')                             AS OmsNumber,
                   t.c.value('./body[1]/MKB[1]', 'varchar(10)')                                    AS Mkb,
                   t.c.value('./body[1]/DIAGNOSIS[1]', 'varchar(4096)')                            AS Diagnosis,
                   t.c.value('./body[1]/MKB_DOP[1]', 'varchar(10)')                                AS MkbDop,
                   t.c.value('./body[1]/DIAGNOSIS_DOP[1]', 'varchar(4096)')                        AS DiagnosisDop,
                   t.c.value('./body[1]/LPU_MAIN_FIRST[1]', 'varchar(6)')                          AS LpuMainFirst,
                   t.c.value('./body[1]/LPU_MAIN[1]', 'varchar(6)')                                AS LpuMain,
                   t.c.value('./body[1]/POST_FIO[1]', 'varchar(255)')                              AS PostFio,
                   t.c.value('./body[1]/REGISTER_ID[1]', 'int')                                    AS RegisterId
            INTO #ORPHAN_REGISTER
            FROM @Xml.nodes('ORPHAN_REGISTER') T(c)

            ALTER TABLE #ORPHAN_REGISTER ADD [Patient] uniqueidentifier

            -- Связываем регистр с пациентами
            -- Поиск по СНИЛС + ДР
            UPDATE orph
            SET orph.Patient = p.PatientID
            FROM #ORPHAN_REGISTER orph
            JOIN AKUZ.T_PATIENT p ON p.SNILS = orph.SNILS AND p.Birthday = orph.Birthday
            WHERE
                  orph.Patient IS NULL
              AND orph.SNILS IS NOT NULL
              AND orph.Birthday IS NOT NULL

            -- Поиск по серии и номеру документа
            UPDATE orph
            SET orph.Patient = p.PatientID
            FROM #ORPHAN_REGISTER orph
            JOIN AKUZ.T_PATIENT p ON LEFT(p.DocSeries, 8) = orph.DocSeries AND LEFT(p.DocNumber, 8) = orph.DocNumber AND
                                     p.Birthday = orph.Birthday
            WHERE
                  orph.Patient IS NULL
              AND orph.DocSeries IS NOT NULL
              AND orph.DocNumber IS NOT NULL
              AND orph.Birthday IS NOT NULL

            -- Поиск по ФИО + ДР
            UPDATE orph
            SET orph.Patient = p.PatientID
            FROM #ORPHAN_REGISTER orph
            JOIN AKUZ.T_PATIENT p ON p.LastName = orph.LastName AND p.FirstName = orph.FirstName AND
                                     (p.FatherName = orph.FatherName OR
                                      p.FatherName IS NULL AND orph.FatherName IS NULL) AND p.Birthday = orph.Birthday
            WHERE orph.Patient IS NULL

            IF(@OperationType = @DELETE)
            BEGIN

                delete pd
                from [AKUZ].T_PATIENT_BENEFITS pd
                    join [AKUZ].T_BENEFITS b on b.BenefitsID = pd.Benefits
                    join #ORPHAN_REGISTER orph on orph.[RegisterId] = pd.PAC_ID
                where b.BenefitViews = 19011 and pd.CreateType = 2

            END
            ELSE
            BEGIN

                delete pd
                from [AKUZ].T_PATIENT_BENEFITS pd
                    join [AKUZ].T_BENEFITS b on b.BenefitsID = pd.Benefits
                    join #ORPHAN_REGISTER orph on orph.[RegisterId] = pd.PAC_ID
                where b.BenefitViews = 19011 and pd.CreateType = 2

                INSERT INTO [AKUZ].[T_PATIENT_BENEFITS]
                       ([PatientBenefitsID]
                       ,[Patient]
                       ,[Benefits]
                       ,[BenefitDocument]
                       ,[BenefitDocumentNumber]
                       ,[BeginDate]
                       ,[EndDate]
                       ,[Mkb]
                       ,[Active]
                       ,[Deleted]
                       ,[CreateType]
                       ,[PAC_ID]
                       ,[LPU_INF]
                       ,[SOST_R]
                       ,[ReasonRegistration]
                       ,[ReasonDeregistration]
                       ,[BenefitDocumentSeries]
                       ,[BenefitDocType]
                       ,[RegDate])
                 SELECT
                       newid()
                       ,orph.[Patient]
                       ,(select TOP 1 b.BenefitsID from [AKUZ].T_BENEFITS b where b.BenefitViews = 19011)
                       ,null
                       ,null
                       ,orph.DateBegin
                       ,orph.DateEnd
                       ,orph.Mkb
                       ,1
                       ,0
                       ,2
                       ,orph.[RegisterId]
                       ,orph.LpuMain
                       ,null
                       ,null
                       ,null
                       ,null
                       ,null
                       ,orph.DateBegin
                       FROM #ORPHAN_REGISTER orph
                       where orph.[Patient] is not null

            END
        END
    END
END