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

@Repository
public class PenyusunanEPlanningDaoCustomImpl extends CoreDaoImpl<DetailSpekAnggaran>
		implements PenyusunanEPlanningDaoCustom {

	public PenyusunanEPlanningDaoCustomImpl() {
		super(DetailSpekAnggaran.class);
	}

	@Override
	public int findCount(String isVerifikasi) {

		StringBuffer buffer = new StringBuffer();
		buffer.append("select count(dsa.noRec) from DetailSpekAnggaran dsa where ");

		if (CommonUtil.isNotNullOrEmpty(isVerifikasi)) {
			buffer.append("dsa.isVerifikasi like :isVerifikasi ");
		}

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

		if (CommonUtil.isNotNullOrEmpty(isVerifikasi)) {
			query.setParameter("isVerifikasi", "%" + isVerifikasi + "%");
		}

		return ((Long) query.getSingleResult()).intValue();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getPenyusunanEPlanning(int rowStart, int rowEnd, String sort, String dir,
			String isVerifikasi) {

		StringBuffer buffer = new StringBuffer();
		buffer.append(
				"select new map(pdk.id as produkId,pdk.namaProduk as namaProduk,SUM(dsa.volumeBarang) as volumeBarang,"
						+ "SUM(dsa.hargaSatuanBarang) as hargaSatuan,SUM(dsa.totalHargaBarang) as totalHarga) from DetailSpekAnggaran dsa "
						+ "left join dsa.produk pdk ");

		if (CommonUtil.isNotNullOrEmpty(isVerifikasi)) {
			buffer.append("where dsa.isVerifikasi like :isVerifikasi ");
		}

		buffer.append("group by pdk.id,pdk.namaProduk order by pdk.namaProduk");

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

		if (CommonUtil.isNotNullOrEmpty(isVerifikasi)) {
			query.setParameter("isVerifikasi", "%" + isVerifikasi + "%");
		}

		query.setFirstResult(rowStart);
		query.setMaxResults(rowEnd);

		List<Map<String, Object>> list = query.getResultList();

		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getMataAnggaran(Integer id) {

		StringBuffer buffer = new StringBuffer();
		buffer.append(
				"select new map(ma.id as mataAnggaranId,ma.kodeMataAnggaran as kodeMataAnggaran,ma.namaMataAnggaran as namaMataAnggaran) "
						+ "from MataAnggaran ma ");

		if (CommonUtil.isNotNullOrEmpty(id)) {
			buffer.append("where ma.id=:id ");
		}

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

		if (CommonUtil.isNotNullOrEmpty(id)) {
			query.setParameter("id", id);
		}

		List<Map<String, Object>> list = query.getResultList();

		return list;
	}

}
