-- Tables

-- Alters

ALTER TABLE AKUZ.T_ACCOMPANYING_DISEASES ADD "typedisease" integer NULL;

UPDATE AKUZ.T_ACCOMPANYING_DISEASES SET "typedisease" = 0;

ALTER TABLE AKUZ.T_ACCOMPANYING_DISEASES ALTER COLUMN "typedisease" SET NOT NULL;


CREATE TABLE TAB
(
	ID uuid NULL,
    MedicalRecordID uuid NULL
);

INSERT INTO TMP_Exam (ID, MedicalRecordID)
SELECT uuid_generate_v4(), ooi.MedicalRecordID
FROM AKUZ.T_OUTCOME_OF_INSPECTION ooi
WHERE ooi.MkbComp is NOT NULL;

DECLARE
    entityID int := (SELECT EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'ACCOMPANYING_DISEASES' LIMIT 1);

	INSERT INTO AKUZ.T_MEDICAL_RECORD (MedicalRecordID, Post, type_)
	SELECT t.ID, mr.Post, entityID
	FROM TAB t
	    join AKUZ.T_MEDICAL_RECORD mr on t.MedicalRecordID = mr.MedicalRecordID;
		
	INSERT INTO AKUZ.T_AMBULANCE_CARD_RECORD (MedicalRecordID, AmbulanceCard, AmbulanceEvent, PostingDate, PatientBase)
	SELECT t.ID, acr.AmbulanceCard, acr.AmbulanceEvent, acr.PostingDate, acr.PatientBase
	FROM TAB t
	    join AKUZ.T_AMBULANCE_CARD_RECORD acr on t.MedicalRecordID = acr.MedicalRecordID;
	
	INSERT INTO AKUZ.T_OUTCOME_OF_INSPECTION (MedicalRecordID, ActiveFindDiagnosis, MKBCode, Diagnosis)
	SELECT t.ID, 0, ooi.MkbComp, ooi.CompDiagnosis
	FROM TAB t
	    join AKUZ.T_OUTCOME_OF_INSPECTION ooi on t.MedicalRecordID = ooi.MedicalRecordID;
	
	INSERT INTO AKUZ.T_ACCOMPANYING_DISEASES (MedicalRecordID, OutcomeOfInspection, TypeDisease)
	SELECT t.ID, ooi.MedicalRecordID, 1
	FROM TAB t
	    join AKUZ.T_OUTCOME_OF_INSPECTION ooi on t.MedicalRecordID = ooi.MedicalRecordID;


DROP INDEX IF EXISTS IX_T_OUTCOME_OF_INSPECTION_MkbComp;
ALTER TABLE AKUZ.T_OUTCOME_OF_INSPECTION DROP COLUMN MkbComp;
ALTER TABLE AKUZ.T_OUTCOME_OF_INSPECTION DROP COLUMN CompDiagnosis;

