package com.jasamedika.medifirst2000.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.stereotype.Service;

import com.jasamedika.medifirst2000.constants.Master;
import com.jasamedika.medifirst2000.converter.BaseConverterImpl;
import com.jasamedika.medifirst2000.dao.LogbookKinerjaDao;
import com.jasamedika.medifirst2000.dao.LogbookKinerjaDetailDao;
import com.jasamedika.medifirst2000.dao.SettingDataFixedDao;
import com.jasamedika.medifirst2000.entities.LogbookKinerja;
import com.jasamedika.medifirst2000.entities.LogbookKinerjaDetail;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.LogbookKinerjaDetailService;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.util.DateUtil;
import com.jasamedika.medifirst2000.vo.LogbookKinerjaDetailVO;

@Service("LogbookKinerjaDetailService")
public class LogbookKinerjaDetailServiceImpl extends BaseVoServiceImpl implements LogbookKinerjaDetailService {

	@Autowired
	private BaseConverterImpl<LogbookKinerjaDetailVO, LogbookKinerjaDetail> logbookKinerjaDetailConverter;

	@Autowired
	private SettingDataFixedDao settingDataFixedDao;

	@Autowired
	private LogbookKinerjaDao logbookKinerjaDao;

	@Autowired
	private LogbookKinerjaDetailDao logbookKinerjaDetailDao;

	@Override
	public LogbookKinerjaDetailVO add(LogbookKinerjaDetailVO vo) throws JpaSystemException, ServiceVOException {
		LogbookKinerja logbookKinerja = logbookKinerjaDao.findOne(vo.getLogbookKinerja().getNoRec());

		LogbookKinerjaDetail logbookKinerjaDetail = logbookKinerjaDetailConverter.transferVOToModel(vo,
				new LogbookKinerjaDetail());

		logbookKinerjaDetail.setLogbookKinerja(logbookKinerja);
		logbookKinerjaDetail.setTanggalKegiatan(new Date());

		logbookKinerjaDao.save(logbookKinerja);

		LogbookKinerjaDetail resultModel = logbookKinerjaDetailDao.save(logbookKinerjaDetail);
		if (CommonUtil.isNotNullOrEmpty(resultModel)) {
			/**
			 * menghitung capaian indikator satuan yang harus dihitung secara
			 * akumulatif
			 */
			List<Map<String, Object>> dataSatuanJumlah = logbookKinerjaDetailDao.findSumCapaianByKontrak(
					vo.getLogbookKinerja().getNoRec(), Arrays.asList(Master.SatuanIndikator.PERCENTAGE));
			if (CommonUtil.isNotNullOrEmpty(dataSatuanJumlah)) {
				List<LogbookKinerja> models = new ArrayList<>();
				for (Map<String, Object> map : dataSatuanJumlah) {
					LogbookKinerja model = logbookKinerjaDao.findOne(map.get("logbookId").toString());
					model.setCapaian(Double.valueOf(map.get("sumCapaian").toString()));
					models.add(model);
				}
				logbookKinerjaDao.save(models);
			}

			/**
			 * menghitung capaian indikator satuan yang harus dihitung secara
			 * rata-rata
			 */
			List<Map<String, Object>> dataSatuanRatarata = logbookKinerjaDetailDao.findAvgCapaianByKontrak(
					vo.getLogbookKinerja().getNoRec(), Arrays.asList(Master.SatuanIndikator.PERCENTAGE));
			if (CommonUtil.isNotNullOrEmpty(dataSatuanRatarata)) {
				List<LogbookKinerja> models = new ArrayList<>();
				for (Map<String, Object> map : dataSatuanRatarata) {
					LogbookKinerja model = logbookKinerjaDao.findOne(map.get("logbookId").toString());
					model.setCapaian(Double.valueOf(map.get("avgCapaian").toString()));
					models.add(model);
				}
				logbookKinerjaDao.save(models);
			}
		}

		LogbookKinerjaDetailVO resultVO = new LogbookKinerjaDetailVO();
		resultVO = logbookKinerjaDetailConverter.transferModelToVO(resultModel, resultVO);

		return resultVO;
	}

	@Override
	public LogbookKinerjaDetailVO update(LogbookKinerjaDetailVO vo) throws JpaSystemException, ServiceVOException {
		LogbookKinerja logbookKinerja = logbookKinerjaDao.findOne(vo.getLogbookKinerja().getNoRec());
		LogbookKinerjaDetail logbookKinerjaDetailLama = logbookKinerjaDetailDao.findOne(vo.getNoRec());

		/**
		 * menghitung indikator capaian satuan yang harus dihitung secara
		 * akumulatif
		 */
		if (!vo.getStatusEnabled() && !vo.getStatusVerifikasi()) {
			logbookKinerja.setCapaian(logbookKinerja.getCapaian() - vo.getCapaian());
		} else if (vo.getStatusEnabled() && vo.getStatusVerifikasi()) {
			logbookKinerja.setCapaian(logbookKinerja.getCapaian() + vo.getCapaian());
		}

		LogbookKinerjaDetail logbookKinerjaDetailBaru = logbookKinerjaDetailConverter.transferVOToModel(vo,
				logbookKinerjaDetailLama);

		logbookKinerjaDetailBaru.setLogbookKinerja(logbookKinerja);

		logbookKinerjaDao.save(logbookKinerja);
		LogbookKinerjaDetail resultModel = logbookKinerjaDetailDao.save(logbookKinerjaDetailBaru);

		/**
		 * menghitung capaian indikator satuan yang harus dihitung secara
		 * rata-rata
		 */
		if (CommonUtil.isNotNullOrEmpty(resultModel)) {
			List<Map<String, Object>> dataSatuanRatarata = logbookKinerjaDetailDao.findAvgCapaianByKontrak(
					vo.getLogbookKinerja().getNoRec(), Arrays.asList(Master.SatuanIndikator.PERCENTAGE));
			if (CommonUtil.isNotNullOrEmpty(dataSatuanRatarata)) {
				List<LogbookKinerja> models = new ArrayList<>();
				for (Map<String, Object> map : dataSatuanRatarata) {
					LogbookKinerja model = logbookKinerjaDao.findOne(map.get("logbookId").toString());
					model.setCapaian(Double.valueOf(map.get("avgCapaian").toString()));
					models.add(model);
				}
				logbookKinerjaDao.save(models);
			}
		}

		LogbookKinerjaDetailVO resultVO = new LogbookKinerjaDetailVO();
		resultVO = logbookKinerjaDetailConverter.transferModelToVO(resultModel, resultVO);

		return resultVO;
	}

	@Override
	public Boolean delete(String key) throws JpaSystemException {
		logbookKinerjaDetailDao.delete(key);

		return true;
	}

	@Override
	public LogbookKinerjaDetailVO findById(String key) throws JpaSystemException {
		LogbookKinerjaDetailVO result = new LogbookKinerjaDetailVO();

		LogbookKinerjaDetail logbookKinerjaDetail = logbookKinerjaDetailDao.findOne(key);
		if (CommonUtil.isNotNullOrEmpty(logbookKinerjaDetail)) {
			result = logbookKinerjaDetailConverter.transferModelToVO(logbookKinerjaDetail, result);
		}

		return result;
	}

	@Override
	public List<LogbookKinerjaDetailVO> findAll() throws JpaSystemException {
		List<LogbookKinerjaDetailVO> result = new ArrayList<LogbookKinerjaDetailVO>();

		Iterable<LogbookKinerjaDetail> models = logbookKinerjaDetailDao.findAll();
		if (CommonUtil.isNotNullOrEmpty(models)) {
			for (LogbookKinerjaDetail model : models) {
				LogbookKinerjaDetailVO vo = new LogbookKinerjaDetailVO();
				vo = logbookKinerjaDetailConverter.transferModelToVO(model, vo);
				result.add(vo);
			}
		}

		return result;
	}

	@Override
	public Map<String, Object> findAllWithPageAndLimitAndSortByAndDirectionParameter(Integer page, Integer limit,
			String sort, String dir) throws JpaSystemException {

		return null;
	}

	@Override
	public List<Map<String, Object>> findWorkingRecord(Integer idPegawai, Integer idJabatan, Long bulan,
			Boolean statusVerif) throws JpaSystemException {
		DateFormat df = new SimpleDateFormat("yyyy-MM");
		Date start = DateUtil.startMonth(bulan);
		Date end = DateUtil.endMonth(bulan);

		String strTglLimitVerif = settingDataFixedDao.getSettingDataFixed("tglLimitVerifWorkingRecord");
		LocalDateTime tglLimitVerif = LocalDateTime
				.of(LocalDate.parse(df.format(new Date(bulan)) + strTglLimitVerif).plusMonths(1), LocalTime.MAX);

		List<Map<String, Object>> result = logbookKinerjaDetailDao.findWorkingRecord(idPegawai, idJabatan, start, end,
				statusVerif);
		for (Map<String, Object> map : result) {
			Map<String, Object> logbook = new HashMap<String, Object>();
			logbook.put("noRec", map.get("logbookNoRec"));
			map.put("logbookKinerja", logbook);
			map.put("tglBatasAkhirVerif", Date.from(tglLimitVerif.atZone(ZoneId.systemDefault()).toInstant()));
			map.remove("logbookNoRec");
		}

		return result;
	}

	@Override
	public List<Map<String, Object>> findWorkingRecord(Integer idPegawai, Integer idJabatan, Integer idIndikator,
			Long bulan) throws JpaSystemException {
		Date start = DateUtil.startMonth(bulan);
		Date end = DateUtil.endMonth(bulan);

		List<Map<String, Object>> result = logbookKinerjaDetailDao.findWorkingRecord(idPegawai, idJabatan, idIndikator,
				start, end);
		for (Map<String, Object> map : result) {
			Map<String, Object> logbook = new HashMap<String, Object>();
			logbook.put("noRec", map.get("logbookNoRec"));
			map.put("logbookKinerja", logbook);
			map.remove("logbookNoRec");
		}

		return result;
	}

	@Override
	public List<Map<String, Object>> findAksesPegawai(Integer idPegawai) throws JpaSystemException {
		List<Map<String, Object>> result = logbookKinerjaDao.findAksesPegawaiByAtasan(idPegawai,
				Arrays.asList(Master.KategoryPegawai.PURNA_WAKTU));

		if (CommonUtil.isNotNullOrEmpty(result)) {
			result.sort(Comparator.comparing(m -> (String) m.get("namaLengkap"), String.CASE_INSENSITIVE_ORDER));
		}

		return result;
	}

	@Override
	public Map<String, Object> findWidgetStatusVerifikasi(Integer idPegawai, Long bulan) throws JpaSystemException {
		Map<String, Object> result = new HashMap<>();
		Map<String, Object> rsMap1 = new HashMap<>();
		Map<String, Object> rsMap2 = new HashMap<>();

		DateFormat mf = new SimpleDateFormat("yyyy-MM");

		List<Integer> listKategoriPegawaiWorkingRecord = new ArrayList<>();
		listKategoriPegawaiWorkingRecord.addAll(Arrays.asList(Master.KategoryPegawai.REMUN));
		listKategoriPegawaiWorkingRecord.add(Master.KategoryPegawai.BLU_PKWT);

		List<Map<String, Object>> tugasVerifikasi = logbookKinerjaDetailDao.findVerifWorkingRecord(idPegawai,
				mf.format(new Date(bulan)), listKategoriPegawaiWorkingRecord, Arrays.asList(Master.UnitKerja.KSM));
		if (CommonUtil.isNotNullOrEmpty(tugasVerifikasi) && tugasVerifikasi.size() == 2) {
			for (Map<String, Object> tv : tugasVerifikasi) {
				if (Boolean.valueOf(tv.get("statusVerifikasi").toString())) {
					rsMap1.put("sudahDiverifikasi", tv.get("jumlah"));
				} else {
					rsMap1.put("belumDiverifikasi", tv.get("jumlah"));
				}
			}
		} else if (CommonUtil.isNotNullOrEmpty(tugasVerifikasi) && tugasVerifikasi.size() == 1) {
			for (Map<String, Object> tv : tugasVerifikasi) {
				if (Boolean.valueOf(tv.get("statusVerifikasi").toString())) {
					rsMap1.put("sudahDiverifikasi", tv.get("jumlah"));
					rsMap1.put("belumDiverifikasi", 0);
				} else {
					rsMap1.put("sudahDiverifikasi", 0);
					rsMap1.put("belumDiverifikasi", tv.get("jumlah"));
				}
			}
		} else {
			rsMap1.put("sudahDiverifikasi", 0);
			rsMap1.put("belumDiverifikasi", 0);
		}
		result.put("tugasVerifikasi", rsMap1);

		List<Map<String, Object>> statusVerifikasi = logbookKinerjaDetailDao.findVerifWorkingRecord(idPegawai,
				mf.format(new Date(bulan)), listKategoriPegawaiWorkingRecord);
		if (CommonUtil.isNotNullOrEmpty(statusVerifikasi) && statusVerifikasi.size() == 2) {
			for (Map<String, Object> sv : statusVerifikasi) {
				if (Boolean.valueOf(sv.get("statusVerifikasi").toString())) {
					rsMap2.put("sudahDiverifikasi", sv.get("jumlah"));
				} else {
					rsMap2.put("belumDiverifikasi", sv.get("jumlah"));
				}
			}
		} else if (CommonUtil.isNotNullOrEmpty(statusVerifikasi) && statusVerifikasi.size() == 1) {
			for (Map<String, Object> sv : statusVerifikasi) {
				if (Boolean.valueOf(sv.get("statusVerifikasi").toString())) {
					rsMap2.put("sudahDiverifikasi", sv.get("jumlah"));
					rsMap2.put("belumDiverifikasi", 0);
				} else {
					rsMap2.put("sudahDiverifikasi", 0);
					rsMap2.put("belumDiverifikasi", sv.get("jumlah"));
				}
			}
		} else {
			rsMap2.put("sudahDiverifikasi", 0);
			rsMap2.put("belumDiverifikasi", 0);
		}
		result.put("statusVerifikasi", rsMap2);

		return result;
	}

}
