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

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.common.util.SystemUtil;
import com.eactive.eai.rms.common.base.BapBaseAnnotationController;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.IbatisComboService;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.util.MonitoringSyncAgent;
import com.eactive.eai.rms.common.vo.JsonPageVo;

@Controller
public class BapSystemIDController extends BapBaseAnnotationController  {

	@Autowired
	@Qualifier("bapSystemIDService")
	private BapSystemIDService service;

	@Autowired
	private ComboService comboService;
	
    @Autowired
    private IbatisComboService ibatisComboService; 
    
	@Autowired
    @Qualifier("monitoringContext")
    private MonitoringContext monitoringContext;
	
	@Autowired
	@Qualifier("monitoringSyncAgent")
	private MonitoringSyncAgent monitoringSyncAgent;

	@RequestMapping(value= "/bap/admin/work/systemIDMan.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/systemIDMan.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/systemIDMan.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/systemIDMan.json",params = "cmd=INSERT")
	public void insert(HttpServletRequest request,
			HttpServletResponse response,@RequestParam HashMap<String,Object> map ) throws Exception {

    	service.insert(map);

		if(SystemUtil.isDevServer()){ 
			//MMI 연계
			HashMap param = new HashMap();
			param.put("inttSysDcd",map.get("systemId") != null ? map.get("systemId") : "" );	// 시스템ID
			param.put("inttSysNm",map.get("systemName") != null ? map.get("systemName") : "");  // 시스템명
			param.put("actType","I");  //실행구분
			param.put("inaoDcd","2");  //인터페이스구분(온라인:1/일괄전송:2) 추가  
			callMmiService(param);
		}
	}	
	@RequestMapping(value= "/bap/admin/work/systemIDMan.json",params = "cmd=UPDATE")
	public void update(HttpServletRequest request,
			HttpServletResponse response,@RequestParam HashMap<String,Object> map) throws Exception {

		service.update(map);

		if(SystemUtil.isDevServer()){ 
			//MMI 연계
			HashMap param = new HashMap();
			param.put("inttSysDcd",map.get("systemId") != null ? map.get("systemId") : "" );	// 시스템ID
			param.put("inttSysNm",map.get("systemName") != null ? map.get("systemName") : "");  // 시스템명
			param.put("actType","U");  //실행구분
			param.put("inaoDcd","2");  //인터페이스구분(온라인:1/일괄전송:2) 추가  
			callMmiService(param);
		}
	}
	@RequestMapping(value= "/bap/admin/work/systemIDMan.json",params = "cmd=DELETE")
	public void delete(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String, Object> map ) throws Exception {

		service.delete(map);
		
		if(SystemUtil.isDevServer()){ 
			//MMI 연계
			HashMap param = new HashMap();
			param.put("inttSysDcd",map.get("systemId") != null ? map.get("systemId") : "" );	// 시스템ID
			param.put("inttSysNm",map.get("systemName") != null ? map.get("systemName") : "");  // 시스템명
			param.put("actType","D");  //실행구분
			param.put("inaoDcd","2");  //인터페이스구분(온라인:1/일괄전송:2) 추가  
			callMmiService(param);
		}
	}
	@RequestMapping(value= "/bap/admin/work/systemIDMan.json",params = "cmd=LIST_INIT_COMBO")
    public ModelAndView initCombo( HttpServletRequest request,
            HttpServletResponse response) throws Exception {
		List<Map<String, Object>> bjobBzwkDstcdRows = ibatisComboService.selectListComboForTable("TSEAIBJ02", "BJOBBZWKDSTCD", "BJOBBZWKNAME");
        
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("bjobBzwkDstcdRows"         , bjobBzwkDstcdRows);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);
		
		return modelAndView;            
    }     
	@RequestMapping(value= "/bap/admin/work/systemIDMan.json",params = "cmd=LIST_FILTER_COMBO")
    public ModelAndView initFilterCombo( HttpServletRequest request,
            HttpServletResponse response, String bJobBzwkDstcd) throws Exception {
		List<Map<String, Object>> osidInstiRows     
			= ibatisComboService.selectListComboForTable("TSEAIBJ06", "OSIDINSTIDSTCD", "OSIDINSTINAME", "BJOBBZWKDSTCD='"+bJobBzwkDstcd+"'");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("osidInstiRows"         	  , osidInstiRows);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);
		
		return modelAndView;            
    }
	
	//[MMI연계] 개발에서만 http://10.37.10.103:8010/sqa/eaiSystemReg.do (본오픈 MMI) 호출
	public void callMmiService(HashMap<String,String> paramMap) throws Exception{
		if (true) return;
		String ret = null;
		String extUrl = monitoringContext.getStringProperty(MonitoringContext.RMS_ADAPTER_NICKNAME_SYNC_URL,"");
		if ("".equals(extUrl)){
			return;
		}
		
		String targetUrl = "" + extUrl;
		
		logger.info("mmi paramMap : " + paramMap.toString());
		logger.info("mmi call Url : " + targetUrl);
		
		try{
			ret = monitoringSyncAgent.callService2(targetUrl, paramMap);
			logger.info("ret : " + ret.toString());
		}
		catch(Exception e)
		{
			logger.error("callMmiService error", e);
		}
		finally{
			logger.info("callMmiService Result : " + ret);
		}
	}
	@RequestMapping(value= "/bap/admin/work/systemIDMan.json",params = "cmd=LIST_DELETE")
	public void deleteList(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String,Object> map ) throws Exception {

		for (String systemID : map.get("systemIDList").toString().split(",")) {
			HashMap<String, Object> param = new HashMap<String,Object>();
			param.put("systemId", systemID);
			
			HashMap<String, Object> paramDetail = service.selectDetail(param);
			service.delete(param);

			if(SystemUtil.isDevServer()){ 
				//MMI 연계
				HashMap paramMmi = new HashMap();
				paramMmi.put("inttSysDcd",paramDetail.get("SYSTEMID") != null ? paramDetail.get("SYSTEMID") : "" );	// 시스템ID
				paramMmi.put("inttSysNm",paramDetail.get("SYSTEMNAME") != null ? paramDetail.get("SYSTEMNAME") : "");  // 시스템명
				paramMmi.put("actType","D");  //실행구분
				paramMmi.put("inaoDcd","2");  //인터페이스구분(온라인:1/일괄전송:2) 
				callMmiService(paramMmi);
			}
		}
	}
	@RequestMapping(value= "/bap/admin/work/systemIDMan.json",params = "cmd=LIST_DOWNLOAD_SQL")
	public ModelAndView downloadSql(HttpServletRequest request,
		HttpServletResponse response,@RequestParam HashMap<String,Object> map) throws Exception {		

    	ModelAndView modelAndView = new ModelAndView("jsonView",service.mkInsertSqlForSystemId(map));	
		
		return modelAndView;
	}
	@RequestMapping(value= "/bap/admin/work/systemIDMan.view",params = "cmd=LIST_FILE_DOWNLOAD")
	public String fileDownload(HttpServletRequest request) throws Exception {
		
		return "/bap/admin/common/filedownload";
	}
}