package com.eactive.eai.rms.bat.manage.rule.schedule;

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

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.bat.manage.rule.inter.BatInterfaceService;
import com.eactive.eai.rms.common.acl.user.BizDao;
import com.eactive.eai.rms.common.base.BatBaseAnnotationController;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.common.vo.JsonPageVo;
import com.google.gson.Gson;

@Controller
public class BatScheduleController extends BatBaseAnnotationController  {

	@Autowired
	@Qualifier("batScheduleService")
	private BatScheduleService service;
	
	@Autowired
	@Qualifier("bizDao")
	private BizDao bizDao;

	@Autowired
	@Qualifier("batInterfaceService")
	private BatInterfaceService interfaceService;

	
	@RequestMapping(value= "/bat/admin/schedule/scheduleMan.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= "/bat/admin/schedule/scheduleMan.json", params = "cmd=LIST")
	public ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo ,@RequestParam HashMap<String,Object> paramap) throws Exception {
		
		String userid = SessionManager.getUserId(request);
		paramap.put("loginEmpno", userid);
		
		HashMap<String, Object> map = service.selectList( pageVo.getStartNum(), pageVo.getEndNum(), paramap);
		
		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= "/bat/admin/schedule/scheduleMan.json",params = "cmd=LIST_INIT_COMBO")
    public ModelAndView initCombo( HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	
    	
		String userId = SessionManager.getUserId(request);
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", userId);
 
		//업무구분
		List<HashMap<String, Object>> listBiz = bizDao.selectUserBizCodes(paramMap);
        
        Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("bizList"         , listBiz);
		
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;            
    }   

	@RequestMapping(value= "/bat/admin/schedule/scheduleMan.json",params = "cmd=DETAIL")
	public ModelAndView selectDetail(HttpServletRequest request,
			HttpServletResponse response,String bjobMsgScheID) throws Exception {
		
		HashMap<String, Object> map = service.selectDetail(bjobMsgScheID);

		ModelAndView modelAndView = new ModelAndView("jsonView",map);	
		
		return modelAndView;
	}
	
	@RequestMapping(value= "/bat/admin/schedule/scheduleMan.json",params = "cmd=INSERT")
	public ModelAndView insert(HttpServletRequest request,
			HttpServletResponse response,@RequestParam HashMap<String,Object> map, String gridData) throws Exception {
		
		String userid = SessionManager.getUserId(request);
		map.put("userid", userid);
    	Gson gson = new Gson();
    	@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);
    	
    	service.insert(map,list);
    	
    	Vector<String> interfaces = service.selectInterfacesByScheduleId(String.valueOf(map.get("bjobMsgScheID")));
    	
		HashMap<String, Object> broadcastResult = agentUtilService.broadcast(new CommonCommand("com.eactive.eai.agent.scheduler.ReloadBatchInterfaceJobListCommand", interfaces));
		if(!broadcastResult.entrySet().stream().allMatch(entry -> entry.getValue().equals("success"))) {
			String mapString = CommonUtil.getMapString(broadcastResult, false);
			throw new Exception("데이터 수정 완료하였으나 인스턴스 동기화에 실패하였습니다. " + mapString);
		}
		
		ModelAndView modelAndView = new ModelAndView("jsonView",map);	
				
		return modelAndView;
	}	
	@RequestMapping(value= "/bat/admin/schedule/scheduleMan.json",params = "cmd=UPDATE")
	public String update(HttpServletRequest request,
			HttpServletResponse response,@RequestParam HashMap<String,Object> map, String gridData) throws Exception {
		String userid = SessionManager.getUserId(request);
		map.put("userid", userid);
    	Gson gson = new Gson();
    	@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);
		
		service.update(map, list);
		
		Vector<String> interfaces = service.selectInterfacesByScheduleId(String.valueOf(map.get("bjobMsgScheID")));
		
		HashMap<String, Object> broadcastResult = agentUtilService.broadcast(new CommonCommand("com.eactive.eai.agent.scheduler.ReloadBatchInterfaceJobListCommand", interfaces));
		if(!broadcastResult.entrySet().stream().allMatch(entry -> entry.getValue().equals("success"))) {
			String mapString = CommonUtil.getMapString(broadcastResult, false);
			throw new Exception("데이터 수정 완료하였으나 인스턴스 동기화에 실패하였습니다. " + mapString);
		}
		
		return null;
	}
	@RequestMapping(value= "/bat/admin/schedule/scheduleMan.json",params = "cmd=DELETE")
	public String delete(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String,Object> map ) throws Exception {
		
		Vector<String> interfaces = service.selectInterfacesByScheduleId(String.valueOf(map.get("bjobMsgScheID")));
		
		service.delete(map);
		
		HashMap<String, Object> broadcastResult = agentUtilService.broadcast(new CommonCommand("com.eactive.eai.agent.scheduler.RemoveBatchInterfaceJobListCommand", interfaces));
		if(!broadcastResult.entrySet().stream().allMatch(entry -> entry.getValue().equals("success"))) {
			String mapString = CommonUtil.getMapString(broadcastResult, false);
			throw new Exception("데이터 수정 완료하였으나 인스턴스 동기화에 실패하였습니다. " + mapString);
		}
		
		return null;
	}	
	@RequestMapping(value= "/bat/admin/schedule/scheduleMan.json",params = "cmd=LIST_DELETE")
	public String deleteList(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String,Object> map ) throws Exception {

		Vector<String> allInterfaces = new Vector<>();
		String[] bjobMsgScheIDList = map.get("bjobMsgScheIDList").toString().split(",");
		for ( int i=0; i < bjobMsgScheIDList.length; i++ ) {
			String bjobMsgScheID = bjobMsgScheIDList[i];
			HashMap<String, Object> schedMap = new HashMap<String,Object>();
			schedMap.put("bjobMsgScheID", bjobMsgScheID);
			
			Vector<String> interfaces = service.selectInterfacesByScheduleId(bjobMsgScheID);
			allInterfaces.addAll(interfaces);
			
			service.delete(schedMap);
		}
		
		HashMap<String, Object> broadcastResult = agentUtilService.broadcast(new CommonCommand("com.eactive.eai.agent.scheduler.RemoveBatchInterfaceJobListCommand", allInterfaces));
		if(!broadcastResult.entrySet().stream().allMatch(entry -> entry.getValue().equals("success"))) {
			String mapString = CommonUtil.getMapString(broadcastResult, false);
			throw new Exception("데이터 수정 완료하였으나 인스턴스 동기화에 실패하였습니다. " + mapString);
		}
		
		return null;
	}
	@RequestMapping(value= "/bat/admin/schedule/scheduleMan.json", params = "cmd=LIST_INTERFACE")
	public ModelAndView interfaceList(HttpServletRequest request,
			JsonPageVo pageVo ,@RequestParam HashMap<String,Object> paramap) throws Exception {
		
		String userid = SessionManager.getUserId(request);
		paramap.put("loginEmpno", userid);
		
		HashMap<String, Object> map = interfaceService.selectList( pageVo.getStartNum(), pageVo.getEndNum(), paramap);
		
		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= "/bat/admin/schedule/scheduleMan.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.mkInserSqlForSched(map));	
		
		return modelAndView;
	}
	@RequestMapping(value= "/bat/admin/schedule/scheduleMan.view",params = "cmd=LIST_FILE_DOWNLOAD")
	public String fileDownload(HttpServletRequest request) throws Exception {
		
		return "/bat/admin/common/filedownload";
	}
}