package com.jasamedika.medifirst2000.service.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;

import org.apache.commons.codec.binary.Base64;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jasamedika.medifirst2000.converter.BaseConverterImpl;
import com.jasamedika.medifirst2000.dao.DetailPengadaanDao;
import com.jasamedika.medifirst2000.dao.DetailSpekAnggaranDao;
import com.jasamedika.medifirst2000.dao.KartuPengendaliDao;
import com.jasamedika.medifirst2000.dao.KartuPengendaliDetailDao;
import com.jasamedika.medifirst2000.dao.MapKartuPengendaliToMetodeSubDetailDao;
import com.jasamedika.medifirst2000.dao.MetodePengadaanDetailDao;
import com.jasamedika.medifirst2000.dao.MetodePengadaanSubDetailDao;
import com.jasamedika.medifirst2000.dao.PenawaranHargaDao;
import com.jasamedika.medifirst2000.dao.PenawaranHargaSupplierDao;
import com.jasamedika.medifirst2000.dao.PengadaanDao;
import com.jasamedika.medifirst2000.dao.RekananDao;
import com.jasamedika.medifirst2000.dao.StrukRekapPemenangDao;
import com.jasamedika.medifirst2000.dao.custom.KartuPengendaliDaoCustom;
import com.jasamedika.medifirst2000.dao.custom.StrukPelayananDetailDaoCustom;
import com.jasamedika.medifirst2000.entities.AsalProduk;
import com.jasamedika.medifirst2000.entities.DetailPengadaan;
import com.jasamedika.medifirst2000.entities.DetailRup;
import com.jasamedika.medifirst2000.entities.DetailSpekAnggaran;
import com.jasamedika.medifirst2000.entities.KartuPengendali;
import com.jasamedika.medifirst2000.entities.KartuPengendaliDetail;
import com.jasamedika.medifirst2000.entities.KelompokUser;
import com.jasamedika.medifirst2000.entities.MapKartuPengendaliToMetodeSubDetail;
import com.jasamedika.medifirst2000.entities.MataAnggaran;
import com.jasamedika.medifirst2000.entities.MetodePengadaanSubDetail;
import com.jasamedika.medifirst2000.entities.PenawaranHarga;
import com.jasamedika.medifirst2000.entities.PenawaranHargaSupplier;
import com.jasamedika.medifirst2000.entities.Rekanan;
import com.jasamedika.medifirst2000.entities.StrukRekapPemenang;
import com.jasamedika.medifirst2000.enums.VerifikasiEnum;
import com.jasamedika.medifirst2000.service.KartuPengendaliService;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.util.DateUtil;
import com.jasamedika.medifirst2000.util.IndonesianNumberToWords;
import com.jasamedika.medifirst2000.vo.AsalProdukVO;
import com.jasamedika.medifirst2000.vo.DetailRupVO;
import com.jasamedika.medifirst2000.vo.KartuPengendaliCustomVO;
import com.jasamedika.medifirst2000.vo.KartuPengendaliDetailVO;
import com.jasamedika.medifirst2000.vo.KartuPengendaliVO;
import com.jasamedika.medifirst2000.vo.MapKartuPengendaliToMetodeSubDetailVO;
import com.jasamedika.medifirst2000.vo.MataAnggaranVO;
import com.jasamedika.medifirst2000.vo.PenawaranHargaSupplierVO;
import com.jasamedika.medifirst2000.vo.PenawaranHargaVO;
import com.jasamedika.medifirst2000.vo.RekananVO;
import com.jasamedika.medifirst2000.vo.RekapPemenangUlpVO;
import com.jasamedika.medifirst2000.vo.UpdateJadwalVO;
import com.jasamedika.medifirst2000.vo.UploadExcelVO;
import com.jasamedika.medifirst2000.vo.VerifikasiKartuPengendaliDetailVO;
import com.jasamedika.medifirst2000.vo.VerifikasiKartuPengendaliHeaderVO;

@Service("kartuPengendaliService")
public class KartuPengendaliServiceImpl extends BaseAngaranServiceImpl implements KartuPengendaliService{
	
	@Value("${reportDirectory}")
	String reportDirectory;
	
	@Autowired
	private KartuPengendaliDao kartupengendaliDao;
	
	@Autowired
	private StrukPelayananDetailDaoCustom strukPelayananDetailDaoCustom;
	
	@Autowired
	private StrukRekapPemenangDao strukRekapPemenangDao;
	
	@Autowired
	private RekananDao rekananDao;
	
	@Autowired
	private PenawaranHargaSupplierDao penawaranHargaSupplierDao;
	
	@Autowired
	private PengadaanDao pengadaanDao;
	
	@Autowired
	private PenawaranHargaDao penawaranHargaDao;
	
	@Autowired
	private KartuPengendaliDetailDao kartuPengendaliDetailDao;
	
	@Autowired
	private DetailPengadaanDao detailPengadaanDao;
	
	@Autowired
	private MapKartuPengendaliToMetodeSubDetailDao mapKartuPengendaliToMetodeSubDetailDao;
	
	@Autowired
	private MetodePengadaanSubDetailDao metodePengadaanSubDetailDao;
	
	@Autowired
	private DetailSpekAnggaranDao detailSpekAnggaranDao;
	
	@Autowired
	private KartuPengendaliDaoCustom kartupengendaliDaoCustom;
	
	@Autowired
	private MetodePengadaanDetailDao metodePengadaanDetailDao;
	
	@Autowired
	private BaseConverterImpl <KartuPengendaliCustomVO, KartuPengendali> kartuPengendaliConverter;
	
	@Autowired
	private BaseConverterImpl <AsalProdukVO, AsalProduk> asalProdukConverter;
	
	@Autowired
	private BaseConverterImpl <KartuPengendaliDetailVO, KartuPengendaliDetail> kartuPengendaliDetailConverter;
	
	@Autowired
	private BaseConverterImpl <MataAnggaranVO, MataAnggaran> mataAnggaranConverter;
	
	@Autowired
	private BaseConverterImpl <RekananVO, Rekanan> rekananConverter;
	
	@Autowired
	private BaseConverterImpl <DetailRupVO, DetailRup> detailRupConverter;
	
	private KartuPengendali kartuPengendali = new KartuPengendali();
	private long size = 0;

	//Save kartu Pengedali
	@Override
	public Map<String, Object> saveKartuPengendali(KartuPengendaliCustomVO vo) {
		Map<String, Object> result = new HashMap<>();
		
		Double JumlahHarga = 0.00;
		Double TotalPPN    = 0.00;
		
		if(CommonUtil.isNotNullOrEmpty(vo)){
			kartuPengendali = kartuPengendaliConverter.transferVOToModel(vo, new KartuPengendali());
			kartuPengendali.setNoUsulan(GenerateNoUsulan());
			kartuPengendali.setPaketPengadaan(vo.getPaketPengadaan());
			kartuPengendali.setTanggalDibutuhkan(vo.getTanggalDibutuhkan());
		}
		if(CommonUtil.isNotNullOrEmpty(vo.getAsalProduk())){
			kartuPengendali.setAsalProduk(asalProdukConverter.transferVOToModel(vo.getAsalProduk(), new AsalProduk()));
		}
		
		if(CommonUtil.isNotNullOrEmpty(vo.getMataAnggaran())){
			kartuPengendali.setMataAnggaran(mataAnggaranConverter.transferVOToModel(vo.getMataAnggaran(),new MataAnggaran()));
		}
		List<KartuPengendaliDetail> list = new ArrayList<>();
		if(CommonUtil.isNotNullOrEmpty(vo.getKartuPengendaliDetail())){
			size = 0;
			for(KartuPengendaliDetailVO kartuPengendaliDetailVO : vo.getKartuPengendaliDetail()){
				KartuPengendaliDetail detail=inisialisasiKartuPengendaliDetail(kartuPengendaliDetailVO);
				detail.setKartuPengendali(kartuPengendali);
				list.add(detail);
				
			}
			kartuPengendali.setKartuPengendaliDetail(list);
			
		}
		
		if(CommonUtil.isNotNullOrEmpty(JumlahHarga)){
			kartuPengendali.setJumlah(JumlahHarga);
		}
		
		if(CommonUtil.isNotNullOrEmpty(TotalPPN)){
			kartuPengendali.setPpn(TotalPPN);
		}
		
		if(CommonUtil.isNotNullOrEmpty(JumlahHarga+TotalPPN)){
			kartuPengendali.setTotal(JumlahHarga+TotalPPN);
		}
		
		if(CommonUtil.isNotNullOrEmpty(JumlahHarga+TotalPPN)){
			kartuPengendali.setTerbilang(terbilang(JumlahHarga+TotalPPN));
		}
		
		if(CommonUtil.isNotNullOrEmpty(JumlahHarga+TotalPPN)){
			double pembulatan = JumlahHarga+TotalPPN;
			kartuPengendali.setPembulatan(Math.ceil(pembulatan));
		}
		
		if(CommonUtil.isNotNullOrEmpty(kartuPengendali)){
			KartuPengendali resultKartuPengendali = kartupengendaliDao.save(kartuPengendali);
			result.put("noRec", resultKartuPengendali.noRec);
		}
		
		return result;
	}
	
	//Inisisalisasi Kartu Pengendali
	public KartuPengendaliDetail inisialisasiKartuPengendaliDetail(KartuPengendaliDetailVO kartuPengendaliDetailVO){
		KartuPengendaliDetail kartuPengendaliDetail = new KartuPengendaliDetail();
		
		//Cek data Pertama jika kosong maka default nya VERIFIKASI PENGENDALI
		if(CommonUtil.isNullOrEmpty(kartuPengendaliDetailVO.getIsVerifikasi())){
			kartuPengendaliDetailVO.setIsVerifikasi(VerifikasiEnum.VERIF_PENGENDALI.getVal());
		}
		Double totalHargaBarang = 0.00;
		Double totalHargaBarangPlusPpn=0.00;
		Double totalPpn=0.00;
		
		if(CommonUtil.isNotNullOrEmpty(kartuPengendaliDetailVO)){
			kartuPengendaliDetail = kartuPengendaliDetailConverter.transferVOToModel(kartuPengendaliDetailVO, new KartuPengendaliDetail());
			kartuPengendaliDetail.setKeterangan(kartuPengendaliDetailVO.getKeterangan());
			kartuPengendaliDetail.setKartuPengendali(kartuPengendali);
			if(CommonUtil.isNullOrEmpty(kartuPengendaliDetail.getNoUsulan())){
				kartuPengendaliDetail.setNoUsulan(GenerateNoUsulanDetail(size));
				size++;
			}
			
		}

		if(CommonUtil.isNotNullOrEmpty(kartuPengendaliDetail.getHargaSatuanBarang()) && CommonUtil.isNotNullOrEmpty(kartuPengendaliDetailVO.getVolumeBarang())){
			totalHargaBarang = kartuPengendaliDetail.getHargaSatuanBarang()*kartuPengendaliDetailVO.getVolumeBarang();
			totalPpn    = (totalHargaBarang*10)/100;
			totalHargaBarangPlusPpn=totalHargaBarang+totalPpn;

		}
		
		if(CommonUtil.isNotNullOrEmpty(kartuPengendaliDetailVO.getDetailRup())){
			kartuPengendaliDetail.setDetailRup(detailRupConverter.transferVOToModel(kartuPengendaliDetailVO.getDetailRup(), new DetailRup()));
		}
		
		if(CommonUtil.isNotNullOrEmpty(kartuPengendaliDetail.getHargaSatuanBarang())){
			kartuPengendaliDetail.setHargaSatuanBarang(kartuPengendaliDetail.getHargaSatuanBarang());
		}
		
		if(CommonUtil.isNotNullOrEmpty(totalPpn)){
			kartuPengendaliDetail.setPpn(totalPpn);
		}
		
		if(CommonUtil.isNotNullOrEmpty(totalHargaBarang)){
			kartuPengendaliDetail.setTotalHargaBarang(totalHargaBarangPlusPpn);
		}
		
		if(CommonUtil.isNotNullOrEmpty(totalHargaBarang)){
			kartuPengendaliDetail.setTerbilang(terbilang(totalHargaBarangPlusPpn));
		}
		kartuPengendaliDetail.setIsActive(true);
		kartuPengendaliDetail.setIsVerifikasi(kartuPengendaliDetailVO.getIsVerifikasi());
		kartuPengendaliDetail.setStatusCode(1);
		if(CommonUtil.isNotNullOrEmpty(totalHargaBarang)){
			kartuPengendaliDetail.setPembulatan(Math.ceil(totalHargaBarangPlusPpn));
		}
		
		return kartuPengendaliDetail;
	}

	//Paging List Untuk Kartu Pengendalai
	@Override
	public Map<String, Object> kartuPengenDaliPAging(Integer page, Integer limit, String sort, String dir,String dateStart,String dateEnd,Integer pengendaliId,Boolean isPpk,Boolean isUlp,Boolean isPp) {
		
		int totalRow = kartupengendaliDaoCustom.findKartuPengendaliCount(sort,dateStart,dateEnd,pengendaliId,isPpk,isUlp,isPp);
		int totalPages = 0;

		int pageRequested = page;

		if (totalRow > 0) {
			totalPages = (int) Math.ceil((double) totalRow / (double) limit);
		} else {
			totalPages = 0;
		}

		if (pageRequested > totalPages)
			pageRequested = totalPages;
		int rowStart = pageRequested * limit - limit;
		if (rowStart < 0) {
			rowStart = 0;
		}
		int rowEnd = limit;
		Map<String, Object> result=new HashMap<String,Object>();
		result.put("data", kartupengendaliDaoCustom.findKartuPengendali(rowStart, rowEnd, sort,dir,dateStart,dateEnd,pengendaliId,isPpk,isUlp,isPp));
		result.put("totalPages", totalPages);
		result.put("totalRow", totalRow);
		return result;
	}
	
	// Paging List Untuk Kartu Header
	@Override
	public Map<String, Object> kartuPengenDaliPagingHeader(Integer page, Integer limit, String sort, String dir,
			String dateStart, String dateEnd, Integer pengendaliId, Boolean isPpk, Boolean isUlp,Boolean isPp, Boolean isAnggaran,
			Boolean isPengendali, Boolean isDirekturTerkait) {
		List<Integer> pengedaliIdList = getPengendaliByUserLoginList();
		int totalRow = kartupengendaliDaoCustom.findKartuPengendaliHeaderCount(sort, dateStart, dateEnd, pengendaliId,
				isPpk, isUlp,isPp, isAnggaran, isPengendali, isDirekturTerkait, pengedaliIdList);
		int totalPages = 0;

		int pageRequested = page;

		if (totalRow > 0) {
			totalPages = (int) Math.ceil((double) totalRow / (double) limit);
		} else {
			totalPages = 0;
		}

		if (pageRequested > totalPages)
			pageRequested = totalPages;
		int rowStart = pageRequested * limit - limit;
		if (rowStart < 0) {
			rowStart = 0;
		}
		int rowEnd = limit;
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, Object>> tmpMap = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> test : kartupengendaliDaoCustom.findKartuPengendaliHeader(rowStart, rowEnd, sort, dir,
				dateStart, dateEnd, pengendaliId, isPpk, isUlp,isPp, isAnggaran, isPengendali, isDirekturTerkait,
				pengedaliIdList)) {
			test.put("isVerifikasi", kartupengendaliDaoCustom.checkStatusKartuKendaliHeader(isPpk, isUlp,isPp, isAnggaran,
					isPengendali, isDirekturTerkait, test.get("noRec").toString()));
			tmpMap.add(test);

		}
		result.put("data", tmpMap);
		result.put("totalPages", totalPages);
		result.put("totalRow", totalRow);
		return result;
	}
	
	@Override
	public Map<String,Object> result(String dateStart,String dateEnd){
		List<Map<String,Object>> result=new ArrayList<Map<String,Object>>();
		//result=kartupengendaliDaoCustom.generateTemplateExel(dateStart,dateEnd);
		Map<String,Object> re=new HashMap<String,Object>();
		return re;
	}
	
	//Detail Kartu Pengendali By No Rc
	@Override
	public Map<String,Object> getKartuPengendaliHeaderByNoRec(String noRec){
		Map<String,Object> result=new HashMap<String,Object>();
		result.put("kartuPengendaliHeader",kartupengendaliDaoCustom.getKartuPengendaliHeaderByNoRec(noRec));
		result.put("kartuPengendaliDetail",kartupengendaliDaoCustom.getKartuPengendaliDetailByParent(noRec));
		result.put("pengadaan",detailPengadaanDao.findByKartuPengendaliHeader(noRec));
		return result;
	}
	
	//Detail Kartu Pengendali By No Rc
	@Override
	public Map<String,Object> getPreAddJadwal(String noRec){
		Map<String,Object> result=new HashMap<String,Object>();
		result.put("kartuPengendaliHeader",kartupengendaliDaoCustom.getKartuPengendaliHeaderByNoRec(noRec));
		result.put("jadwal",mapKartuPengendaliToMetodeSubDetailDao.findByParent(noRec));
		return result;
	}

	//insert data baru (duplicate)
	private void createKartuPengendaliDetailSecondRow(KartuPengendaliDetailVO vo,KartuPengendaliDetail model) {
		vo.setHargaSatuanBarang(model.getHargaSatuanBarang());
		vo.setVolumeBarang(model.getVolumeBarang());
		vo.setNoUsulan(model.getNoUsulan());
		
		//jika di update dari VERIFIKASI PPK Maka Fungsi Ini Diekseskusi
		if(CommonUtil.isNotNullOrEmpty(model.getHargaSatuanBarangHps())){
			vo.setHargaSatuanBarangHps(model.getHargaSatuanBarangHps());
			vo.setPembulatan(model.getPembulatanHps());
			vo.setTerbilangHps(model.getTerbilangHps());
			vo.setTotalHargaBarangHps(model.getHargaSatuanBarangHps());
		}
	
		KartuPengendaliDetail kartuPengendaliDetail=inisialisasiKartuPengendaliDetail(vo);
		kartuPengendaliDetail.setNoRec(null);
		if(CommonUtil.isNotNullOrEmpty(vo.getHargaSatuanBarangHps())){
			
			Double totalHargaBarang = 0.00;
			Double totalHargaBarangPlusPpn=0.00;
			Double totalPpn=0.00;
			
			totalHargaBarang = kartuPengendaliDetail.getHargaSatuanBarangHps()*vo.getVolumeBarang();
			totalPpn    = (totalHargaBarang*10)/100;
			totalHargaBarangPlusPpn=totalHargaBarang+totalPpn;
			
			kartuPengendaliDetail.setHargaSatuanBarangHps(vo.getHargaSatuanBarangHps());
			kartuPengendaliDetail.setTotalHargaBarangHps(totalHargaBarangPlusPpn);
			kartuPengendaliDetail.setPembulatanHps(Math.ceil(totalHargaBarangPlusPpn));
			kartuPengendaliDetail.setTerbilangHps(terbilang(Math.ceil(totalHargaBarangPlusPpn)));
		}
		
		if(CommonUtil.isNotNullOrEmpty(model.getKartuPengendali())){
			kartuPengendaliDetail.setKartuPengendali(model.getKartuPengendali());
			
		}
		if(CommonUtil.isNotNullOrEmpty(model.getDetailRup())){
			kartuPengendaliDetail.setDetailRup(model.getDetailRup());
		}
		
		//inisialisasi parent,jika data diverifikasi maka akan insert data baru,
		kartuPengendaliDetail.setKartuPengendaliDetail(model);
		kartuPengendaliDetail.setSupplier(model.getSupplier());
		kartuPengendaliDetailDao.save(kartuPengendaliDetail);
		
	}

	//VERIFIKASI PPK
	@Override
	@Transactional(readOnly=false)
	public Map<String, Object> verifikasiPpk(VerifikasiKartuPengendaliDetailVO vo) {
		
		Map<String,Object> result=new HashMap<String,Object>();
		List<String> r=new ArrayList<String>();
		KartuPengendaliDetail kartuPengendaliDetailTmp=new KartuPengendaliDetail();
		for(KartuPengendaliDetailVO kartuPengendaliDetailVO:vo.getKartuPengendaliDetail()){
			KartuPengendaliDetail kartuPengendaliDetail=kartuPengendaliDetailDao.findByNoRec(kartuPengendaliDetailVO.getNoRec());
			kartuPengendaliDetail.setIsActive(false);
			kartuPengendaliDetail.setIsVerifikasi(VerifikasiEnum.VERIF_ANGGARAN.getVal());
			
			kartuPengendaliDetailVO.setIsVerifikasi(VerifikasiEnum.VERIF_PPK.getVal());
			createKartuPengendaliDetailSecondRow(kartuPengendaliDetailVO,kartuPengendaliDetail);
			r.add(kartuPengendaliDetailVO.getNoRec());
			
			kartuPengendaliDetailTmp=kartuPengendaliDetail;
			updateDetailPengadaan(kartuPengendaliDetailVO,vo);
			
			if(CommonUtil.isNotNullOrEmpty(kartuPengendaliDetail.getDetailRup())){
				if(CommonUtil.isNotNullOrEmpty(kartuPengendaliDetail.getDetailRup().getDetailSpekAnggaranId())){
					setStatusDetailSpekAnggaran(kartuPengendaliDetail.getDetailRup().getDetailSpekAnggaranId(), VerifikasiEnum.VERIF_PPK.getVal());
				}
			}
		}
		saveJadwal(kartuPengendaliDetailTmp,vo);
		result.put("result", r);
		return  result;
	
	}
	
	
	// Rekap Pemenang
	@Override
	@Transactional(readOnly = false)
	public Map<String, Object> rekapPemenang(VerifikasiKartuPengendaliDetailVO vo) {

		Map<String, Object> result = new HashMap<String, Object>();
		List<String> r = new ArrayList<String>();
		KartuPengendaliDetail kartuPengendaliDetailTmp=new KartuPengendaliDetail();
		for (KartuPengendaliDetailVO kartuPengendaliDetailVO : vo.getKartuPengendaliDetail()) {
			KartuPengendaliDetail kartuPengendaliDetail = kartuPengendaliDetailDao.findByNoRec(kartuPengendaliDetailVO.getNoRec());
			kartuPengendaliDetail.setIsActive(false);
			kartuPengendaliDetail.setIsVerifikasi(VerifikasiEnum.VERIF_ANGGARAN.getVal());
			kartuPengendaliDetail.setHargaSupplier(kartuPengendaliDetailVO.getHargaSupplier());
			if(CommonUtil.isNotNullOrEmpty(kartuPengendaliDetailVO.getSupplier())){
				kartuPengendaliDetail.setSupplier(rekananConverter.transferVOToModel(kartuPengendaliDetailVO.getSupplier(), new Rekanan()));
			}
			kartuPengendaliDetailVO.setIsVerifikasi(VerifikasiEnum.VERIF_PPK.getVal());
			createKartuPengendaliDetailSecondRow(kartuPengendaliDetailVO, kartuPengendaliDetail);
			r.add(kartuPengendaliDetailVO.getNoRec());
			kartuPengendaliDetailTmp=kartuPengendaliDetail;
			
			
		}
		result.put("result", r);
		strukRekapPemenang(kartuPengendaliDetailTmp);
		return result;

	}
	
	// Rekap Pemenang Fom Ulp
	@Override
	@Transactional(readOnly = false)
	public Map<String, Object> rekapPemenangFromUlp(RekapPemenangUlpVO vo) {

		Map<String, Object> result = new HashMap<String, Object>();
		KartuPengendaliDetail kartuPengendaliDetailTmp=kartuPengendaliDetailDao.findByNoRec(vo.getNoRecDetailKartuPengendali());
		if(CommonUtil.isNotNullOrEmpty(vo.getSupplierId())){
			kartuPengendaliDetailTmp.setSupplier(rekananDao.findOne(vo.getSupplierId()));
		}
		kartuPengendaliDetailTmp.setHargaSupplier(vo.getHargaPenawaranSupplier());
		kartuPengendaliDetailDao.save(kartuPengendaliDetailTmp);
		result.put("noRec", kartuPengendaliDetailTmp.getNoRec());
		strukRekapPemenang(kartuPengendaliDetailTmp);
		return result;

	}
	
	//Mengelompokkan Kartu Pengendali Detail By strukRekapPemenang
	private void strukRekapPemenang(KartuPengendaliDetail kartuPengendaliDetailTmp) {
		KartuPengendaliDetail kartuPengendaliDetail=kartuPengendaliDetailDao.findByNoRec(kartuPengendaliDetailTmp.getNoRec());
		KartuPengendali kartuPengendali=kartuPengendaliDetail.getKartuPengendali();
		for(Rekanan supplier:kartuPengendaliDetailDao.findSupplierBykartuPengendaliDetail(kartuPengendali.getNoRec())){
			if(CommonUtil.isNotNullOrEmpty(supplier)){
				for(KartuPengendaliDetail detail:kartuPengendaliDetailDao.findBySupplierAndKartuPengendaliHeaderList(kartuPengendali.getNoRec(),supplier.getId())){
					List<StrukRekapPemenang> strukRekapPemenangList=strukRekapPemenangDao.findBySupplierAndKartuPengendali(supplier.getId(), detail.getKartuPengendali().getNoRec());
					if(CommonUtil.isNotNullOrEmpty(strukRekapPemenangList)){
						StrukRekapPemenang strukRekapPemenang=strukRekapPemenangList.get(0);
						detail.setStrukRekapPemenang(strukRekapPemenang);
						kartuPengendaliDetailDao.save(detail);
					}else{
						StrukRekapPemenang strukRekapPemenang=new StrukRekapPemenang();
						strukRekapPemenang.setTanggal(new Date());
						strukRekapPemenang.setKartuPengendali(kartuPengendali);
						strukRekapPemenang.setSupplier(supplier);
						strukRekapPemenang.setNoRekap(GenerateNoStrukPemanang());
						strukRekapPemenang=strukRekapPemenangDao.save(strukRekapPemenang);
						detail.setStrukRekapPemenang(strukRekapPemenang);
						kartuPengendaliDetailDao.save(detail);
					}
				}
			}
			
		}
		
	}

	//Update detail Pengadaan dari Ppk
	private void updateDetailPengadaan(KartuPengendaliDetailVO kartuPengendaliDetailVO,VerifikasiKartuPengendaliDetailVO vo) {
		DetailPengadaan detailPengadaan=detailPengadaanDao.findByParent(kartuPengendaliDetailVO.getNoRec());
		detailPengadaan.setPengadaan(pengadaanDao.findByIdPengadaan(vo.getPengadaanId()));
		detailPengadaanDao.save(detailPengadaan);
	}

	//save jadwal Dari Ppk
	private void saveJadwal(KartuPengendaliDetail kartuPengendaliDetailTmp, VerifikasiKartuPengendaliDetailVO vo) {
		KartuPengendaliDetail kartuPengendaliDetail=kartuPengendaliDetailDao.findByNoRec(kartuPengendaliDetailTmp.getNoRec());
		KartuPengendali kartuPengendali=kartuPengendaliDetail.getKartuPengendali();
		for(MetodePengadaanSubDetail metodePengadaanSubDetail:metodePengadaanSubDetailDao.findByParent(vo.getMetodePengadaanDetailId())){
			MapKartuPengendaliToMetodeSubDetail model=new MapKartuPengendaliToMetodeSubDetail();
			model.setKartuPengendali(kartuPengendali);
			model.setMetodePengadaanSubDetail(metodePengadaanSubDetail);
			mapKartuPengendaliToMetodeSubDetailDao.save(model);
		}
		
	}

	// Paging List Untuk Kartu Pengendalai
	@Override
	public Map<String, Object> preAddPenerimaan(Integer page, Integer limit, String sort, String dir,String dateStart, String dateEnd, Integer supplierId) {
		KelompokUser kelompokUser=getKelompokUserLogin();
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String,Object>> listData=new ArrayList<Map<String,Object>>();
		for(Map<String, Object> data:kartupengendaliDaoCustom.preAddPphpList(dateStart, dateEnd, supplierId)){
			if(!strukPelayananDetailDaoCustom.CheckLogistikTerhadapPphp((String) data.get("noRec"))){
				if(kelompokUser.getKelompokUser().equalsIgnoreCase("logistik")){
					data.put("jenisPenerimaan", "logistik");
				}else if(kelompokUser.getKelompokUser().equalsIgnoreCase("bagianUmum")){
					data.put("jenisPenerimaan", "bagianUmum");
				}
				listData.add(data);
			}
			
		}
		result.put("data", listData);
		return result;
	}
	
	// get Struk Rekap
	@Override
	public Map<String, Object> getStrukRekap(String noRec) {
		Map<String, Object> result = new HashMap<String, Object>();
		Pageable topOne = new PageRequest(0, 1);
		List<Map<String,Object>> r=strukRekapPemenangDao.findByNoRec(noRec,topOne);
		if(CommonUtil.isNotNullOrEmpty(r)){
			result.put("penerimaanHeader", r.get(0));
		}else{
			result.put("penerimaanHeader", "");
		}
		List<Map<String,Object>>dataChild=new ArrayList<Map<String,Object>>();
		for(Map<String,Object>data:kartuPengendaliDetailDao.getKartuPengendaliDetailLogistik(noRec)){
			Double jumlahOrder=0.0;
			Double sisa=0.0;
			if(CommonUtil.isNotNullOrEmpty(data.get("jumlahOrder"))){
				jumlahOrder=(Double) data.get("jumlahOrder");
			}
			Double totalPenerimaan=kartuPengendaliDetailDao.getSisaPenerimaanLogistik((String) data.get("noRecStrukPelayananDetail"));
			if(CommonUtil.isNullOrEmpty(totalPenerimaan)){
				totalPenerimaan=0.0;
			}
			sisa=jumlahOrder-totalPenerimaan;
			data.put("sisa", sisa);
			if(sisa>0){
				dataChild.add(data);
			}
			
		}
		result.put("penerimaanDetail",dataChild );
		return result;
	}
	
	
	//VERIFIKASI ANGARAN Dari Detail
	@Override
	@Transactional(readOnly=false)
	public Map<String, Object> verifikasiKartuPengendaliDetailByAnggaran(VerifikasiKartuPengendaliDetailVO vo) {
		Map<String,Object> result=new HashMap<String,Object>();
		List<String> r=new ArrayList<String>();
		for(KartuPengendaliDetailVO kartuPengendaliDetailVO:vo.getKartuPengendaliDetail()){
			KartuPengendaliDetail kartuPengendaliDetail=kartuPengendaliDetailDao.findByNoRec(kartuPengendaliDetailVO.getNoRec());
			kartuPengendaliDetail.setIsActive(false);
			kartuPengendaliDetail.setIsVerifikasi(VerifikasiEnum.VERIF_PENGENDALI.getVal());
			
			kartuPengendaliDetailVO.setIsVerifikasi(VerifikasiEnum.VERIF_ANGGARAN.getVal());
			createKartuPengendaliDetailSecondRow(kartuPengendaliDetailVO,kartuPengendaliDetail);
			r.add(kartuPengendaliDetailVO.getNoRec());
			
		}
		result.put("result", r);
		return  result;
	}
	
	//Verifikasi Anggaran
	@Override
	@Transactional(readOnly=false)
	public Map<String, Object> verifikasiAnggaran(VerifikasiKartuPengendaliHeaderVO vo) {
		Map<String,Object> result=new HashMap<String,Object>();
		List<String> r=new ArrayList<String>();
		for(KartuPengendaliVO kartuPengendaliVO:vo.getKartuPengendali()){
			KartuPengendali kartuPengendali=kartupengendaliDao.findByNoRec(kartuPengendaliVO.getNoRec());
			kartuPengendali.setKeterangan(vo.getKeterangan());
			kartupengendaliDao.save(kartuPengendali);
			r.add(kartuPengendali.getNoRec());
			for(KartuPengendaliDetail detail:kartuPengendaliDetailDao.findByParent(kartuPengendaliVO.getNoRec())){
				detail.setIsVerifikasi(VerifikasiEnum.VERIF_ANGGARAN.getVal());
				detail.setKeterangan(vo.getKeterangan());
				kartuPengendaliDetailDao.save(detail);
				if(CommonUtil.isNotNullOrEmpty(detail.getDetailRup())){
					if(CommonUtil.isNotNullOrEmpty(detail.getDetailRup().getDetailSpekAnggaranId())){
						setStatusDetailSpekAnggaran(detail.getDetailRup().getDetailSpekAnggaranId(), VerifikasiEnum.VERIF_ANGGARAN.getVal());
					}
				}
			}
		}
		result.put("result", r);
		return  result;
	}
	
	
	// verikasi Direktur Terkait
	@Override
	@Transactional(readOnly = false)
	public Map<String, Object> verfikasiDirekturTerkait(VerifikasiKartuPengendaliHeaderVO vo) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<String> r = new ArrayList<String>();
		for (KartuPengendaliVO kartuPengendaliVO : vo.getKartuPengendali()) {
			KartuPengendali kartuPengendali = kartupengendaliDao.findByNoRec(kartuPengendaliVO.getNoRec());
			kartuPengendali.setKeterangan(vo.getKeterangan());
			kartupengendaliDao.save(kartuPengendali);
			r.add(kartuPengendali.getNoRec());
			for (KartuPengendaliDetail detail : kartuPengendaliDetailDao.findByParent(kartuPengendaliVO.getNoRec())) {
				detail.setIsVerifikasi(VerifikasiEnum.VERIF_DIREKTUR.getVal());
				detail.setKeterangan(vo.getKeterangan());
				kartuPengendaliDetailDao.save(detail);
				if(CommonUtil.isNotNullOrEmpty(detail.getDetailRup())){
					if(CommonUtil.isNotNullOrEmpty(detail.getDetailRup().getDetailSpekAnggaranId())){
						setStatusDetailSpekAnggaran(detail.getDetailRup().getDetailSpekAnggaranId(), VerifikasiEnum.VERIF_DIREKTUR.getVal());
					}
				}
				
			}
		}
		result.put("result", r);
		return result;
	}
	
	// verikasi pp
	@Override
	@Transactional(readOnly = false)
	public Map<String, Object> verfikasiPp(VerifikasiKartuPengendaliHeaderVO vo) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<String> r = new ArrayList<String>();
		for (KartuPengendaliVO kartuPengendaliVO : vo.getKartuPengendali()) {
			KartuPengendali kartuPengendali = kartupengendaliDao.findByNoRec(kartuPengendaliVO.getNoRec());
			kartuPengendali.setKeterangan(vo.getKeterangan());
			kartupengendaliDao.save(kartuPengendali);
			r.add(kartuPengendali.getNoRec());
			for (KartuPengendaliDetail detail : kartuPengendaliDetailDao.findByParent(kartuPengendaliVO.getNoRec())) {
				detail.setIsVerifikasi(VerifikasiEnum.VERIF_PP.getVal());
				detail.setKeterangan(vo.getKeterangan());
				kartuPengendaliDetailDao.save(detail);
				if (CommonUtil.isNotNullOrEmpty(detail.getDetailRup())) {
					if (CommonUtil.isNotNullOrEmpty(detail.getDetailRup().getDetailSpekAnggaranId())) {
						setStatusDetailSpekAnggaran(detail.getDetailRup().getDetailSpekAnggaranId(),VerifikasiEnum.VERIF_PP.getVal());
					}
				}

			}
		}
		result.put("result", r);
		return result;
	}
	
	// verikasi ulp
	@Override
	@Transactional(readOnly = false)
	public Map<String, Object> verfikasiULP(VerifikasiKartuPengendaliHeaderVO vo) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<String> r = new ArrayList<String>();
		for (KartuPengendaliVO kartuPengendaliVO : vo.getKartuPengendali()) {
			KartuPengendali kartuPengendali = kartupengendaliDao.findByNoRec(kartuPengendaliVO.getNoRec());
			kartuPengendali.setKeterangan(vo.getKeterangan());
			kartupengendaliDao.save(kartuPengendali);
			r.add(kartuPengendali.getNoRec());
			for (KartuPengendaliDetail detail : kartuPengendaliDetailDao.findByParent(kartuPengendaliVO.getNoRec())) {
				detail.setIsVerifikasi(VerifikasiEnum.VERIF_ULP.getVal());
				detail.setKeterangan(vo.getKeterangan());
				kartuPengendaliDetailDao.save(detail);
				if (CommonUtil.isNotNullOrEmpty(detail.getDetailRup())) {
					if (CommonUtil.isNotNullOrEmpty(detail.getDetailRup().getDetailSpekAnggaranId())) {
						setStatusDetailSpekAnggaran(detail.getDetailRup().getDetailSpekAnggaranId(),VerifikasiEnum.VERIF_ULP.getVal());
					}
				}

			}
		}
		result.put("result", r);
		return result;
	}
	//============================================================================================================================
	//Menampilkan Kartu Pengendali Berdasarkan Norec (array)
	@Override
	public List<Map<String, Object>> kartuPengendliDetailList(String noRec) {
		String[] array = noRec.split("\\,",-1); 
		List<String> list = Arrays.asList(array);
		return kartuPengendaliDetailDao.kartuPengendliDetailList(list);
	}
	//====================================================================
	//update to detail spek
	public void setStatusDetailSpekAnggaran(String noRec,String value){
		DetailSpekAnggaran detailSpekAnggaran=detailSpekAnggaranDao.findById(noRec);
		if(CommonUtil.isNotNullOrEmpty(detailSpekAnggaran)){
			detailSpekAnggaran.setIsVerifikasi(value);
			detailSpekAnggaranDao.save(detailSpekAnggaran);
		}
	}
	
	// UpdateJadwal
	@Override
	@Transactional(readOnly = false)
	public Map<String, Object> updateJadwal(UpdateJadwalVO vo) {

		Map<String, Object> result = new HashMap<String, Object>();
		List<String> r = new ArrayList<String>();
		for (MapKartuPengendaliToMetodeSubDetailVO detailVo : vo.getListJadwal()) {
			MapKartuPengendaliToMetodeSubDetail model=mapKartuPengendaliToMetodeSubDetailDao.findOne(detailVo.getNoRec());
			model.setTanggalMulai(detailVo.getTanggalMulai());
			model.setTanggalSelesai(detailVo.getTanggalSelesai());
			model.setKeterangan(detailVo.getKeterangan());
			mapKartuPengendaliToMetodeSubDetailDao.save(model);
			r.add(detailVo.getNoRec());
		}
		result.put("result", r);
		return result;

	}
	
	/*/
	Generate No Usulan
	**/
	@Override
	public String GenerateNoUsulan() {
		Date dateNow=new Date();
		Integer month=DateUtil.getMonthFromDate(dateNow);
		Integer year=DateUtil.getYearFromDate(dateNow);
		Long count=kartupengendaliDao.count();
		
		String monthNow=month.toString();
		String yearNow=year.toString().substring(2, 4);
		String noOrder=null;
		
		count++;
		if(count.toString().length()==1){
			noOrder="00000";}
		else if(count.toString().length()==2){
			noOrder="0000";}
		else if(count.toString().length()==3){
			noOrder="000";}
		else if(count.toString().length()==4){
			noOrder="00";}
		else if(count.toString().length()==5){
			noOrder="0";}
		if(monthNow.length()==1)
			monthNow = "0"+monthNow;

		return yearNow+monthNow+noOrder+count;
	}
	
	@Override
	public String GenerateNoUsulanDetail(Long size){
		Date dateNow=new Date();
		Integer month=DateUtil.getMonthFromDate(dateNow);
		Integer year=DateUtil.getYearFromDate(dateNow);

		Long count = kartuPengendaliDetailDao.count()+size;
		
		String monthNow=month.toString();
		String yearNow=year.toString().substring(2, 4);
		String noOrder=null;
		
		count++;
		if(count.toString().length()==1){
			noOrder="00000";}
		else if(count.toString().length()==2){
			noOrder="0000";}
		else if(count.toString().length()==3){
			noOrder="000";}
		else if(count.toString().length()==4){
			noOrder="00";}
		else if(count.toString().length()==5){
			noOrder="0";}
		if(monthNow.length()==1)
			monthNow = "0"+monthNow;

		return yearNow+monthNow+noOrder+count;
	}
	
	//No Struk Pemenang
	public String GenerateNoStrukPemanang() {
		Date dateNow=new Date();
		Integer month=DateUtil.getMonthFromDate(dateNow);
		Integer year=DateUtil.getYearFromDate(dateNow);
		Long count=strukRekapPemenangDao.count();
		
		String monthNow=month.toString();
		String yearNow=year.toString().substring(2, 4);
		String noOrder=null;
		
		count++;
		if(count.toString().length()==1){
			noOrder="00000";}
		else if(count.toString().length()==2){
			noOrder="0000";}
		else if(count.toString().length()==3){
			noOrder="000";}
		else if(count.toString().length()==4){
			noOrder="00";}
		else if(count.toString().length()==5){
			noOrder="0";}
		if(monthNow.length()==1)
			monthNow = "0"+monthNow;

		return yearNow+monthNow+noOrder+count;
	}

	public String terbilang(Double value){
		long intValue = value.intValue();
		String result = IndonesianNumberToWords.convert(intValue);
		return result;
	}

	@Override
	public Map<String, Object> metodePengadaanDetail(Integer noRec) {
		Map<String,Object> result=new HashMap<String,Object>();
		result.put("data",metodePengadaanDetailDao.findByParent(noRec));
		return result;
	}

	@Override
	public String generateTemplateExcel(String noRec) throws FileNotFoundException {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		// Create
		// blank
		// workbook
		HSSFWorkbook workbook = new HSSFWorkbook();
		// Create a blank sheet
		HSSFSheet spreadsheet = workbook.createSheet(" LELANG OBAT");
		// Create row object
		HSSFRow row;
		// This data needs to be written (Object[])
		Map<String, Object[]> empinfo = new TreeMap<String, Object[]>();

		CellStyle style = workbook.createCellStyle();
		style.setFillForegroundColor(IndexedColors.AQUA.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		Font font = workbook.createFont();
		font.setColor(IndexedColors.BLACK.getIndex());
		//font.setBold(true);
		style.setFont(font);
		style.setWrapText(true);

		CellStyle styleIsi = workbook.createCellStyle();
		Font fontIsi = workbook.createFont();
		fontIsi.setColor(IndexedColors.BLACK.getIndex());
		//fontIsi.setBold(false);
		fontIsi.setFontName("Arial");
		fontIsi.setFontHeightInPoints((short) 8);
		styleIsi.setFont(fontIsi);
		styleIsi.setWrapText(true);
		
		CellStyle hiddenstyle =workbook.createCellStyle();
		hiddenstyle.setHidden(true);
		
		List<Map<String,Object>> dataDb=kartupengendaliDaoCustom.generateTemplateExel(noRec);

		empinfo.put("000001", new Object[] { "", "", "LAMPIRAN SURAT PENAWARAN HARGA OBAT TAHUN 2016 ", "","","","","","","","" });
		empinfo.put("000002", new Object[] { "", "", "TAHUN 2016", "","","","","","" });
		empinfo.put("000003", new Object[] { "", "", "", "","","","","","" });
		empinfo.put("000004", new Object[] { "","No Record","No","Nama Obat","Spesifikasi", "Nama Dagang", "Kemasan","isi Kemasan","Harga Satuan Terkecil","Generik / Generik Bermerek" });
		Long count=new Long(5);
		Integer noCount=1;
		for(Map<String,Object> obj:dataDb){
			String headNoRec="";
			String headNamaProduk="";
			String headSpesifikasi="";
			if(CommonUtil.isNotNullOrEmpty(obj.get("noRec"))){
				headNoRec=obj.get("noRec").toString();
			}
			if(CommonUtil.isNotNullOrEmpty(obj.get("namaProduk"))){
				headNamaProduk=obj.get("namaProduk").toString();
			}
			if(CommonUtil.isNotNullOrEmpty(obj.get("spesifikasi"))){
				headSpesifikasi=obj.get("spesifikasi").toString();
			}
			empinfo.put(generateKey(count), new Object[] {"",headNoRec, noCount.toString(), headNamaProduk, headSpesifikasi });
			count++;
			noCount++;
		}

		// Iterate over data and write to sheet
		Set<String> keyid = empinfo.keySet();
		int rowid = 0;
		for (String key : keyid) {
			row = spreadsheet.createRow(rowid++);
			Object[] objectArr = empinfo.get(key);
			int cellid = 0;
			for (Object obj : objectArr) {

				Cell cell = row.createCell(cellid++);
				if (key.equalsIgnoreCase("000004") && cellid != 1 && cellid!=2) {
					cell.setCellStyle(style);

				}else if(cellid==2){
					cell.getCellStyle().setHidden(false);
				}else {
					cell.setCellStyle(styleIsi);
				}
				cell.setCellValue((String) obj);
			}
		}
		spreadsheet.setColumnWidth(0, 100);
		spreadsheet.setColumnWidth(1, 10);
		spreadsheet.setColumnWidth(2, 3500);
		spreadsheet.setColumnWidth(3, 7500);
		spreadsheet.setColumnWidth(4, 7500);
		spreadsheet.setColumnWidth(5, 7500);
		spreadsheet.setColumnWidth(6, 4000);
		spreadsheet.setColumnWidth(7, 4000);
		spreadsheet.setColumnWidth(8, 7500);
		spreadsheet.setColumnWidth(9, 7500);
		spreadsheet.addMergedRegion(new CellRangeAddress(0, 0, 2, 4));
		// Write the workbook in file system
		String fileName=reportDirectory+ UUID.randomUUID().toString().replaceAll("-", "")+".xls";
		FileOutputStream out = new FileOutputStream(fileName);
		try {
			workbook.write(out);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return fileName;
	}
	
	public String generateKey(Long count){
		String noOrder="";
		if(count.toString().length()==1){
			noOrder="00000";}
		else if(count.toString().length()==2){
			noOrder="0000";}
		else if(count.toString().length()==3){
			noOrder="000";}
		else if(count.toString().length()==4){
			noOrder="00";}
		else if(count.toString().length()==5){
			noOrder="0";}
		return noOrder+count;
	}
	
	
	@Override
	public Map<String, Object> uploadExel(UploadExcelVO vo) throws IOException {
		byte[] decodedBytes = Base64.decodeBase64(vo.getFileInput());
		String targetFile = reportDirectory+ UUID.randomUUID().toString().replaceAll("-", "")+".xls";
		writeByteArraysToFile(targetFile, decodedBytes);

		List<PenawaranHargaSupplierVO> listBooks = new ArrayList<>();
		try {

			FileInputStream file = new FileInputStream(new File(targetFile));

			// Get the workbook instance for XLS file
			HSSFWorkbook workbook = new HSSFWorkbook(file);

			// Get first sheet from the workbook
			HSSFSheet sheet = workbook.getSheetAt(0);

			// Iterate through each rows from first sheet
			Iterator<Row> rowIterator = sheet.iterator();
			while (rowIterator.hasNext()) {
				Row row = rowIterator.next();
				if(row.getRowNum()==0){
					
				}else if(row.getRowNum()==1){
					
				}else if(row.getRowNum()==2){
					
				}else if(row.getRowNum()==3){
					
				}else{

					Iterator<Cell> cellIterator = row.cellIterator();
					PenawaranHargaSupplierVO hps = new PenawaranHargaSupplierVO();
					while (cellIterator.hasNext()) {
						Cell nextCell = cellIterator.next();
						int columnIndex = nextCell.getColumnIndex();
						
						if(CommonUtil.isNotNullOrEmpty(getCellValue(nextCell))){
							switch (columnIndex) {
							case 1:
								hps.setNoRec((String) getCellValue(nextCell));
								break;
							case 2:
								hps.setNo((String) getCellValue(nextCell));
								break;
							case 3:
								hps.setNamaObat((String) getCellValue(nextCell));
								break;
							case 4:
								hps.setSpesifikasi((String) getCellValue(nextCell));
								break;
							case 5:
								hps.setNamaDagang((String) getCellValue(nextCell));
								break;
							case 6:
								hps.setKemasan((String) getCellValue(nextCell));
								break;
							case 7:
								hps.setIsiKemasan((Double) getCellValue(nextCell));
								break;
							case 8:
								hps.setHargaSatuanTerkecil((Double) getCellValue(nextCell));
								break;
							case 9:
								hps.setTipeObat((String) getCellValue(nextCell));
								break;
							}
						}

					}
					listBooks.add(hps);
				
				}
				
			}
			file.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Map<String, Object> r = new HashMap<String, Object>();
		r.put("data", listBooks);
		return r;
	}

	private Object getCellValue(Cell cell) {
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_STRING:
			return cell.getStringCellValue();

		case Cell.CELL_TYPE_BOOLEAN:
			return cell.getBooleanCellValue();

		case Cell.CELL_TYPE_NUMERIC:
			return cell.getNumericCellValue();
		}

		return null;
	}
	
	public static void writeByteArraysToFile(String fileName, byte[] content) throws IOException {

		File file = new File(fileName);
		BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(file));
		writer.write(content);
		writer.flush();
		writer.close();

	}
	
	@Override
	public Map<String, Object> savePenawaranHargaSupplier(PenawaranHargaVO vo) throws IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		PenawaranHarga penawaranHarga=new PenawaranHarga();
		penawaranHarga.setTanggal(new Date());
		if(CommonUtil.isNotNullOrEmpty(vo.getSupplier())){
			penawaranHarga.setSupplier(rekananConverter.transferVOToModel(vo.getSupplier(), new Rekanan()));
		}
		List<PenawaranHargaSupplier> newList=new ArrayList<PenawaranHargaSupplier>();
		for (PenawaranHargaSupplierVO penawaranHargaSupplierVO : vo.getPenawaranHargaSupplier()) {
			PenawaranHargaSupplier penawaranHargaSupplier =new PenawaranHargaSupplier();
			penawaranHargaSupplier.setKemasan(penawaranHargaSupplierVO.getKemasan());
			penawaranHargaSupplier.setHargaSatuanTerkecil(penawaranHargaSupplierVO.getHargaSatuanTerkecil());
			penawaranHargaSupplier.setNamaDagang(penawaranHargaSupplierVO.getNamaDagang());
			penawaranHargaSupplier.setNo(penawaranHargaSupplierVO.getNo());
			penawaranHargaSupplier.setIsiKemasan(penawaranHargaSupplierVO.getIsiKemasan());
			penawaranHargaSupplier.setTipeObat(penawaranHargaSupplierVO.getTipeObat());
			penawaranHargaSupplier.setSpesifikasi(penawaranHargaSupplierVO.getSpesifikasi());
			penawaranHargaSupplier.setPenawaranHarga(penawaranHarga);
			if(CommonUtil.isNotNullOrEmpty(penawaranHargaSupplierVO.getNoRec())){
				penawaranHargaSupplier.setKartuPengendaliDetail(kartuPengendaliDetailDao.findByNoRec(penawaranHargaSupplierVO.getNoRec()));
			}
			newList.add(penawaranHargaSupplier);
			
		}
		penawaranHarga.getPenawaranHargaSupplier().clear();
		penawaranHarga.getPenawaranHargaSupplier().addAll(newList);
		penawaranHarga=penawaranHargaDao.save(penawaranHarga);
		result.put("result", penawaranHarga.getNoRec());
		return result;

	
	}
	
	// Detail Kartu Pengendali By No Rc dan penawaraan Harga supplier
	@Override
	public Map<String, Object> preRekapPemenang(String noRec) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("kartuPengendaliDetail", kartuPengendaliDetailDao.findByNoRecMap(noRec));
		result.put("penerimaanDetail", penawaranHargaSupplierDao.findByKartuPengendaliDetail(noRec));
		return result;
	}
	
	// Paging List Untuk Kartu Header
	@Override
	public Map<String, Object> listKontrakGrid(Integer page, Integer limit, String sort, String dir,String dateStart, String dateEnd,Integer supplierId,Integer tahun) {
		KelompokUser kelompokUser=getKelompokUserLogin();
		int totalRow = kartupengendaliDaoCustom.listKontrakCount(sort, dateStart, dateEnd, supplierId, kelompokUser, tahun);
		int totalPages = 0;

		int pageRequested = page;

		if (totalRow > 0) {
			totalPages = (int) Math.ceil((double) totalRow / (double) limit);
		} else {
			totalPages = 0;
		}

		if (pageRequested > totalPages)
			pageRequested = totalPages;
		int rowStart = pageRequested * limit - limit;
		if (rowStart < 0) {
			rowStart = 0;
		}
		int rowEnd = limit;
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, Object>> tmpMap = new ArrayList<Map<String, Object>>();
		result.put("data", kartupengendaliDaoCustom.listKontrakGrid(rowStart, rowEnd, sort, dir, dateStart, dateEnd, supplierId, kelompokUser, tahun));
		result.put("totalPages", totalPages);
		result.put("totalRow", totalRow);
		return result;
	}
	
	
	
	
	
	/*	
	public void createSpek(VerifikasiKartuPengendaliDetailVO verifikasiKartuPengendaliDetailVO){
		for(KartuPengendaliDetailVO vo:verifikasiKartuPengendaliDetailVO.getKartuPengendaliDetail()){
			KartuPengendaliDetail model=kartuPengendaliDetailDao.findById(vo.getNoRec());
			createKartuPengendaliDetail(vo, model);
		}
	}
*/
	
	/*@Override
	public KartuPengendaliDetailVO updateKartuPengendali(KartuPengendaliDetailVO vo){
		KartuPengendaliDetail model = kartuPengendaliDetailDao.findOne(vo.getNoRec());
		model = kartuPengendaliDetailConverter.transferVOToModel(vo, model);
		kartuPengendaliDetailDao.save(model);
		return vo;
	}*/
	
	/*@Override
	@Transactional(readOnly=false)
	public Map<String, Object> verifikasiKartuPengendaliDetail(KartuPengendaliDetailVO vo) {
		KartuPengendaliDetail kartuPengendaliDetail=kartuPengendaliDetailDao.findByNoRec(vo.getNoRec());
		kartuPengendaliDetail.setIsActive(false);
		kartuPengendaliDetail.setIsVerifikasi(VerifikasiEnum.VERIF_ANGGARAN.getVal());
		
		Map<String,Object> result=new HashMap<String,Object>();
		result.put("noRec", kartuPengendaliDetail.getNoRec());
		vo.setIsVerifikasi(VerifikasiEnum.VERIF_PPK.getVal());
		createKartuPengendaliDetailSecondRow(vo,kartuPengendaliDetail);
		return result;
	}*/

}
