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.RekananSkKontrakDaoCustom;
import com.jasamedika.medifirst2000.dao.custom.base.impl.CoreDaoImpl;
import com.jasamedika.medifirst2000.entities.RekananSkKontrak;
import com.jasamedika.medifirst2000.util.CommonUtil;

@Repository
public class RekananSkKontrakDaoCustomImpl extends CoreDaoImpl<RekananSkKontrak> implements RekananSkKontrakDaoCustom {

	public RekananSkKontrakDaoCustomImpl() {
		super(RekananSkKontrak.class);
	}

	@Override
	public int countRekananSkKontrak(String namaKontrak, Integer rekananId, String noKontrak) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(" select count(p.noRec) from RekananSkKontrak p left join p.rekanan rekanan where p.noRec is not null ");
		
		if(CommonUtil.isNotNullOrEmpty(rekananId)){
			buffer.append(" and rekanan.id=:rekananId ");
		}
		
		if(CommonUtil.isNotNullOrEmpty(namaKontrak)){
			buffer.append(" and p.namaKontrak=:namaKontrak ");
		}
		
		if(CommonUtil.isNotNullOrEmpty(noKontrak)){
			buffer.append(" and lower(p.noSk) like :noKontrak ");
		}
	
		Query query = em.createQuery(buffer.toString());
		
		if(CommonUtil.isNotNullOrEmpty(rekananId)){
			query.setParameter("rekananId",rekananId );
		}
		
		if(CommonUtil.isNotNullOrEmpty(namaKontrak)){
			query.setParameter("namaKontrak",namaKontrak );
		}
		
		if(CommonUtil.isNotNullOrEmpty(noKontrak)){
			query.setParameter("noKontrak","%"+noKontrak.toLowerCase()+"%" );
		}
		return ((Long) query.getSingleResult()).intValue();
	}

	@Override
	public List<Map<String, Object>> listRekananSkKontrak(Integer page, Integer limit, String sort, String dir,
			String namaKontrak, Integer rekananId, String noKontrak) {

		StringBuffer buffer = new StringBuffer();
		buffer.append(" select new map(p.noRec as noRec,rekanan.namaRekanan as namaRekanan,p.noSk as noSk,p.namaKontrak as namaKontrak) from RekananSkKontrak p left join p.rekanan rekanan where p.noRec is not null ");
		
		if(CommonUtil.isNotNullOrEmpty(rekananId)){
			buffer.append(" and rekanan.id=:rekananId ");
		}
		
		if(CommonUtil.isNotNullOrEmpty(namaKontrak)){
			buffer.append(" and p.namaKontrak=:namaKontrak ");
		}
		
		if(CommonUtil.isNotNullOrEmpty(noKontrak)){
			buffer.append(" and lower(p.noSk) like :noKontrak ");
		}
	
		Query query = em.createQuery(buffer.toString());
		
		if(CommonUtil.isNotNullOrEmpty(rekananId)){
			query.setParameter("rekananId",rekananId );
		}
		
		if(CommonUtil.isNotNullOrEmpty(namaKontrak)){
			query.setParameter("namaKontrak",namaKontrak );
		}
		
		if(CommonUtil.isNotNullOrEmpty(noKontrak)){
			query.setParameter("noKontrak","%"+noKontrak.toLowerCase()+"%" );
		}
	
		List<Map<String,Object>>data=query.getResultList();
		return data;
	
	}

}
