DROP PROCEDURE IF EXISTS public.sp_plancutprepare;
DROP FUNCTION IF EXISTS public.sp_plancutprepare;

CREATE OR REPLACE PROCEDURE public.sp_plancutprepare(IN "planCutDictionaryId" uuid)
 LANGUAGE plpgsql
AS $procedure$
DECLARE
    v_year int;
    v_quarter int;
    v_month int;
    v_planCutDictionaryId uuid := "planCutDictionaryId";
BEGIN
    --RAISE NOTICE 'Генерация записей предварительного среза для случаев, срезанных по причине присутствия срезанной записи в законченном случаев %', to_char(clock_timestamp(), 'DD.MM.YYYY HH24:MI:SS');
    
    select fcs.PeriodYear
          ,case
            when fcs.PeriodValue > 12 then null
            else fcs.PeriodValue
           end
          ,case
            when fcs.PeriodValue in (1, 2, 3) then 1
            when fcs.PeriodValue in (4, 5, 6) then 2
            when fcs.PeriodValue in (7, 8, 9) then 3
            when fcs.PeriodValue in (10, 11, 12) then 4
            else fcs.PeriodValue - 12
           END
    INTO v_year
        ,v_month
        ,v_quarter
    from IES.T_PLAN_CUT_DICTIONARY pcd
        join IES.T_FACT_CALC_SETTING fcs on fcs.FactCalcSettingID = pcd.FactCalcSetting
    where pcd.PlanCutDictionaryID = v_planCutDictionaryId;

    --Если законченный случай срезан из-за превышения плана/остатков плана по одному из Параметров плана
    --То все остальные Значения Параметров плана этого Законченного случая так же срезаются
    INSERT INTO IES.T_PLAN_CUT_ITEM
               (PlanCutItemID
               ,PlanCutDictionary
               ,SchetItemFakt
               ,SchetActItem
               ,CutReason
               ,Rest
               ,CalcRest
               ,CreationDateTime
               ,F014DenyReason)
    SELECT
               gen_random_uuid()--<PlanCutItemID, uniqueidentifier,>
              ,v_planCutDictionaryId--<PlanCutDictionary, uniqueidentifier,>
              ,sif.SchetItemFaktID--<SchetItemFakt, uniqueidentifier,>
              ,null--<SchetActItem, uniqueidentifier,>
              ,case rpci.CutReason
               when 0 then 1
               when 2 then 2
               when 3 then 3
               end--<CutReason, int,>
              ,rpci.Rest--<Rest, decimal>
              ,rpci.CalcRest--<CalcRest, decimal>
              ,rpci.CreationDateTime--<CreationDateTime, datetime>
              ,rpci.F014DenyReason--<F014DenyReason, uniqueidentifier,>
    from IES.T_SCHET_ITEM_FAKT sif
        join IES.T_SCHET_SLUCH ss on ss.SchetSluchID = sif.ObjectID
        cross JOIN lateral
        (
            select  pci.F014DenyReason, pci.Rest, pci.CalcRest, pci.CreationDateTime, pci.CutReason
            from IES.T_PLAN_CUT_ITEM pci
                join IES.T_SCHET_ITEM_FAKT sif1 on sif1.SchetItemFaktID = pci.SchetItemFakt
                join IES.T_SCHET_SLUCH ss1 on ss1.SchetSluchID = sif1.ObjectID
            where pci.PlanCutDictionary = v_planCutDictionaryId
                    and
                sif1.SchetItemFaktID <> sif.SchetItemFaktID
                    and
                ss1.SchetSluchAccomplished = ss.SchetSluchAccomplished LIMIT 1
        ) rpci
    where sif.PeriodYear = v_year
                and
            sif.PlanQuarter = v_quarter
                and
            (v_month is null or sif.PlanMonth = v_month)
                and
            sif.IsMek = true
                and
            not exists
            (
                select *
                from IES.T_PLAN_CUT_ITEM pci
                where pci.PlanCutDictionary = v_planCutDictionaryId
                        and
                    pci.SchetItemFakt = sif.SchetItemFaktID
            );
--*/
end;
$procedure$;
