with params as (
    select 
        $1::int8 as p_lpu_id, 
        $2::int8 as p_lpubuilding_id, 
        $3::int8 as p_lpuunit_id, 
        $4::int8 as p_lpusection_id, 
        dbo.getdiagcodebyid($5::int8) as p_begdiag_code, 
        dbo.getdiagcodebyid($6::int8) as p_enddiag_code, 
        to_timestamp($7, 'DD.MM.YYYY') as p_begdate, 
        to_timestamp($8, 'DD.MM.YYYY') as p_enddate, 
        $9::int8 as p_yesno, 
        $10::int8 as p_nationality,
        $11::int8 as p_covidtype_id, 
        $12::int8 as p_diagsetphase_id
)
select 
    row_number() over (order by concat_ws(' ', Person.Person_SurName, Person.Person_FirName, Person.Person_SecName)) as v1,
    EvnPS.EvnPS_NumCard as v2,
    to_char(EvnPS.EvnPS_setDT, 'dd.mm.yyyy') as v3,
    EvnPS.EvnPS_setTime as v4,
    LpuSection.LpuSection_Name as v5,
    concat_ws(' ', Person.Person_SurName, Person.Person_FirName, Person.Person_SecName) as v6,
    to_char(Person.Person_Birthday, 'dd.mm.yyyy') as v7,
    EvnPS.Person_Age as v8,
    KLCountry_Name as v9,
    Polis.Polis_Ser as v10,
    case when Polis.PolisType_id = 4 then Person.Person_EdNum else Polis.Polis_Num end as v11,
    OrgSmo.OrgSMO_Name as v12,
    coalesce(AU.Address_Address, PA.Address_Address) as v13,
    case 
        when EvnPS.PrehospDirect_id = 2 then PrehospDirect.PrehospDirect_Name || ': ' || coalesce(Org_lpu.Org_Nick, Org.Org_Nick, '')
        when EvnPS.PrehospDirect_id = 3 then PrehospDirect.PrehospDirect_Name || ': ' || coalesce(Org.Org_Nick,'')
        when EvnPS.PrehospDirect_id = 1 then PrehospDirect.PrehospDirect_Name || ': ' || LpuSectioPrehosp.LpuSection_FullName
        else PrehospDirect.PrehospDirect_Name 
    end as v14,
    coalesce(ED.EvnDirection_num, EvnPS.EvnDirection_num) as v15,
    to_char(coalesce(ED.EvnDirection_setDate, EvnPS.EvnDirection_setDT), 'dd.mm.yyyy') as v16,
    case when coalesce(ed.EvnDirection_IsAuto, 1) = 2 or EvnPS.EvnDirection_id is not null then 'ЭН' end as v17,
    PrehospArrive_Name as v18,
    D.diag_FullName as v19,
    Diag.diag_FullName as v20,
    PSrpt.EvnPS_PhaseDescr_pid as v21,
    sdiag.Soput_Diag as v22,
    pht.PreHospTrauma_Name as v23,
    DiagExter.Diag_FullName as v24,
    MP.Person_Fio as v25,
    LSGosp.LpuSection_FullName as v26,
    PWC.PrehospWaifRefuseCause_Name as v27,
    to_char(EvnPS_OutcomeDT, 'dd.mm.yyyy') || ' ' || to_char(EvnPS_OutcomeDT, 'hh24:mi') as v28,
    ((dbo.datediff('minute', EvnPS.EvnPS_setDT, EvnPS_OutcomeDT) / 60)::varchar || ' ч ' ||
			(dbo.datediff('minute', EvnPS.EvnPS_setDT, EvnPS_OutcomeDT) % 60)::varchar || ' мин')::varchar as v29,
    coalesce(PVP.PersonVitalParam_BreathFrequency, Ro.CovidEvnPS_BreathFrequency) as v30,
    coalesce(PVP.PersonVitalParam_SistolPress, Ro.CovidEvnPS_SistolPress) as v31,
    coalesce(PVP.PersonVitalParam_DiastolPress, Ro.CovidEvnPS_DiastolPress) as v32,
    coalesce(PH.PersonHeight_Height, Ro.CovidEvnPS_Height) as v33,
    coalesce(PW.PersonWeight_Weight, Ro.CovidEvnPS_Weight) as v34,
    coalesce(PVP.PersonVitalParam_Temperature, Ro.CovidEvnPS_Temperature) as v35,
    Ro.CovidEvnPS_OxygenSaturation as v36,
    CovidType_name as v37,
    DiagSetPhase.DiagSetPhase_name as v38
from params 
join v_EvnPS as EvnPS on true
join v_LpuSection as LpuSection 
    on LpuSection.LpuSection_id = EvnPS.LpuSection_pid
    and (LpuSection.LpuSection_id = p_lpusection_id or p_lpusection_id is null)
    and (LpuSection.Lpu_id = p_lpu_id or p_lpu_id is null)
    and (LpuSection.LpuUnit_id = p_lpuunit_id or p_lpuunit_id is null)
    and (LpuSection.LpuBuilding_id = p_lpubuilding_id or p_lpubuilding_id is null)
join v_Person_all as Person 
    on Person.PersonEvn_id = EvnPS.PersonEvn_id
    and Person.Server_id = EvnPS.Server_id
left join v_LpuSection as LSGosp 
    on EvnPS.LpuSection_eid = LSGosp.LpuSection_id
left join v_Diag as Diag 
    on Diag.Diag_id = EvnPS.Diag_pid
left join v_EvnDirection_all as ED 
    on EvnPs.EvnDirection_id = ED.EvnDirection_id
left join v_Address as AU 
    on AU.Address_id = Person.UAddress_id
left join v_Address as PA
    on PA.address_id = Person.PAddress_id
left join v_Polis as Polis
    on Polis.Polis_id = Person.Polis_id
left join v_OrgSMO as OrgSMO 
    on OrgSMO.OrgSMO_id = Polis.OrgSmo_id
left join v_PrehospDirect as PrehospDirect
    on EvnPS.PrehospDirect_id = PrehospDirect.PrehospDirect_id
left join v_PrehospArrive as PrehospArrive
    on EvnPS.PrehospArrive_id = PrehospArrive.PrehospArrive_id
left join v_Lpu as lpu 
    on lpu.lpu_id = EvnPS.lpu_did
left join v_Org as Org_lpu 
    on Org_lpu.Org_id = lpu.Org_id 
left join v_LpuSection as LpuSectioPrehosp 
    on EvnPS.LpuSection_did = LpuSectioPrehosp.LpuSection_id
left join v_Org as Org 
    on Org.Org_id = EvnPS.Org_did
left join v_MedPersonal as MP 
    on EvnPS.MedPersonal_pid = MP.MedPersonal_id
    and MP.Lpu_id = EvnPS.Lpu_id
left join v_PrehospWaifRefuseCause as PWC 
    on EvnPS.PrehospWaifRefuseCause_id = PWC.PrehospWaifRefuseCause_id
left join v_Diag as D 
    on D.Diag_id = EvnPS.Diag_did
left join v_PersonNationalityStatus as PNS 
    on PNS.Person_id = Person.Person_id
    and Person.NationalityStatus_id = PNS.NationalityStatus_id
left join v_KLCountry as KLCountry 
    on PNS.KLCountry_id = KLCountry.KLCountry_id
left join v_EvnPS_rpt as PSrpt 
    on EvnPS.EvnPS_id = PSrpt.EvnPS_id
left join v_prehosptrauma as pht 
    on pht.prehosptrauma_id = EvnPS.prehosptrauma_id
left join v_Diag as DiagExter 
    on EvnPS.Diag_eid = DiagExter.Diag_id   
left join lateral (
    select 
        RepositoryObserv_setDT,
        RepositoryObserv_BreathRate as CovidEvnPS_BreathFrequency,
        RepositoryObserv_Systolic as CovidEvnPS_SistolPress,
        RepositoryObserv_Diastolic as CovidEvnPS_DiastolPress,
        RepositoryObserv_Height as CovidEvnPS_Height,
        RepositoryObserv_Weight as CovidEvnPS_Weight,
        RepositoryObserv_TemperatureFrom as CovidEvnPS_Temperature,
        RepositoryObserv_SpO2 as CovidEvnPS_OxygenSaturation,
        CovidType.CovidType_name,
        RO.CovidType_id,
        DiagSetPhase_id
    from v_RepositoryObserv as RO
    left join v_CovidType as CovidType
        on CovidType.CovidType_id = RO.CovidType_id
    where 1 = 1
        and RO.Evn_id = EvnPS.EvnPS_id
    order by RO.RepositoryObserv_updDT desc 
    limit 1
) as RO on true
left join v_PersonVitalParam as PVP 
    on PVP.Evn_id = EvnPS.EvnPS_id
left join lateral (
    select 
        PH.PersonHeight_Height
    from v_PersonHeight as PH
    where PH.Evn_id = EvnPS.EvnPS_id
    order by PH.PersonHeight_insDT desc 
    limit 1
) as PH on true
left join lateral (
    select 
        PW.PersonWeight_Weight
    from v_PersonWeight as PW
    where PW.Evn_id = EvnPS.EvnPS_id
    order by PW.PersonWeight_insDT desc 
    limit 1
) as PW on true
left join v_DiagSetPhase as DiagSetPhase 
    on EvnPS.DiagSetPhase_pid = DiagSetPhase.DiagSetPhase_id
left join lateral (
    select distinct 
        string_agg(distinct sd.Diag_FullName, ', ') as Soput_Diag
    from v_EvnDiagPS as EDPS
    join v_Diag as sd 
        on sd.Diag_id = EDPS.Diag_id
    where EDPS.EvnDiagPS_pid = EvnPS.EvnPS_id
) as sdiag on true
where 1 = 1
    and (EvnPS.Lpu_id = p_lpu_id or p_lpu_id is null)
    and (EvnPS.EvnPS_setdt between p_begdate and p_enddate + interval '1 day' - interval '1 minute')
    and EvnPS.LpuSection_pid is not null
    and (Diag.Diag_Code >= p_begdiag_code or p_begdiag_code is null)
    and (Diag.Diag_Code <= p_enddiag_code or p_enddiag_code is null)
    and (p_yesno = (
        case 
            when EvnPS.PrehospWaifRefuseCause_id is not null and LpuSection_eid is null then 2 
            when EvnPS.PrehospWaifRefuseCause_id is null and LpuSection_eid is not null then 1 
        end
    ) or p_yesno is null)
    and (p_nationality is null or p_nationality = 1 and PNS.KLCountry_id = 643 or p_nationality = 2 and PNS.KLCountry_id != 643)
    and (EvnPS.DiagSetPhase_pid = p_diagsetphase_id or coalesce(p_diagsetphase_id, -2) = -2)
    and (RO.CovidType_id = p_covidtype_id or coalesce(p_covidtype_id, -2) = -2)

