
	  
      create temp table evntable on commit drop as  
     	select * 
     	 
   		from (
		SELECT 
			q.*
		FROM (
			SELECT
				t.TimetableResource_begTime,
				t.RecMethodType_id, 
				t.TimeTableResourceHist_insDT, 
				t.TimeTableActionType_id,
				CASE WHEN t.TimeTableActionType_id = 3 then x.TimeTableResourceHist_id ELSE t.TimeTableResourceHist_id END TimeTableResourceHist_id,
				CASE WHEN t.TimeTableActionType_id = 3 then x.UserId ELSE t.UserId END UserId,
				t.Person_id,
				t.UslugaComplex_did,
				t.MedService_id,
				t.Resource_id,
				t.Evn_pid,
				CASE 
					WHEN TimeTableActionType_id = 3 and TimeTableResourceHist_insDT >= $1 THEN
						CASE WHEN TimeTableResourceHist_insDT < TimetableResource_begTime then 'CANCELED' ELSE 'PATIENT_NOT_ARRIVED' END 
					WHEN TimeTableActionType_id = 2 and TimeTableResourceHist_insDT >= $2 THEN 'RECORDED'
					WHEN TimeTableActionType_id = 2 AND TimeTableResourceHist_insDT < cast($3::timestamp - interval '5 day' as date) AND t.rn = 1 and t.visited = 0 and cast($4::date as timestamp)+interval '5 hour' between $5 and $6 then 'PATIENT_NOT_ARRIVED'
				END AS Status_id
			FROM timeTable t
			 left join lateral  (
				select   x.UserId,  x.TimeTableResourceHist_id from timeTable x 
				where x.TimeTableResource_id = t.TimeTableResource_id AND t.rn < x.rn and x.TimeTableActionType_id = 2
				ORDER BY rn
				 LIMIT 1 
			) x  ON TRUE 
		) q where q.Status_id is not null AND q.TimeTableActionType_id is not null 
		UNION
		SELECT 
			t.TimetableResource_begTime,
			t.RecMethodType_id, 
			t.TimeTableResourceHist_insDT, 
			t.TimeTableActionType_id,
			t.TimeTableResourceHist_id,
			t.UserId UserId, 
			t.Person_id, 
			t.UslugaComplex_did,
			t.MedService_id,
			t.Resource_id,
			t.Evn_pid,
			'SUCCESS' Status_id
		FROM timeTable t
		WHERE (t.updated = 1 or TimeTableResourceHist_insDT >= $7) and t.visited = 1
	) z
