DO $$
declare
	mCurs refcursor;
	p_PersonPrivilege_id bigint;
	p_person_id bigint;
	p_lpu_id bigint;
	p_PrivilegeType_id bigint;
	p_PersonPrivilege_begdate timestamp without time zone;
	p_PersonPrivilege_enddate timestamp without time zone;
	p_id bigint;

	p_pmuser_id bigint = 1;
	p_server_id bigint = 101;
	p_error_code varchar = NULL;
	p_error_message varchar = NULL;
begin

IF (dbo.getregion()=5) THEN

	delete from public.psv_PROMEDWEB52833_20210412_todel;
	
	UPDATE dbo.privilegetype 
	SET privilegetype_code = 207, pmuser_updid = 1, privilegetype_upddt = getdate() 
	WHERE privilegetype_id = 50101000000319;
	
	OPEN mCurs FOR
		select 	
				pp.PersonPrivilege_id,
				pp.Person_id,
				pp.PrivilegeType_id,
				pp.lpu_id,
				coalesce(pp.PersonPrivilege_begdate,'1900-01-01'::date) as PersonPrivilege_begdate,
				coalesce(pp.PersonPrivilege_enddate,'9999-12-31'::date) as PersonPrivilege_enddate
		from dbo.v_PersonPrivilege pp
		inner join dbo.lpu l on l.lpu_id = pp.lpu_id
		;

	LOOP FETCH mCurs INTO
		p_PersonPrivilege_id, p_person_id, p_PrivilegeType_id, p_lpu_id,
		p_PersonPrivilege_begdate, p_PersonPrivilege_enddate
		;

    exit WHEN NOT FOUND;

		p_error_code := null;
		p_error_message := null;

		-- ищем льготу-дубль с большим сроком
		select pp.PersonPrivilege_id
		into p_id
		from dbo.v_PersonPrivilege pp
		where pp.person_id = p_person_id -- пациент
		and pp.PrivilegeType_id = p_PrivilegeType_id -- тип льготы
		and pp.lpu_id = p_lpu_id -- МО
		and coalesce(pp.PersonPrivilege_begdate, '1900-01-01'::date) <= p_PersonPrivilege_begdate -- дата начала льготы
		and coalesce(pp.PersonPrivilege_enddate, '9999-12-31'::date) >= p_PersonPrivilege_enddate -- дата окончания льготы
		and pp.PersonPrivilege_id <> p_PersonPrivilege_id -- другая льгота
/*		and not exists (
				select 1 from public.psv_PROMEDWEB52833_20210412_todel d
				where d.PersonPrivilege_id = pp.PersonPrivilege_id and coalesce(d.isdel,1)=2
				limit 1
    )*/
		limit 1;

		if coalesce(p_id,0) <> 0	then
			-- есть льгота с большим сроком, значит эту удаляем
			
			select fnc.error_code, fnc.error_message
			into p_error_code, p_error_message
			from dbo.p_PersonPrivilege_del(
					PersonPrivilege_id := p_PersonPrivilege_id,
					pmuser_id := p_pmuser_id
			)fnc;

			insert into public.psv_PROMEDWEB52833_20210412_todel (PersonPrivilege_id, isdel, error) values (p_PersonPrivilege_id, 2, p_error_message) on conflict do nothing;
		end if;


	END LOOP;
	CLOSE mCurs;

end if;

end $$;

-- select * from public.psv_PROMEDWEB52833_20210412_todel where coalesce(d.isdel,1)=2
