package com.eactive.eai.rms.bap.manage.comm.property;

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.apache.commons.lang.StringEscapeUtils;
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.common.util.SqlUtil;

@Service("bapPropertyService")
public class BapPropertyService extends BapBaseService {

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

	public HashMap<String, Object> selectList(int startNum,int endNum, HashMap 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 prptyGroupName) throws Exception {

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

		HashMap<String, Object>   detail = dao.propertyGroupDetail(paramMap);
		List<Map<String, Object>> list   = dao.propertyDetail(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 {
		dao.insert(paramMap);
		HashMap<String, Object> data ;
		for(HashMap<String, Object> map : list){
			data = new HashMap<String, Object>();
			data.putAll(paramMap);
			data.put("prptyName", StringEscapeUtils.unescapeHtml(map.get("PRPTYNAME").toString()));
			data.put("prpty2Val", StringEscapeUtils.unescapeHtml(map.get("PRPTY2VAL").toString()));
			dao.insertProperty(data);
		}

	}

	public void update(HashMap<String, Object> paramMap, HashMap<String, Object>[] list) throws Exception {
		dao.update(paramMap);
		dao.deleteProperty(paramMap);
		HashMap<String, Object> data ;
		for(HashMap<String, Object> map : list){
			data = new HashMap<String, Object>();
			data.putAll(paramMap);
			data.put("prptyName", StringEscapeUtils.unescapeHtml(map.get("PRPTYNAME").toString()));
			data.put("prpty2Val", StringEscapeUtils.unescapeHtml(map.get("PRPTY2VAL").toString()));
			dao.insertProperty(data);
		}
	}	

	public void delete(HashMap<String, Object> paramMap) throws Exception {
		dao.delete(paramMap);
		dao.deleteProperty(paramMap);
	}	
	
	@SuppressWarnings("unchecked")
	public HashMap<String,String> mkInsertSqlForProperty(HashMap<String, Object> propDetail) throws Exception {
		
		StringBuffer propInsertSql = new StringBuffer();
		
		HashMap<String, Object>   detail      = (HashMap<String, Object>)propDetail.get("detail");
		List<Map<String, Object>> propList    = (List<Map<String, Object>>)propDetail.get("rows");

		// Property Group (TSEAIBP01)
		List<String> columnGroupArr = new ArrayList<String>();
		String[] columnGroupList = {"PRPTYGROUPNAME","PRPTYGROUPDESC"};
		columnGroupArr = Arrays.asList(columnGroupList);
		propInsertSql.append("INSERT INTO EAIPKG.TSEAIBP01 (");
		
		// 필드명 입력
		for (String column : columnGroupArr) {
			propInsertSql.append((column.equals(columnGroupArr.get(columnGroupArr.size()-1))) ? column : column+",");
		}
		propInsertSql.append(") VALUES (");
		// 필드값 입력
		for (String column : columnGroupArr) {
			if (column.equals(columnGroupArr.get(columnGroupArr.size()-1))) {
				propInsertSql.append("'"+(detail.get(column) != null ? detail.get(column) : "")+"');\n");
			} else {
				propInsertSql.append("'"+(detail.get(column) != null ? detail.get(column) : "")+"',");
			}
		}
		
		// Property Detail (TSEAIBP02)
		List<String> columnPropArr = new ArrayList<String>();
		String[] columnPropList = {"PRPTYGROUPNAME","PRPTYNAME","PRPTY2VAL"};
		columnPropArr = Arrays.asList(columnPropList);

		for (Map<String, Object> prop : propList) {
			propInsertSql.append("INSERT INTO EAIPKG.TSEAIBP02 (");
			
			// 필드명 입력
			for (String column : columnPropArr) {
				propInsertSql.append((column.equals(columnPropArr.get(columnPropArr.size()-1))) ? column : column+",");
			}
			propInsertSql.append(") VALUES (");
			// 필드값 입력
			for (String column : columnPropArr) {
				if (column.equals("PRPTYGROUPNAME")) {
					propInsertSql.append("'"+detail.get("PRPTYGROUPNAME")+"',");
				} else if (column.equals(columnPropArr.get(columnPropArr.size()-1))) {
					propInsertSql.append("'"+(prop.get(column) != null ? prop.get(column) : "")+"');\n");
				} else {
					propInsertSql.append("'"+(prop.get(column) != null ? prop.get(column) : "")+"',");
				}
			}
		}
		
		HashMap<String,String> retMap = new HashMap<String,String>(); 
		if (propDetail.get("fileName") != null) {
			OutputStream output = null;
			try {
				String sqlDownloadPath = getProperties("SQL_DOWNLOAD", "DOWNLOAD_PATH");
				String sqlDownloadFile = sqlDownloadPath+propDetail.get("fileName");
				output = new FileOutputStream(sqlDownloadFile);
				if (sqlDownloadPath != null) {
					byte[] bt = propInsertSql.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(propInsertSql.toString(), "BAP_"+propDetail.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 = dao.getProperties(params);
		
		return props.get("PRPTY2VAL").toString();
	}
}
