package com.eactive.eai.rms.bap.manage.work.inst;

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

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
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.CommonCommand;
import com.eactive.eai.rms.bap.tansaction.transactionStatus.BapTransactionStatusService;
import com.eactive.eai.rms.common.base.BapBaseAnnotationController;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.combo.IbatisComboService;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.vo.JsonPageVo;
import com.google.gson.Gson;

@Controller
public class BapSystemInstController extends BapBaseAnnotationController  {

	@Autowired
	@Qualifier("bapSystemInstService")
	private BapSystemInstService service;
	
	@Autowired
	@Qualifier("bapTransactionStatusService")
	private BapTransactionStatusService transactionService;

	@Autowired
	private ComboService comboService;
	
    @Autowired
    private IbatisComboService ibatisComboService;   

	@RequestMapping(value= "/bap/admin/work/systemInstMan.view")
	public String viewList(HttpServletRequest request, @RequestParam(value = "cmd", required = false ) String cmd ) throws Exception {
		if (cmd == null || "LIST".equals(cmd.toUpperCase())){
			cmd = "";
		}else {
			cmd = CamelCaseUtil.converCamelCase(cmd);
		}
		String path = request.getServletPath();
		return path.split("[.]")[0]+cmd;
	}
	
	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value= "/bap/admin/work/systemInstMan.json", params = "cmd=LIST")
	public ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo , @RequestParam HashMap<String, Object> paramMap) throws Exception {
		
		HashMap<String, Object> map = service.selectList( pageVo.getStartNum(), pageVo.getEndNum(), paramMap);
		
		pageVo.setTotalCount((Integer)map.get("totalCount"));
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("total"  , pageVo.getTotal());  //전체 페이지수
		resultMap.put("page"   , pageVo.getPage());   //현재 페이지수
		resultMap.put("records", pageVo.getTotalCount());//전체 레코드건수	
		resultMap.put("rows"   , map.get("list"));
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}

	@RequestMapping(value= "/bap/admin/work/systemInstMan.json",params = "cmd=DETAIL")
	public ModelAndView selectDetail(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String,Object> param) throws Exception {
		
		HashMap<String, Object> map = service.selectDetail(param);

		ModelAndView modelAndView = new ModelAndView("jsonView", map);	
		
		return modelAndView;
	}
	@RequestMapping(value= "/bap/admin/work/systemInstMan.json",params = "cmd=INSERT")
	public String insert(HttpServletRequest request,
			HttpServletResponse response,@RequestParam HashMap<String,Object> map, String gridData, String sysConnList ) throws Exception {
    	Gson gson = new Gson();
    	@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);
    	@SuppressWarnings("unchecked")
    	HashMap<String, Object> connList = gson.fromJson(sysConnList, HashMap.class);
		String userid = com.eactive.eai.rms.common.login.SessionManager.getUserId(request);
		map.put("userid", userid );
    	service.insert(map,list, connList);
		String[] arg = new String[3];
		arg[0] = (String)map.get("bjobBzwkDstcd");
		arg[1] = (String)map.get("osidInstiDstcd");
		arg[2] = (String)map.get("adapterGroupName");

		String[] dirarg = new String[4];
		dirarg[0] = (String)map.get("bjobBzwkName");
		dirarg[1] = (String)map.get("bjobBzwkDstcd");
		dirarg[2] = (String)map.get("osidInstiName");
		dirarg[3] = (String)map.get("osidInstiDstcd");

		//CommonCommand command = new CommonCommand("com.eactive.eai.agent.makeDir.MakeDirOrganCommand",dirarg);
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.makeDir.MakeDirOrganCommand",arg);
		agentUtilService.broadcast(command);
		command = new CommonCommand("com.eactive.eai.agent.osd.UpdateOutsideCommand",arg);
		agentUtilService.broadcast(command);
		String adptrBzwkGroupName = (String)map.get("adptrBzwkGroupName");
		if ( !adptrBzwkGroupName.trim().equals("")){
			command = new CommonCommand("com.eactive.eai.agent.adapter.UpdateAdapterGroupCommand",adptrBzwkGroupName);
			agentUtilService.broadcast(command);
		}
		command = new CommonCommand("com.eactive.eai.agent.flowController.AddBatchTargetCommand",arg);
		agentUtilService.broadcast(command);
		
    	command = new CommonCommand("com.eactive.eai.agent.property.UpdatePropertyCommand",(String)map.get("prptyGroupName"));
		agentUtilService.broadcast(command);

		return null;
	}	
	@RequestMapping(value= "/bap/admin/work/systemInstMan.json",params = "cmd=UPDATE")
	public String update(HttpServletRequest request,
			HttpServletResponse response,@RequestParam HashMap<String,Object> map, String gridData, String sysConnList ) throws Exception {

    	Gson gson = new Gson();
    	@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);
    	@SuppressWarnings("unchecked")
    	HashMap<String, Object> connList = gson.fromJson(sysConnList, HashMap.class);
		String userid = com.eactive.eai.rms.common.login.SessionManager.getUserId(request);
		map.put("userid", userid);
		service.update(map, list, connList);
		String[] arg = new String[3];
		arg[0] = (String)map.get("bjobBzwkDstcd");
		arg[1] = (String)map.get("osidInstiDstcd");
		arg[2] = (String)map.get("adapterGroupName");
		
		String[] dirarg = new String[5];
		dirarg[0] = (String)map.get("bjobBzwkName");
		dirarg[1] = (String)map.get("bjobBzwkDstcd");
		dirarg[2] = (String)map.get("osidInstiName");
		dirarg[3] = (String)map.get("osidInstiDstcd");
		dirarg[4] = (String)map.get("oldOsidInstiName");
		//TODO HD RenameDirOrganCommand 사용할 수 있는지 확인
		//CommonCommand command = new CommonCommand("com.eactive.eai.agent.makeDir.RenameDirOrganCommand",dirarg);
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.makeDir.MakeDirOrganCommand", arg);
		agentUtilService.broadcast(command);
		command = new CommonCommand("com.eactive.eai.agent.osd.UpdateOutsideCommand",arg);
		agentUtilService.broadcast(command);
		String adptrBzwkGroupName = (String)map.get("adptrBzwkGroupName");
		if ( !adptrBzwkGroupName.trim().equals("")){
			command = new CommonCommand("com.eactive.eai.agent.adapter.UpdateAdapterGroupCommand",adptrBzwkGroupName);
			agentUtilService.broadcast(command);
		}
		command = new CommonCommand("com.eactive.eai.agent.flowController.AddBatchTargetCommand",arg);
		agentUtilService.broadcast(command);

    	command = new CommonCommand("com.eactive.eai.agent.property.UpdatePropertyCommand",(String)map.get("prptyGroupName"));
		agentUtilService.broadcast(command);

		return null;
	}
	@RequestMapping(value= "/bap/admin/work/systemInstMan.json",params = "cmd=DELETE")
	public String delete(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String, Object> map ) throws Exception {
		service.delete(map);
		
		String[] arg = new String[2];
		arg[0] = (String)map.get("bjobBzwkDstcd");
		arg[1] = (String)map.get("osidInstiDstcd");

		String[] dirarg = new String[4];
		dirarg[0] = (String)map.get("bjobBzwkName");
		dirarg[1] = (String)map.get("bjobBzwkDstcd");
		dirarg[2] = (String)map.get("osidInstiName");
		dirarg[3] = (String)map.get("osidInstiDstcd");

		CommonCommand command = new CommonCommand("com.eactive.eai.agent.makeDir.RemoveDirOrganCommand",dirarg);
		agentUtilService.broadcast(command);
		command = new CommonCommand("com.eactive.eai.agent.osd.RemoveOutsideCommand",arg);
		agentUtilService.broadcast(command);
		String adptrBzwkGroupName = (String)map.get("adptrBzwkGroupName");
		if ( adptrBzwkGroupName != null && !adptrBzwkGroupName.trim().equals("")){
			command = new CommonCommand("com.eactive.eai.agent.adapter.RemoveAdapterGroupCommand",adptrBzwkGroupName);
			agentUtilService.broadcast(command);
		}
		command = new CommonCommand("com.eactive.eai.agent.flowController.RemoveBatchTargetCommand",arg);
		agentUtilService.broadcast(command);
		
		return null;
	}

	@RequestMapping(value= "/bap/admin/work/systemInstMan.json",params = "cmd=LIST_INIT_COMBO")
    public ModelAndView initGroupCoCdCombo( HttpServletRequest request,
            HttpServletResponse response) throws Exception {
		
		String bjobBzwkDstcdParam = request.getParameter("bjobBzwkDstcd");

		List<ComboVo> groupCoCd     = comboService.getFromCode("EAIGROUPCOCD");
		List<Map<String, Object>> bjobBzwkDstcd  = ibatisComboService.selectListComboForTableWithCode("TSEAIBJ02", "BJOBBZWKDSTCD", "BJOBBZWKNAME");
		
		List<Map<String, Object>> osidInstiDstcd = null;
		
		if(bjobBzwkDstcdParam == null || bjobBzwkDstcdParam.equals("")) {
			osidInstiDstcd  = transactionService.selectOsidInstiDstcd("");
		}else {
			osidInstiDstcd  = transactionService.selectOsidInstiDstcd(bjobBzwkDstcdParam);
		}
		
		List<ComboVo> useYN          = comboService.getFromCode("USE_YN");
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("bjobBzwkDstcd"         , bjobBzwkDstcd);
		resultMap.put("osidInstiDstcd"         , osidInstiDstcd);
		resultMap.put("useYN"         , useYN);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);
		
		return modelAndView;            
    }     

	@RequestMapping(value= "/bap/admin/work/systemInstMan.json",params = "cmd=LIST_BJOB_BZWK_COMBO")
    public ModelAndView initBjobBzwkDstcdCombo( HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	
		List<Map<String, Object>> bjobBzwkDstcd     = ibatisComboService.selectListComboForTableWithCode("TSEAIBJ02", "BJOBBZWKDSTCD", "BJOBBZWKNAME");		
        
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("bjobBzwkDstcd"         , bjobBzwkDstcd);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);	
		
		return modelAndView;            
    }     

	@RequestMapping(value= "/bap/admin/work/systemInstMan.json",params = "cmd=LIST_BJOB_BZWK_PRCSS_COMBO")
    public ModelAndView initBjobBzwkPrcssDstcdCombo( HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	
		List<Map<String, Object>> bjobBzwkPrcssDstcd     = ibatisComboService.selectListComboForTableWithCode("TSEAIBR04", "BJOBBZWKPRCSSDSTCD", "FLOWRULEPTRNDESC");		
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("bjobBzwkPrcssDstcd"         , bjobBzwkPrcssDstcd);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		
		return modelAndView;            
    }     

	@RequestMapping(value= "/bap/admin/work/systemInstMan.json",params = "cmd=LIST_ADPTR_BZWK_GROUP_NAME_COMBO")
    public ModelAndView initAdptrBzwkGroupName( HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	
		List<Map<String, Object>> adptrBzwkGroupName     = service.getAdaptorGroup();		
        
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("adptrBzwkGroupName"         , adptrBzwkGroupName);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);	
		
		return modelAndView;            
    }     

	@RequestMapping(value= "/bap/admin/work/systemInstMan.json",params = "cmd=LIST_ADPTR_BZWK_NAME_COMBO")
    public ModelAndView initAdptrBzwkName( HttpServletRequest request,
            HttpServletResponse response, @RequestParam  String adptrBzwkGroupName, String rqstRspnsDstcd ) throws Exception {
    	
		logger.debug("adptrBzwkGroupName--->" + adptrBzwkGroupName);
		logger.debug("rqstRspnsDstcd--->" + rqstRspnsDstcd);
		List<Map<String, Object>> adptrBzwkNameList     = service.getAdptrBzwkName(adptrBzwkGroupName, rqstRspnsDstcd);		
//        
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("adptrBzwkNameList"         , adptrBzwkNameList);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);	
		
		return modelAndView;            
    }     

	@RequestMapping(value= "/bap/admin/work/systemInstMan.json",params = "cmd=LIST_PROP")
    public ModelAndView getProps( HttpServletRequest request,
            /*HttpServletResponse response, @RequestParam  String bjobBzwkDstcd) throws Exception {*/
    		HttpServletResponse response, @RequestParam  String bjobBzwkDstcd, String osidInstiDstcd) throws Exception {
    	
		logger.debug("bjobBzwkDstcd--->" + bjobBzwkDstcd);
		logger.debug("osidInstiDstcd--->" + osidInstiDstcd);
		
		String prptyGroupName = "";
		if (bjobBzwkDstcd != null && osidInstiDstcd != null) {
			prptyGroupName = osidInstiDstcd.isEmpty() ? "TelegramInfo{" + bjobBzwkDstcd + "}" : "TelegramInfo{" + bjobBzwkDstcd + "_" + osidInstiDstcd + "}";
		}
		
		HashMap<String, Object> map     = service.getProps(bjobBzwkDstcd, prptyGroupName);		

		ModelAndView modelAndView = new ModelAndView("jsonView", map);	
		
		return modelAndView;
    }     
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value= "/bap/admin/work/systemInstMan.excel",params = "cmd=LIST_GRID_TO_EXCEL")
    public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response, String gridData, String header, String headerTitle, String fileName, String merge) throws Exception {
		HashMap<String,Object> resultMap = new HashMap<String,Object>();
		
    	Gson gson = new Gson();
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);
		String[] headers = gson.fromJson(header, String[].class);
		String[] headerTitles = gson.fromJson(headerTitle, String[].class);
		
		HashMap<String, Object>[] lmerge = null; 
		if (merge !=null){
			lmerge = gson.fromJson(merge, HashMap[].class);
		}
    	
    	resultMap.put("headers", headers);
    	resultMap.put("headerTitles", headerTitles);
    	resultMap.put("datas", list);
    	resultMap.put("fileName", fileName);
    	resultMap.put("merge", lmerge);
		ModelAndView modelAndView = new ModelAndView("excelView",resultMap);	
        
        return modelAndView;
    }
	
	@RequestMapping(value= "/bap/admin/work/systemInstMan.json",params = "cmd=CLONE")
	public ModelAndView clone(HttpServletRequest request,
			HttpServletResponse response,@RequestParam HashMap<String,Object> map, String gridData ) throws Exception {
    	Gson gson = new Gson();
    	@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);
		String userid = com.eactive.eai.rms.common.login.SessionManager.getUserId(request);
		map.put("userid", userid );
    	service.clone(map,list);
		String[] arg = new String[3];
		arg[0] = (String)map.get("bjobBzwkDstcd");
		arg[1] = (String)map.get("osidInstiDstcd");
		arg[2] = (String)map.get("adapterGroupName");
		
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.makeDir.MakeDirOrganCommand",arg);
		agentUtilService.broadcast(command);
		command = new CommonCommand("com.eactive.eai.agent.osd.UpdateOutsideCommand",arg);
		agentUtilService.broadcast(command);
		String adptrBzwkGroupName = (String)map.get("adptrBzwkGroupName");
		if ( !adptrBzwkGroupName.trim().equals("")){
			command = new CommonCommand("com.eactive.eai.agent.adapter.UpdateAdapterGroupCommand",adptrBzwkGroupName);
			agentUtilService.broadcast(command);
		}
		command = new CommonCommand("com.eactive.eai.agent.flowController.AddBatchTargetCommand",arg);
		agentUtilService.broadcast(command);
		
    	command = new CommonCommand("com.eactive.eai.agent.property.UpdatePropertyCommand",(String)map.get("prptyGroupName"));
		agentUtilService.broadcast(command);
		
		ModelAndView modelAndView = new ModelAndView("jsonView", map);	
		
		return modelAndView;
	}	
	
	@RequestMapping(value= "/bap/admin/work/systemInstMan.json",params = "cmd=LIST_DOWNLOAD_SQL")
	public ModelAndView downloadSql(HttpServletRequest request,
		HttpServletResponse response,@RequestParam HashMap<String,Object> map) throws Exception {		

		HashMap<String, Object> systemInstDetail = service.selectDetail(map);
		systemInstDetail.put("userid",com.eactive.eai.rms.common.login.SessionManager.getUserId(request));
		systemInstDetail.putAll(map);
		
    	ModelAndView modelAndView = new ModelAndView("jsonView",service.mkInsertSqlForSystemInst(systemInstDetail));	
		
		return modelAndView;
	}
	
	@RequestMapping(value= "/bap/admin/work/systemInstMan.view",params = "cmd=LIST_FILE_DOWNLOAD")
	public String fileDownload(HttpServletRequest request) throws Exception {
		
		return "/bap/admin/common/filedownload";
	}	
}