package com.jasamedika.medifirst2000.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jasamedika.medifirst2000.dao.AntrianPasienRegistrasiDao;
import com.jasamedika.medifirst2000.dao.BridgingDao;
import com.jasamedika.medifirst2000.dao.JadwalPraktikDokterDao;
import com.jasamedika.medifirst2000.dao.KelompokPasienDao;
import com.jasamedika.medifirst2000.dao.PasienDao;
import com.jasamedika.medifirst2000.dao.PegawaiDao;
import com.jasamedika.medifirst2000.dao.PendidikanDao;
import com.jasamedika.medifirst2000.dao.RuanganDao;
import com.jasamedika.medifirst2000.dto.RegistrasiPasienDto;
import com.jasamedika.medifirst2000.entities.AntrianPasienRegistrasi;
import com.jasamedika.medifirst2000.entities.JadwalDokter;
import com.jasamedika.medifirst2000.entities.JadwalPraktek;
import com.jasamedika.medifirst2000.entities.KelompokPasien;
import com.jasamedika.medifirst2000.entities.Pasien;
import com.jasamedika.medifirst2000.entities.Pegawai;
import com.jasamedika.medifirst2000.entities.Pendidikan;
import com.jasamedika.medifirst2000.entities.Ruangan;
import com.jasamedika.medifirst2000.enums.TipePasienEnum;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.AntrianPasienDiPeriksaService;
import com.jasamedika.medifirst2000.service.JadwalDokterService;
import com.jasamedika.medifirst2000.service.ModelService;
import com.jasamedika.medifirst2000.service.PasienService;
import com.jasamedika.medifirst2000.service.PegawaiService;
import com.jasamedika.medifirst2000.service.RegistrasiPasienService;
import com.jasamedika.medifirst2000.service.RuanganService;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.util.DateUtil;
import com.jasamedika.medifirst2000.vo.AlamatVO;
import com.jasamedika.medifirst2000.vo.PasienVO;
import com.jasamedika.medifirst2000.vo.RegistrasiSmsVO;
import com.jasamedika.medifirst2000.vo.RuanganVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarCaraBayarListVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarCaraBayarVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarJadwalDokterListVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarJadwalDokterVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarJadwalJamKunjunganListVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarJadwalJamKunjunganVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarKlinikListVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarKlinikVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarPasienDaftarBaruConsumeVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarPasienDaftarConsumeVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarPasienDaftarFailedProduceVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarPasienDaftarFailedVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarPasienDaftarOkProduceVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarPasienDaftarOkVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarVerifikasiPasienConsumeVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarVerifikasiPasienFoundReplyProduceVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarVerifikasiPasienFoundReplyVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarVerifikasiPasienNotFoundReplyProduceVO;
import com.jasamedika.medifirst2000.vo.custom.BridgeDaftarVerifikasiPasienNotFoundReplyVO;

@RestController
@RequestMapping("/daftar-ol")
public class BridgingDaftarOnlineController {
	private static final Logger LOGGER = LoggerFactory.getLogger(BridgingDaftarOnlineController.class);

	@Autowired
	private AntrianPasienRegistrasiDao antrianPasienRegistrasiDao;

	@Autowired
	private PasienDao pasienDao;

	@Autowired
	private PendidikanDao pendidikanDao;

	@Autowired
	private RuanganDao ruanganDao;

	@Autowired
	private KelompokPasienDao kelompokPasienDao;

	@Autowired
	private BridgingDao bridgingDao;

	@Autowired
	private PegawaiDao pegawaiDao;

	@Autowired
	private JadwalPraktikDokterDao jadwalPraktikDokterDao;

	@Autowired
	private PasienService<Pasien> pasienService;

	@Autowired
	private ModelService<Ruangan> modelServiceRuangan;

	@Autowired
	private JadwalDokterService jadwalDokterService;

	@Autowired
	private RuanganService<RuanganVO> ruanganService;

	@Autowired
	private PegawaiService pegawaiService;

	@Autowired
	private AntrianPasienDiPeriksaService antrianService;

	@Autowired
	private RegistrasiPasienService registrasiPasienService;

	@RequestMapping(value = "/klinik_rs", method = RequestMethod.GET, produces = { MediaType.APPLICATION_XML_VALUE })
	public BridgeDaftarKlinikListVO daftarKlinikRs() {
		BridgeDaftarKlinikListVO y = new BridgeDaftarKlinikListVO();
		List<Map<String, Object>> ruanganT = bridgingDao.getJadwalKlinik();

		for (Map<String, Object> ruanganTmp : ruanganT) {
			BridgeDaftarKlinikVO x = new BridgeDaftarKlinikVO();
			x.setIdKlinik(ruanganTmp.get("id").toString());
			x.setNamaKlinik(ruanganTmp.get("namaRuangan").toString());
			x.setHari(ruanganTmp.get("hari").toString());

			if (CommonUtil.isNullOrEmpty(ruanganTmp.get("jamBuka"))) {
				x.setJamBukaPelayanan("");
			} else {
				x.setJamBukaPelayanan(ruanganTmp.get("jamBuka").toString());
			}
			if (CommonUtil.isNullOrEmpty(ruanganTmp.get("jamTutup"))) {
				x.setJamTutupPelayanan("");
			} else {
				x.setJamTutupPelayanan(ruanganTmp.get("jamTutup").toString());
			}
			Calendar cal = Calendar.getInstance();
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			x.setUpdate(dateFormat.format(cal.getTime()));
			x.setKuota(30);// dari antrian
			y.addBridgePendaftaranDaftarKlinikVO(x);
		}
		return y;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/jadwal_dokters", method = RequestMethod.GET, produces = {
			MediaType.APPLICATION_XML_VALUE })
	// public BridgeDaftarJadwalDokterListVO jadwalDokterRs() {
	public BridgeDaftarJadwalDokterListVO jadwalDokterRs() {
		BridgeDaftarJadwalDokterListVO y = new BridgeDaftarJadwalDokterListVO();
		List<Map<String, Object>> ruanganT = modelServiceRuangan.getAllData("Ruangan", "id,departemenId", 1500, null,
				null, null, null, null, null, null, null, null, null);
		ArrayList<Integer> ytemp = new ArrayList<Integer>();

		for (int i = 0; i < ruanganT.size(); i++) {
			Integer deptId = (Integer) ruanganT.get(i).get("departemenId");
			if (deptId != null) {
				if (((Integer) ruanganT.get(i).get("departemenId") == 18)
						|| ((Integer) ruanganT.get(i).get("departemenId") == 28)) {
					// Hanya di departement ruang RJ dan rehab medik saja
					ytemp.add((Integer) ruanganT.get(i).get("id"));
				}
			}
		}
		// System.out.println(ytemp.size());
		for (int idruang = 0; idruang < ytemp.size(); idruang++) {
			Map<String, Object> jd = new HashMap<>();
			try {
				jd = jadwalDokterService.findByRuangan(ytemp.get(idruang));
			} catch (Exception ex) {
				jd = null;
			}
			if (jd != null) {
				if (jd.get("data") != null) {
					List<JadwalDokter> temp = (List<JadwalDokter>) jd.get("data");

					for (int i = 0; i < temp.size(); i++) {
						BridgeDaftarJadwalDokterVO x = new BridgeDaftarJadwalDokterVO();

						x.setIdKlinik(temp.get(i).getRuangan().getId().toString());
						String hari = bridgingDao.getDay(DateUtil.dayOfWeek(temp.get(i).getTanggalJadwal()));
						x.setHari(hari);
						JadwalPraktek jp = temp.get(i).getJadwalPraktek();
						if (CommonUtil.isNotNullOrEmpty(jp.getJamPraktek())) {
							String[] pp = jp.getJamPraktek().split("-");
							if (pp.length == 2) {
								x.setJamTutupPraktek(pp[1]);
								x.setJamMulaiPraktek(pp[0]);
							} else {
								// System.out.println("Invalid len:" +
								// jp.getJamPraktek());
							}
						} else {
							x.setJamTutupPraktek("");
							x.setJamMulaiPraktek("");
						}

						if (CommonUtil.isNotNullOrEmpty(temp.get(i).getQuota())) {
							x.setKuota(temp.get(i).getQuota().toString());
						} else {
							x.setKuota("30");
						}
						try {
							x.setIddokter(temp.get(i).getDokter().getId().toString());
							x.setNamadokter(temp.get(i).getDokter().getNamaLengkap());
						} catch (Exception ex) {
							x.setIddokter("?");
							x.setNamadokter("?");
						}

						Calendar cal = Calendar.getInstance();
						DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						x.setUpdate(dateFormat.format(cal.getTime()));
						y.addBridgePendaftaranJadwalDokterVO(x);
					}
				}
			}
		}
		return y;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/jadwal_dokter_rev", method = RequestMethod.GET, produces = {
			MediaType.APPLICATION_XML_VALUE })
	// public BridgeDaftarJadwalDokterListVO jadwalDokterRs() {
	public BridgeDaftarJadwalDokterListVO jadwalDokterRse() {
		BridgeDaftarJadwalDokterListVO y = new BridgeDaftarJadwalDokterListVO();
		List<BridgeDaftarJadwalDokterVO> filterTemp = new ArrayList<BridgeDaftarJadwalDokterVO>();
		List<Map<String, Object>> ruanganT = modelServiceRuangan.getAllData("Ruangan", "id,departemenId", 1500, null,
				null, null, null, null, null, null, null, null, null);
		ArrayList<Integer> ytemp = new ArrayList<Integer>();

		for (int i = 0; i < ruanganT.size(); i++) {
			Integer deptId = (Integer) ruanganT.get(i).get("departemenId");
			if (deptId != null) {
				if (((Integer) ruanganT.get(i).get("departemenId") == 18)
						|| ((Integer) ruanganT.get(i).get("departemenId") == 28)) {
					// Hanya di departement ruang RJ dan rehab medik saja
					ytemp.add((Integer) ruanganT.get(i).get("id"));
				}
			}
		}

		// System.out.print("ruangan yang benar");
		// System.out.println(ytemp.size());
		for (int idruang = 0; idruang < ytemp.size(); idruang++) {
			Map<String, Object> jd = new HashMap<>();
			try {
				jd = jadwalDokterService.findByRuangan(ytemp.get(idruang));
			} catch (Exception ex) {
				jd = null;
			}
			if (jd != null) {
				if (jd.get("data") != null) {
					List<JadwalDokter> temp = (List<JadwalDokter>) jd.get("data");

					for (int i = 0; i < temp.size(); i++) {
						BridgeDaftarJadwalDokterVO x = new BridgeDaftarJadwalDokterVO();

						x.setIdKlinik(temp.get(i).getRuangan().getId().toString());
						String hari = bridgingDao.getDay(DateUtil.dayOfWeek(temp.get(i).getTanggalJadwal()));
						x.setHari(hari);
						if (CommonUtil.isNullOrEmpty(hari)) {
							x.setHari("");
						}
						JadwalPraktek jp = temp.get(i).getJadwalPraktek();
						if (CommonUtil.isNotNullOrEmpty(jp.getJamPraktek())) {
							String[] pp = jp.getJamPraktek().split("-");
							if (pp.length == 2) {
								x.setJamTutupPraktek(pp[1]);
								x.setJamMulaiPraktek(pp[0]);
							} else {
								// System.out.println("Invalid len:" +
								// jp.getJamPraktek());
							}
						} else {
							x.setJamTutupPraktek("");
							x.setJamMulaiPraktek("");
						}

						if (CommonUtil.isNotNullOrEmpty(temp.get(i).getQuota())) {
							x.setKuota(temp.get(i).getQuota().toString());
						} else {
							x.setKuota("30");
						}
						try {
							x.setIddokter(temp.get(i).getDokter().getId().toString());
							x.setNamadokter(temp.get(i).getDokter().getNamaLengkap());
						} catch (Exception ex) {
							x.setIddokter("?");
							x.setNamadokter("?");
						}

						Calendar cal = Calendar.getInstance();
						DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						x.setUpdate(dateFormat.format(cal.getTime()));

						if (!filterTemp.contains(x)) {
							filterTemp.add(x);
							y.addBridgePendaftaranJadwalDokterVO(x);
						}

					}
				}
			}
		}
		return y;
	}

	@RequestMapping(value = "/jadwal_dokter", method = RequestMethod.GET, produces = {
			MediaType.APPLICATION_XML_VALUE })
	// public BridgeDaftarJadwalDokterListVO jadwalDokterRs() {
	public BridgeDaftarJadwalDokterListVO jadwalDokterRseRev() {
		BridgeDaftarJadwalDokterListVO y = new BridgeDaftarJadwalDokterListVO();
		List<Map<String, Object>> data = jadwalPraktikDokterDao.findAllJadwalPraktikDokter();

		Calendar cal = Calendar.getInstance();
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		for (Map<String, Object> map : data) {
			BridgeDaftarJadwalDokterVO bridge = new BridgeDaftarJadwalDokterVO();
			bridge.setHari(map.get("namaHari").toString());
			bridge.setIddokter(map.get("idPegawai").toString());
			bridge.setIdKlinik(map.get("idRuangan").toString());
			bridge.setJamMulaiPraktek(map.get("waktumulai").toString());
			bridge.setJamTutupPraktek(map.get("waktuselesai").toString());
			bridge.setKuota(map.get("quota").toString());
			bridge.setNamadokter(map.get("namaLengkap").toString());
			bridge.setUpdate(dateFormat.format(cal.getTime()));
			y.addBridgePendaftaranJadwalDokterVO(bridge);
		}

		return y;
	}

	@RequestMapping(value = "/jam_kunjungan", method = RequestMethod.GET, produces = {
			MediaType.APPLICATION_XML_VALUE })
	// public BridgeDaftarJadwalDokterListVO jadwalDokterRs() {
	public BridgeDaftarJadwalJamKunjunganListVO jamKunjungan(
			@RequestParam(value = "idklinik", required = true) Integer idKlinik,
			@RequestParam(value = "iddokter", required = true) Integer idDokter,
			@RequestParam(value = "tanggal", required = false) String tgl) {
		BridgeDaftarJadwalJamKunjunganListVO y = new BridgeDaftarJadwalJamKunjunganListVO();

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date tanggal = null;
		try {
			tanggal = formatter.parse(tgl);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(tanggal);
		Integer tanggalId = calendar.get(Calendar.DAY_OF_WEEK) - 1;

		// System.out.println(tanggal);
		List<Map<String, Object>> datas = bridgingDao.getJadwalKlinikbyId(idDokter, idKlinik, tanggalId);
		// System.out.println(datas.toString());
		if (CommonUtil.isNotNullOrEmpty(datas)) {
			for (Map<String, Object> data : datas) {
				BridgeDaftarJadwalJamKunjunganVO x = new BridgeDaftarJadwalJamKunjunganVO();
				x.setIdKlinik(data.get("idklinik").toString());
				String[] pp = data.get("jam").toString().split("-");
				x.setJamMulai(pp[0]);
				x.setJamSelesai(pp[1]);
				x.setKuota("30"); // harus ada perhitungan lagi mengegnai quota,
				x.setIdDokter(data.get("iddokter").toString());
				Calendar cal = Calendar.getInstance();
				DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				x.setUpdate(dateFormat.format(cal.getTime()));
				y.addBridgePendaftaranJadwalJamKunjunganVO(x);
			}
		}
		return y;
	}

	@RequestMapping(value = "/cara_bayar", method = RequestMethod.GET, produces = { MediaType.APPLICATION_XML_VALUE })
	public BridgeDaftarCaraBayarListVO caraBayar() {
		BridgeDaftarCaraBayarListVO y = new BridgeDaftarCaraBayarListVO();

		List<Map<String, Object>> caraBayar = modelServiceRuangan.getAllData("KelompokPasien", "*", 1500, null, null,
				null, null, null, null, null, null, null, null);

		for (int i = 0; i < caraBayar.size(); i++) {
			BridgeDaftarCaraBayarVO x = new BridgeDaftarCaraBayarVO();
			x.setIdCaraBayar(caraBayar.get(i).get("id").toString());
			x.setDeskripsi(caraBayar.get(i).get("kelompokPasien").toString());
			y.addBridgeDaftarCaraBayarVO(x);
		}
		return y;
	}

	@RequestMapping(value = "/verifikasi_pasien", method = RequestMethod.POST, produces = {
			MediaType.APPLICATION_XML_VALUE }, consumes = { MediaType.APPLICATION_XML_VALUE })
	public Object verifikasiPasien(@RequestBody BridgeDaftarVerifikasiPasienConsumeVO vox) {
		System.out.print("NoCM:");
		System.out.println(vox.getObjVO().getNoCM());
		PasienVO p = pasienService.findByNoCm(vox.getObjVO().getNoCM());
		Boolean pasienExist = false;
		if (p != null) {
			pasienExist = true;
		} else {
			System.out.println("p is null");
		}

		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String dd_post = vox.getObjVO().getTglLahir();

		String dd = "";
		if (pasienExist) {
			dd = dateFormat.format(p.getTglLahir());
		}

		// System.out.println(dd + "vs" + dd_post);
		if (dd.equals(dd_post)) {
			BridgeDaftarVerifikasiPasienFoundReplyVO y = new BridgeDaftarVerifikasiPasienFoundReplyVO();
			String notel = p.getNoTelepon();
			if (notel == null) {
				notel = "";
			}
			y.setNomorContact(notel);
			y.setNama(p.getNamaPasien());
			y.setAlamat("");
			for (AlamatVO alamatVO : p.getAlamats()) {
				y.setAlamat(alamatVO.getAlamatLengkap());
				break;
			}
			y.setTgllahir(vox.getObjVO().getTglLahir());
			y.setStatus(true);
			BridgeDaftarVerifikasiPasienFoundReplyProduceVO ret = new BridgeDaftarVerifikasiPasienFoundReplyProduceVO(
					y);
			return ret;
		} else {
			BridgeDaftarVerifikasiPasienNotFoundReplyVO z = new BridgeDaftarVerifikasiPasienNotFoundReplyVO();
			z.setPesan("Tidak ada");
			z.setStatus(false);
			BridgeDaftarVerifikasiPasienNotFoundReplyProduceVO ret = new BridgeDaftarVerifikasiPasienNotFoundReplyProduceVO(
					z);
			return ret;
		}
	}

	@RequestMapping(value = "/pendaftaran_pasien", method = RequestMethod.POST, produces = {
			MediaType.APPLICATION_XML_VALUE }, consumes = { MediaType.APPLICATION_XML_VALUE })
	public Object pendaftaranPasien(@RequestBody BridgeDaftarPasienDaftarConsumeVO vox) {

		RegistrasiSmsVO vo = new RegistrasiSmsVO();
		Pasien p = new Pasien();
		boolean pasienValid = false;
		System.out.println("service re-register registered patient has entered");
		try {
			p = pasienDao.findPasienByNoCm(vox.getData().getNoCM());
			pasienValid = true;
			vo.setKodeDokter(Short.parseShort(vox.getData().getIdDokter()));
			vo.setKodeRegulerEkslusif(0);
			vo.setKodeRuangan(vox.getData().getIdPoli());
			vo.setNoCm(vox.getData().getNoCM());
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			try {
				vo.setTanggal(dateFormat.parse(vox.getData().getTglKunjungan()));
			} catch (ParseException e) {
				vo.setTanggal(new Date());
				e.printStackTrace();
			}
			vo.setTanggallahir(p.getTglLahir());
		} catch (Exception ex) {
			pasienValid = false;
		}

		AntrianPasienRegistrasi model = new AntrianPasienRegistrasi();
		AntrianPasienRegistrasi hasil = null;
		UUID noReservasi = null;
		Pegawai pegawai = new Pegawai();
		pegawai = pegawaiDao.getPegawaiById(Integer.parseInt(vox.getData().getIdDokter()));
		if (pasienValid) {
			Ruangan ruangan = ruanganDao.findRuanganByDepartemenAndKdRuangan(vo.getKodeRuangan());
			//// print in log
			System.out.println("CaraBayar " + vox.getData().getCaraBayar());
			System.out.println("IdDokter " + vox.getData().getIdDokter());
			System.out.println("Klinik " + vox.getData().getIdPoli());
			System.out.println("Jam Kunjungan " + vox.getData().getTglKunjungan());
			System.out.println("nocm " + vox.getData().getNoCM());
			System.out.println("nomor Kontak " + vox.getData().getNomorContact());
			System.out.println("tglDaftar " + vox.getData().getTanggalDaftar());
			System.out.println("tglkunjungan " + vox.getData().getTglKunjungan());
			////
			model.setPasien(p);
			model.setRuangan(ruangan);
			model.setPegawai(pegawai);
			model.setPendidikan(p.getPendidikan());
			model.setTipePasien(TipePasienEnum.LAMA.getVal());
			model.setTglReservasi(vo.getTanggal());
			model.setType(vo.getKodeRegulerEkslusif().equals("0") ? "REGULER"
					: (vo.getKodeRegulerEkslusif().equals("1") ? "EKSLUSIF" : ""));
			model.setJenisKelamin(p.getJenisKelamin());
			noReservasi = UUID.randomUUID();
			model.setNoReservasi(noReservasi.toString().substring(1, 8));
			List<String> antrianPasienRegistrasi = antrianPasienRegistrasiDao.findAntrianPasienLamaRegistrasi(
					p.getNoCm(), Integer.parseInt(vo.getKodeRuangan()), Integer.parseInt(vox.getData().getIdDokter()),
					vox.getData().getTglKunjungan());
			if (CommonUtil.isNullOrEmpty(antrianPasienRegistrasi)) {
				hasil = antrianPasienRegistrasiDao.save(model);
			}
		}
		if (hasil != null) {
			BridgeDaftarPasienDaftarOkVO y = new BridgeDaftarPasienDaftarOkVO();
			y.setNomorReservasi(noReservasi.toString().substring(1, 8));
			y.setJamKunjungan(vox.getData().getTglKunjungan());
			y.setStatus(true);
			BridgeDaftarPasienDaftarOkProduceVO ret = new BridgeDaftarPasienDaftarOkProduceVO(y);
			return ret;
		} else {
			BridgeDaftarPasienDaftarFailedVO z = new BridgeDaftarPasienDaftarFailedVO();
			z.setPesan("Gagal Daftar");
			z.setStatus(false);
			BridgeDaftarPasienDaftarFailedProduceVO ret = new BridgeDaftarPasienDaftarFailedProduceVO(z);
			return ret;
		}

	}

	@RequestMapping(value = "/pendaftaran_pasien_baru", method = RequestMethod.POST, produces = {
			MediaType.APPLICATION_XML_VALUE }, consumes = { MediaType.APPLICATION_XML_VALUE })
	public Object pendaftaranPasienBaru(@RequestBody BridgeDaftarPasienDaftarBaruConsumeVO vo) {

		AntrianPasienRegistrasi model = new AntrianPasienRegistrasi();
		AntrianPasienRegistrasi hasil = null;
		UUID noReservasi = null;
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		DateFormat hourFormat = new SimpleDateFormat("HH:mm");
		////
		System.out.println("CaraBayar " + vo.getData().getCarabayar());
		System.out.println("IdDokter " + vo.getData().getIdDokter());
		System.out.println("Klinik " + vo.getData().getIdKlinik());
		System.out.println("Jam Kunjungan " + vo.getData().getJamKunjungan());
		System.out.println("NamaPasien " + vo.getData().getNamaPasien());
		System.out.println("nomor Kontak " + vo.getData().getNomorKontak());
		System.out.println("tempat lahir " + vo.getData().getTempatLahir());
		System.out.println("tglkunjungan " + vo.getData().getTglKunjungan());
		System.out.println("tglLahir " + vo.getData().getTglLahir());
		////
		String jamKunjungan = "";
		if (CommonUtil.isNotNullOrEmpty(vo.getData())) {
			Ruangan ruangan = ruanganDao.findRuanganByDepartemenAndKdRuangan(vo.getData().getIdKlinik());
			Pendidikan pendidikan = pendidikanDao.findByIdPendidikan(13);// basically
																			// pendidikan
																			// has
																			// been
																			// set
																			// to
																			// id
																			// 13
			Integer ids = 1;
			if (vo.getData().getCarabayar().toString().toLowerCase().equals("jkn")
					|| vo.getData().getCarabayar().toString().toLowerCase().equals("jamkesda")) {
				ids = 2;
			}
			KelompokPasien kelompokPasien = kelompokPasienDao.findById(ids);
			Pegawai pegawai = new Pegawai();
			pegawai = pegawaiDao.getPegawaiById(Integer.parseInt(vo.getData().getIdDokter()));
			model.setNamaPasien(vo.getData().getNamaPasien());
			model.setTempatLahir(vo.getData().getTempatLahir());
			model.setNoTelepon(vo.getData().getNomorKontak());
			model.setRuangan(ruangan);
			model.setPegawai(pegawai);
			model.setJenisPasien(kelompokPasien);
			model.setType("REGULER");// type must not null so it has been set to
										// be reguler
			model.setTipePasien(TipePasienEnum.BARU.getVal());
			model.setPendidikan(pendidikan);
			String tanggal = vo.getData().getTglKunjungan();

			Date tglReservasi = null;
			Date jamReservasi = null;
			try {
				if (CommonUtil.isNotNullOrEmpty(tanggal)) {
					tglReservasi = dateFormat.parse(tanggal);
				}
				if (CommonUtil.isNotNullOrEmpty(vo.getData().getJamKunjungan())) {
					jamKunjungan = vo.getData().getJamKunjungan();
					jamReservasi = hourFormat.parse(jamKunjungan);
				} else {
					jamKunjungan = "10:00";
					jamReservasi = hourFormat.parse(jamKunjungan);
				}
				if (CommonUtil.isNotNullOrEmpty(vo.getData().getTglLahir())) {
					Date tglLahir = dateFormat.parse(vo.getData().getTglLahir());
					model.setTglLahir(tglLahir);
				}
				Date reservasi = concatenateTime(tglReservasi, jamReservasi);
				model.setTglReservasi(reservasi);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			// model.setJenisKelamin(p.getJenisKelamin());

			noReservasi = UUID.randomUUID();
			model.setNoReservasi(noReservasi.toString().substring(1, 8));
			List<String> antrianPasienRegistrasi = antrianPasienRegistrasiDao.findAntrianPasienRegistrasi(
					vo.getData().getNamaPasien(), vo.getData().getTglLahir(),
					Integer.parseInt(vo.getData().getIdKlinik()), Integer.parseInt(vo.getData().getIdDokter()),
					vo.getData().getTglKunjungan());
			if (CommonUtil.isNullOrEmpty(antrianPasienRegistrasi)) {
				hasil = antrianPasienRegistrasiDao.save(model);
			}
		}

		if (hasil != null) {
			BridgeDaftarPasienDaftarOkVO y = new BridgeDaftarPasienDaftarOkVO();
			y.setNomorReservasi(noReservasi.toString().substring(1, 8));
			y.setJamKunjungan(jamKunjungan);
			y.setStatus(true);
			BridgeDaftarPasienDaftarOkProduceVO ret = new BridgeDaftarPasienDaftarOkProduceVO(y);
			return ret;
		} else {
			BridgeDaftarPasienDaftarFailedVO z = new BridgeDaftarPasienDaftarFailedVO();
			z.setPesan("Gagal Daftar");
			z.setStatus(false);
			BridgeDaftarPasienDaftarFailedProduceVO ret = new BridgeDaftarPasienDaftarFailedProduceVO(z);
			return ret;
		}

	}

	public Date concatenateTime(Date date, Date time) {
		Calendar aDateTime = Calendar.getInstance();
		Calendar aDate = Calendar.getInstance();

		if (CommonUtil.isNotNullOrEmpty(date)) {
			aDate.setTime(date);
		}
		Calendar aTime = Calendar.getInstance();
		if (CommonUtil.isNotNullOrEmpty(time)) {
			aTime.setTime(time);
		}
		aDateTime.set(Calendar.DAY_OF_MONTH, aDate.get(Calendar.DAY_OF_MONTH));
		aDateTime.set(Calendar.MONTH, aDate.get(Calendar.MONTH));
		aDateTime.set(Calendar.YEAR, aDate.get(Calendar.YEAR));
		aDateTime.set(Calendar.HOUR_OF_DAY, aTime.get(Calendar.HOUR_OF_DAY));
		aDateTime.set(Calendar.MINUTE, aTime.get(Calendar.MINUTE));
		return aDateTime.getTime();
	}

	@RequestMapping(value = "/bpjs/poli/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Object> getListPoliklinik() {
		List<Map<String, Object>> entity = ruanganService.findRajalBPJS();
		return new ResponseEntity<>(entity, HttpStatus.OK);
	}

	@RequestMapping(value = "/bpjs/dpjp/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Object> getListDpjp() {
		List<Map<String, Object>> entity = pegawaiService.getDokterBpjs();
		return new ResponseEntity<>(entity, HttpStatus.OK);
	}

	@RequestMapping(value = "/bpjs/patient/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Object> saveNewPatient(@Valid @RequestBody PasienVO vo) {
		try {
			PasienVO result = pasienService.add(vo);
			if (result != null)
				return new ResponseEntity<>(result.getId(), HttpStatus.CREATED);
			return new ResponseEntity<>(null, HttpStatus.NOT_ACCEPTABLE);
		} catch (ServiceVOException e) {
			LOGGER.error("Got exception {} when add Pasien", e.getMessage());
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		} catch (JpaSystemException jse) {
			LOGGER.error("Got exception {} when add Pasien", jse.getMessage());
			return new ResponseEntity<>(null, HttpStatus.CONFLICT);
		}
	}

	@RequestMapping(value = "/bpjs/medical-record-id/patient/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<String> getPatientMedicalRecordId(@PathVariable Integer id) {
		PasienVO result = pasienService.findById(id);
		if (result != null)
			return new ResponseEntity<>(result.getNoCm(), HttpStatus.OK);
		return new ResponseEntity<>(null, HttpStatus.OK);
	}

	@RequestMapping(value = "/bpjs/card-number/{noBpjs}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Boolean> checkNoBPJSPasien(@PathVariable String noBpjs) {
		PasienVO result = pasienService.findByNoBpjs(noBpjs);
		if (result != null)
			return new ResponseEntity<>(true, HttpStatus.OK);
		return new ResponseEntity<>(false, HttpStatus.OK);
	}

	@RequestMapping(value = "/bpjs/patient/get/{noRM}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Object> getListPatient(@PathVariable String noRM) {
		List<Map<String, Object>> entity = pasienService.findByNoRM(noRM);
		return new ResponseEntity<>(entity, HttpStatus.OK);
	}

	@RequestMapping(value = "/bpjs/antrian/get/{tglMasuk}/{ruanganId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Object> getCountAntrean(
			@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate tglMasuk, @PathVariable Integer ruanganId) {
		Map<String, Object> entity = antrianService.getAntreanByRuangan(tglMasuk, ruanganId);
		return new ResponseEntity<>(entity, HttpStatus.OK);
	}

	@RequestMapping(value = "/bpjs/registration/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Object> saveNewRegistration(@RequestBody RegistrasiPasienDto dto) {
		try {
			String result = registrasiPasienService.saveRegistrasiPasien(dto);
			return new ResponseEntity<>(result, HttpStatus.CREATED);
		} catch (ServiceVOException e) {
			LOGGER.error("Got exception {} when add Pasien", e.getMessage());
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		} catch (JpaSystemException jse) {
			LOGGER.error("Got exception {} when add Pasien", jse.getMessage());
			return new ResponseEntity<>(null, HttpStatus.CONFLICT);
		}
	}
}
