package com.jasamedika.medifirst2000.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jasamedika.medifirst2000.converter.BaseConverterImpl;
import com.jasamedika.medifirst2000.converter.ProdukConverter;
import com.jasamedika.medifirst2000.dao.OrderPelayananDao;
import com.jasamedika.medifirst2000.dao.ProdukDao;
import com.jasamedika.medifirst2000.dao.RuanganDao;
import com.jasamedika.medifirst2000.dao.RunningNumberDao;
import com.jasamedika.medifirst2000.dao.StrukOrderDao;
import com.jasamedika.medifirst2000.entities.MappingPegawaiKendaraanDinas;
import com.jasamedika.medifirst2000.entities.OrderPelayanan;
import com.jasamedika.medifirst2000.entities.Pegawai;
import com.jasamedika.medifirst2000.entities.Produk;
import com.jasamedika.medifirst2000.entities.Ruangan;
import com.jasamedika.medifirst2000.entities.RunningNumber;
import com.jasamedika.medifirst2000.entities.StrukOrder;
import com.jasamedika.medifirst2000.enums.Status;
import com.jasamedika.medifirst2000.service.LoginUserService;
import com.jasamedika.medifirst2000.service.OrderKendaraanDinasService;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.util.DateUtil;
import com.jasamedika.medifirst2000.util.StringUtil;
import com.jasamedika.medifirst2000.vo.MappingPegawaiKendaraanDinasVO;
import com.jasamedika.medifirst2000.vo.OrderKendaraanDinasVO;
import com.jasamedika.medifirst2000.vo.OrderPelayananVO;
import com.jasamedika.medifirst2000.vo.PegawaiVO;
import com.jasamedika.medifirst2000.vo.RuanganVO;
import com.jasamedika.medifirst2000.vo.StrukOrderVO;

@Service("OrderKendaraanDinasService")
public class OrderKendaraanDinasServiceImpl extends BaseVoServiceImpl implements OrderKendaraanDinasService {

	@Autowired
	private StrukOrderDao strukOrderDao;

	@Autowired
	private OrderPelayananDao orderPelayananDao;

	@Autowired
	private ProdukDao produkDao;

	@Autowired
	private RuanganDao ruanganDao;

	@Autowired
	private RunningNumberDao runningNumberDao;

	@Autowired
	private BaseConverterImpl<StrukOrderVO, StrukOrder> strukOrderConverter;

	@Autowired
	private BaseConverterImpl<OrderPelayananVO, OrderPelayanan> orderPelayananConverter;

	@Autowired
	private LoginUserService loginUserService;

	@Autowired
	private ProdukConverter produkConverter;

	@Autowired
	private BaseConverterImpl<RuanganVO, Ruangan> ruanganConverter;

	@Autowired
	private BaseConverterImpl<PegawaiVO, Pegawai> petugasConverter;

	@Autowired
	private BaseConverterImpl<MappingPegawaiKendaraanDinasVO, MappingPegawaiKendaraanDinas> mappingKendaraanDinasConverter;

//	@Transactional(readOnly = false)
	private String getRunningNumber(String kegunaan) {

		RunningNumber runningNumber = runningNumberDao.findByResetAndKegunaan("0", kegunaan);
		Integer number = (runningNumber.getNomerTerbaru() + (Integer) 1);
		runningNumber.setNomerTerbaru(runningNumber.getNomerTerbaru() + (Integer) 1);
		String noOrderIntern = StringUtil.formatNumber(number.toString(), 6);
		runningNumberDao.save(runningNumber);
		return noOrderIntern;
	}

	@Override
	public Map<String, Object> saveOrderKendaraanDinas(OrderKendaraanDinasVO vo) {

		Map<String, Object> result = new HashMap<String, Object>();
		SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");

		try {
			System.out.println("==================START SAVE ORDER KENDARAAN DINAS======================");
			if (CommonUtil.isNotNullOrEmpty(vo.getStrukOrder())) {
				System.out.println(":::START STRUK ORDER:::");
				StrukOrder strukOrder = strukOrderConverter.transferVOToModel(vo.getStrukOrder(), new StrukOrder());
				// set no order kendaraan dinas
				strukOrder.setNoOrder(StringUtil
						.formatNumber(String.valueOf(strukOrderDao.getCountByMonthAndYear(new Date()) + 1), 10));
				strukOrder.setNoOrderIntern("KD" + generateNoOrderByDayMonthAndYear(vo));
				// Konversi dari string ke tanggal
				Date TglCheckIn = df.parse(df.format(strukOrder.getTglPelayananAwal()));
				Date tglCheckOut = df.parse(df.format(strukOrder.getTglPelayananAkhir()));
				// Tanggal di konversi ke milidetik
				long Hari1 = TglCheckIn.getTime();
				long Hari2 = tglCheckOut.getTime();
				long diff = Hari2 - Hari1;
				long Lama = diff / (24 * 60 * 60 * 1000);
				strukOrder.setLamaSewa(Long.toString(Lama) + "" + " Hari");
				// get unit pemesan
				if (CommonUtil.isNotNullOrEmpty(vo.getStrukOrder().getUnitPemesan())) {
					strukOrder.setUnitPemesan(
							ruanganConverter.transferVOToModel(vo.getStrukOrder().getUnitPemesan(), new Ruangan()));
				}
				strukOrder.setStatus(Status.ORDER.getVal());
				strukOrder.setQtyJenisProduk(1.0);
				strukOrder.setQtyProduk(1.0);
				strukOrder.setTotalBeaMaterai(0.0);
				strukOrder.setTotalHargaSatuan(0.0);
				strukOrder.setTotalBiayaKirim(0.0);
				strukOrder.setTotalBiayaTambahan(0.0);
				strukOrder.setTotalDiscount(0.0);
				strukOrder.setTotalHarusDibayar(0.0);
				strukOrder.setTotalPph(0.0);
				strukOrder.setTotalPpn(0.0);
				strukOrder.setPegawaiOrder(loginUserService.getLoginUser().getPegawai());
				// get supir kendaraan dinas
				if (CommonUtil.isNotNullOrEmpty(vo.getStrukOrder().getMapPegawaiKendaraanDinas())) {
					Set<MappingPegawaiKendaraanDinas> listMapPegawaiKendaraanDinas = new HashSet<MappingPegawaiKendaraanDinas>();
					for (MappingPegawaiKendaraanDinasVO modelMapPegawaiKendaraanDinas : vo.getStrukOrder()
							.getMapPegawaiKendaraanDinas()) {
						MappingPegawaiKendaraanDinas mappingPegawaiKendaraanDinas = mappingKendaraanDinasConverter
								.transferVOToModel(modelMapPegawaiKendaraanDinas, new MappingPegawaiKendaraanDinas());
						if (CommonUtil.isNotNullOrEmpty(modelMapPegawaiKendaraanDinas.getPetugas())) {
							mappingPegawaiKendaraanDinas.setPetugas(petugasConverter
									.transferVOToModel(modelMapPegawaiKendaraanDinas.getPetugas(), new Pegawai()));
						}
						mappingPegawaiKendaraanDinas.setStrukOrder(strukOrder);
						listMapPegawaiKendaraanDinas.add(mappingPegawaiKendaraanDinas);
					}
					strukOrder.setMapPegawaiKendaraanDinas(listMapPegawaiKendaraanDinas);
				}
				strukOrder.setIsDelivered((byte) 1);
				strukOrder.setKeteranganOrder("Order Kendaraan Dinas");
				strukOrder.setTglOrder(DateUtil.getShortDate());
				if (CommonUtil.isNotNullOrEmpty(vo.getOrderPelayanan())) {
					System.out.println(":::START ORDER PELAYANAN:::");
					OrderPelayanan orderPelayanan = orderPelayananConverter.transferVOToModel(vo.getOrderPelayanan(),
							new OrderPelayanan());
					orderPelayanan.setStrukOrder(strukOrder);// set strukorderfk
					orderPelayanan.setNoOrder(strukOrder);// set noOrderfk
					orderPelayanan.setIsCito((byte) 1);
					orderPelayanan.setQtyProduk(1.0);
					orderPelayanan.setQtyProdukRetur(1.0);
					orderPelayanan.setTglPelayanan(strukOrder.getTglOrder());
					if (CommonUtil.isNotNullOrEmpty(vo.getOrderPelayanan().getRuangan())) {
						orderPelayanan.setRuangan(
								ruanganConverter.transferVOToModel(vo.getOrderPelayanan().getRuangan(), new Ruangan()));
						orderPelayanan.setRuanganTujuan(ruanganConverter
								.transferVOToModel(vo.getOrderPelayanan().getRuanganTujuan(), new Ruangan()));
						orderPelayanan.setRuangan(ruanganDao.findById(
								Integer.parseInt((String) this.GetSettingDataFixed("KdRuanganKendaraanDinas"))));
						orderPelayanan.setRuanganTujuan(ruanganDao.findById(
								Integer.parseInt((String) this.GetSettingDataFixed("KdRuanganTujuanKendaraanDinas"))));
					}
					if (CommonUtil.isNotNullOrEmpty(vo.getOrderPelayanan().getProduk())) {
						orderPelayanan.setProduk(
								produkConverter.transferVOToModel(vo.getOrderPelayanan().getProduk(), new Produk()));
						orderPelayanan.setProduk(produkDao.findById(
								Integer.parseInt((String) this.GetSettingDataFixed("KdProdukKendaraanDinas"))));
						orderPelayanan.getProduk().setNilaiNormal((short) 1);
						orderPelayanan.getProduk().setqProduk(1);
						orderPelayanan.getProduk().setQtyJualTerkecil(1.0);
						orderPelayanan.getProduk().setQtySatuKemasan(1);
						orderPelayanan.getProduk().setQtyTerkecil(1.0);
					}
					StrukOrder resultModelStrukOrder = strukOrderDao.save(strukOrder);
					result.put("noRecStrukOrder", resultModelStrukOrder.getNoRec());
					System.out.println(":::END STRUK ORDER:::");
					OrderPelayanan resultModelOrderPelayanan = orderPelayananDao.save(orderPelayanan);
					result.put("noRecOrderPelayanan", resultModelOrderPelayanan.getNoRec());
					System.out.println(":::END ORDER PELAYANAN:::");
				}
			}
			System.out.println("==================END SAVE ORDER KENDARAAN DINAS======================");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	@Override
	public String generateNoOrderByDayMonthAndYear(OrderKendaraanDinasVO vo) {

		StrukOrder strukOrder = strukOrderConverter.transferVOToModel(vo.getStrukOrder(), new StrukOrder());

		Date dateNow = strukOrder.getTglPelayananAwal();
		Integer day = getDayFromDate(dateNow);
		Integer month = DateUtil.getMonthFromDate(dateNow);
		Integer year = DateUtil.getYearFromDate(dateNow);
		Integer countByDayMonthAndYear = 0;

		countByDayMonthAndYear = strukOrderDao.getCountByDayMonthAndYear(day, month, year);

		Integer dayNow = getDayFromDate(dateNow);
		Integer monthNow = DateUtil.getMonthFromDate(dateNow);
		Integer yearNow = DateUtil.getYearFromDate(dateNow);
		String dayNowString = dayNow.toString();
		String monthNowString = monthNow.toString();
		String yearNowString = yearNow.toString().substring(2, 4);
		String countString = null;
		countByDayMonthAndYear++;

		if (CommonUtil.isNotNullOrEmpty(countByDayMonthAndYear)) {
			if (countByDayMonthAndYear.toString().length() == 1) {
				countString = "000" + countByDayMonthAndYear.toString();
			} else if (countByDayMonthAndYear.toString().length() == 2) {
				countString = "000" + countByDayMonthAndYear.toString();
			} else if (countByDayMonthAndYear.toString().length() == 3) {
				countString = "000" + countByDayMonthAndYear.toString();
			} else if (countByDayMonthAndYear.toString().length() == 4) {
				countString = "000" + countByDayMonthAndYear.toString();
			} else if (countByDayMonthAndYear.toString().length() == 5) {
				countString = "000" + countByDayMonthAndYear.toString();
			}
		}

		if ((monthNowString.length()) == 1) {
			monthNowString = "0" + monthNow;
		} else if ((monthNowString.length()) == 2) {
			monthNowString = "0" + monthNow;
		} else if ((monthNowString.length()) == 3) {
			monthNowString = "0" + monthNow;
		} else if ((monthNowString.length()) == 4) {
			monthNowString = "0" + monthNow;
		} else if ((monthNowString.length()) == 5) {
			monthNowString = "0" + monthNow;
		}

		return dayNowString + "" + monthNowString + "" + yearNowString + "" + countString;
	}

	private Integer getDayFromDate(Date date) {

		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int day = cal.get(Calendar.DAY_OF_MONTH);
		return day;
	}

}
