package com.eactive.eai.rms.onl.statistics.statisticinfo.osidinstistatistic;

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 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.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.spring.BaseController;
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;





/**
 * @author  : yk
 * @version : $Revision: 1.1 $
 */
@Controller
public class OsidInstiStatisticController extends BaseController  {
	
    @Autowired
    @Qualifier("osidInstiStatisticService")
    private OsidInstiStatisticService service ;
	
	@RequestMapping(value= "/onl/statistics/statisticinfo/osidInstiStatisticMan.view")
	private 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;
	}      
    

	@RequestMapping(value= "/onl/statistics/statisticinfo/osidInstiStatisticMan.json",params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo ,@RequestParam HashMap<String, Object> paramMap ) throws Exception {
		List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> companCountMap = new HashMap<String,Object>();  
		//각 서버의 대외기관 조회 전체 카운트 
		for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes() ) {
			if(d.getName() != null){
				
				companCountMap = new HashMap<String,Object>();  
				DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
				DataSourceContextHolder.setDataSourceType(dt);
				String schemaId = "";
				if(dt != null){
					schemaId = dt.getSchema();
				}
				String value =  d.getName();
				value = value.substring(0,1);
				
				paramMap.put("schemaId", schemaId);
				paramMap.put("sqlValue", value);
				
				int  companyNum = 0;
				int  apcodeNum = 0;
				companyNum = service.selectCompanyListCount(paramMap);
				apcodeNum = service.selectApcodeListCount(paramMap);
				
				companCountMap.put("SERVERTYPE", d.getText());
				companCountMap.put("SERVERTYPE_VALUE", value);
				companCountMap.put("SERVERTYPE_NAME", d.getName());
				companCountMap.put("COMPANYNUM", companyNum);
				companCountMap.put("APCODENUM", apcodeNum);
				
			}
			resultList.add(companCountMap);
		}
		
		
		Map resultMap = new HashMap();
		resultMap.put("rows"   , resultList);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}
	

	@RequestMapping(value= "/onl/statistics/statisticinfo/osidInstiStatisticMan.json",params = "cmd=DETAIL")
	private ModelAndView selectCompanyList(HttpServletRequest request,
			JsonPageVo pageVo ,@RequestParam HashMap<String, Object> paramMap ) throws Exception {
		
		List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
		DataSourceContextHolder.setDataSourceType(dt);
		String schemaId = "";
		if(dt != null){
			schemaId = dt.getSchema();
		}
		
		paramMap.put("schemaId", schemaId);
		
		if("company".equals(paramMap.get("flag").toString())){
			resultList = service.selectCompanyList(paramMap);
		}else{
			resultList = service.selectApcodeList(paramMap);
		}
		
		Map resultMap = new HashMap();
		resultMap.put("rows"   , resultList);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}
	

	@RequestMapping(value = "/onl/statistics/statisticinfo/osidInstiStatisticMan.json", params = "cmd=TRANSACTION_COMPANY")
	public ModelAndView insert(HttpServletRequest request,HttpServletResponse response,@RequestParam HashMap<String, Object> map) throws Exception {
		
		String message = "success";
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
      	DataSourceContextHolder.setDataSourceType(dt);
		String schemaId ="";
		if(dt != null){
			schemaId = dt.getSchema();
		}
		
    	map.put("schemaId", schemaId);
		try{
			service.insertCompanyList(map);
		}catch(Exception e){
			logger.error("insert error " + e.getMessage());
			message = "등록에 실패했습니다.";
		}
		
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", message);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;

	}
	
	@RequestMapping(value = "/onl/statistics/statisticinfo/osidInstiStatisticMan.json", params = "cmd=DELETE_COMPANY")
	public ModelAndView deleteList(HttpServletRequest request,
			HttpServletResponse response,String gridData,String eaiSevrDstcd) throws Exception {
		
		String message = "success";
		
		Gson gson = new Gson();
		@SuppressWarnings("unchecked")
		
		HashMap<String, Object>[] list = gson.fromJson(gridData,HashMap[].class);
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
      	DataSourceContextHolder.setDataSourceType(dt);
		String schemaId ="";
		if(dt != null){
			schemaId = dt.getSchema();
		}
		
		try{
			for (HashMap<String, Object> map : list) {
				paramMap.put("eaiSevrDstcd", eaiSevrDstcd);
				paramMap.put("schemaId", schemaId);
				paramMap.put("instiName", map.get("INSTINAME"));
				service.deleteCompanyList(paramMap);
			}
		}catch (Exception e){
			logger.debug("delete comany error"+e.getMessage());
			message = "error";
		}

		Map resultMap = new HashMap();
		resultMap.put("result"   , message);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
	}
	
	@RequestMapping(value = "/onl/statistics/statisticinfo/osidInstiStatisticMan.json", params = "cmd=TRANSACTION_APCODE")
	public ModelAndView insertApcode(HttpServletRequest request,HttpServletResponse response,@RequestParam HashMap<String, Object> map) throws Exception {
		
		String message = "success";
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
      	DataSourceContextHolder.setDataSourceType(dt);
		String schemaId ="";
		if(dt != null){
			schemaId = dt.getSchema();
		}
		
		map.put("schemaId", schemaId);
		
		int duplChk = 0;
		duplChk = service.selectApcodeDuplchk(map);
		
		if(duplChk > 0){
			message = "존재하는 AP코드  입니다";
		}else{
			try{
				service.insertApCodeList(map);
			}catch(Exception e){
				logger.error("insert error " + e.getMessage());
				message = "등록에 실패했습니다.";
			}
		}
		
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", message);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;

	}
	
	@RequestMapping(value = "/onl/statistics/statisticinfo/osidInstiStatisticMan.json", params = "cmd=DELETE_APCODE")
	public ModelAndView deleteApcodeList(HttpServletRequest request,
			HttpServletResponse response,String gridData ,String eaiSevrDstcd) throws Exception {
		String message = "success";
			
		Gson gson = new Gson();
		@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = gson.fromJson(gridData,HashMap[].class);
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
      	DataSourceContextHolder.setDataSourceType(dt);
		String schemaId ="";
		if(dt != null){
			schemaId = dt.getSchema();
		}
		
		try{
			for (HashMap<String, Object> map : list) {
				paramMap.put("eaiSevrDstcd", eaiSevrDstcd);
				paramMap.put("schemaId", schemaId);
				paramMap.put("apCode", map.get("APCODE"));
				service.deleteApCodeList(paramMap);
			}
		}catch (Exception e){
			logger.debug("delete apcode error"+e.getMessage());
			message = "error";
		}

		Map resultMap = new HashMap();
		resultMap.put("result"   , message);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
	}
	
	@RequestMapping(value= "/onl/statistics/statisticinfo/osidInstiStatisticMan.json",params = "cmd=LIST_BLACK")
	private ModelAndView blacklist(HttpServletRequest request,
			JsonPageVo pageVo ,@RequestParam HashMap<String, Object> paramMap ) throws Exception {
		
		List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
		
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
		DataSourceContextHolder.setDataSourceType(dt);
		String schemaId = "";
		if(dt != null){
			schemaId = dt.getSchema();
		}
		
		paramMap.put("schemaId", schemaId);
		paramMap.put("sqlValue", "X");
		
		if("company".equals(paramMap.get("flag").toString())){
			resultList = service.selectCompanyList(paramMap);
		}else{
			resultList = service.selectApcodeList(paramMap);
		}
				
		
		Map resultMap = new HashMap();
		resultMap.put("rows"   , resultList);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}
	
	@RequestMapping(value = "/onl/statistics/statisticinfo/osidInstiStatisticMan.json", params = "cmd=TRANSACTION_BLACK_COMPANY")
	public ModelAndView insertBlackCompany(HttpServletRequest request,HttpServletResponse response,@RequestParam HashMap<String, Object> map) throws Exception {
		
		String message = "success";
		
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
      	DataSourceContextHolder.setDataSourceType(dt);
		String schemaId ="";
		
		if(dt != null){
			schemaId = dt.getSchema();
		}
		
    	map.put("schemaId", schemaId);
    	map.put("baseYmd", CommonUtil.getToday("yyyyMMdd"));
		try{
			service.insertBlackCompanyList(map);
		}catch(Exception e){
			logger.error("insert error " + e.getMessage());
			message = "등록에 실패했습니다.";
		}
		
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", message);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;

	}
	
	@RequestMapping(value = "/onl/statistics/statisticinfo/osidInstiStatisticMan.json", params = "cmd=TRANSACTION_BLACK_APCODE")
	public ModelAndView insertBlackApcode(HttpServletRequest request,HttpServletResponse response,@RequestParam HashMap<String, Object> map) throws Exception {
		
		String message = "success";
		
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
      	DataSourceContextHolder.setDataSourceType(dt);
		String schemaId ="";
		
		if(dt != null){
			schemaId = dt.getSchema();
		}
    	map.put("schemaId", schemaId);
    	map.put("baseYmd", CommonUtil.getToday("yyyyMMdd"));
    	map.put("sqlValue", "X");
    	
    	int duplChk = 0;
		duplChk = service.selectApcodeDuplchk(map);
		
		if(duplChk > 0){
			message = "존재하는 AP코드  입니다";
		}else{
			try{
				service.insertBlackApCodeList(map);
			}catch(Exception e){
				logger.error("insert error " + e.getMessage());
				message = "등록에 실패했습니다.";
			}
		}
		
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", message);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;

	}
	
	@RequestMapping(value = "/onl/statistics/statisticinfo/osidInstiStatisticMan.json", params = "cmd=TRANSACTION_BLACKLIST_DB_SYNC")
	public ModelAndView insertDbSync(HttpServletRequest request,HttpServletResponse response,@RequestParam HashMap<String, Object> map) throws Exception {
		
		String message = "success";
		
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
      	DataSourceContextHolder.setDataSourceType(dt);
		String schemaId ="";
		
		if(dt != null){
			schemaId = dt.getSchema();
		}
		
    	map.put("schemaId", schemaId);
		
    	List<HashMap<String, Object>> blackList_company = null;
		List<HashMap<String, Object>> blackList_apcode = null;
		List<HashMap<String, Object>> SelectCompanyList = null;
		List<HashMap<String, Object>> SelectAPCodeList = null;

		map.put("sqlValue", "X");

		blackList_company = service.selectCompanyList(map);
		blackList_apcode = service.selectApcodeList(map);
		SelectCompanyList = service.selectNotInCompanyList(map);
		SelectAPCodeList = service.selectNotInApcodeList(map);

		Map<String,String> CompanyListMap = new HashMap<String,String>();
		for ( HashMap<String, Object> tmpVo : SelectCompanyList ) {
			CompanyListMap.put((String) tmpVo.get("INSTINAME"), (String) tmpVo.get("INSTINAME"));
		}

		Map<String,String> ApCodeListMap = new HashMap<String,String>();
		for ( HashMap<String, Object> tmpVo : SelectAPCodeList ) {
			ApCodeListMap.put(tmpVo.get("APCODE").toString().trim(), (String) tmpVo.get("APCODE"));
		}

		//블랙리스트에 있는 대외기관 업무코드 삭제
		for( HashMap<String, Object> vo_update : blackList_company ) {
			if (CompanyListMap.containsKey(vo_update.get("INSTINAME"))){
				HashMap paramMap = new HashMap();
				paramMap.put("instiName" , vo_update.get("INSTINAME"));
				paramMap.put("eaiSevrDstcd", null);
				paramMap.put("notIn", "X");
				try{
					service.deleteCompanyList(paramMap);
				}catch(Exception e){
					logger.warn("블랙리스트 기관 sync error "+ " ["+vo_update.get("INSTINAME")+"]", e);
				}	
			}
		}			
		
		for(  HashMap<String, Object> vo_update : blackList_apcode ) {
			if (ApCodeListMap.containsKey(vo_update.get("APCODE").toString().trim())){
				HashMap paramMap = new HashMap();
				paramMap.put("apCode", vo_update.get("APCODE"));
				paramMap.put("eaiSevrDstcd", null);
				paramMap.put("notIn", "X");
				try{
					service.deleteApCodeList(paramMap);
				}catch(Exception e){
					logger.warn("블랙리스트 기관 sync error "+ " ["+vo_update.get("APCODE")+"]", e);
				}	
			} 
		}
		
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", message);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
		
	}
	
	@RequestMapping(value = "/onl/statistics/statisticinfo/osidInstiStatisticMan.json", params = "cmd=TRANSACTION_MOVE_TO_BLACKLIST_COMPANY")
	public ModelAndView moveCompany(HttpServletRequest request,HttpServletResponse response,String gridData,String eaiSevrDstcd) throws Exception {
		
		String message = "success";
		Gson gson = new Gson();
		@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = gson.fromJson(gridData,HashMap[].class);
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
      	DataSourceContextHolder.setDataSourceType(dt);
		String schemaId ="";
		if(dt != null){
			schemaId = dt.getSchema();
		}
		
		try{
			for (HashMap<String, Object> map : list) {
				paramMap.put("schemaId", schemaId);
				//paramMap.put("eaiSevrDstcd", null);
				paramMap.put("eaiSevrDstcd", eaiSevrDstcd);
				paramMap.put("NotIn", "X");
				paramMap.put("baseYmd", CommonUtil.getToday("yyyyMMdd"));
				paramMap.put("instiName", map.get("INSTINAME"));
				service.insertBlackCompanyList(paramMap);
				service.deleteCompanyList(paramMap);
			}
		}catch (Exception e){
			logger.debug("moveCompany error"+e.getMessage());
			message = "error";
		}
		
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", message);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
		
	}	
	
	@RequestMapping(value = "/onl/statistics/statisticinfo/osidInstiStatisticMan.json", params = "cmd=TRANSACTION_MOVE_TO_BLACKLIST_APCODE")
	public ModelAndView moveApcode(HttpServletRequest request,HttpServletResponse response,String gridData,String eaiSevrDstcd) throws Exception {
		
		String message = "success";

		Gson gson = new Gson();
		@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = gson.fromJson(gridData,HashMap[].class);
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
      	DataSourceContextHolder.setDataSourceType(dt);
		String schemaId ="";
		if(dt != null){
			schemaId = dt.getSchema();
		}
		
		try{
			for (HashMap<String, Object> map : list) {
				paramMap.put("schemaId", schemaId);
				//paramMap.put("eaiSevrDstcd", null);
				paramMap.put("eaiSevrDstcd", eaiSevrDstcd);
				paramMap.put("NotIn", "X");
				paramMap.put("baseYmd", CommonUtil.getToday("yyyyMMdd"));
				paramMap.put("apCode", map.get("APCODE"));
				service.insertBlackApCodeList(paramMap);
				service.deleteApCodeList(paramMap);
			}
		}catch (Exception e){
			logger.debug("moveCompany error"+e.getMessage());
			message = "error";
		}
		
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", message);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
		
	}	
		
	
	@RequestMapping(value= "/onl/statistics/statisticinfo/osidInstiStatisticMan.excel",params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String,Object> paramMap) throws Exception {
		
		HashMap<String,Object> resultMap = new HashMap<String,Object>();
		Gson gson = new Gson();
    	String jsonStr = (String)paramMap.get("gridData");
    	HashMap<String, Object>[] dataList = 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);
    	
    	resultMap.put("headers", headers);
    	resultMap.put("headerTitles", headerTitles);
    	resultMap.put("datas", dataList);
    	resultMap.put("fileName", (String)paramMap.get("fileName"));
		ModelAndView modelAndView = new ModelAndView("excelView",resultMap);	
        return modelAndView;
    }	
	
}
