-- =============================================
-- Author: Vitacard System
-- Create date: 2016-02-29
-- Description:	Добавление льготы по прикреплению после изменений
-- =============================================
DROP PROCEDURE IF EXISTS sp_afterchangeregistration;
CREATE PROCEDURE sp_afterchangeregistration("PatientID" uuid)
AS
$BODY$
DECLARE	_Birthday TimeStamp;
	_EndDate TimeStamp;
	_Status int;
	_LpuCode text;
	_DocType int;
	_DocSeries text;
	_DocNumber text;
	_Num int;
	_BenefitsID UUID;
	_Today TimeStamp;
	_Preferences int;
Begin
	-- льгота "Ребенок первых трех лет жизни"
	select b.BenefitsID 
	from akuz.T_BENEFITS b
	into _BenefitsID
	where b.BenefitViews = 19002 
	and b.BenefitCode = '57'
	limit 1;
	-- текущее прикрепление
	select into
		 _Status, _LpuCode, _Preferences
		 r.Status, lm.Code, coalesce(ls.Preferences,0)
	from akuz.T_REGISTRATION r
	left join 
		akuz.T_LPU_MAIN lm 
		On r.LpuMain = lm.LpuID
	left Join 
		akuz.T_LPU_SETTINGS ls 
		On lm.LpuID = ls.LpuMain	
	where r.Patient = "PatientID" and r.Profile in (1,2)
	order by r.RegistrationDate desc
	limit 1;
	-- если в установках ЛПУ установлена галочка "Использовать региональный регистр"
	-- (см. LocalConfiguration.UseRegionalRegister)
	if _Preferences&4 > 0
	then
		return;
	end if;
	-- данные пациента
	select into
		_Birthday, _DocType, _DocSeries, _DocNumber, _EndDate, _Today
		p.Birthday, p.DocType, p.DocSeries, p.DocNumber, p.Birthday + interval '3 year'	- interval '1 day', date_trunc('day', current_timestamp::TIMESTAMP)
	from akuz.T_PATIENT p
	where p.PatientID = "PatientID"
	limit 1;
	-- сняли льготу
	update	akuz.T_PATIENT_BENEFITS
	set	EndDate = _Today
	,	SOST_R = 2
	,	ReasonDeregistration = 1
	,	ReasonRegistration = null
	,	RegDate = _Today
	where Benefits = _BenefitsID 
	and Patient = "PatientID"
	and EndDate >= _Today;
	-- если прикреплен и меньше 3х лет, то добавляем льготу от ЛПУ прикрепления
	if _Status = 1 and _Today <= _EndDate
	then
		-- если в этом ЛПУ льгота уже есть, то обновляем
		if exists(select * from akuz.T_PATIENT_BENEFITS pb where pb.Benefits = _BenefitsID and pb.Patient = "PatientID" and pb.LPU_INF = _LpuCode)
		then
			update	akuz.T_PATIENT_BENEFITS
			set	EndDate = _EndDate
			,	SOST_R = 1
			,	ReasonDeregistration = null
			,	ReasonRegistration = 4
			,	RegDate = _Today
			where Benefits = _BenefitsID 
			and Patient = "PatientID"
			and LPU_INF = _LpuCode;
		else
			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	gen_random_uuid()
			,	"PatientID"
			,	_BenefitsID
			,	case when _DocType in (10503,10523) then 'Свидетельство о рождении' else null end
			,	case when _DocType in (10503,10523) then _DocNumber else null end
			,	_Birthday
			,	_EndDate
			,	NULL
			,	'1'
			,	'0'
			,	1
			,	_Num
			,	_LpuCode
			,	1
			,	4
			,	null
			,	case when _DocType in (10503,10523) then _DocSeries else null end
			,	case when _DocType in (10503,10523) then 30111 else null end
			,	_Today;
		end if;
	end if;
End;
$BODY$
  LANGUAGE plpgsql;
