package com.eactive.eai.rms.onl.manage.serviceinfo.jmsqueuereceiver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.SortDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.util.ControllerValidationHelper;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.data.entity.onl.flowcontrol.jms.FCQueueReceiverSearch;
import com.google.gson.Gson;

/**
 *  JMS Queue 수신자 관리 컨트롤러
 */
@Controller
public class JmsQueueReceiverManController extends OnlBaseAnnotationController {

    /**
     * JMS Queue 관리 서비스
     */
    @Autowired
    private JmsQueueReceiverManService service;
    
    @Autowired
    private ComboService comboService;
    
    @RequestMapping(value= "/onl/admin/service/jmsQueueReceiverMan.view")
	public void viewList(){
	}
    
    @RequestMapping(value= "/onl/admin/service/jmsQueueReceiverMan.view", params = "cmd=DETAIL")
	public String detailView() {
    	return "/onl/admin/service/jmsQueueReceiverManDetail";
    }
    
    @RequestMapping(value= "/onl/admin/service/jmsQueueReceiverMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<JmsQueueReceiverManUI>> selectList(HttpServletRequest request,
			@SortDefault.SortDefaults({ @SortDefault(sort = "quercvername", direction = Sort.Direction.ASC),
					@SortDefault(sort = "eaisevrinstncname", direction = Sort.Direction.ASC) }) Pageable pageable,
			FCQueueReceiverSearch uiSearch) throws Exception {
		Page<JmsQueueReceiverManUI> pageUI = service.selectList(pageable, uiSearch);
		return ResponseEntity.ok(new GridResponse<JmsQueueReceiverManUI>(pageUI));
	}
	
	@RequestMapping(value= "/onl/admin/service/jmsQueueReceiverMan.json",params = "cmd=DETAIL")
	public ModelAndView selectDetail(HttpServletRequest request,
			HttpServletResponse response,String queRcverName) throws Exception {
		JmsQueueReceiverManUI ui = service.selectDetail(queRcverName);
		Map<String, List<ComboVo>> quemMap = service.selectQueList(ui.getSevrInstncName());

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("detail", ui);
		resultMap.put("listQueRows", quemMap.get("listQue"));
		resultMap.put("listErrQueRows", quemMap.get("listErrQue"));
		
		return new ModelAndView("jsonView",resultMap);
	}
	
	@RequestMapping(value= "/onl/admin/service/jmsQueueReceiverMan.json",params = "cmd=LIST_DETAIL_COMBO")
    public ModelAndView initCombo( HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<ComboVo> listInstance = comboService.getFromEAIServerWithoutAll();
        List<ComboVo> listBascQueRcverYn	= comboService.getFromCode("BASC_QUE_RCVER_YN");
        
        Map<String, List<ComboVo>> resultMap = new HashMap<>();
		resultMap.put("instanceRows"		, listInstance);
		resultMap.put("bascQueRcverYnRows"	, listBascQueRcverYn);
		if (!listInstance.isEmpty()) {
        	Map<String, List<ComboVo>> map = service.selectQueList(listInstance.get(0).getCode());
        	resultMap.put("listQueRows"			, map.get("listQue"));
			resultMap.put("listErrQueRows"		, map.get("listErrQue"));
		} else {
			resultMap.put("listQueRows"			, new ArrayList<>());
			resultMap.put("listErrQueRows"		, new ArrayList<>());
		}
		return new ModelAndView("jsonView", resultMap);
    }
	
	@RequestMapping(value= "/onl/admin/service/jmsQueueReceiverMan.json",params = "cmd=LIST_QUE_COMBO")
    public ModelAndView queCombo( HttpServletRequest request,
            HttpServletResponse response, String instance) throws Exception {
		Map<String, List<ComboVo>> map = service.selectQueList(instance);
        
		Map<String, List<ComboVo>> resultMap = new HashMap<>();
		resultMap.put("listQueRows"		, map.get("listQue"));
		resultMap.put("listErrQueRows"	, map.get("listErrQue"));
		
		return new ModelAndView("jsonView", resultMap);
    }
	
	@RequestMapping(value= "/onl/admin/service/jmsQueueReceiverMan.json",params = "cmd=INSERT")
	public ResponseEntity<?> insert(HttpServletRequest request,
			HttpServletResponse response, @Valid JmsQueueReceiverManUI ui, BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors())
			return ControllerValidationHelper.checkValidation(bindingResult);
		service.insert(ui);
		
		// 메모리 정보 Reload
		Command command = new CommonCommand("com.eactive.eai.agent.fcqueuereceiver.ReloadFCReceiverCommand", ui.getQueRcverName());
		HashMap<String, Object> agentResult = agentUtilService.broadcast(command);
		
		return ResponseEntity.ok(agentResult);
	}
	
	@RequestMapping(value= "/onl/admin/service/jmsQueueReceiverMan.json",params = "cmd=UPDATE")
	public ResponseEntity<?> update(HttpServletRequest request,
			HttpServletResponse response, @Valid JmsQueueReceiverManUI ui, BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors())
			return ControllerValidationHelper.checkValidation(bindingResult);
		
		service.update(ui);
		
		// 메모리 정보 Reload
		Command command = new CommonCommand("com.eactive.eai.agent.fcqueuereceiver.ReloadFCReceiverCommand", ui.getQueRcverName());
		HashMap<String, Object> agentResult = agentUtilService.broadcast(command);
		
		return ResponseEntity.ok(agentResult);
	}
	
	@RequestMapping(value= "/onl/admin/service/jmsQueueReceiverMan.json",params = "cmd=DELETE")
	public ResponseEntity<?> delete(HttpServletRequest request,
			HttpServletResponse response, JmsQueueReceiverManUI ui) throws Exception {
		service.delete(ui.getQueRcverName());
		
		// 메모리 정보 Reload(삭제 후)
		Command command = new CommonCommand("com.eactive.eai.agent.fcqueuereceiver.RemoveFCReceiverCommand", ui.getQueRcverName());
		HashMap<String, Object> agentResult = agentUtilService.broadcast(command);
		
		return ResponseEntity.ok(agentResult);
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value= "/onl/admin/service/jmsQueueReceiverMan.excel",params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response,
			FCQueueReceiverSearch uiSearch, @RequestParam HashMap<String, Object> paramMap) throws Exception {
		HashMap<String,Object> resultMap = new HashMap<>();
		String headersStr = (String) paramMap.get("headersStr"); 
		headersStr = headersStr.substring(0, headersStr.length()-1);
		paramMap.put("headersStr", headersStr);
		
    	Gson gson = new Gson();
    	Map<String, List<?>> list = service.selectListToExcel(uiSearch);
    	
    	String jsonStr = gson.toJson(list.get("list"));
    	HashMap<String, String>[] list2 = gson.fromJson(jsonStr, HashMap[].class);
    	
		String[] headers = gson.fromJson((String) paramMap.get("header"), String[].class);
		String[] headerTitles = gson.fromJson((String)paramMap.get("headerTitle"), String[].class);
		
		HashMap<String, Object>[] lmerge = null; 
		String merge = (String)paramMap.get("merge");
		if (merge !=null){
			lmerge = gson.fromJson(merge, HashMap[].class);
		}
    	
    	resultMap.put("headers", headers);
    	resultMap.put("headerTitles", headerTitles);
    	resultMap.put("datas", list2);
    	resultMap.put("fileName", (String)paramMap.get("fileName"));
    	resultMap.put("merge", lmerge);
		ModelAndView modelAndView = new ModelAndView("excelView",resultMap);	
        return modelAndView;
	}	

}
