-- =============================================
-- Author: 
-- Create date: 
-- DatabaseModel:    Metr7
-- Description: 
-- Use:
-- Changes:
--    20.05.2021  Сафонов А.Е.  DATAMODEL70-136 Исправлена ошибка с пересечением. Отформатирован код
--    12.05.2021  Седаков А.В.  DATAMODEL70-155 Отказ от физического удаления записей в экземплярах СИ.
--    13.10.2020  Седаков А.В.  ASUMS70-209. Из таблицы EKZMK удалено поле MKPRV и добавлены поля IDSPVDSBMK, PRCHNPGDN. 
--    04.09.2020  Седаков А.В.  ASUMS70-209. Добавлено новое поле MKPRV из таблицы EKZMK.
--    18.03.2020  Седаков А.В.  DATAMODEL70-28. Добавлены 2 новых поля из таблицы EKZMK: DPZNmp, HRTCmp.
--    13.02.2020  Сафонов А.Е.  ELMETRO-5 Добавлен GUID организации,
--                              убрана "звездочка" при выборке из uf_vw_FRPD_ms() и uf_vw_SPMU_ms()
--    03.02.2020  Седаков А.В.  DATAMODEL70-28. Добавлены новые поля из таблицы EKZMK.
-- =============================================

CREATE PROCEDURE dbo.up_ds_EkzmkSelect 
  @fltr varchar(MAX) = '',
  @vbr varchar(MAX) = '',
  @prm varchar(MAX) = '',
  @nmid varchar(200) = '',
  @nnid int = 0,
  @per varchar(2) = '0',  --"0" - нет пересечений, "1" - пересечение, 
                          --"-1" - НЕпересечение, "2" - заполнить таблицу пересечения.
  @idspvdd varchar(20) = '0' 
WITH EXECUTE AS 'metr6'
AS
BEGIN
  set dateformat dmy
  set nocount on

	declare @systemUser varchar(100)
	execute as caller
		select @systemUser = CAST(SYSTEM_USER AS nvarchar(MAX))
	revert

  declare @s varchar(MAX)
  declare @select varchar(MAX)

  if @per = '2' -- при заполнении данных для пересечения идентификатор в фильтре не учитывается
  begin
    set @nmid = ''
    set @nnid = 0
  end
  set @fltr = dbo.uf_GetSelectFltr_dk(@fltr, @vbr, @prm, @nmid, @nnid)

  set @s = '
IF OBJECT_ID(N''#TempFRPD'', N''U'') IS NOT NULL
DROP TABLE #TempFRPD;
CREATE TABLE #TempFRPD
(
	IDFRPD int PRIMARY KEY NOT NULL,
	IDFRPDR int,
	NMFRPD varchar(80) collate Cyrillic_General_CI_AS,
	LEVEL int,
  KDFRPDLC varchar(20) collate Cyrillic_General_CI_AS,
	PATH VARCHAR(8000) collate Cyrillic_General_CI_AS,
  GUIDFRPD UNIQUEIDENTIFIER
);
CREATE NONCLUSTERED INDEX RIndex ON #TempFRPD (IDFRPDR)
INSERT INTO #TempFRPD SELECT IDFRPD, IDFRPDR, NMFRPD, LEVEL, KDFRPDLC, PATH, GUIDFRPD FROM uf_vw_FRPD_ms();

IF OBJECT_ID (N''#TempSPMU'', N''U'') IS NOT NULL
DROP TABLE #TempSPMU;
CREATE TABLE #TempSPMU
(
	nmmu varchar(50) collate Cyrillic_General_CI_AS,
	IDSPMU int PRIMARY KEY NOT NULL,
	IDSPMUR int,
	LEVEL int,
	PATH VARCHAR(8000) collate Cyrillic_General_CI_AS,
	mu1 varchar(50) collate Cyrillic_General_CI_AS,
	mu2 varchar(50) collate Cyrillic_General_CI_AS,
	mu3 varchar(50) collate Cyrillic_General_CI_AS,
	mu4 varchar(50) collate Cyrillic_General_CI_AS
);
CREATE NONCLUSTERED INDEX RIndex ON #TempSPMU (IDSPMUR)
INSERT INTO #TempSPMU SELECT nmmu, IDSPMU, IDSPMUR, LEVEL, PATH, mu1, mu2, mu3, mu4 FROM uf_vw_SPMU_ms();

IF OBJECT_ID (N''#TempEkzmkShfkl'', N''U'') IS NOT NULL
DROP TABLE #TempEkzmkShfkl;
CREATE TABLE #TempEkzmkShfkl
(
	IDEKZMK int,
	NNNKL nvarchar(30),
	SHFKL varchar(30) collate Cyrillic_General_CI_AS,
	DTPREVMK datetime
);

insert into #TempEkzmkShfkl(idekzmk, SHFKL, NNNKL, DTPREVMK)
select IDEKZMK, SHFKL, NNNKL, DTMKFK from (
select ekzmk.IDEKZMK,  e2.SHFKL, e2.NNNKL, e2.dtmkfk,
ROW_NUMBER() over (partition by ekzmk.idekzmk order by e2.dtmkfk desc) nn
 from EKZMK 
left join EKZMK e2 on ekzmk.IDEKZ = e2.IDEKZ and e2.GDN = 1 and e2.DTMKFK < ekzmk.dtmkfk
) s
where nn = 1;

IF OBJECT_ID (N''#TempEkzmkNNDMS'', N''U'') IS NOT NULL
DROP TABLE #TempEkzmkNNDMS;
CREATE TABLE #TempEkzmkNNDMS
(
	IDEKZMK int,
	NNDMS varchar(30) collate Cyrillic_General_CI_AS,
	dtd datetime,
	nmvdd varchar(50) collate Cyrillic_General_CI_AS ,
	nmfrd  varchar(50) collate Cyrillic_General_CI_AS, 
	PTTXDMS  varchar(max) collate Cyrillic_General_CI_AS
);

insert into #TempEkzmkNNDMS(idekzmk, NNDMS, dtd, nmvdd, nmfrd, PTTXDMS)
select idod, nnd, dtd, nmvdd, nmfrd, PTTXDMS from (
select IDOD, NND, dtd, nmvdd, nmfrd, pttxdms,
ROW_NUMBER() over (partition by idod order by dtd desc) nn
from DMS 
join VDODVDD vdd on vdd.IDVDODVDD = dms.IDVDODVDD
join FRDMS on frdms.IDFRDMS = dms.IDFRDMS
join SPVDD on spvdd.IDSPVDD = frdms.IDSPVDD
where IDSPVDOD = 2 and spvdd.IDSPVDD in (2,6,8)
) s 
where nn = 1;
'
  set @s = @s + ' 
SELECT  DISTINCT
  SPOI.KDOI,
  SPNMTP.NMTP,
  SPKT.NMKT,
  SPKI.NMKI,
  TIPS.TP,
  TPRZ.DPZN,
  TPRZ.HRTC,
  EKZ.IDEKZ,
  EKZ.NNZV,
  EKZ.NNIN,
  EKZ.KLSIPR,

  SPSS.NMSS,
  SPTS.NMTS,

  VL.NMFRPD  AS FRPDVL, 
  MKF.NMFRPD AS FRPDMK,
  VL.PATH AS VL_PATH, 
  MKF.PATH AS MKF_PATH,
  VD.PRFIO AS PRSNVD,

  sD.PRFIO AS PRSNSD,
  pr.PRFIO AS PRSNPR,
  Vy.PRFIO AS PRSNVY,
  ssmp.NMSS as NMSSMP,
  tsmp.NMTS as NMTSMP,

  GRSI.NMGRSI,
  G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KZMK.IDKSP,
  EKZMK.DPZNmp,
  EKZMK.HRTCmp,
  EKZMK.IDSPVDSBMK,
  SPVDSBMK.NMVDSBMK,
  EKZMK.PRCHNPGDN
	
FROM EKZMK

INNER JOIN EKZ ON EKZMK.IDEKZ=EKZ.IDEKZ and ISNULL(EKZ.IsDeleted, 0) = 0
LEFT JOIN GRSI ON EKZMK.IDGRSI=GRSI.IDGRSI
LEFT JOIN SPVDMC ON EKZMK.IDSPVDMC=SPVDMC.IDSPVDMC
LEFT JOIN KSPRL ON EKZMK.IDKSPRL=KSPRL.IDKSPRL
INNER JOIN SPVDMK ON EKZMK.IDSPVDMK=SPVDMK.IDSPVDMK
LEFT JOIN SPMPOB ON EKZMK.IDSPMPOB=SPMPOB.IDSPMPOB
LEFT JOIN PRSN ON EKZMK.IDPRSN=PRSN.IDPRSN
LEFT JOIN SPKMMK ON EKZMK.IDSPKMMK=SPKMMK.IDSPKMMK
LEFT JOIN SPVDKL ON EKZMK.IDSPVDKL=SPVDKL.IDSPVDKL

LEFT JOIN #TempSPMU MU ON  MU.IDSPMU=EKZMK.IDSPMU

INNER JOIN  #TempFRPD  MKF ON EKZMK.IDFRPD=MKF.IDFRPD
LEFT JOIN  #TempFRPD  VL ON EKZ.IDFRPDV=VL.IDFRPD

LEFT JOIN PRSN VD ON EKZMK.IDPRSNVD=VD.IDPRSN
LEFT JOIN SPKT ON EKZ.IDSPKT=SPKT.IDSPKT
LEFT JOIN SPSS ON EKZ.IDSPSS=SPSS.IDSPSS
LEFT JOIN SPTS ON EKZ.IDSPTS=SPTS.IDSPTS
LEFT JOIN EKZRM ON EKZ.IDEKZ=EKZRM.IDEKZ
INNER JOIN TPRZ ON EKZ.IDTPRZ=TPRZ.IDTPRZ
INNER JOIN TIPS ON TIPS.IDTIPS=TPRZ.IDTIPS
INNER JOIN SPNMTP ON TIPS.IDSPNMTP=SPNMTP.IDSPNMTP
LEFT JOIN SPKI ON TIPS.IDSPKI=SPKI.IDSPKI
INNER JOIN SPOI ON TIPS.IDSPOI=SPOI.IDSPOI 

LEFT JOIN PRSN sd ON EKZMK.IDPRSNsd=sd.IDPRSN
LEFT JOIN PRSN pr ON EKZMK.IDPRSNpr=pr.IDPRSN
LEFT JOIN PRSN vy ON EKZMK.IDPRSNvy=vy.IDPRSN
LEFT JOIN SPSS ssmp ON EKZmk.IDSPSSmp=ssmp.IDSPSS
LEFT JOIN SPTS tsmp ON EKZmk.IDSPTSmp=tsmp.IDSPTS

LEFT JOIN FRPDRK on FRPDRK.IDFRPD = EKZMK.IDFRPD
LEFT JOIN FRDSPV on FRDSPV.IDFRPD = EKZMK.IDFRPD
LEFT JOIN #TempEkzmkShfkl pk on pk.idekzmk = ekzmk.idekzmk
LEFT join #TempEkzmkNNDMS nnd on nnd.idekzmk = ekzmk.idekzmk
LEFT JOIN SPVDSBMK ON EKZMK.IDSPVDSBMK=SPVDSBMK.IDSPVDSBMK	 

where '

  set @select = @select + @fltr

  if @per = '1'
    set @fltr = @fltr +
      ' and  ekz.idekz in (select idekz from PS_TempFltrEkz where suser = ''' + @systemuser + ''') '

  if @per = '-1'
    set @fltr = @fltr +
      ' and ekz.idekz not in (select idekz from PS_TempFltrEkz where suser = ''' + @systemuser + ''') '

  set @s = @s + @fltr

  set @s = @s + ' 
IF OBJECT_ID(N''#TempFRPD'', N''U'') IS NOT NULL
DROP TABLE #TempFRPD;

IF OBJECT_ID (N''#TempSPMU'', N''U'') IS NOT NULL
DROP TABLE #TempSPMU;'

  if @per = '2'
    set @s = @select

  exec (@s)
END

