package com.jasamedika.medifirst2000.dao;

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

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.jasamedika.medifirst2000.entities.KartuStok;

/**
 * Repository class for StokProdukGlobal
 * 
 * @author Adik
 */
@Repository("KartuStokDao")
public interface KartuStokDao extends PagingAndSortingRepository<KartuStok, String> {
	@Query("select count(p.noRec) from KartuStok p where p.ruangan.id=:idRuangan and p.produk.id=:idProduk")
	Integer checkData(@Param("idProduk") Integer idProduk,@Param("idRuangan") Integer idRuangan);

	@Query(" select new map ( p.keterangan as keterangan,"
			+ " str(p.tglInput) as tanggalKejadian,"
			+ " produk.namaProduk as namaProduk,"
			+ " coalesce(p.jumlah,0.0) as jumlah,"
			+ " coalesce(p.saldoAwal,0.0) as saldoAhir ,"
			+ " p.status as status ) "
			+ " from KartuStok p left join p.produk produk"
			+ " left join p.ruangan ruangan "
			+ " where p.ruanganId=:idRuangan "
			+ " and p.produkId=:idProduk "
			+ " and date(tglInput) between :dateStart and :dateEnd "
			+ " order by p.tglInput")
	List<Map<String, Object>> kartuStokList(@Param("idProduk") Integer idProduk,@Param("idRuangan") Integer idRuangan,@Param("dateStart") Date dateStart,@Param("dateEnd") Date dateEnd);

	@Query("select p from KartuStok p "
			+ " left join p.produk produk "
			+ " left join p.ruangan ruangan  "
			+ " where p.ruanganId=:ruanganId  "
			+ " and p.produkId=:produkId  "
			+ " and p.tglInput=(select max(sub.tglInput) from KartuStok sub where sub.produkId=:produkId and p.ruanganId=:ruanganId ) "
			+ " order by p.tglInput")
	List<KartuStok> findKartuStokLatest(@Param("ruanganId") Integer ruanganId, @Param("produkId") Integer produkId);
}
