package com.eactive.eai.rms.bap.manage.message.flowrule;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.eactive.eai.rms.bap.common.base.BapBaseService;
import com.eactive.eai.rms.bap.manage.comm.property.BapPropertyDao;
import com.eactive.eai.rms.common.util.SqlUtil;

@Service("bapFlowRuleService")
public class BapFlowRuleService extends BapBaseService {

	@Autowired
	@Qualifier("bapFlowRuleDao")
	private BapFlowRuleDao dao;

	@Autowired
	@Qualifier("bapPropertyDao")
	private BapPropertyDao propDao;

	public HashMap<String, Object> selectList(int startNum,int endNum, HashMap<String, Object> paramMap) throws Exception {
 
		// 전체 목록수 얻기
		int totalCount = dao.selectListCount(paramMap);

		paramMap.put("startNum" , startNum);// 시작 record
		paramMap.put("endNum"   , endNum);// 끝 record

		List<Map<String, Object>> list = dao.selectList(paramMap);
		HashMap<String, Object> map = new HashMap<String, Object>();

		map.put("totalCount", totalCount);
		map.put("list", list);
		
		return map;
	}	

	public HashMap<String, Object> selectDetail(String key) throws Exception {
		// key = bjobBzwkPrcssDstcd
		HashMap<String, Object>   detail = dao.selectDetail(key);
		List<Map<String, Object>> list   = dao.msgList(key);		

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("detail", detail);
		map.put("list", list);
		
		return map;
	}	

	public HashMap<String, Object> selectPopCombo(HashMap<String,Object> paramMap) throws Exception {
		List<Map<String, Object>> stgeDstcdList   = dao.getBjobStgeDstcd(paramMap);

		HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("stgeDstcdList", stgeDstcdList);
		
		return map;

	}		
	public void update(HashMap<String, Object> paramMap, HashMap<String, Object>[] list )throws Exception {
		dao.update(paramMap);
		dao.deleteList(paramMap);

		HashMap<String, Object> data ;
		for(HashMap<String, Object> map : list){
			data = new HashMap<String, Object>();
			data.putAll(paramMap);
			data.put("bjobBzwkPrcssDstcd",map.get("BJOBBZWKPRCSSDSTCD"));
			data.put("bjobStgeSerno",map.get("BJOBSTGESERNO"));
			data.put("bjobStgeDstcd",map.get("BJOBSTGEDSTCD"));
			data.put("nextStgeDstcdName",map.get("NEXTSTGEDSTCDNAME"));
			data.put("bjobStgePtrnName",map.get("BJOBSTGEPTRNNAME"));
			data.put("telgmPtrnDstcd",map.get("TELGMPTRNDSTCD"));
			data.put("telgmDtalsOperCd",map.get("TELGMDTALSOPERCD"));
			data.put("bjobCmnTelgmTranCd",map.get("BJOBCMNTELGMTRANCD"));
			data.put("toutVal",map.get("TOUTVAL"));
			data.put("bjobIterNotms",map.get("BJOBITERNOTMS"));
			data.put("telgmClsID",map.get("TELGMCLSID"));
			data.put("cndnItemDcsnCtnt",map.get("CNDNITEMDCSNCTNT"));
			data.put("cndnTelgmPtrnCd",map.get("CNDNTELGMPTRNCD"));
			data.put("cndnTelgmMgtCd",map.get("CNDNTELGMMGTCD"));
			data.put("cndnTranClsfiCd",map.get("CNDNTRANCLSFICD"));
			data.put("cndnRspnsCd",map.get("CNDNRSPNSCD"));
			data.put("bjobStgeFlxblCndnDesc",map.get("BJOBSTGEFLXBLCNDNDESC"));
			data.put("tranPrcssPrity",map.get("TRANPRCSSPRITY"));
			dao.insertList(data);
		}		
	}

	public void insert(HashMap<String, Object> paramMap, HashMap<String, Object>[] list) throws Exception {
		
		dao.insert(paramMap);
		HashMap<String, Object> data ;

		for(HashMap<String, Object> map : list){
			data = new HashMap<String, Object>();
			data.put("bjobBzwkPrcssDstcd",map.get("BJOBBZWKPRCSSDSTCD"));
			data.put("bjobStgeSerno",map.get("BJOBSTGESERNO"));
			data.put("bjobStgeDstcd",map.get("BJOBSTGEDSTCD"));
			data.put("nextStgeDstcdName",map.get("NEXTSTGEDSTCDNAME"));
			data.put("bjobStgePtrnName",map.get("BJOBSTGEPTRNNAME"));
			data.put("telgmPtrnDstcd",map.get("TELGMPTRNDSTCD"));
			data.put("telgmDtalsOperCd",map.get("TELGMDTALSOPERCD"));
			data.put("bjobCmnTelgmTranCd",map.get("BJOBCMNTELGMTRANCD"));
			data.put("toutVal",map.get("TOUTVAL"));
			data.put("bjobIterNotms",map.get("BJOBITERNOTMS"));
			data.put("telgmClsID",map.get("TELGMCLSID"));
			data.put("cndnItemDcsnCtnt",map.get("CNDNITEMDCSNCTNT"));
			data.put("cndnTelgmPtrnCd",map.get("CNDNTELGMPTRNCD"));
			data.put("cndnTelgmMgtCd",map.get("CNDNTELGMMGTCD"));
			data.put("cndnTranClsfiCd",map.get("CNDNTRANCLSFICD"));
			data.put("cndnRspnsCd",map.get("CNDNRSPNSCD"));
			data.put("bjobStgeFlxblCndnDesc",map.get("BJOBSTGEFLXBLCNDNDESC"));
			data.put("tranPrcssPrity",map.get("TRANPRCSSPRITY"));
			dao.insertList(data);
		}		
	}

	public void delete(HashMap<String, Object> paramMap) throws Exception {
		dao.delete(paramMap);
		dao.deleteList(paramMap);
	}	
	
	@SuppressWarnings("unchecked")
	public HashMap<String,String> mkInserSqlForFlowRule(HashMap<String, Object> stageInfo) throws Exception {
		
		HashMap<String,Object> detail = (HashMap<String,Object>)stageInfo.get("detail");
		List<HashMap<String,Object>> stageList = (List<HashMap<String,Object>>)stageInfo.get("list");
		
		// FLOW RULE into BR04
		StringBuffer flowRuleInsertSql = new StringBuffer();
		flowRuleInsertSql.append("INSERT INTO EAIPKG.TSEAIBR04 (BJOBBZWKPRCSSDSTCD,FLOWRULEPTRNDESC) VALUES (");
		flowRuleInsertSql.append("'"+(detail.containsKey("BJOBBZWKPRCSSDSTCD") ? detail.get("BJOBBZWKPRCSSDSTCD") : "")+"',");
		flowRuleInsertSql.append("'"+(detail.containsKey("FLOWRULEPTRNDESC") ? detail.get("FLOWRULEPTRNDESC") : "")+"');\n");
		
		// FLOW RULE STAGE LIST into BR02
		for (HashMap<String,Object> stage : stageList) {
			List<String> columnArr = new ArrayList<String>();
			String[] columnList = {"BJOBBZWKPRCSSDSTCD","BJOBSTGESERNO","BJOBSTGEDSTCD","BJOBSTGEPTRNNAME","BJOBSTGEFLXBLCNDNDESC",
								   "TELGMPTRNDSTCD","TELGMDTALSOPERCD","BJOBCMNTELGMTRANCD","TOUTVAL","BJOBITERNOTMS","CNDNITEMDCSNCTNT",
								   "TRANPRCSSPRITY","TELGMCLSID","CNDNTELGMPTRNCD","CNDNTELGMMGTCD","CNDNTRANCLSFICD","CNDNRSPNSCD","NEXTSTGEDSTCDNAME"};
			columnArr = Arrays.asList(columnList);
			flowRuleInsertSql.append("INSERT INTO EAIPKG.TSEAIBR02 (");
			
			// 필드명 입력
			for (String column : columnArr) {
				flowRuleInsertSql.append((column.equals(columnArr.get(columnArr.size()-1))) ? column : column+",");
			}
			flowRuleInsertSql.append(") VALUES (");
			// 필드값 입력
			String[] columnInt = {"TOUTVAL","BJOBITERNOTMS","TRANPRCSSPRITY"};  // Integer 컬럼 구분
			for (String column : columnArr) {
				if (column.equals(columnArr.get(columnArr.size()-1))) {
					if (Arrays.asList(columnInt).contains(column)) {
						flowRuleInsertSql.append((stage.containsKey(column) ? stage.get(column) : 0)+");\n");
					} else {
						flowRuleInsertSql.append("'"+(stage.containsKey(column) ? stage.get(column) : "")+"');\n");
					}
				} else {
					if (Arrays.asList(columnInt).contains(column)) {
						flowRuleInsertSql.append((stage.containsKey(column) ? stage.get(column) : 0)+",");
					} else {
						flowRuleInsertSql.append("'"+(stage.containsKey(column) ? stage.get(column) : "")+"',");
					}
				}
			}
		}

		HashMap<String,String> retMap = new HashMap<String,String>(); 
		if (stageInfo.get("fileName") != null) {
			OutputStream output = null;
			try {
				String sqlDownloadPath = getProperties("SQL_DOWNLOAD", "DOWNLOAD_PATH");
				String sqlDownloadFile = sqlDownloadPath+stageInfo.get("fileName");
				output = new FileOutputStream(sqlDownloadFile);
				if (sqlDownloadPath != null) {
					byte[] bt = flowRuleInsertSql.toString().getBytes();
					output.write(bt);
					output.close();
				}
				retMap.put("path", sqlDownloadPath);
			} catch (Exception e) {
				logger.error( e.getMessage(), e);
			} finally {
				if(output != null) try { output.close(); } catch(Exception ee) {logger.error( ee.getMessage(), ee);}
			}
		} else {
			retMap = SqlUtil.executeSql(flowRuleInsertSql.toString(), "BAP_"+stageInfo.get("svrType").toString().toUpperCase());
		}
		
		return retMap;
	}
	
	private String getProperties(String propGroup, String propName) throws Exception {
		HashMap<String,Object> params = new HashMap<String,Object>();
		params.put("prptyGroupName", propGroup);
		params.put("prptyName", propName);
		
		HashMap<String, Object> props = propDao.getProperties(params);
		
		return props.get("PRPTY2VAL").toString();
	}
}