package com.jasamedika.medifirst2000.dao.custom.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.jasamedika.medifirst2000.dao.custom.StrukResepDaoCustom;
import com.jasamedika.medifirst2000.dao.custom.base.impl.CoreDaoImpl;
import com.jasamedika.medifirst2000.entities.StrukResep;
import com.jasamedika.medifirst2000.util.CommonUtil;

@Repository
public class StrukResepDaoCustomImpl extends CoreDaoImpl<StrukResep> implements StrukResepDaoCustom{

	public StrukResepDaoCustomImpl() {
		super(StrukResep.class);
	}

	@Override
	public List<Map<String, Object>> getReturStrukResep(Integer departemenId, Integer ruanganId, String noResep, String noCm, String tglAwal, String tglAhir){
		List<Map<String, Object>> result = new ArrayList<>();
		
		StringBuffer buffer = new StringBuffer();
		buffer.append("select NEW Map ("
			+ "a.noResep as noResep,"
			+ "a.tglResep as tglResep,"
			+ "a.namaPemberi as namaPemberi,"
			+ "a.namaLengkapAmbilResep as namaPengambil,"
			+ "b.noRec as noRecOrder,"
			+ "b.noOrder as noStruk,"
			+ "b.tglOrder as tglStruk,"
			+ "c.noCm as noCm,"
			+ "c.namaPasien as namaPasien,"
			+ "e.noRec as noRegistrasi) "
			+ "from StrukResep a "
			+ "left join a.strukOrder b "
			+ "left join b.noCm c "
			+ "left join a.ruanganTujuan d "
			+ "left join a.pasien e "
			+ "left join d.departemen f "
			+ "left join e.pasienDaftar g "
			+ "left join g.pasien h "
			+ "where f.id=:departemenId ");
		
		if(CommonUtil.isNotNullOrEmpty(ruanganId)){
			buffer.append("and d.id=:ruanganId ");
		}
		if(CommonUtil.isNotNullOrEmpty(noResep)){
			buffer.append("and a.noResep=:noResep ");
		}
		if(CommonUtil.isNotNullOrEmpty(noCm)){
			buffer.append("and (lower(h.noCm)=:noCm or lower(h.namaPasien)=:noCm) ");
		}
		if(CommonUtil.isNotNullOrEmpty(tglAwal)&&CommonUtil.isNotNullOrEmpty(tglAhir)){
			buffer.append("and (date(b.tglOrder) between date(:tglAwal) and date(:tglAhir))");
		}
		
		Query query = em.createQuery(buffer.toString());
		query.setParameter("departemenId", departemenId);
		
		if(CommonUtil.isNotNullOrEmpty(ruanganId)){
			query.setParameter("ruanganId", ruanganId);
		}
		if(CommonUtil.isNotNullOrEmpty(noResep)){
			query.setParameter("noResep", noResep);
		}
		if(CommonUtil.isNotNullOrEmpty(noCm)){
			String lowNoCm = noCm.toLowerCase();
			query.setParameter("noCm", lowNoCm);
		}
		if(CommonUtil.isNotNullOrEmpty(tglAwal)&&CommonUtil.isNotNullOrEmpty(tglAhir)){
			query.setParameter("tglAwal", tglAwal);
			query.setParameter("tglAhir", tglAhir);
		}
		
		if(CommonUtil.isNotNullOrEmpty(buffer)){
			result = query.getResultList();
		}
		
		return result;
	}
}
