package com.eactive.eai.rms.bat.manage.rule.schedule;

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 java.util.Vector;

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

import com.eactive.eai.rms.bat.common.base.BatBaseService;
import com.eactive.eai.rms.bat.manage.rule.adapter.BatAdapterDao;
import com.eactive.eai.rms.common.util.SqlUtil;

@Service("batScheduleService")
public class BatScheduleService extends BatBaseService {

	@Autowired
	@Qualifier("batScheduleDao")
	private BatScheduleDao dao;
	
	@Autowired
	@Qualifier("batAdapterDao")
	private BatAdapterDao adaptdao;

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

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

		List<Map<String, Object>> list = dao.selectList(paramap);

		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 {

		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("bjobMsgScheID", bjobMsgScheID);

		HashMap<String, Object>   detail   = dao.selectDetail(paramMap);
		List<Map<String, Object>> list     = dao.scheduleInterfaceList(paramMap);

		HashMap<String, Object> map = new HashMap<String, Object>();

		map.put("detail"   , detail);
		map.put("rows"     , list);

		return map;

	}	

	public void insert(HashMap<String, Object> paramMap, HashMap<String, Object>[] list) throws Exception {
		
		String bjobMsgScheID = "U_" + ((String)paramMap.get("workGrpCd")).trim() + "_" + paramMap.get("batchType") + "_D_" + paramMap.get("scheKind") + "_";
		paramMap.put("bjobMsgScheID",bjobMsgScheID);
		bjobMsgScheID = dao.getScheduleID(paramMap);
		paramMap.put("bjobMsgScheID",bjobMsgScheID);
		dao.insert(paramMap);
		dao.deleteMapping(paramMap);
		HashMap<String, Object> data ;
		for(HashMap<String, Object> map : list){
			data = new HashMap<String, Object>();
			data.putAll(paramMap);
			data.put("intfId",map.get("INTFID"));
			dao.insertMapping(data);
		}
	}

	public void update(HashMap<String, Object> paramMap, HashMap<String, Object>[] list) throws Exception {
		dao.update(paramMap);
		dao.deleteMapping(paramMap);
		HashMap<String, Object> data ;
		for(HashMap<String, Object> map : list){
			data = new HashMap<String, Object>();
			data.putAll(paramMap);
			data.put("intfId",map.get("INTFID"));
			dao.insertMapping(data);
		}
	}	

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

	@SuppressWarnings("unchecked")
	public HashMap<String,String> mkInserSqlForSched(HashMap<String, Object> paramMap) throws Exception {
		
		StringBuffer schedInsertSql = new StringBuffer();

		List<String> schedIdList = new ArrayList<String>(); 
		if (paramMap.get("bjobMsgScheIDList") != null) {
			schedIdList = Arrays.asList(paramMap.get("bjobMsgScheIDList").toString().split(","));
		}
		for (String schedId : schedIdList) {
			HashMap<String, Object> schedDetail = (HashMap<String, Object>)selectDetail(schedId).get("detail");

			String[] columnList = {"BJOBMSGSCHEID","INTFID","BATCHTYPE","SCHEKIND","SNDRCVSTARTHMS","SNDRCVENDHMS",
								   "MSGSNDRID","SCHEFRSTREGIHMS","RQSTRECVFILESTORGDIRNAME","THISMSGUSEYN","THISMSGSCHEDESC",
								   "THISMSGREGSNTID","THISMSGREGIHMS","THISMSGAMNDRID","THISMSGAMNDHMS","CYCLEKIND","CYCLECODE",
								   "MONWEEKCODE1","MONWEEKCODE2","DAYCYCLETIME","ACTTIME1","ACTTIME2","ACTTIME3","ACTTIME4",
								   "ACTTIME5","ACTTIME6","ACTDAY","ACTDAY2","ACTDAY3","ACTDAY4"};
			List<String> columnArr = Arrays.asList(columnList);
			schedInsertSql.append("INSERT INTO EAIPKG.TSEAIES07 (");
			
			// 필드명 입력
			for (String column : columnArr) {
				schedInsertSql.append((column.equals(columnArr.get(columnArr.size()-1))) ? column : column+",");
			}
			schedInsertSql.append(") VALUES (");
			// 필드값 입력
			for (String column : columnArr) {
				if (column.equals(columnArr.get(columnArr.size()-1))) {
					schedInsertSql.append("'"+(schedDetail.containsKey(column) ? schedDetail.get(column) : "")+"');\n");
				} else {
					schedInsertSql.append("'"+(schedDetail.containsKey(column) ? schedDetail.get(column) : "")+"',");
				}
			}
		}
		
		HashMap<String,String> retMap = new HashMap<String,String>(); 
		if (paramMap.get("fileName") != null) {
			OutputStream output = null;
			try {
				String sqlDownloadPath = getProperties("SQL_DOWNLOAD", "DOWNLOAD_PATH");
				String sqlDownloadFile = sqlDownloadPath + paramMap.get("fileName").toString();    		
				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 if (paramMap.get("svrType") != null) {
			retMap = SqlUtil.executeSql(schedInsertSql.toString(), "ISG_"+paramMap.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 = adaptdao.getProperties(params);
		
		return props.get("PRPTYDETAIL").toString();
	}

	public Vector<String> selectInterfacesByScheduleId(String bjobMsgScheID) {
		
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("bjobMsgScheID", bjobMsgScheID);
		
		List<String> interfaces = dao.selectInterfacesByScheduleId(paramMap);
		
		Vector<String> result = new Vector<>();
		for(String intf : interfaces) {
			result.add(intf);
		}
		
		return result;
	}

	public HashMap<String, Object> selectSchedulesByInterfaceId(String intfId) {
		
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("intfId", intfId);
		
		List<Map<String, Object>> list = dao.selectSchedulesByInterfaceId(paramMap);

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