//package com.eactive.eai.rms.onl.manage.serviceinfo.osidinsti;
//
//import java.util.List;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
//import org.apache.log4j.Logger;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.stereotype.Controller;
//import org.springframework.ui.ModelMap;
//import org.springframework.web.bind.annotation.ModelAttribute;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.servlet.View;
//
//import com.eactive.eai.rms.common.logging.UserAccessLogger;
//import com.eactive.eai.rms.onl.common.view.EmptyGauceView;
//import com.eactive.eai.rms.onl.manage.serviceinfo.osidinsti.view.OsidInstiSubView;
//import com.eactive.eai.rms.onl.manage.serviceinfo.osidinsti.view.OsidInstiView;
//import com.gauce.http.HttpGauceResponse;
//
//@Controller
//@RequestMapping("/admin/insti/osidInsti.do")
//public class OsidInstiController {
//
//    private static final Logger logger = Logger.getLogger(OsidInstiController.class);
//
//    @Autowired
//    @Qualifier("osidInstiService")
//    private OsidInstiService serviceBean;
//    
//    @RequestMapping(params = "cmd=LIST")
//    public View list(@ModelAttribute("osidInstiVo") OsidInstiVo vo,
//            ModelMap modelMap, HttpServletRequest request,
//            HttpServletResponse response) {
//
//        UserAccessLogger.log(request, "대외기관 관리 리스트", "L", "cmd=LIST");
//
//        List<OsidInstiVo> list = null;
//        try {
//            list = serviceBean.findList(vo);
//            
//            modelMap.addAttribute("list", list);
//            modelMap.addAttribute("osidInstiVo", vo);
//            return new OsidInstiView();
//        } catch (Exception e) {
//            logger.error( e );
//            ((HttpGauceResponse) response).addException(e);
//        }
//        return new EmptyGauceView();
//    }
//
//    @RequestMapping(params = "cmd=UPDATE_SELECT")
//    public View listSub(
//            ModelMap modelMap, HttpServletRequest request,
//            HttpServletResponse response, String adptrBzwkGroupName, String osidInstiNo) {
//
//        UserAccessLogger.log(request, "대외기관 관리 담당자 리스트", "L", "cmd=UPDATE_SELECT");
//
//        List<OsidInstiSubVo> list = null;
//        try {
//            list = serviceBean.findListSub(adptrBzwkGroupName, osidInstiNo);
//            
//            modelMap.addAttribute("list", list);
//            return new OsidInstiSubView();
//        } catch (Exception e) {
//            logger.error( e );
//            ((HttpGauceResponse) response).addException(e);
//        }
//        return new EmptyGauceView();
//    }
//
//    @RequestMapping(params = "cmd=INSERT")
//    public View insertOsidInsti(@ModelAttribute("osidInstiVo") OsidInstiVo vo,
//    		ModelMap modelMap, HttpServletRequest request,
//            HttpServletResponse response) {
//        
//    	UserAccessLogger.log(request, "대외기관 정보 등록", "L", "cmd=INSERT");
//
//        try {
//            int ret = serviceBean.insertOsidInsti(vo);
//            if (ret < 1)
//            	throw new Exception();
//        } catch (Exception e) {
//            logger.error( e );
//            e.printStackTrace();
//            ((HttpGauceResponse) response).addException(e);
//        }
//        return new EmptyGauceView();
//    }
//
//    @RequestMapping(params = "cmd=INSERT_SUB")
//    public View insertOsidInstiSub(@ModelAttribute("osidInstiSubVo") OsidInstiSubVo vo,
//    		ModelMap modelMap, HttpServletRequest request,
//            HttpServletResponse response) {
//        
//    	UserAccessLogger.log(request, "대외기관 담당자 정보 등록", "L", "cmd=INSERT_SUB");
//
//        try {
//            int ret = serviceBean.insertOsidInstiSub(vo);
//            if (ret < 1)
//            	throw new Exception();
//        } catch (Exception e) {
//            logger.error( e );
//            e.printStackTrace();
//            ((HttpGauceResponse) response).addException(e);
//        }
//        return new EmptyGauceView();
//    }
//
//    @RequestMapping(params = "cmd=UPDATE_SUB")
//    public View updateOsidInstiSub(@ModelAttribute("osidInstiSubVo") OsidInstiSubVo vo,
//    		ModelMap modelMap, HttpServletRequest request,
//            HttpServletResponse response) {
//        
//    	UserAccessLogger.log(request, "대외기관 담당자 정보 수정", "L", "cmd=UPDATE_SUB");
//
//        try {
//            int ret = serviceBean.updateOsidInstiSub(vo);
//            if (ret < 1)
//            	throw new Exception();
//        } catch (Exception e) {
//            logger.error( e );
//            e.printStackTrace();
//            ((HttpGauceResponse) response).addException(e);
//        }
//        return new EmptyGauceView();
//    }
//
//    @RequestMapping(params = "cmd=DELETE_SUB")
//    public View deleteOsidInstiSub(@ModelAttribute("osidInstiSubVo") OsidInstiSubVo vo,
//    		ModelMap modelMap, HttpServletRequest request,
//            HttpServletResponse response) {
//        
//    	UserAccessLogger.log(request, "대외기관 담당자 정보 삭제", "L", "cmd=DELETE_SUB");
//
//        try {
//            int ret = serviceBean.deleteOsidInstiSub(vo);
//            if (ret < 1)
//            	throw new Exception();
//        } catch (Exception e) {
//            logger.error( e );
//            e.printStackTrace();
//            ((HttpGauceResponse) response).addException(e);
//        }
//        return new EmptyGauceView();
//    }
//
//    @RequestMapping(params = "cmd=UPDATE")
//    public View updateOsidInsti(@ModelAttribute("osidInstiVo") OsidInstiVo vo,
//    		ModelMap modelMap, HttpServletRequest request,
//            HttpServletResponse response) {
//        
//    	UserAccessLogger.log(request, "대외기관 정보 수정", "L", "cmd=UPDATE");
//
//        try {
//            int ret = serviceBean.updateOsidInsti(vo);
//            if (ret < 1)
//            	throw new Exception();
//        } catch (Exception e) {
//            logger.error( e );
//            e.printStackTrace();
//            ((HttpGauceResponse) response).addException(e);
//        }
//        return new EmptyGauceView();
//    }
//
//    @RequestMapping(params = "cmd=DELETE")
//    public View deleteOsidInsti(@ModelAttribute("osidInstiVo") OsidInstiVo vo,
//    		ModelMap modelMap, HttpServletRequest request,
//            HttpServletResponse response) {
//        
//    	UserAccessLogger.log(request, "대외기관 정보 삭제", "L", "cmd=DELETE");
//
//        try {
//            int ret = serviceBean.deleteOsidInsti(vo);
//            if (ret < 1)
//            	throw new Exception();
//        } catch (Exception e) {
//            logger.error( e );
//            e.printStackTrace();
//            ((HttpGauceResponse) response).addException(e);
//        }
//        return new EmptyGauceView();
//    }
//}
package com.eactive.eai.rms.onl.manage.serviceinfo.osidinsti;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.SortDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.data.entity.onl.server.EAIServer;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.data.entity.onl.adapter.OsidinstiSearch;
import com.eactive.eai.rms.data.entity.onl.server.EAIServerService;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.common.util.CallAgentUtil;
import com.eactive.eai.rms.onl.common.util.DataSetUtil;
import com.eactive.eai.rms.onl.common.vo.HostInfomationForm;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;


@Controller
public class OsidInstiController extends BaseController {

	private final String AGENT_PAGE_STATUS		= "adapter_socket2_agent1.jsp";
	private final String AGENT_PAGE_STATUS2      = "adapter_socket2_agent3.jsp";
	private final String AGENT_PAGE_STARTSTOP	= "adapter_socket2_startstop.jsp";
	
    private static final Logger logger = Logger.getLogger(OsidInstiController.class);

    private OsidInstiManService osidInstiManService;
    
    private ComboService comboService;
    
    private ObjectMapper objectMapper;
    
    private EAIServerService eaiServerService;
    
    @Autowired
    public OsidInstiController(OsidInstiManService osidInstiManService, ComboService comboService, ObjectMapper objectMapper, EAIServerService eaiServerService) {
    	this.osidInstiManService = osidInstiManService;
    	this.comboService = comboService;
    	this.objectMapper = objectMapper;
    	this.eaiServerService = eaiServerService;
    }
    
    @GetMapping(value= "/onl/admin/service/osidInstiMan.view")
    public void view() {
    	// view
    }
    
    @GetMapping(value= "/onl/admin/service/osidInstiMan.view", params = "cmd=DETAIL")
	public String detailView() {
    	return  "/onl/admin/service/osidInstiManDetail";
    }
	
	@PostMapping(value= "/onl/admin/service/osidInstiMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<OsidinstiUI>> selectList(@SortDefault("prptyGroupName") Pageable pageable, OsidinstiSearch osidinstiSearch) {
		Page<OsidinstiUI> page = osidInstiManService.selectList(pageable, osidinstiSearch);
		return ResponseEntity.ok(new GridResponse<>(page));
	}
	
	@PostMapping(value= "/onl/admin/service/osidInstiMan.json",params = "cmd=DETAIL")
	public ResponseEntity<OsidinstiUI> selectDetail(String adptrBzwkGroupName ) {
		OsidinstiUI osidinstiUI = osidInstiManService.selectDetail(adptrBzwkGroupName);
		return ResponseEntity.ok(osidinstiUI);
	}
	
	@PostMapping(value= "/onl/admin/service/osidInstiMan.json",params = "cmd=LIST_DETAIL_COMBO")
    public ResponseEntity<Map<String, Object>> initCombo() {
        List<ComboVo> listBiz = comboService.getFromBusinessType();
        Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("bizRows"	 , listBiz);
		return ResponseEntity.ok(resultMap);
	}
	
	@PostMapping(value= "/onl/admin/service/osidInstiMan.json",params = "cmd=DETAIL_RSEMP")
	public ResponseEntity<Map<String, Object>> detailRsEmp(String adptrBzwkGroupName) {
		List<OsidinstiRsEmpUI> osidinstiRsEmpUI = osidInstiManService.selectDetailRsempInfo(adptrBzwkGroupName);
		return ResponseEntity.ok(Collections.singletonMap("rows" , osidinstiRsEmpUI));
	}
	
	@PostMapping(value= "/onl/admin/service/osidInstiMan.json", params = "cmd=DETAIL_ADPTSTUS")
	public ResponseEntity<Map<String, Object>> detailAdptStus(HttpServletRequest request, String adptrBzwkGroupName ) {
		List<EAIServer> serverList = Optional.ofNullable(eaiServerService.selectEaiServerIpList())
																	    .filter(list -> !list.isEmpty())
																	    .orElseThrow(() -> new BizException("서버리스트가 없습니다."));

		List<String> urlList = new ArrayList<>();
		for (EAIServer eaiServer : serverList){
			String url = "http://" + eaiServer.getEaisevrip() + ":"
										+ eaiServer.getSevrlsnportname()
										+ HostInfomationForm.WEB_AGENT_CONTEXT_PATH
										+ AGENT_PAGE_STATUS + "?adapterType=SOC"
										+ "&eaiSvrInstNm=" + eaiServer.getEaisevrinstncname();
			urlList.add(url);
			logger.debug(url);
		}

		HashMap<String,String> filter = new HashMap<>();
		
		if (StringUtils.isNotBlank(adptrBzwkGroupName)){
			filter.put("AdptrBzwkGroupName",adptrBzwkGroupName);
		}
		
		DataSetUtil gUtil = new DataSetUtil();
		gUtil.setFilter(filter);
		List<HashMap<String, Object>> list = gUtil.flushXmlToClient(urlList);
		
		return ResponseEntity.ok(Collections.singletonMap("rows" , list));
	}
	
	@PostMapping(value= "/onl/admin/service/osidInstiMan.json", params = "cmd=DETAIL_ADPTCONN")
	public ResponseEntity<Map<String, Object>> detailAdptConn(HttpServletRequest request, String adptrBzwkGroupName ) {
		
		List<EAIServer> serverList = Optional.ofNullable(eaiServerService.selectEaiServerIpList())
			    .filter(list -> !list.isEmpty())
			    .orElseThrow(() -> new BizException("서버리스트가 없습니다."));
		
		List<String> urlList = new ArrayList<>();
		
		for (EAIServer eaiServer : serverList){
			String url = "http://" + eaiServer.getEaisevrip() + ":"
										+ eaiServer.getSevrlsnportname()
										+ HostInfomationForm.WEB_AGENT_CONTEXT_PATH
										+ AGENT_PAGE_STATUS2 + "?adapterGroupName=" + adptrBzwkGroupName
										+ "&eaiSvrInstNm=" + eaiServer.getEaisevrinstncname();
			urlList.add(url);
			logger.debug(url);
		}
		
		HashMap<String,String> filter = new HashMap<>();
		
		if (StringUtils.isNotBlank(adptrBzwkGroupName)){
			filter.put("AdptrBzwkGroupName", adptrBzwkGroupName);
		}
		
		DataSetUtil gUtil = new DataSetUtil();
		gUtil.setFilter(filter);
		List<HashMap<String, Object>> list = gUtil.flushXmlToClient(urlList);
		
		List<HashMap<String, Object>> filteredList = list.stream()
				.filter(map -> StringUtils.isNotBlank((String) map.get("AdptrBzwkName")))
				.collect(Collectors.toList());
		
		return ResponseEntity.ok(Collections.singletonMap("rows", filteredList));
	}	
	
	@PostMapping(value = "/onl/admin/service/osidInstiMan.json", params = "cmd=TRANSACTION_STARTSTOP")
	public ResponseEntity<Map<String, Object>> transactionStartStop(HttpServletRequest request,
			String eaiSevrInstncName, String adapterGroupName, String control, String adapterName, String remoteAddress,
			String localAddress, String session) throws Exception {
		
		Optional<EAIServer> selectedServerOptional = eaiServerService.findByEaiSevrInstncName(eaiSevrInstncName);
		
		if (!selectedServerOptional.isPresent()) {
			return ResponseEntity.ok(Collections.singletonMap("message", "선택된 서버가 목록에 없습니다."));
		}
		
		EAIServer eaiServer = selectedServerOptional.get();
		String url = "http://" + eaiServer.getEaisevrip() + ":"
									+ eaiServer.getSevrlsnportname()
									+ HostInfomationForm.WEB_AGENT_CONTEXT_PATH
									+ AGENT_PAGE_STARTSTOP;
		
		//cmd 는 start/stop
		NameValuePair[] postParameters = new NameValuePair[] {
				new NameValuePair("adapterGroupName", adapterGroupName ),
				new NameValuePair("adapterName",      adapterName),
				new NameValuePair("cmd",    control),
				new NameValuePair("localAddress",     localAddress),
				new NameValuePair("sessionName",      session)
				};

		// Agent를 호출한다.
		CallAgentUtil util = new CallAgentUtil();
		String message = util.getAgentDataToString(url, postParameters);

		return ResponseEntity.ok(Collections.singletonMap("message", message));
	}
	
	@PostMapping(value= "/onl/admin/service/osidInstiMan.excel",params = "cmd=LIST_GRID_TO_EXCEL")
    public ModelAndView listGridToExcel(@RequestParam Map<String, Object> paramMap, OsidinstiSearch osidinstiSearch) throws JsonProcessingException {
		Map<String,Object> resultMap = new HashMap<>();
		
		String[] headers = objectMapper.readValue((String) paramMap.get("header"), String[].class);
		String[] headerTitles = objectMapper.readValue((String) paramMap.get("headerTitle"), String[].class);
		
		List<Map<String, Object>> datas = osidInstiManService.selectListToExcel(osidinstiSearch);
		
    	HashMap<String, Object>[] lmerge = null; 
		String merge = (String) paramMap.get("merge");
		if (merge != null) {
			lmerge = objectMapper.readValue(merge, new TypeReference<HashMap<String, Object>[]>() {
			});
		}
    	
    	resultMap.put("headers", headers);
    	resultMap.put("headerTitles", headerTitles);
    	resultMap.put("datas", datas);
    	resultMap.put("fileName", paramMap.get("fileName"));
    	resultMap.put("merge", lmerge);
        return new ModelAndView("excelView", resultMap);
    }	

}
