package com.eactive.eai.rms.bat.manage.comm.bizDist;

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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.eactive.eai.rms.bat.manage.rule.adapter.BatAdapterDao;
import com.eactive.eai.rms.common.acl.user.UserDao;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.util.SqlUtil;

@Service("bizDistService")
public class BizDistService extends BaseService {

	@Autowired
	@Qualifier("bizDistDao")
	private BizDistDao dao;
	
    @Autowired
	@Qualifier("userDao")
    private UserDao userDao;

	@Autowired
	@Qualifier("batAdapterDao")
	private BatAdapterDao adaptdao;
    
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public HashMap 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<HashMap<String, Object>> list = dao.selectList(paramMap);
		
		//모니터링 사용자 정보 테이블(TSEAIRM02)부서/팀명 가져와서 MAP 에 담기
		for(HashMap<String, Object> bizDistMap : list) {		
			String userId = (String)bizDistMap.get("RSPBLPSNCNTPCTNT");
			HashMap userMap = new HashMap() ;
			if(userId != null){
				userMap.put("userId", userId);
				HashMap userInfoMap = userDao.selectDetail(userMap);
				
				if(userInfoMap != null) {
					bizDistMap.replace("TRACKASISKEY1NAME", userInfoMap.get("DVSNNAME"));
					bizDistMap.replace("TRACKASISKEY2NAME", userInfoMap.get("TEAMNAME"));
				}
			}
		}
		
		HashMap map = new HashMap();
		map.put("totalCount", totalCount);
		map.put("list", list);

		return map;
	}
	
	@SuppressWarnings({ "rawtypes" })
	public int selectCnt(HashMap paramMap) throws Exception{
		return dao.selectCount(paramMap);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public HashMap selectDetail(String eaiBzwkDstcd) throws Exception {

		HashMap paramMap = new HashMap();
		paramMap.put("eaiBzwkDstcd", eaiBzwkDstcd);
		
		HashMap resultMap = dao.selectDetail( paramMap);
		
		//모니터링 사용자 정보 테이블(TSEAIRM02)부서/팀명 가져와서 MAP 에 담기
		String userId = (String)resultMap.get("RSPBLPSNCNTPCTNT");
		HashMap userMap = new HashMap() ;
		if(userId != null){
			userMap.put("userId", userId);
			HashMap userInfoMap = userDao.selectDetail(userMap);
			
			if(userInfoMap != null) {
				resultMap.replace("TRACKASISKEY1NAME", userInfoMap.get("DVSNNAME"));
				resultMap.replace("TRACKASISKEY2NAME", userInfoMap.get("TEAMNAME"));
			}
		}

		return resultMap;
	}	

	@SuppressWarnings({ "rawtypes" })
	public void update(HashMap paramMap) throws Exception {
		dao.update(paramMap);
	}	
	@SuppressWarnings({ "rawtypes" })
	public void insert(HashMap paramMap) throws Exception {
		dao.insert(paramMap);
	}
	@SuppressWarnings({ "rawtypes" })
	public void delete(HashMap paramMap) throws Exception {
		dao.delete(paramMap);
	}	
	
	//TSEAICM01 테이블 업무코드 가져오기
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<HashMap<String, Object>> selectBizCodeList() throws Exception {
		HashMap paramMap = new HashMap();
		List<HashMap<String, Object>> list = dao.selectBizCodeList(paramMap);
		
		return  list;	
	}
	
	@SuppressWarnings("unchecked")
	public HashMap<String,String> mkInserSqlForBzwkDstcd(HashMap<String, Object> bzwkDstcdInfo) throws Exception {
		
		
		StringBuffer bzwkDstcdSql = new StringBuffer();

		List<String> bzwkDstcdList = new ArrayList<String>(); 
		if (bzwkDstcdInfo.get("eaiBzwkDstcdList") != null) {
			bzwkDstcdList = Arrays.asList(bzwkDstcdInfo.get("eaiBzwkDstcdList").toString().split(","));
		}
		
		for (String bzwkDstcd : bzwkDstcdList) {
			HashMap<String, Object> detailMap = (HashMap<String, Object>)selectDetail(bzwkDstcd);
			
			String[] columnList = {"EAIBZWKDSTCD","BZWKDSTICNAME","APPLCD","BZWKDSTICDESC","TRACKASISKEY1NAME",
					"TRACKASISKEY2NAME","RSEMPNAME","RSPBLPSNCNTPCTNT","GROUPCOCD"};
			List<String> columnArr = Arrays.asList(columnList);
			bzwkDstcdSql.append("INSERT INTO EAIPKG.TSEAICM01 (");
			
			// 필드명 입력
			for (String column : columnArr) {
				bzwkDstcdSql.append((column.equals(columnArr.get(columnArr.size()-1))) ? column : column+",");
			}
			bzwkDstcdSql.append(") VALUES (");
			// 필드값 입력
			for (String column : columnArr) {
				if (column.equals(columnArr.get(columnArr.size()-1))) {
					bzwkDstcdSql.append("'"+(detailMap.containsKey(column) ? detailMap.get(column) : "")+"');\n");
				} else {
					bzwkDstcdSql.append("'"+(detailMap.containsKey(column) ? detailMap.get(column) : "")+"',");
				}
			}
		}
		
		HashMap<String,String> retMap = new HashMap<String,String>(); 
		if (bzwkDstcdInfo.get("fileName") != null) {
			OutputStream output = null;
			try {
				String sqlDownloadPath = getProperties("SQL_DOWNLOAD", "DOWNLOAD_PATH");
				String sqlDownloadFile = sqlDownloadPath + bzwkDstcdInfo.get("fileName").toString(); 
				output = new FileOutputStream(sqlDownloadFile);
				if (sqlDownloadPath != null) {
					byte[] bt = bzwkDstcdSql.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 (bzwkDstcdInfo.get("svrType") != null) {
			retMap = SqlUtil.executeSql(bzwkDstcdSql.toString(), "ISG_"+bzwkDstcdInfo.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();
	}
}
