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

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("bapFlowStepService")
public class BapFlowStepService extends BapBaseService {

	@Autowired
	@Qualifier("bapFlowStepDao")
	private BapFlowStepDao 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 int selectTotalCount(HashMap<String, Object> paramMap) throws Exception {

		return dao.selectListCount(paramMap); 		// 전체 목록수 얻기
	}
	
	public HashMap<String, Object> selectDetail(HashMap<String, Object> paramMap) throws Exception {
		HashMap<String, Object> list;
		// paramMap {key = bjobBzwkPrcssDstcd, key2 = bjobStgeDstcd }
		list   = dao.selectDetail(paramMap);

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

	}	
	
	public HashMap<String, Object> selectDetailCombo(HashMap<String,Object> paramMap) throws Exception {
		List<Map<String, Object>> clsIDList   = dao.getTelgmClsID(paramMap);
		HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("clsIDList", clsIDList);
		
		return map;

	}	

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

	public void insert(HashMap<String, Object> paramMap) throws Exception {
		dao.insert(paramMap);
	}

	public void delete(HashMap<String, Object> paramMap) throws Exception {
		dao.delete(paramMap);
	}
	
	@SuppressWarnings("unchecked")
	public HashMap<String,String> mkInserSqlForFlowSteps(HashMap<String, Object> flowStepInfo) throws Exception {
		
		StringBuffer flowStepInsertSql = new StringBuffer();
		List<Map<String, Object>> flowStepList = (List<Map<String, Object>>)flowStepInfo.get("list");
		
		// FLOW STEP LIST into BR03
		for (Map<String,Object> step : flowStepList) {
			List<String> columnArr = new ArrayList<String>();
			String[] columnList = {"BJOBBZWKPRCSSDSTCD","BJOBSTGEDSTCD","BJOBSTGEPTRNNAME","BJOBFLOWCMPONAME","TELGMCLSID","UNITTELGMLEN","BJOBNODEDESC"};
			columnArr = Arrays.asList(columnList);
			flowStepInsertSql.append("INSERT INTO EAIPKG.TSEAIBR03 (");
			
			// 필드명 입력
			for (String column : columnArr) {
				flowStepInsertSql.append((column.equals(columnArr.get(columnArr.size()-1))) ? column : column+",");
			}
			flowStepInsertSql.append(") VALUES (");
			// 필드값 입력
			String[] columnInt = {"UNITTELGMLEN"};  // Integer 컬럼 구분
			for (String column : columnArr) {
				if (column.equals(columnArr.get(columnArr.size()-1))) {
					if (Arrays.asList(columnInt).contains(column)) {
						flowStepInsertSql.append((step.containsKey(column) ? step.get(column) : 0)+");\n");
					} else {
						flowStepInsertSql.append("'"+(step.containsKey(column) ? step.get(column) : "")+"');\n");
					}
				} else {
					if (Arrays.asList(columnInt).contains(column)) {
						flowStepInsertSql.append((step.containsKey(column) ? step.get(column) : 0)+",");
					} else {
						flowStepInsertSql.append("'"+(step.containsKey(column) ? step.get(column) : "")+"',");
					}
				}
			}
		}

		HashMap<String,String> retMap = new HashMap<String,String>(); 
		if (flowStepInfo.get("fileName") != null) {
			OutputStream output = null;
			try {
				String sqlDownloadPath = getProperties("SQL_DOWNLOAD", "DOWNLOAD_PATH");
				String sqlDownloadFile = sqlDownloadPath+flowStepInfo.get("fileName");
				output = new FileOutputStream(sqlDownloadFile);
				if (sqlDownloadPath != null) {
					byte[] bt = flowStepInsertSql.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(flowStepInsertSql.toString(), "BAP_"+flowStepInfo.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();
	}	
}