package com.jasamedika.medifirst2000.controller;

import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.dao.BentukProdukDao;
import com.jasamedika.medifirst2000.dao.MapGenerikToProdukDao;
import com.jasamedika.medifirst2000.dao.StrukPelayananDetailDao;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.ProdukService;
import com.jasamedika.medifirst2000.vo.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import static com.jasamedika.medifirst2000.util.JsonUtil.ToMaps;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttpStatus;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
@RequestMapping("/product")
public class ProductController extends LocaleController<ProdukVO> {

	private static final Logger LOGGER = getLogger(ProductController.class);

	@Autowired
	private ProdukService produkService;

	@Autowired
	private BentukProdukDao bentukProdukDao;

	@Autowired
	private StrukPelayananDetailDao strukPelayananDetailDao;

	@Autowired
	private MapGenerikToProdukDao mapGenerikToProdukDao;

	@RequestMapping(value = "/find-same-generic", method = GET)
	public ResponseEntity<List<Map<String, Object>>> findSameGeneric(
			@RequestParam(value = "idGeneric", required = false) Integer idGeneric) {
		try {
			List<Map<String, Object>> resultPageMap = ToMaps(produkService.findByGenericId(idGeneric));
			return getJsonResponse(resultPageMap, OK);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new ServiceVOException(e.getMessage());
		}
	}

	@RequestMapping(value = "/find-kekuatan", method = GET)
	public ResponseEntity<List<Map<String, Object>>> findKekuatan(
			@RequestParam(value = "idProduk", required = false) Integer idProduk,
			@RequestParam(value = "idGenerik", required = false) Integer idGenerik) {
		try {
			List<Map<String, Object>> resultPageMap = ToMaps(mapGenerikToProdukDao.findByGenerik(idGenerik));
			return getJsonResponse(resultPageMap, OK);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new ServiceVOException(e.getMessage());
		}
	}

	@RequestMapping(value = "/find-stok-produk-darah", method = GET)
	public ResponseEntity<List<Map<String, Object>>> finStokProdukDarah(
			@RequestParam(value = "idProduk", required = false) Integer idProduk) {
		try {
			List<Map<String, Object>> resultPageMap = ToMaps(strukPelayananDetailDao.findByProdukId(idProduk));
			return getJsonResponse(resultPageMap, OK);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new ServiceVOException(e.getMessage());
		}
	}

	@RequestMapping(value = "/find-bentuk-darah", method = GET)
	public ResponseEntity<List<Map<String, Object>>> findBentukProdukDarah(
			@RequestParam(value = "namaBentuk", required = false) String namaBentuk) {
		try {
			if (namaBentuk == null)
				namaBentuk = "";
			List<Map<String, Object>> resultPageMap = ToMaps(
					bentukProdukDao.findByDepartemenIdAndNamaBentukProdukContains(
							Integer.parseInt(GetSettingDataFixed("KdDepartemenBankDarah")), namaBentuk));
			return getJsonResponse(resultPageMap, OK);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new ServiceVOException(e.getMessage());
		}
	}

	@RequestMapping(value = "/find-detail-jenis-produk", method = GET)
	public ResponseEntity<List<DetailJenisProdukVO>> findDetailJenisProdukByJenisProduk(
			@RequestParam(value = "idJenisProduk", required = false) Integer idJenisProduk) {
		List<DetailJenisProdukVO> resultPageMap = produkService.findDetailJenisProdukByJenisProduk(idJenisProduk);
		return getJsonResponse(resultPageMap, OK);
	}

	@RequestMapping(value = "/kelompok-produk-have-stok", method = GET)
	public ResponseEntity<List<KelompokProdukVO>> kelompokProdukHaveStok() {
		List<KelompokProdukVO> resultPageMap = produkService.findKelompokProdukHaveStok();
		return getJsonResponse(resultPageMap, OK);
	}

	@RequestMapping(value = "/get-hirarki-satuan-produk", method = GET)
	public ResponseEntity<List<SatuanStandarVO>> getHirarkiSatuanProduk(
			@RequestParam(value = "id", required = false) String id) {
		List<SatuanStandarVO> resultPageMap = produkService.findAllSatuanStandardProduk(id);
		return getJsonResponse(resultPageMap, OK);
	}

	@RequestMapping(value = "/save-deposit", method = GET)
	public ResponseEntity<Map<String, Object>> saveDeposit(
			@RequestParam(value = "noRec", required = false) String noRec,
			@RequestParam(value = "deposite", required = false) Double deposite,
			@RequestParam(value = "tanggal", required = false) String tanggal) {
		Map<String, Object> resultPageMap = produkService.saveDeposite(noRec, deposite, tanggal);
		return getJsonResponse(resultPageMap, OK);
	}

	@RequestMapping(value = "/update-total-biaya", method = GET)
	public ResponseEntity<Map<String, Object>> updateTotalBiaya(
			@RequestParam(value = "noRec", required = false) String noRec,
			@RequestParam(value = "total", required = false) Double total) {
		Map<String, Object> resultPageMap = produkService.saveTotalBiaya(noRec, total);
		return getJsonResponse(resultPageMap, OK);
	}

	@RequestMapping(value = "/find-menu-diet", method = GET)
	public ResponseEntity<List<ProdukVO>> findMenuDiet(HttpServletRequest request) {
		List<ProdukVO> resultPageMap2 = produkService
				.findProdukByDetailJenisProduk(Integer.valueOf(GetSettingDataFixed("IdDetailJenisProduk")));
		return getJsonResponse(resultPageMap2, OK);
	}

	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/find-barang-by-kelompok", method = GET)
	public Map<String, Object> findProdukByKelompokProduk(@RequestParam(value = "id", required = false) Integer id,
			HttpServletRequest request) {
		String data = request.getQueryString();
		data = URLDecoder.decode(data);
		String[] arrQueries = data.split("&");
		StringBuilder values = new StringBuilder();
		for (String query : arrQueries)
			if (query.contains("filter[filters][0][value]"))
				values.append(query.replace("filter[filters][0][value]=", ""));
		return produkService.findProdukByKelompok(id, values.toString());
	}

	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/find-obat", method = GET)
	public ResponseEntity<List<ProdukVO>> findObatProduk(
			@RequestParam(value = "namaObat", required = false) String namaObat, HttpServletRequest request) {
		String data = request.getQueryString();
		data = URLDecoder.decode(data);
		StringBuilder values = new StringBuilder();
		String[] arrQueries = data.split("&");
		for (String query : arrQueries)
			if (query.contains("filter[filters][0][value]"))
				values.append(query.replace("filter[filters][0][value]=", ""));
		List<ProdukVO> resultPageMap = produkService.findObatByName(values.toString());
		return getJsonResponse(resultPageMap, OK);
	}

	@RequestMapping(value = "/find-produk", method = GET)
	public ResponseEntity<List<ProdukVO>> findProdukByJenisProduk(
			@RequestParam(value = "idDetailJenisProduk", required = false) Integer idDetailJenisProduk) {
		List<ProdukVO> resultPageMap = produkService.findDetailProdukByDetailJenisProduk(idDetailJenisProduk);
		return getJsonResponse(resultPageMap, OK);
	}

	@RequestMapping(value = "/find-stok-produk", method = GET)
	public ResponseEntity<Integer> findStokProduk(@RequestParam(value = "idProduk", required = false) Integer idProduk,
			@RequestParam(value = "idRuangan", required = false) Integer idRuangan) {
		Integer resultPageMap = produkService.findStokProdukService(idProduk, idRuangan);
		return getJsonResponse(resultPageMap, OK);
	}

	@RequestMapping(value = "/find-jenis-produk", method = GET)
	public ResponseEntity<List<JenisProdukVO>> findJenisProdukByJenisProduk(
			@RequestParam(value = "idKelompokProduk", required = false) Integer idKelompokProduk) {
		List<JenisProdukVO> resultPageMap = produkService.findJenisProdukByKelompokProduk(idKelompokProduk);
		return getJsonResponse(resultPageMap, OK);
	}

	@RequestMapping(value = "/find-produk-by-detail-jenis-produk-and-nama-produk", method = GET)
	public ResponseEntity<Map<String, Object>> findProdukByDetailJenisProdukAndNamaProduk(HttpServletRequest request,
			@RequestParam(value = "idDetailJenisProduk", required = false) Integer idDetailJenisProduk) {
		try {
			Map<String, Object> result = produkService.findProdukByDetailJenisProdukAndNamaProduk(idDetailJenisProduk);
			mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
			return getJsonResponse(result, OK, mapHeaderMessage);
		} catch (ServiceVOException e) {
			LOGGER.error("Got ServiceVOException {} when findProdukByDetailJenisProdukAndNamaProduk", e.getMessage());
			addHeaderMessage(ERROR_MESSAGE, e.getMessage());
			return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
		} catch (JpaSystemException jse) {
			LOGGER.error("Got JpaSystemException {} when findProdukByDetailJenisProdukAndNamaProduk", jse.getMessage());
			addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
			return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
		}
	}

	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/find-produk-by-jenis-produk-and-nama-produk", method = GET)
	public Map<String, Object> findProdukByJenisProdukAndNamaProduk(HttpServletRequest request,
			@RequestParam(value = "idDetailJenisProduk", required = false) Integer idDetailJenisProduk) {
		String data = request.getQueryString();
		data = URLDecoder.decode(data);
		String[] arrQueries = data.split("&");
		StringBuilder values = new StringBuilder();
		for (String query : arrQueries)
			if (query.contains("filter[filters][0][value]"))
				values.append(query.replace("filter[filters][0][value]=", ""));
		return produkService.findProdukByJenisProdukAndNamaProduk(idDetailJenisProduk, values.toString());
	}

	@RequestMapping(value = "/detail-jenis-produk", method = GET)
	public ResponseEntity<Map<String, Object>> findDetailJenisProduk(HttpServletRequest request) {
		try {
			Map<String, Object> result = produkService.detailJenisProduk();
			mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
			return getJsonResponse(result, OK, mapHeaderMessage);
		} catch (ServiceVOException e) {
			LOGGER.error("Got ServiceVOException {} when detailJenisProduk", e.getMessage());
			addHeaderMessage(ERROR_MESSAGE, e.getMessage());
			return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
		} catch (JpaSystemException jse) {
			LOGGER.error("Got JpaSystemException {} when detailJenisProduk", jse.getMessage());
			addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
			return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
		}
	}

	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/find-supplier", method = GET)
	public Map<String, Object> findSupplier(HttpServletRequest request) {
		String data = request.getQueryString();
		data = URLDecoder.decode(data);
		String[] arrQueries = data.split("&");
		StringBuilder values = new StringBuilder();
		for (String query : arrQueries)
			if (query.contains("filter[filters][0][value]"))
				values.append(query.replace("filter[filters][0][value]=", ""));
		return produkService.findSupplier(values.toString());
	}

}
