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

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

	@Autowired
	@Qualifier("bapMessageItemDao")
	private BapMessageItemDao 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 MsgItemDsticName) throws Exception {
		HashMap<String, Object> list;

		list   = dao.selectDetail(MsgItemDsticName);

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		
		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);
	}
	
	public List<Map<String, Object>> getMsgGroupDstcd(HashMap<String, Object> paramMap) throws Exception {
		return dao.getMsgGroupDstcd(paramMap);
	}
	
	@SuppressWarnings("unchecked")
	public HashMap<String,String> mkInserSqlForMsgItem(HashMap<String, Object> msgItemMap) throws Exception {
		
		StringBuffer msgItemInsertSql = new StringBuffer();
		String[] columnUserId = {"THISMSGREGSNTID","THISMSGAMNDRID","THISMSGCLMNREGSNTID","THISMSGCLMNAMNDRID"};  // userID 입력컬럼 구분
		String[] columnDateTime = {"THISMSGREGIHMS","THISMSGAMNDHMS","THISMSGCLMNREGIHMS","THISMSGCLMNAMNDHMS"};  // DateTime 입력컬럼 구분
		List<Map<String, Object>> msgItemList = (List<Map<String, Object>>)msgItemMap.get("list");
		String userid = msgItemMap.containsKey("userid") ? msgItemMap.get("userid").toString() : "";
		
		// MESSAGE ITEM LIST into BM01
		for (Map<String, Object> msgItem : msgItemList) {	
			List<String> columnClmArr = new ArrayList<String>();
			String[] columnClmList = {"MSGITEMDSTICNAME","THISMSGCLMNUSEYN","MSGCLMNNAME","MSGCLMNATTRIPTRNCD","MSGCLMNVAL","THISMSGCLMNREGSNTID","THISMSGCLMNREGIHMS","THISMSGCLMNAMNDRID","THISMSGCLMNAMNDHMS"};
			columnClmArr = Arrays.asList(columnClmList);
			
			msgItemInsertSql.append("MERGE INTO EAIPKG.TSEAIBM01 r USING (VALUES(");
			// 필드값 입력
			for (String column : columnClmArr) {
				if (column.equals(columnClmArr.get(columnClmArr.size()-1))) {
					if (Arrays.asList(columnUserId).contains(column)) {
						msgItemInsertSql.append("'"+userid+"')) ");
					} else if (Arrays.asList(columnDateTime).contains(column)) {
						msgItemInsertSql.append("TO_CHAR(LOCALTIMESTAMP, 'YYYYMMDDHH24MISSFF3'))) ");
					} else {
						msgItemInsertSql.append("'"+(msgItem.containsKey(column) ? msgItem.get(column) : "")+"')) ");
					}
				} else {
					if (Arrays.asList(columnUserId).contains(column)) {
						msgItemInsertSql.append("'"+userid+"',");
					} else if (Arrays.asList(columnDateTime).contains(column)) {
						msgItemInsertSql.append("TO_CHAR(LOCALTIMESTAMP, 'YYYYMMDDHH24MISSFF3'),");
					} else {
						msgItemInsertSql.append("'"+(msgItem.containsKey(column) ? msgItem.get(column) : "")+"',");
					}
				}
			}
			// 필드명 입력
			msgItemInsertSql.append("AS s(");
			for (String columnClm : columnClmArr) {
				msgItemInsertSql.append((columnClm.equals(columnClmArr.get(columnClmArr.size()-1))) ? columnClm+")\n" : columnClm+",");
			}
			msgItemInsertSql.append("ON r.MSGITEMDSTICNAME = s.MSGITEMDSTICNAME WHEN NOT MATCHED THEN\n");
			msgItemInsertSql.append("INSERT (");
			for (String columnClm : columnClmArr) {
				msgItemInsertSql.append((columnClm.equals(columnClmArr.get(columnClmArr.size()-1))) ? "r."+columnClm : "r."+columnClm+",");
			}
			msgItemInsertSql.append(") VALUES (");
			for (String columnClm : columnClmArr) {
				msgItemInsertSql.append((columnClm.equals(columnClmArr.get(columnClmArr.size()-1))) ? "s."+columnClm+");\n" : "s."+columnClm+",");
			}
		}

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