
-- Осложнения

CREATE TEMP TABLE TAB
(
	ID uuid NULL,

	MovementResult uuid NULL,

	Post uuid NULL,
	RecordDate timestamp NULL,
	RecordTime timestamp NULL,

	AmbulanceEvent uuid NULL,
	AmbulanceCard uuid NULL,
	PatientBase uuid NULL,
	PostingDate timestamp NULL,

	Mkb varchar(8) NULL,
	Diagnosis text NULL,

	ActiveFindDiagnosis bit NULL
);

INSERT INTO TAB (ID, MovementResult, Post, RecordDate, RecordTime, AmbulanceEvent, AmbulanceCard, PatientBase, PostingDate, Mkb, Diagnosis, ActiveFindDiagnosis)
SELECT NEWID(), mres.MedicalRecordID, mr.Post, mr.RecordDate, mr.RecordTime, acr.AmbulanceEvent, acr.AmbulanceCard, acr.PatientBase, acr.PostingDate, mres.MkbAggravation, mres.DiagAggravation, ooi.ActiveFindDiagnosis
FROM AKUZ.T_MOVEMENT_RESULT mres 
JOIN AKUZ.T_MEDICAL_RECORD mr on mres.MedicalRecordID = mr.MedicalRecordID
JOIN AKUZ.T_AMBULANCE_CARD_RECORD acr on mres.MedicalRecordID = acr.MedicalRecordID
JOIN AKUZ.T_OUTCOME_OF_INSPECTION ooi on mres.MedicalRecordID = ooi.MedicalRecordID
WHERE MkbAggravation is not null;

DO $$DECLARE newEntityID int := (SELECT EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'ACCOMPANYING_DISEASES' and e.Schema = 'AKUZ'  LIMIT 1);

BEGIN
INSERT INTO AKUZ.T_MEDICAL_RECORD (MedicalRecordID, Post, type_, RecordDate, RecordTime)
	SELECT t.ID, t.Post, @newEntityID, t.RecordDate, t.RecordTime
	FROM TAB t;
	
INSERT INTO AKUZ.T_AMBULANCE_CARD_RECORD (MedicalRecordID, AmbulanceCard, AmbulanceEvent, PostingDate, PatientBase)
	SELECT t.ID, t.AmbulanceCard, t.AmbulanceEvent, t.PostingDate, t.PatientBase
	FROM TAB t ;

INSERT INTO AKUZ.T_OUTCOME_OF_INSPECTION (MedicalRecordID, ActiveFindDiagnosis, MKBCode, Diagnosis) 
	SELECT t.ID, t.ActiveFindDiagnosis, t.Mkb, t.Diagnosis
	FROM TAB t;
	
INSERT INTO AKUZ.T_ACCOMPANYING_DISEASES (MedicalRecordID, OutcomeOfInspection, TypeDisease) 
	SELECT t.ID, t.MovementResult, 1
	FROM TAB t;



ALTER TABLE AKUZ.T_MOVEMENT_RESULT DROP COLUMN MkbAggravation;
ALTER TABLE AKUZ.T_MOVEMENT_RESULT DROP COLUMN DiagAggravation;

END
$$