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

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

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.jasamedika.medifirst2000.dao.custom.SkoringTindakanMedisDaoCustom;
import com.jasamedika.medifirst2000.dao.custom.base.impl.CoreDaoImpl;
import com.jasamedika.medifirst2000.entities.SkoringTindakanMedis;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.vo.ReferensiSkorAnestesiVO;

/**
 * @author salmanoe
 * @since Nov 23, 2021
 */
@Repository
public class SkoringTindakanMedisDaoCustomImpl extends CoreDaoImpl<SkoringTindakanMedis>
		implements SkoringTindakanMedisDaoCustom {

	public SkoringTindakanMedisDaoCustomImpl() {
		super(SkoringTindakanMedis.class);
	}

	@Override
	public List<Map<String, Object>> findSkoringLogbookDokter(String bulan,
			List<ReferensiSkorAnestesiVO> listReferensiSkor) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(
				"select distinct new Map(" + "mj.subUnitKerjaPegawaiId as kelompokKerjaId,mj.pegawaiId as pegawaiId,"
						+ "pr.id as produkId,pr.namaProduk as namaProduk,"
						+ "stm.skor as skor,stm.tanggalMulaiBerlaku as tglMulaiBerlaku,stm.tanggalPembaharuanData as tglPembaharuanData) "
						+ "from SkoringTindakanMedis stm, " + "MapPegawaiJabatanToUnitKerja mj "
						+ "inner join stm.produk pr " + "where stm.kelompokKerjaId = mj.subUnitKerjaPegawaiId "
						+ "and stm.statusEnabled is true " + "and stm.statusVerifikasi is true "
						+ "and pr.statusEnabled is true " + "and mj.statusEnabled is true "
						+ "and to_char(stm.tanggalMulaiBerlaku,'yyyy-MM') <= '" + bulan + "' and ");

		if (CommonUtil.isNotNullOrEmpty(listReferensiSkor)) {
			String appendData = "";
			for (ReferensiSkorAnestesiVO ref : listReferensiSkor) {
				if (appendData.isEmpty()) {
					appendData += "((mj.pegawaiId = " + ref.getDokterPemeriksaId() + " and mj.subUnitKerjaPegawaiId = "
							+ ref.getKelompokKerjaId() + " and pr.id = " + ref.getProdukId() + ")";
				} else {
					appendData += " or (mj.pegawaiId = " + ref.getDokterPemeriksaId()
							+ " and mj.subUnitKerjaPegawaiId = " + ref.getKelompokKerjaId() + " and pr.id = "
							+ ref.getProdukId() + ")";
				}

			}
			appendData += ") ";
			buffer.append(appendData);
		}

		buffer.append(" order by pr.namaProduk, stm.skor desc, stm.tanggalPembaharuanData desc");

		Query query = em.createQuery(buffer.toString());

		@SuppressWarnings("unchecked")
		List<Map<String, Object>> result = query.getResultList();

		return result;
	}

}
