package com.eactive.eai.rms.onl.manage.rule.cm;

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

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

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
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.RequestMethod;
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.common.acl.bizKeyTran.BizKeyTranManService;
import com.eactive.eai.rms.common.acl.user.BizService;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.context.MonitoringContext;
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.login.SessionManager;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.common.util.HttpClientUploadUtil;
import com.eactive.eai.rms.onl.manage.rule.upload.IoMapLoaderKey;
import com.google.gson.Gson;

@Controller
public class CMCancelController extends OnlBaseAnnotationController {

	@Autowired
	@Qualifier("monitoringContext")
	private MonitoringContext monitoringContext;
 
    @Autowired
	@Qualifier("bizService")
    private BizService bizService;
	
	@Autowired
    private BizKeyTranManService bizKeyTranManService;
	
	@Autowired
    @Qualifier("cMCancelService")
    private CMCancelService service;
	 
    /**
     * CM 저장취소 관련 컨트롤러
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    
    @RequestMapping(value= "/onl/admin/rule/cmCancel.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/admin/rule/cmCancel.json", params="cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request, String searchBzwkDstcd,String searchPkgNum) throws Exception {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		String userId = SessionManager.getUserId(request);
		Properties prop = monitoringContext.getProperties();
		
//		if (!SystemUtil.isStagingServer()){
//    		throw new Exception("only support staging server ");
//    	}
		
		if (prop == null || prop.size()==0) {
			throw new Exception("프라퍼티 정보가 없습니다. - CM_CONFIG"); 
		}
		String auroraIni = (String)prop.getProperty(MonitoringContext.CM_AURORA_INI_PATH,"/fshome/greai/eaiadm/aurora/auroraApi_config.ini");
			//List ret = new ArrayList();
		try {
//			AuroraUtil aurora = new AuroraUtil(auroraIni);
			String apCode = bizKeyTranManService.selectBizKeyForApCode(searchBzwkDstcd);
			String groupCoCd = bizService.selectGroupCoCdByEAIBzwkDstCd(searchBzwkDstcd);
//			userId = "S012447";
			List cmList = new ArrayList();
			if (userId != null && groupCoCd != null && apCode != null && searchPkgNum != null) {
//				cmList = aurora.getCmFileList(userId, groupCoCd, apCode,searchPkgNum);
			}
			if (cmList == null || cmList.size() == 0) {
				resultMap.put("status","fail");
				resultMap.put("message","해당 패키지에 대한 리스트가 없습니다.");
			}
			resultMap.put("cmList", cmList);
		} catch (BizException be) {
			throw new Exception(be.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new Exception(e.getMessage());
		}
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}
    
    @RequestMapping(value= "/onl/admin/rule/cmCancel.json", params="cmd=LIST_PKG_COMBO")
   	private ModelAndView selectComboChange(HttpServletRequest request, String searchBzwkDstcd) throws Exception {
   		HashMap<String, Object> resultMap = new HashMap<String, Object>();
   		String userId = SessionManager.getUserId(request);
   		Properties prop = monitoringContext.getProperties();
   		
//   		if (!SystemUtil.isStagingServer()){
//       		throw new Exception("only support staging server ");
//       	}
   		
   		if (prop == null || prop.size()==0) {
   			throw new Exception("프라퍼티 정보가 없습니다. - CM_CONFIG"); 
   		}
   		String auroraIni = (String)prop.getProperty(MonitoringContext.CM_AURORA_INI_PATH,"/fshome/greai/eaiadm/aurora/auroraApi_config.ini");
   		try {
   			String groupCoCd = bizService.selectGroupCoCdByEAIBzwkDstCd(searchBzwkDstcd);
//   			AuroraUtil aurora = new AuroraUtil(auroraIni);
   			String apCode = bizKeyTranManService.selectBizKeyForApCode(searchBzwkDstcd);
//   			userId = "S012447";
//   			List cmList = aurora.getCMList(userId, groupCoCd, apCode);
//   			if (cmList == null || cmList.size() == 0) {
//   				throw new BizException("해당 업무에 대한 CM 패키지가 없습니다.");
//   			}
//   			resultMap.put("cmList", cmList);
   		} catch (BizException be) {
   			throw new Exception(be.getMessage());
   		} catch (Exception e) {
   			logger.error(e.getMessage());
   			throw new Exception(e.getMessage());
   		}
   		
   		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
   		return modelAndView;
   	}
    @RequestMapping(value= "/onl/admin/rule/cmCancel.json",params = "cmd=LIST_INIT_COMBO")
    public ModelAndView initBizCombo( HttpServletRequest request,
            HttpServletResponse response,String searchBzwkDstcd) throws Exception {
    	
		String userId = SessionManager.getUserId(request);
		 //취약점소스 수정 2020.08.25
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", userId);
		paramMap.put("searchBzwkName", "");
		paramMap.put("targetGridYn", "Y");
		List<HashMap<String,Object>> bizList = bizService.selectUserBizList(paramMap);
		//List<HashMap<String,Object>> bizList = bizService.selectUserBizList(userId,"","Y");
		
		Map resultMap = new HashMap();
		resultMap.put("bizList", bizList);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;            
    } 
    @RequestMapping(value= "/onl/admin/rule/cmCancel.json",params = "cmd=CHANGE_CANCEL")
    public ModelAndView cmCancelList( HttpServletRequest request,
            HttpServletResponse response, @RequestParam HashMap paramMap) throws Exception {
    	Properties prop = monitoringContext.getProperties();
    	String userId = SessionManager.getUserId(request);
    	String groupCoCd = bizService.selectGroupCoCdByEAIBzwkDstCd((String)paramMap.get("apCode"));
//    	userId = "S012447";
    	paramMap.put("groupCoCd", groupCoCd);
    	paramMap.put("userId", userId);
    	
    	String chkItems = (String)paramMap.get("chkItems");
		String statusItems = (String)paramMap.get("statusItems");
		String apCode = (String)paramMap.get("apCode");
		String pkgNum = (String)paramMap.get("pkgNum");
		String versionItems = (String)paramMap.get("versionItems");
		String sevrDstcdItems = (String)paramMap.get("sevrDstcdItems");
		
		String[] chkItemsArr = chkItems.split(",");			// ex) EAI_TST003_REQ1.txt
		String[] statusArr = statusItems.split(",");		// ex) true or false
		String[] itemPath = sevrDstcdItems.split(",");		// ex) /DSG/layout
		String[] versionStr = versionItems.split(",");		// ex) 0,1..
		int[] version = new int[versionStr.length];
		
		for(int i=0; i<versionStr.length; i++){
			version[i]=Integer.parseInt(versionStr[i]);
		}
    	for(int i=0; i<chkItemsArr.length; i++){
    		try{
				String itemName = chkItemsArr[i]; //자원명(file name)
				//CM취소가 가능한 상태는 무조건 개발확정[ N ] 상태
				//스테이징 적용 미적용으로 데이터를 변경할지 cm 취소만 할지 결정  
				
				if(statusArr[i].equals("false")){
					String auroraIni = (String)prop.getProperty(MonitoringContext.CM_AURORA_INI_PATH,"/fshome/greai/eaiadm/aurora/auroraApi_config.ini");
//					AuroraUtil aurora = new AuroraUtil(auroraIni);
					//변환, 레이아웃 둘다
//					aurora.cancelCmSave(pkgNum, userId, apCode, itemName, auroraIni,itemPath[i]);
					
				}else{
					// 패스에서 서버구분코드 받아오기.
					String[] sevrDstcdTmp = itemPath[i].split("/");
					String sevrDstcd = "";
					for(String s : sevrDstcdTmp){
						if("NSG".equals(s) || "DSG".equals(s) || "GSG".equals(s) ||"ZSG".equals(s) || "ASG".equals(s)){
							sevrDstcd = s;
						}
					}
					DataSourceType dataSourceType = DataSourceTypeManager.getDataSourceType(sevrDstcd);
					DataSourceContextHolder.setDataSourceType(dataSourceType);	
					String itemStr = itemName.replace(".txt", "");
					if(itemName.startsWith("TRANSFORM_"+apCode.toUpperCase())){	//변환
						String targetBaseUrl = prop.getProperty(MonitoringContext.CM_PROD_BASEURL , "http://127.0.0.1:30711/monitoring");
						//변환일 때 서비스코드 업데이트
						logger.info("------- EAISVCNAME SELECT -------");
						//스테이징에서 변환 ID로 운영의 EAI 서비스코드 조회
						HashMap eaiSvcParam = new HashMap();
						eaiSvcParam.put("CNVSNNAME", itemStr);
						String eaiSvcNameStr = "";
						// 서비스코드에 서버구분코드 받아오기.
						
						HashMap map = new HashMap();
						List<HashMap> eaiSvcArr = service.selectEaiSvcName(eaiSvcParam);
						Vector vec = new Vector<>();	//나중에 메모리 Reload용 벡터 
						String svrDstcd ="";
						for(HashMap m : eaiSvcArr){
							String eaiSvcName = (String)m.get("EAISVCNAME");
							svrDstcd = (String)m.get("EAISEVRDSTCD");
							eaiSvcNameStr+=eaiSvcName+",";
							vec.add(eaiSvcName);
						}
				    	
						String extUrl = "/onl/admin/rule/cmCancel.file";
						
						map.put("cmd", "PROD_DATA");
						map.put("eaiSvcName", eaiSvcNameStr);
						map.put("svrDstcd", IoMapLoaderKey.getEaiSevrName(svrDstcd) );
						logger.info("------------- SYSTEM DATA -----------\n"+eaiSvcNameStr);
						logger.info("------------- TARGET URL -----------\n"+targetBaseUrl+extUrl);
						
						String data = HttpClientUploadUtil.post( targetBaseUrl+extUrl, map );
						logger.info("-------------- PROD DATA ---------  \n"+ data);
						List<HashMap> list = new ArrayList<>();
						if(!"".equals(data)){
							data = data.trim();
							JSONParser parser = new JSONParser();
							JSONObject obj = (JSONObject)parser.parse(data);
							JSONArray rows = (JSONArray)obj.get("rows");
							for(int s=0;s<rows.size();s++){
								JSONObject dataObj = (JSONObject)rows.get(s);
								HashMap resMap = new HashMap();
								for(Object key : dataObj.keySet()){
									resMap.put(key.toString(), dataObj.get(key));
									if(key.equals("EAISVCNAME")){
										for(HashMap m : eaiSvcArr){
											if(m.get("EAISVCNAME").equals(dataObj.get("EAISVCNAME"))){
												if(m.get("CHNGMSGIDNAME").equals("O")){
													resMap.put("REQ", itemStr);
												}
												if(m.get("BASCRSPNSCHNGMSGIDNAME").equals("O")){
													resMap.put("RES", itemStr);
												}
												if(m.get("ERRRSPNSCHNGMSGIDNAME").equals("O")){
													resMap.put("ERR", itemStr);
												}
											}
										}
									}
								}
								list.add(resMap);
							}
						}
						service.transactionTran(itemName, apCode, pkgNum, userId, groupCoCd,list,itemPath[i],version[i]);
						CommonCommand command = new CommonCommand("com.eactive.eai.agent.transformer.ReloadTransformCommand",itemStr);
						agentUtilService.broadcast(command);
				    	if(vec != null && vec.size()>0){
				    		command = new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadEAIMessageListCommand",vec);
				    		agentUtilService.broadcast(command);    
				    	}
						
					}else if(itemName.startsWith(apCode.toUpperCase()+"_")){	//레이아웃 
						
						service.transactionLout(itemName, apCode, pkgNum, userId, groupCoCd,itemPath[i],version[i]);
						CommonCommand command = new CommonCommand("com.eactive.eai.agent.transformer.ReloadLayoutCommand",itemStr);
						//레이아웃에 걸려있는 변환 검색 ! 
						List<HashMap> tranList = service.selectTrasnForm(itemStr);
						if(tranList!=null && tranList.size()>0){
							Vector<String> vec = new Vector<>();
							for(HashMap m : tranList){
								vec.add((String)m.get("CNVSNNAME"));
							}
				    		command = new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadTransformListCommand",vec);
				    		agentUtilService.broadcast(command);    
						}
					}
				}
    		}catch(Exception e){
    			throw new Exception(chkItemsArr[i] + " 실패  , error : "+e.getMessage());
    		}
		}
		return null;            
    } 
    
    @RequestMapping(value= "/onl/admin/rule/cmCancel.file",params = "cmd=PROD_DATA", method=RequestMethod.POST)
    public ModelAndView selectFileList(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	
//    	if (!SystemUtil.isProdServer()){
//            HashMap resultMap = new HashMap();
//            resultMap.put("status", "fail");
//            resultMap.put("errorMsg","not support this server");
//            return new ModelAndView("jsonView", resultMap);
//    	}        
    	
		String eaiSvcStr = request.getParameter("eaiSvcName");
		String eaiSevrDstcd = request.getParameter("svrDstcd");
		
		List list = new ArrayList();
		if (eaiSvcStr != null && eaiSevrDstcd != null) {
			list = service.searchEaiSvcName(eaiSvcStr,eaiSevrDstcd);
		}
		logger.debug("cmCancel(PROD DATA) content-Type="+request.getContentType());

		Map resultMap = new HashMap();
		resultMap.put("rows"   , list);
		return new ModelAndView("jsonView",resultMap);		
    }    
    @RequestMapping(value= "/onl/admin/rule/cmCancel.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;
    }	
}
