package com.jasamedika.medifirst2000.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
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.KamarDao;
import com.jasamedika.medifirst2000.dao.OrderPelayananDao;
import com.jasamedika.medifirst2000.dao.ProdukDao;
import com.jasamedika.medifirst2000.dao.RunningNumberDao;
import com.jasamedika.medifirst2000.dao.StrukOrderDao;
import com.jasamedika.medifirst2000.dto.PemakaianRumahDukaDto;
import com.jasamedika.medifirst2000.dto.RumahDukaDto;
import com.jasamedika.medifirst2000.entities.Kamar;
import com.jasamedika.medifirst2000.entities.OrderPelayanan;
import com.jasamedika.medifirst2000.entities.PenambahanKebutuhanSarana;
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.PemakaianRumahDukaService;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.util.DateUtil;
import com.jasamedika.medifirst2000.util.StringUtil;
import com.jasamedika.medifirst2000.vo.KamarVO;
import com.jasamedika.medifirst2000.vo.OrderPelayananVO;
import com.jasamedika.medifirst2000.vo.PemakaianRumahDukaVO;
import com.jasamedika.medifirst2000.vo.PenambahanKebutuhanSaranaVO;
import com.jasamedika.medifirst2000.vo.RuanganVO;
import com.jasamedika.medifirst2000.vo.StrukOrderVO;

@Service("PemakaianRumahDukaService")
public class PemakaianRumahDukaServiceImpl extends BaseVoServiceImpl implements PemakaianRumahDukaService {

	@Autowired
	private StrukOrderDao strukOrderDao;

	@Autowired
	private OrderPelayananDao orderPelayananDao;

	@Autowired
	private ProdukDao produkDao;

	@Autowired
	private KamarDao kamarDao;

	@Autowired
	private RunningNumberDao runningNumberDao;

	@Autowired
	private BaseConverterImpl<RuanganVO, Ruangan> ruanganConverter;

	@Autowired
	private BaseConverterImpl<StrukOrderVO, StrukOrder> strukOrderConverter;

	@Autowired
	private BaseConverterImpl<OrderPelayananVO, OrderPelayanan> orderPelayananConverter;

	@Autowired
	private BaseConverterImpl<PenambahanKebutuhanSaranaVO, PenambahanKebutuhanSarana> penambahanKebutuhanSaranaConverter;

	@Autowired
	private BaseConverterImpl<KamarVO, Kamar> noKamarConverter;

	@Autowired
	private LoginUserService loginUserService;

	@Autowired
	private ProdukConverter produkConverter;

//	@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
//	@Transactional(readOnly = false)
	public Map<String, Object> savePemakaianRumahDuka(PemakaianRumahDukaVO vo) {

		Map<String, Object> result = new HashMap<String, Object>();

		//StrukOrder strukOrder = this.strukOrderDao.findOne(vo.getNoRec());
		//strukOrder.setTglPelayananAkhir(vo.getTglPelayananAkhir());
		//StrukOrder strukOrderResult = this.strukOrderDao.save(strukOrder);
		
		//if(CommonUtil.isNotNullOrEmpty(strukOrderResult)){
		//	result.put("noRec", strukOrderResult.noRec);
		//}
		
		if(CommonUtil.isNotNullOrEmpty(vo.getNoRec())){
			System.out.println("Start update");
			StrukOrder strukOrder = this.strukOrderDao.findOne(vo.getNoRec());
			strukOrder.setTglPelayananAkhir(vo.getTglPelayananAkhir());
			StrukOrder strukOrderResult = this.strukOrderDao.save(strukOrder);
			
			if(CommonUtil.isNotNullOrEmpty(strukOrderResult)){
				result.put("noRec", strukOrderResult.noRec);
			}
			
			System.out.println("End Update");
			
		} else {
			
			System.out.println("==================START SAVE PEMAKAIAN RUMAH DUKA======================");

			if (CommonUtil.isNotNullOrEmpty(vo.getStrukOrder())) {
				System.out.println(":::START STRUK ORDER:::");
				StrukOrder strukOrder = strukOrderConverter.transferVOToModel(vo.getStrukOrder(), new StrukOrder());
				// StrukOrder strukOrder = new StrukOrder();
				// set no order rumah duka
				
				strukOrder.setNoOrder(StringUtil
						.formatNumber(String.valueOf(strukOrderDao.getCountByMonthAndYear(new Date()) + 1), 10));
				// strukOrder.setNoOrderIntern("PNRM" +
				// getRunningNumber("PNRM"));
				//strukOrder.setNoRec(vo.getNoRec()); //untuk setting jika terjadi peng-updatean
				strukOrder.setNoOrderIntern("RD" + generateNoOrderByDayMonthAndYear(vo));
				// set status sewa asrama
				strukOrder.setStatus(Status.DIPAKAI.getVal());
				strukOrder.setTglOrder(DateUtil.getShortDate());
				strukOrder.setQtyJenisProduk(1.0);
				strukOrder.setQtyProduk(1.0);
				strukOrder.setTotalBeaMaterai(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());
				// set penambahan kebutuhan sarana rumah duka
				Set<PenambahanKebutuhanSarana> list = new HashSet<PenambahanKebutuhanSarana>();
				for (PenambahanKebutuhanSaranaVO model : vo.getStrukOrder().getPenambahanKebutuhanSarana()) {
					PenambahanKebutuhanSarana kebutuhanSarana = penambahanKebutuhanSaranaConverter
							.transferVOToModel(model, new PenambahanKebutuhanSarana());
					kebutuhanSarana.setStrukOrder(strukOrder);
					list.add(kebutuhanSarana);
				}
				strukOrder.setPenambahanKebutuhanSarana(list);
				strukOrder.setIsDelivered((byte) 1);
				strukOrder.setKeteranganOrder("Pemakaian Rumah Duka");
				StrukOrder resultModelStrukOrder = strukOrderDao.save(strukOrder);
				result.put("noRecStrukOrder", resultModelStrukOrder.getNoRec());
				System.out.println(":::END STRUK ORDER:::");
				if (CommonUtil.isNotNullOrEmpty(vo.getOrderPelayanan())) {
					System.out.println(":::START ORDER PELAYANAN:::");
					OrderPelayanan orderPelayanan = orderPelayananConverter.transferVOToModel(vo.getOrderPelayanan(),
							new OrderPelayanan());
					// OrderPelayanan orderPelayanan = new OrderPelayanan();
					orderPelayanan.setStrukOrder(strukOrder);// set strukorderfk
					orderPelayanan.setNoOrder(strukOrder);// set noOrderfk
					// get no kamar
					if (CommonUtil.isNotNullOrEmpty(vo.getOrderPelayanan().getKamar())) {
						orderPelayanan.setKamar(
								noKamarConverter.transferVOToModel(vo.getOrderPelayanan().getKamar(), new Kamar()));
					}
					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()));
					}
					if (CommonUtil.isNotNullOrEmpty(vo.getOrderPelayanan().getRuanganTujuan())) {
						orderPelayanan.setRuanganTujuan(ruanganConverter
								.transferVOToModel(vo.getOrderPelayanan().getRuanganTujuan(), new Ruangan()));
					}
					if (CommonUtil.isNotNullOrEmpty(vo.getOrderPelayanan().getProduk())) {
						orderPelayanan.setProduk(
								produkConverter.transferVOToModel(vo.getOrderPelayanan().getProduk(), new Produk()));
						orderPelayanan.getProduk().setNilaiNormal((short) 1);
						orderPelayanan.getProduk().setqProduk(1);
						orderPelayanan.getProduk().setQtyJualTerkecil(1.0);
						orderPelayanan.getProduk().setQtySatuKemasan(1);
						orderPelayanan.getProduk().setQtyTerkecil(1.0);
					}
					OrderPelayanan resultModelOrderPelayanan = orderPelayananDao.save(orderPelayanan);
					result.put("noRecOrderPelayanan", resultModelOrderPelayanan.getNoRec());
					System.out.println(":::END ORDER PELAYANAN:::");
				}
			}
			
			System.out.println("==================END SAVE PEMAKAIAN RUMAH DUKA======================");
			
		}
			
		
		/*
		try {
				
			System.out.println("==================START SAVE PEMAKAIAN RUMAH DUKA======================");

			if (CommonUtil.isNotNullOrEmpty(vo.getStrukOrder())) {
				System.out.println(":::START STRUK ORDER:::");
				StrukOrder strukOrder = strukOrderConverter.transferVOToModel(vo.getStrukOrder(), new StrukOrder());
				// StrukOrder strukOrder = new StrukOrder();
				// set no order rumah duka
				
				strukOrder.setNoOrder(StringUtil
						.formatNumber(String.valueOf(strukOrderDao.getCountByMonthAndYear(new Date()) + 1), 10));
				// strukOrder.setNoOrderIntern("PNRM" +
				// getRunningNumber("PNRM"));
				strukOrder.setNoRec(vo.getNoRec()); //untuk setting jika terjadi peng-updatean
				strukOrder.setNoOrderIntern("RD" + generateNoOrderByDayMonthAndYear(vo));
				// set status sewa asrama
				strukOrder.setStatus(Status.DIPAKAI.getVal());
				strukOrder.setTglOrder(DateUtil.getShortDate());
				strukOrder.setQtyJenisProduk(1.0);
				strukOrder.setQtyProduk(1.0);
				strukOrder.setTotalBeaMaterai(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());
				// set penambahan kebutuhan sarana rumah duka
				Set<PenambahanKebutuhanSarana> list = new HashSet<PenambahanKebutuhanSarana>();
				for (PenambahanKebutuhanSaranaVO model : vo.getStrukOrder().getPenambahanKebutuhanSarana()) {
					PenambahanKebutuhanSarana kebutuhanSarana = penambahanKebutuhanSaranaConverter
							.transferVOToModel(model, new PenambahanKebutuhanSarana());
					kebutuhanSarana.setStrukOrder(strukOrder);
					list.add(kebutuhanSarana);
				}
				strukOrder.setPenambahanKebutuhanSarana(list);
				strukOrder.setIsDelivered((byte) 1);
				strukOrder.setKeteranganOrder("Pemakaian Rumah Duka");
				StrukOrder resultModelStrukOrder = strukOrderDao.save(strukOrder);
				result.put("noRecStrukOrder", resultModelStrukOrder.getNoRec());
				System.out.println(":::END STRUK ORDER:::");
				if (CommonUtil.isNotNullOrEmpty(vo.getOrderPelayanan())) {
					System.out.println(":::START ORDER PELAYANAN:::");
					OrderPelayanan orderPelayanan = orderPelayananConverter.transferVOToModel(vo.getOrderPelayanan(),
							new OrderPelayanan());
					// OrderPelayanan orderPelayanan = new OrderPelayanan();
					orderPelayanan.setStrukOrder(strukOrder);// set strukorderfk
					orderPelayanan.setNoOrder(strukOrder);// set noOrderfk
					// get no kamar
					if (CommonUtil.isNotNullOrEmpty(vo.getOrderPelayanan().getKamar())) {
						orderPelayanan.setKamar(
								noKamarConverter.transferVOToModel(vo.getOrderPelayanan().getKamar(), new Kamar()));
					}
					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()));
					}
					if (CommonUtil.isNotNullOrEmpty(vo.getOrderPelayanan().getRuanganTujuan())) {
						orderPelayanan.setRuanganTujuan(ruanganConverter
								.transferVOToModel(vo.getOrderPelayanan().getRuanganTujuan(), new Ruangan()));
					}
					if (CommonUtil.isNotNullOrEmpty(vo.getOrderPelayanan().getProduk())) {
						orderPelayanan.setProduk(
								produkConverter.transferVOToModel(vo.getOrderPelayanan().getProduk(), new Produk()));
						orderPelayanan.getProduk().setNilaiNormal((byte) 1);
						orderPelayanan.getProduk().setqProduk(1);
						orderPelayanan.getProduk().setQtyJualTerkecil(1.0);
						orderPelayanan.getProduk().setQtySatuKemasan(1);
						orderPelayanan.getProduk().setQtyTerkecil(1.0);
					}
					OrderPelayanan resultModelOrderPelayanan = orderPelayananDao.save(orderPelayanan);
					result.put("noRecOrderPelayanan", resultModelOrderPelayanan.getNoRec());
					System.out.println(":::END ORDER PELAYANAN:::");
				}
			}
			
			System.out.println("==================END SAVE PEMAKAIAN RUMAH DUKA======================");

		} catch (Exception e) {
			e.printStackTrace();
		}
		*/
		return result;
	}

	@Override
	public String generateNoOrderByDayMonthAndYear(PemakaianRumahDukaVO 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;
	}

	@Override
	public List<PemakaianRumahDukaDto> findProdukRumahDuka() {

		List<PemakaianRumahDukaDto> model = new ArrayList<PemakaianRumahDukaDto>();
		try {
			System.out.println("==================START FIND PRODUK(RUMAH DUKA)======================");
			model = produkDao.findProdukRumahDuka();
			System.out.println("==================END FIND PRODUK(RUMAH DUKA)======================");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return model;
	}

	@Override
	public Map<String, Object> findKamarRumahDuka() {

		List<RumahDukaDto> model = new ArrayList<RumahDukaDto>();
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			System.out.println("==================START FIND KAMAR RUMAH DUKA======================");
			model = kamarDao.findKamarRumahDuka();
			if (CommonUtil.isNotNullOrEmpty(model)) {
				result.put("data", model);
				result.put("RumahDuka", true);
			} else {
				result.put("RumahDuka", false);
			}
			System.out.println("==================END FIND KAMAR RUMAH DUKA======================");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
