package com.eactive.eai.rms.bap.manage.schedule.shedule;

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

	@Autowired
	@Qualifier("bapScheduleDao")
	private BapScheduleDao 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 bJobMsgScheId) throws Exception {

		return dao.selectDetail( bJobMsgScheId );
	}	

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

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

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

	public List<Map<String, Object>> selectBjobMsgDstcd(String bjobBzwkDstcd) throws Exception {
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("bjobBzwkDstcd" , bjobBzwkDstcd);
		return dao.selectBjobMsgDstcd(param);
	}	

	public List<Map<String, Object>> selectOsidInstiDstcd(String bjobBzwkDstcd) throws Exception {
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("bjobBzwkDstcd" , bjobBzwkDstcd);
		return dao.selectOsidInstiDstcd(param);
	}	

	public List<Map<String, Object>> selectBjobPtrnDstcd(String bjobMsgDstcd) throws Exception {
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("bjobMsgDstcd" , bjobMsgDstcd);
		return dao.selectBjobPtrnDstcd(param);
	}
	
	public HashMap<String,String> mkInsertSqlForSched(HashMap<String, Object> sched) throws Exception {
		
		StringBuffer schedInsertSql = new StringBuffer();
		for (String bjobMsgScheId : sched.get("bjobMsgScheIdList").toString().split(",")) {
			HashMap<String, Object> schedDetail = selectDetail(bjobMsgScheId);
	
			String[] columnUserId = {"THISMSGREGSNTID","THISMSGAMNDRID"};  // userID 입력컬럼 구분
			String[] columnDateTime = {"SCHEFRSTREGIHMS","THISMSGREGIHMS","THISMSGAMNDHMS"};  // DateTime 입력컬럼 구분
			String userid = sched.get("userid") != null ? sched.get("userid").toString() : "";
			
			// 일괄스케쥴 into BS01
			List<String> columnArr = new ArrayList<String>();
			String[] columnList = {"BJOBMSGSCHEID","OSIDINSTIDSTCD","BJOBMSGDSTCD","BJOBPTRNDSTCD","SNDRCVSTARTHMS",
									"SNDRCVENDHMS","MSGSNDRID","SCHEFRSTREGIHMS","RQSTRECVFILESTORGDIRNAME","RQSTRECVRETRALCNT",
									"RQSTRECVRETRALUSEYN","RQSTRECVRETRALINTVALTTM","HOLDYPRCSSDSTCD","STARTDLAYNODAY","ENDDLAYNODAY",
									"THISMSGUSEYN","THISMSGSCHEDESC","THISMSGREGSNTID","THISMSGREGIHMS","THISMSGAMNDRID","THISMSGAMNDHMS","RPTTYN"};
			columnArr = Arrays.asList(columnList);
			schedInsertSql.append("INSERT INTO EAIPKG.TSEAIBS01 (");
			
			// 필드명 입력
			for (String column : columnArr) {
				schedInsertSql.append((column.equals(columnArr.get(columnArr.size()-1))) ? column : column+",");
			}
			schedInsertSql.append(") VALUES (");
			// 필드값 입력
			String[] columnInt = {"RQSTRECVRETRALCNT","RQSTRECVRETRALINTVALTTM","STARTDLAYNODAY","ENDDLAYNODAY"};  // Integer 컬럼 구분
			for (String column : columnArr) {
				if (column.equals(columnArr.get(columnArr.size()-1))) {
					if (Arrays.asList(columnInt).contains(column)) {
						schedInsertSql.append((schedDetail.containsKey(column) ? schedDetail.get(column) : 0)+");\n");
					} else {
						if (Arrays.asList(columnUserId).contains(column)) {
							schedInsertSql.append("'"+userid+"');\n");
						} else if (Arrays.asList(columnDateTime).contains(column)) {
							schedInsertSql.append("TO_CHAR(LOCALTIMESTAMP, 'YYYYMMDDHH24MISSFF3'));\n");
						} else {
							schedInsertSql.append("'"+(schedDetail.get(column) != null ? schedDetail.get(column) : "")+"');\n");
						}
					}
				} else {
					if (Arrays.asList(columnInt).contains(column)) {
						schedInsertSql.append((schedDetail.containsKey(column) ? schedDetail.get(column) : 0)+",");
					} else {
						if (Arrays.asList(columnUserId).contains(column)) {
							schedInsertSql.append("'"+userid+"',");
						} else if (Arrays.asList(columnDateTime).contains(column)) {
							schedInsertSql.append("TO_CHAR(LOCALTIMESTAMP, 'YYYYMMDDHH24MISSFF3'),");
						} else {
							schedInsertSql.append("'"+(schedDetail.get(column) != null ? schedDetail.get(column) : "")+"',");
						}
					}
				}
			}
		}
		
		HashMap<String,String> retMap = new HashMap<String,String>(); 
		if (sched.get("fileName") != null) {
			OutputStream output = null;
			try {
				String sqlDownloadPath = getProperties("SQL_DOWNLOAD", "DOWNLOAD_PATH");
				String sqlDownloadFile = sqlDownloadPath+sched.get("fileName");
				output = new FileOutputStream(sqlDownloadFile);
				if (sqlDownloadPath != null) {
					byte[] bt = schedInsertSql.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(schedInsertSql.toString(), "BAP_"+sched.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();
	}
}