with  params as  (
select
cast($1 as int8) as p_lpu_id,
cast($2 as int8) as p_lpubuilding_id,
cast($3 as int8) as p_medpersonal_id,
cast($4 as int8) as p_paytype_id,
cast($5 as int8) as p_orgsmo_id,
cast(to_timestamp($6,'dd.mm.yyyy') as timestamp) as p_begdate,
cast(to_timestamp($7,'dd.mm.yyyy') as timestamp) as p_enddate 
),
eps as (
select 
coalesce(p.Person_SurName,'') || ' ' || coalesce(p.Person_FirName, '') || ' ' || coalesce(p.person_secname, '') as fio,
to_char(p.Person_Birthday, 'DD.MM.YYYY') as birthday,
eps.EvnPS_Numcard,
smo.orgsmo_name,
to_char(eps.evnps_setdt, 'DD.MM.YYYY') as setdate,
to_char(eps.evnps_disdt, 'DD.MM.YYYY') as disdate
from params 
inner join v_EvnPS eps on true
inner join v_LeaveType lt on lt.LeaveType_id=eps.LeaveType_id and lt.LeaveType_Code in ('101','102','105','107','108','110','201','202','205','207','208','301','302','303')
left join v_LpuSection ls on ls.LpuSection_id=eps.LpuSection_id
inner join v_PersonState p on p.Person_id=eps.Person_id
inner join v_Polis pol on p.Polis_id = pol.Polis_id
inner join v_OrgSMO smo on smo.orgsmo_id=pol.orgsmo_id
where cast(eps.evnps_disdt as date) between p_begdate and p_enddate
and (eps.Lpu_id=p_lpu_id or p_lpu_id is null)
and (eps.paytype_id=p_paytype_id or p_paytype_id is null)
and (eps.medpersonal_did=p_medpersonal_id or p_medpersonal_id is null)
and (ls.Lpubuilding_id=p_lpubuilding_id or p_lpubuilding_id is null)
and (smo.orgsmo_id=p_orgsmo_id or p_orgsmo_id is null)
),

epl as (
select 
coalesce(p.Person_SurName,'') || ' ' || coalesce(p.Person_FirName, '') || ' ' || coalesce(p.person_secname, '') as fio,
to_char(p.Person_Birthday, 'DD.MM.YYYY') as birthday,
epl.EvnPL_Numcard,
smo.orgsmo_name,
to_char(epl.evnpl_setdt, 'DD.MM.YYYY') as setdate,
to_char(epl.evnpl_disdt, 'DD.MM.YYYY') as disdate
from params 
inner join v_EvnPL epl on true
inner join v_EvnClass ec on ec.EvnClass_id=epl.EvnClass_id and ec.EvnClass_Sysnick = 'EvnPL'
left join lateral
(
		select ev.paytype_id
		from v_EvnVizitPL evpl
		inner join v_EvnVizit ev on ev.EvnVizit_id=evpl.EvnVizitPL_id
		where epl.EvnPL_id=evpl.EvnVizitPL_pid
		limit 1
)evpl on true
left join v_LpuSection ls on ls.LpuSection_id=epl.LpuSection_id
inner join v_PersonState p on p.Person_id=epl.Person_id
inner join v_Polis pol on p.Polis_id = pol.Polis_id
inner join v_OrgSMO smo on smo.orgsmo_id=pol.orgsmo_id
where cast(epl.evnpl_disdt as date) between p_begdate and p_enddate
and coalesce(epl.evnpl_isfinish,1)=2
and (epl.Lpu_id=p_lpu_id or p_lpu_id is null)
and (evpl.paytype_id=p_paytype_id or p_paytype_id is null)
and (epl.medpersonal_id=p_medpersonal_id or p_medpersonal_id is null)
and (ls.Lpubuilding_id=p_lpubuilding_id or p_lpubuilding_id is null)
and (smo.orgsmo_id=p_orgsmo_id or p_orgsmo_id is null)
),

comb as (
select * from epl
union all
select * from eps
order by fio, birthday, disdate
)

select
ROW_NUMBER()Over(order by comb.fio) as "RowNum",
comb.*
from comb
