package com.jasamedika.medifirst2000.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.*;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
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.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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.entities.DetailSpekAnggaran;
import com.jasamedika.medifirst2000.entities.StrukOrder;
import com.jasamedika.medifirst2000.entities.StrukPelayananDetail;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.security.model.AppPermission;
import com.jasamedika.medifirst2000.service.DistribusiAsetService;
import com.jasamedika.medifirst2000.service.PemusnahanBarangService;
import com.jasamedika.medifirst2000.service.ProdukService;
import com.jasamedika.medifirst2000.service.StrukOrderService;
import com.jasamedika.medifirst2000.service.StrukPelayananDetailService;
import com.jasamedika.medifirst2000.service.StrukPelayananService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.DetailAnggaranVO;
import com.jasamedika.medifirst2000.vo.DistribusiAsetVO;
import com.jasamedika.medifirst2000.vo.DistribusiBarangInvestasiVO;
import com.jasamedika.medifirst2000.vo.KonfirmasiAsetVO;
import com.jasamedika.medifirst2000.vo.PenerimaanBarangDetailVO;
import com.jasamedika.medifirst2000.vo.PenerimaanBarangVO;
import com.jasamedika.medifirst2000.vo.RequestBarangDariRuanganVO;
import com.jasamedika.medifirst2000.vo.StrukKirimVO;
import com.jasamedika.medifirst2000.vo.StrukOrderVO;

import net.kaczmarzyk.spring.data.jpa.domain.DateBetween;
import net.kaczmarzyk.spring.data.jpa.domain.Equal;
import net.kaczmarzyk.spring.data.jpa.domain.Like;
import net.kaczmarzyk.spring.data.jpa.domain.Null;
import net.kaczmarzyk.spring.data.jpa.web.annotation.And;
import net.kaczmarzyk.spring.data.jpa.web.annotation.Spec;

@RestController
@RequestMapping("/distribusi-aset")
public class DistribusiAsetController extends LocaleController<PenerimaanBarangVO> {

	@Autowired
	private DistribusiAsetService distribusiAsetService;
	
	@Autowired
	private ProdukService produkService;
	

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

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/find-produk-aset", method = RequestMethod.GET)
	public Map<String,Object> findProdukAset(HttpServletRequest request) {

		String data = request.getQueryString();
		data = URLDecoder.decode(data);
		String[] arrQueries = data.split("&");
		String criteria = "";
		String values = "";
		for (String query : arrQueries) {
			if (query.indexOf("filter[filters][0][field]") >= 0) {
				if (criteria == null)
					criteria = query.replace("filter[filters][0][field]=", "");
				else
					criteria += "," + query.replace("filter[filters][0][field]=", "");

			} else if (query.indexOf("filter[filters][0][value]") >= 0) {
				if (values == null)
					values = query.replace("filter[filters][0][value]=", "");
				else
					values += query.replace("filter[filters][0][value]=", "");
			}
		}

		Map<String,Object>resultPageMap = produkService.findProdukAset(values);

		return resultPageMap;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/find-aset-by-produk", method = RequestMethod.GET)
	public Map<String,Object> findAsetByProduk(@RequestParam(value = "id", required = false) Integer id,HttpServletRequest request) {

		String data = request.getQueryString();
		data = URLDecoder.decode(data);
		String[] arrQueries = data.split("&");
		String criteria = "";
		String values = "";
		for (String query : arrQueries) {
			if (query.indexOf("filter[filters][0][field]") >= 0) {
				if (criteria == null)
					criteria = query.replace("filter[filters][0][field]=", "");
				else
					criteria += "," + query.replace("filter[filters][0][field]=", "");

			} else if (query.indexOf("filter[filters][0][value]") >= 0) {
				if (values == null)
					values = query.replace("filter[filters][0][value]=", "");
				else
					values += query.replace("filter[filters][0][value]=", "");
			}
		}

		Map<String,Object>resultPageMap = produkService.findAsetByProduk(id,values);

		return resultPageMap;
	}
	
	@RequestMapping(value = "/save-distribusi-aset/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Map<String, Object>> saveDistribusiAset(@Valid @RequestBody DistribusiAsetVO vo,HttpServletRequest request,HttpServletResponse response) {
		
		try {
			Map<String, Object> result = distribusiAsetService.saveRequestDistribusi(vo);
			if (null != result)
				mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
						getMessage(MessageResource.LABEL_SUCCESS, request));
			return RestUtil.getJsonResponse(result, HttpStatus.CREATED, mapHeaderMessage);
		} catch (ServiceVOException e) {
			LOGGER.error("Got exception {} when save Penerimaan Barang", e.getMessage());
			addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
			return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
		} catch (JpaSystemException jse) {
			LOGGER.error("Got exception {} when save Penerimaan Barang", jse.getMessage());
			addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
			return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
		}

	}
	
	@RequestMapping(value = "/get-kirim-detail-permintaan-barang/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Map<String,Object>> getKirimDetailPermintaanBarang(
			@RequestParam(value = "noRec", required = true) String noRec) {
		Map<String,Object> strukOrder = distribusiAsetService.findByStrukKirimNoRec(noRec);

		try {
			return RestUtil.getJsonResponse(strukOrder, HttpStatus.OK, mapHeaderMessage);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return RestUtil.getJsonResponse(null, HttpStatus.NOT_FOUND, mapHeaderMessage);
	}
	
	@RequestMapping(value = "/save-konfirmasi-aset/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Map<String, Object>> saveKonfirmasiAset(@Valid @RequestBody KonfirmasiAsetVO vo,HttpServletRequest request,HttpServletResponse response) {
		
		try {
			Map<String, Object> result = distribusiAsetService.saveKonfirmasiAset(vo);
			if (null != result)
				mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
						getMessage(MessageResource.LABEL_SUCCESS, request));
			return RestUtil.getJsonResponse(result, HttpStatus.CREATED, mapHeaderMessage);
		} catch (ServiceVOException e) {
			LOGGER.error("Got exception {} when save Penerimaan Barang", e.getMessage());
			addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
			return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
		} catch (JpaSystemException jse) {
			LOGGER.error("Got exception {} when save Penerimaan Barang", jse.getMessage());
			addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
			return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
		}

	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/daftar-barang-aset")
	@ResponseBody
	public Map<String,Object> daftarBarangAset(
			@RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
			@RequestParam(value = "take", required = false, defaultValue = "10000") Integer limit,
			@RequestParam(value = "sort", required = false, defaultValue = "noRec") String sort,
			@RequestParam(value = "dir", required = false, defaultValue = "asc") String dir,
			@RequestParam(value = "ruanganId", required = false) Integer ruanganId) {
		
		Map<String, Object> resultPageMap = distribusiAsetService.daftarBarangAset(page, limit, sort, dir,ruanganId);
		
		return resultPageMap;
	}
	

}
