/*
 * MasterDAO.java	2011. 03. 17
 *
 * Copyright 2011 FUJITSU KOREA LTD. All rights reserved.
 * FUJITSU KOREA LTD PROPRIETARY/CONFIDENTIAL. 
 * Use is subject to license terms.
 */

package biz.cms_FileAgent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;


import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
 

import kr.fujitsu.com.ffw.daemon.core.config.repository.property.PropertyUtil;
import kr.fujitsu.com.ffw.daemon.core.config.repository.sql.SqlUtil;
import kr.fujitsu.com.ffw.model.GenericDAO;
import kr.fujitsu.com.ffw.model.SqlWrapper;
import kr.fujitsu.com.ffw.model.ProcedureWrapper;
import kr.fujitsu.com.ffw.model.ProcedureResultSet;
import kr.fujitsu.com.ffw.model.DataTypes;
import kr.fujitsu.com.ffw.util.ZipUtil; 

import kr.fujitsu.com.ffw.daemon.core.config.repository.*;

/** 
 * MasterAgentDAO
 * A class that has inherited GenericDAO(GenericDAO를 상속받은 클래스)
 * It is responsible for functions to access DB to retrieve respective information(DB에 접속하여 해당 정보를 조회해 오거나)
 * or update DB information(DB정보를 업데이트 하는 기능을 담당한다).
 * @created  on 1.0,  11/03/17
 * @created  khk(FUJITSU KOREA LTD.) 
 *  
 * @modified on 
 * @modified by ok 
 * @caused   by  
 */ 
public class FileAgentDAO extends GenericDAO{	
	private static Logger logger = Logger.getLogger(FileAgentPollingAction.class);
 
	/*
	 //파일을 이동하는 메소드
	 public static void fileMove(String inFileName, String outFileName) {
	  try {
	   FileInputStream fis = new FileInputStream(inFileName);
	   FileOutputStream fos = new FileOutputStream(outFileName);
	   
	   int data = 0;
	   while((data=fis.read())!=-1) {
	    fos.write(data);
	   }
	   fis.close();
	   fos.close();
	   
	   //복사한뒤 원본파일을 삭제함
	   fileDelete(inFileName);
	   
	  } catch (IOException e) {
	   // TODO Auto-generated catch block
	   e.printStackTrace();
	  }
	 }
	*/
	public  void fileCopy(String sorg , String starget ) throws Throwable{
    	
    	FileInputStream inputStream = new FileInputStream(sorg);         
    	FileOutputStream outputStream = new FileOutputStream(starget);
    	 
    	FileChannel fcin =  inputStream.getChannel();
    	FileChannel fcout = outputStream.getChannel();
    	 
    	 
    	try{
			
    	long size = fcin.size();
    	fcin.transferTo(0, size, fcout);
    	
    	}catch (Exception e ){
    		//e.printStackTrace();
        	logger.info("file copy error :"   + e.getMessage()); 
    		
    	}finally{
    		
        	fcout.close();
        	fcin.close();    	 
        	outputStream.close();
        	inputStream.close();    		
    	}
     }
	
public static void copyFileCommonsIO(String source, String dest)	throws IOException {
		
		File oOldFile = null;
		File oNewFile = null; 
		
		oOldFile = new File(source);
		oNewFile = new File(dest);
		
	    FileUtils.copyFile(oOldFile, oNewFile);
	    
 	}


	public static void copyFileUsingApacheCommonsIO(File source, File dest)	throws IOException { 
	    FileUtils.copyFile(source, dest); 
 	}

	
	/**
	 * Description : 파일 명을 변경 한다.
	 * 
	 * @param String	 *            sDir : 디렉토리
	 * @param String	 *            sOldFileName : 이전 파일명
	 * @param String	 *            sNewFileName : 새 파일명
	 * @return boolean
	 * @exception none
	 */
	public   boolean renameFile( String sOldFileName,	String sNewFileName) {
		File oOldFile = null;
		File oNewFile = null;
		boolean suc = true;

		oOldFile = new File(sOldFileName);
		oNewFile = new File(sNewFileName);
		suc = oOldFile.renameTo(oNewFile);
		return suc;
	}

	 public   void fileDelete(String deleteFileName) {
	  File I = new File(deleteFileName);
	  I.delete();
	 }
	// 파일 백업 및  초기 화 작업 
	public   int   setDirFileList(String orgPath , String destPath ) throws Exception	 {		
	 
		  // 파일 목록을 요청한 디렉토리를 가지고 파일 객체를 생성함
		  File dir = new File(orgPath); 
		  try {
			  // 디렉토리가 존재한다면
			  if (dir.exists()) { 
				  
			   // 파일 목록을 구함
			   File[] files = dir.listFiles(); 		   
			   for (File file : files) { 
				   //파일 카피 함  
	   				logger.info("file backup 시작 :"   + destPath+File.separator+ file.getName());
	   				
	               fileCopy(dir+File.separator+ file.getName() ,destPath+File.separator+ file.getName());	                
	               fileDelete(dir+File.separator+ file.getName());
 				} 
			  }		 
		  }catch( Exception e){
			  
		  }finally{
			  return 0;
		  }
 	 }

	public   void   mkDir(String dirPath ){
		
		File dir = new File(dirPath);
		if(!dir.exists()){
			//디렉토리 생성 메서드
			dir.mkdirs();
		}
	}
	
	public  List getDirFileList(String dirPath )
	 {		
		Calendar calendar = new GregorianCalendar(Locale.KOREA);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		calendar.setTime(new Date());
		
		calendar.add(Calendar.DATE, -1);
		// 전일자 등록 여부 체크 
		String sale_dt = sdf.format(calendar.getTime());
		  
		  // 파일 목록을 요청한 디렉토리를 가지고 파일 객체를 생성함
		  File dir = new File(dirPath);
		  List dirList = new ArrayList();

		  // 디렉토리가 존재한다면
		  if (dir.exists()) { 
			  
		   // 파일 목록을 구함
		   File[] files = dir.listFiles(); 		   
		   for (File file : files) { 
				Date date = new Date(file.lastModified()); 
				String fileDate = sdf.format(date);  
				//if (file.isFile()  && fileDate.equals(sale_dt)){
				if (file.isFile()){
					dirList.add(file.getName());
				} 
			} 
 		  }		  
		  return dirList;
	 }
	
	
	// 변경된 파일 정보만 조회 함 
	public  List getDirModifyFileList(String dirPath )
	 {		
		Calendar calendar = new GregorianCalendar(Locale.KOREA);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		calendar.setTime(new Date());
		
		calendar.add(Calendar.DATE, -7);
		// 전일자 등록 여부 체크 
		String sale_dt = sdf.format(calendar.getTime());
		
		calendar.add(Calendar.DATE, 0 );
		// 전일자 등록 여부 체크 
		String sale_dt1 = sdf.format(calendar.getTime());
		    
		  // 파일 목록을 요청한 디렉토리를 가지고 파일 객체를 생성함
		
		  File dir = new File(dirPath);
		  List dirList = new ArrayList();

			logger.info("[Dir Name is  ]"  + dirPath);
		  // 디렉토리가 존재한다면
		  if (dir.exists()) { 
		   // 파일 목록을 구함
		   File[] files = dir.listFiles(); 		   
			logger.info("[file size ]"  + files.length);
		   
		   for (File file : files) { 
 
				Date date = new Date(file.lastModified()); 
				String fileDate = sdf.format(date);
				logger.info("[file name ]"  + file.getName());
				if (file.isFile()  &&  ( fileDate.compareTo(sale_dt) >= 0 )){
				//if (file.isFile()){
					logger.info("[file name ]"  + file.getName()); 
					dirList.add(file.getName());
				} 
			} 
		  }		  
		  return dirList;
	 }
	/**
     * 정기마스터 배신정보 생성 프로시저 
     * @return Result code (결과코드)
     * @exception exception Description of Exception(예외사항설명)
     */
	public int procMSTINFOCRT(Map map) throws Exception {
		ProcedureWrapper proc = new ProcedureWrapper();
		/* 

		*/
		int i=0;
		int ret=0;
		//DB Connection(DB 접속)
		connect("NHS");
		try {
			begin();

			logger.info("tran_ymd:"   + (String)map.get("SALE_DT"));
			logger.info("com_cd:"     + (String)map.get("CMP_CD"));
			logger.info("FILE_NM:"   + (String)map.get("FILE_NM"));
			logger.info("FILE_PATH:"   + (String)map.get("FILE_PATH"));
			/*
		    IN_SALE_DT                  IN VARCHAR2
		    , IN_CMP_CD                   IN VARCHAR2
		    , IN_FILE_NM                  IN VARCHAR2
		    , IN_STOR_CD                  IN VARCHAR2
		    , IN_FILE_PATH                IN VARCHAR2
		    , IN_DEPLOY_DIV               IN VARCHAR2	
		    */
		    
			logger.info("[DEBUG] [procMSTINFOCRT] Begin");
			proc.put("SP_WAT_DEPLOYDATA_CRT_VER2", 9); 
			//proc.put("SP_WAT_DEPLOYDATA_CRT", 8);
			//IN_SALES_ORG_CD 추가해라
			proc.setString(++i, (String)map.get("SALE_DT"));	// tran_ymd
			proc.setString(++i, (String)map.get("CMP_CD"));		// com_cd
			proc.setString(++i, (String)map.get("SALES_ORG_CD")); // salesorg CD
			proc.setString(++i, (String)map.get("FILE_NM"));	// FILE_NM
			proc.setString(++i, (String)map.get("STOR_CD"));	// store_cd
			proc.setString(++i, (String)map.get("FILE_PATH"));	// FILE_PATH
			proc.setString(++i, (String)map.get("DEPLOY_DIV"));	// create_ty
			proc.registerOutParameter(++i, DataTypes.INTEGER);
			proc.registerOutParameter(++i, DataTypes.VARCHAR);
			
			ProcedureResultSet prs = super.executeUpdateProcedure(proc); 
			 
			logger.info("[DEBUG] [procMSTINFOCRT] sql :" + proc.debug());

			ret = prs.getInt(8);
			String retMsg = prs.getString(9);
			logger.info("[DEBUG] [procMSTINFOCRT] ResultMsg:" + retMsg);
			logger.info("[DEBUG] [procMSTINFOCRT] End");
			
			
		} catch (Exception e) {
			rollback();
			System.out.println(e.getMessage());
			logger.info("[ERROR] procMSTINFOCRT::" + e);
			ret=-1;
		} finally {
			// 모든 trasaction을 종료하고 리소스를 반납합니다.
			end();
		}
		
		return ret;
	}
	
	// 재구 호출 파일 폴더삭제
	public static boolean deleteDirectory(File path) {
		if(!path.exists()) {
			return false;
		}
		
		File[] files = path.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				deleteDirectory(file);
			} else {
				file.delete();
			}
		}
		
		return path.delete();
	}
	public String getFileNm(String cmp_cd , String deploy_dt,  String down_div ) {
		int ret = 0; 
		String sql_debug1 = "";  
		SqlWrapper sql = new SqlWrapper();
		List list = null;
		String retStr =null;
 		Map map = new HashMap();
		int i = 0;  
		
		try { 
				connect("NHS");  
				//begin();  
 
				sql.put(findQuery("pos-sql", "SEL_WAT_FILENM"));

				sql.setString(++i, deploy_dt);   
				sql.setString(++i, cmp_cd);   
				sql.setString(++i, deploy_dt);   
				sql.setString(++i, down_div);   

 				list = executeQuery(sql);
 				
 				logger.info("[SQL info] " + sql.debug());	
				if  ( list.size() > 0) { 
					map = (Map<String, String>)list.get(0);  
					retStr = (String)map.get("FILE_NM"); 
					logger.info("[SQL File version Name] " +retStr);
				}else{
					retStr= "";
				}
				
		} catch(SQLException se) { 	
			retStr= "";
			logger.info("[SQL SUB ERROR 1 ] " + se.getMessage());	 

		} catch(Exception e) { 
			logger.info("[SQL SUB ERROR 2 ] " + e.getMessage());
			retStr= "";
		} finally {			
			return retStr;
			//df.CommLogger("▶ 5: SetData END return: "+ret);				
		}		
	}
	
	
	public List  getDelFileNm(String cmp_cd , String deploy_dt,  String down_div ) {
		int ret = 0; 
		String sql_debug1 = "";  
		SqlWrapper sql = new SqlWrapper();
		List list = null;
		String retStr =null;
 		Map map = new HashMap();
		int i = 0;  
		
		try { 
				connect("NHS");  
				//begin();  
 
				sql.put(findQuery("pos-sql", "SEL_WAT_FILENM"));

				sql.setString(++i, deploy_dt);   
				sql.setString(++i, cmp_cd);   
				sql.setString(++i, deploy_dt);   
				sql.setString(++i, down_div);   

 				list = executeQuery(sql);
 				
 				logger.info("[SQL info] " + sql.debug());	
				if  ( list.size() > 0) { 
					map = (Map<String, String>)list.get(0);  
					retStr = (String)map.get("FILE_NM"); 
					logger.info("[SQL info] " +retStr);
				}else{
					retStr= "";
				}
				
		} catch(SQLException se) { 	
			retStr= "";
			logger.info("[SQL SUB ERROR 1 ] " + se.getMessage());	 

		} catch(Exception e) { 
			logger.info("[SQL SUB ERROR 2 ] " + e.getMessage());
			retStr= "";
		} finally {	 
			return list;
			//df.CommLogger("▶ 5: SetData END return: "+ret);				
		} 
	}
	
	/**
     * 마스터 생성 배치 프로시저 
     * @return Result (결과코드)
     * @exception exception Description of Exception(예외사항설명)
     */
	public String getSysDate(String cmp_cd , int iDay) throws Exception {
		 
		String sql_debug1 = "";  
		SqlWrapper sql = new SqlWrapper();
		List list = null;
		String retStr =null;
 		Map map = new HashMap();
		int i = 0;
		
		SqlUtil su = new SqlUtil();
		
		Calendar calendar = new GregorianCalendar(Locale.KOREA);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		calendar.setTime(new Date());
		String today = sdf.format(calendar.getTime());
		 
		try { 
				connect("NHS");  
				//begin();  
				
				sql.put(su.findQuery("nhssysinq-sql", "SEL_SYSTEM_DATE"));
				sql.setString(++i, cmp_cd);   
				sql.setInt(++i, iDay);    
 				list = executeQuery(sql);
 				
				if  ( list.size() > 0) { 
					map = (Map<String, String>)list.get(0);  
					retStr = (String)map.get("SYS_DATE"); 
					//logger.info("[SQL info] " +retStr);
				}else{
					retStr= today;
				}
				
		} catch(SQLException se) { 	
			retStr= "";
			logger.info("[SQL SUB ERROR 1 ] " + se.getMessage());	 

		} catch(Exception e) { 
			logger.info("[SQL SUB ERROR 2 ] " + e.getMessage());
			retStr= "";
		} finally {			
			return retStr;
			//df.CommLogger("▶ 5: SetData END return: "+ret);				
		}
	}
	
	/**
     * 마스터 생성 배치 프로시저 
     * @return Result (결과코드)
     * @exception exception Description of Exception(예외사항설명)
     */
	public List getbetweenDate(String cmp_cd , String dt1 , String dt2) throws Exception {
		
		
		String sql_debug1 = "";  
		SqlWrapper sql = new SqlWrapper();
		List list = null;
		List retStr =null;
 		Map map = new HashMap();
		int i = 0;  
		
		Calendar calendar = new GregorianCalendar(Locale.KOREA);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		calendar.setTime(new Date());
		String today = sdf.format(calendar.getTime());
		 
		try { 
				connect("BRKR");  
				//SEL_CALENDAR_DATE
				sql.put(findQuery("nhssysinq-sql", "SEL_CALENDAR_DATE"));
				sql.setString(++i, cmp_cd);
				sql.setString(++i, dt1);   
				sql.setString(++i, dt2);   

			
 				list = executeQuery(sql);
 				
 				logger.info("[SQL info] " + sql.debug());	
				if  ( list.size() > 0) { 
					retStr = list;
					logger.info("[SQL info] " +retStr);
				}else{
					retStr= null;
				}
				
		} catch(SQLException se) { 	
			retStr= null;
			logger.info("[SQL SUB ERROR 1 ] " + se.getMessage());	 

		} catch(Exception e) { 
			logger.info("[SQL SUB ERROR 2 ] " + e.getMessage());
			retStr= null;
		} finally {			
			return list;
		}
	}
	
	public List getDelfileName(String cmp_cd ,String del_date , String sel_div ) throws Exception {
		 
		String sql_debug1 = "";  
		SqlWrapper sql = new SqlWrapper();
		List list = null;
		List retStr =null;
 		Map map = new HashMap();
		int i = 0;  
		
		Calendar calendar = new GregorianCalendar(Locale.KOREA);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		calendar.setTime(new Date());
		String today = sdf.format(calendar.getTime());
		 
		try { 
				connect("NHS");   
 
				sql.put(findQuery("pos-sql", "SEL_DEL_IMG_LST"));
				sql.setString(++i, cmp_cd);
				sql.setString(++i, del_date);  
 				 
 				list = executeQuery(sql);
 				
 				if  ( list.size() > 0) { 
					retStr = list;
 				}else{
					retStr= null;
				}
				
		} catch(SQLException se) { 	
			retStr= null;
			logger.info("[SQL SUB ERROR 1 ] " + se.getMessage());	 

		} catch(Exception e) { 
			logger.info("[SQL SUB ERROR 2 ] " + e.getMessage());
			retStr= null;
		} finally {			
			return list;
 		}
	}

	
	public List getStorOrgCd(String cmp_cd) throws Exception {
		 
		String sql_debug1 = "";  
		SqlWrapper sql = new SqlWrapper();
		List list = null; 
 		Map map = new HashMap();
		int i = 0;   
		
		try { 
				connect("BRKR");   
 
				sql.put(findQuery("pos-sql", "SEL_SALESORG_LST"));
				sql.setString(++i, cmp_cd); 
 				list = executeQuery(sql);
 				  
		} catch(SQLException se) { 	 
			logger.info("[SQL SUB ERROR 1 ] " + se.getMessage());	 
		} catch(Exception e) { 
			logger.info("[SQL SUB ERROR 2 ] " + e.getMessage()); 
		} finally {			
			return list;
 		}
	}

	
	public List getCustomerFileNm(String cmp_cd  , String File_div  ) throws Exception {
		 
		String sql_debug1 = "";  
		SqlWrapper sql = new SqlWrapper();
		List list = null; 
 		Map map = new HashMap();
		int i = 0;   
		
		try { 
				connect("BRKR");   
 				//logger.info("[SQL file div ] " + File_div);	 	
				// 파일명 관리 테이블 파일명 그대로 select 함
				if ("03".equals(File_div)){ // customer file
					sql.put(findQuery("pos-sql", "SEL_CUSTOMER_FILE_LST"));
					sql.setString(++i, cmp_cd);
					//sql.setString(++i, sale_orgcd); 
					//sql.setString(++i, upd_date); 					
				}else if ("07".equals(File_div)){ // cdp_com 
					sql.put(findQuery("pos-sql", "SEL_CDP_COM_FILE_LST"));
					sql.setString(++i, cmp_cd);
					sql.setString(++i, cmp_cd);
					sql.setString(++i, cmp_cd);
					sql.setString(++i, cmp_cd);
					sql.setString(++i, cmp_cd);
					sql.setString(++i, cmp_cd);
  	
				}
 				list = executeQuery(sql);
 				//logger.info("[SQL SUB ERROR 1 ] " + sql.debug());	 	
 				  
		} catch(SQLException se) { 	 
			logger.info("[SQL SUB ERROR 1 ] " + se.getMessage() + sql.debug());	 
		} catch(Exception e) { 
			logger.info("[SQL SUB ERROR 2 ] " + e.getMessage()); 
		} finally {			
			return list;
 		}
	}

	/**
     * 배치 프로시저 
     * @return Result (결과코드)
     * @exception exception Description of Exception(예외사항설명)
     */
	public int procBATCHSCHEDULE() throws Exception {
		ProcedureWrapper proc = new ProcedureWrapper();
		int i=0;
		int ret=0;
		//DB Connection(DB 접속)
		connect("CMGNS");
		try {
			begin();

			logger.info("[DEBUG] [procBATCHSCHEDULE] Begin");
			proc.put("SP_BATCH_SCHEDULE", 2);
			proc.registerOutParameter(++i, DataTypes.INTEGER);
			proc.registerOutParameter(++i, DataTypes.VARCHAR);

			ProcedureResultSet prs = super.executeUpdateProcedure(proc);

			ret = prs.getInt(1);
			String retMsg = prs.getString(2);
			logger.info("[DEBUG] [procBATCHSCHEDULE] ResultMsg:" + retMsg);
			logger.info("[DEBUG] [procBATCHSCHEDULE] End");
		} catch (Exception e) {
			rollback();
			System.out.println(e.getMessage());
			logger.info("[ERROR] procBATCHSCHEDULE::" + e);
			ret=-1;
		} finally {
			// 모든 trasaction을 종료하고 리소스를 반납합니다.
			end();
		}
		
		return ret;
	}


	/*
	 *  1.브랜드별 상품 이미지 파일 저장.
	 *   
	 */
	
	public  int  getDirModifyFileList(String dirPath ,  String file_div , String file_sub_div,  String option  ) throws Exception
	 {	
 		int iret =0;
		int i = 0;
		SqlWrapper sql = new SqlWrapper(); 
 
		try {
			begin();
			connect("BRKR");

			sql = new SqlWrapper(); 
			Calendar calendar = new GregorianCalendar(Locale.KOREA);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			calendar.setTime(new Date());
			
			calendar.add(Calendar.DATE, -3);
			// 전일자 등록 여부 체크 
			String sale_dt = sdf.format(calendar.getTime());
			
			calendar.add(Calendar.DATE, 0 );
			// 전일자 등록 여부 체크 
			String sale_dt1 = sdf.format(calendar.getTime());
 			  // 파일 목록을 요청한 디렉토리를 가지고 파일 객체를 생성함
 			  File dir = new File(dirPath);
			  List dirList = new ArrayList();

				logger.info("[Dir Name is ]"  + dirPath);
			  // 디렉토리가 존재한다면
			  if (dir.exists()) { 
			   // 파일 목록을 구함
				   File[] files = dir.listFiles(); 		   
					logger.info("[file size ]"  + files.length);
				   
				   for (File file : files) { 
						Date date = new Date(file.lastModified()); 
						String fileDate = sdf.format(date);
	 					
						if(sql!= null) {			
							sql.close();
						}   
						
					   if (option.equals("1")){ //전체 파일 저장 
						   	//옵션 1 은  전체 파일 반환
							if (file.isFile()){
								 
								//insert 캐셔 테스트 항목  
								sql.put(findQuery("pos-sql", "MER_POS_WAT_FILE_LIST"));
								sql.setString(1, file_div);
								if(file_sub_div.equals("1")){
									sql.setString(2, file.getName().substring(0, file.getName().indexOf("_")));
								}else if(file_sub_div.equals("2")){
									sql.setString(2, file.getName().substring(0, file.getName().indexOf(".")));

								}else{
									sql.setString(2, file.getName());
								}

								sql.setString(3, file_sub_div); 
								sql.setString(4, fileDate.toString());  
								
								//file[j].getName().substring(  0,  file[j].getName().indexOf("."))							
								iret = executeUpdate(sql);
								//logger.info("[file name ]"  + sql.debug() ); 
	 						}
							
					   }else{		// - 3일 이후 데이터 모두 저장 
	
							if (file.isFile()  &&  ( fileDate.compareTo(sale_dt) >= 0 )){				
								logger.info("[file name2 ]"  + file.getName()); 
								 
								//insert 캐셔 테스트 항목 
								sql = new SqlWrapper();
								sql.put(findQuery("pos-sql", "MER_POS_WAT_FILE_LIST"));
								sql.setString(1, file_div);
								if(file_sub_div.equals("1")){ 
									sql.setString(2, file.getName().substring(0, file.getName().indexOf("_")));

								}else if(file_sub_div.equals("2")) {
									sql.setString(2, file.getName().substring(0, file.getName().indexOf(".")));
								}else{
									sql.setString(2, file.getName());
								}								
								sql.setString(3, file_sub_div); 
								sql.setString(4, fileDate.toString());  
								iret = executeUpdate(sql);
 							} 
					   } //if end 
					   
					} //for end 
			   
			  }
		} catch(SQLException e){
			logger.info( "▶ SQLException  Rollback=====>"+ e.getMessage() + "   " + e.toString() );
			logger.info( "▶ SQLException  SQL=====>"+ sql.debug()); 
			iret = 20;
			rollback();
			
		}catch( Exception e) {
			logger.info("[err   ]"  + e.toString()); 

			iret = 9;
		//}catch( )
		}finally{
			end();
		}
		 
		  return iret;
	 }
	
	
	/**
	 * getMakeFileNmList - 복사할 파일 명 조회 
	 * @param m 
 	 * @return  file List
	 * @throws Exception
	 */
	public List  getMakeFileNmList(String cmp_cd , String sOrgCd,  String file_div , String file_sub_div ) {
		int ret = 0; 
		String sql_debug1 = "";  
		SqlWrapper sql = new SqlWrapper();
		List list = null;
		String retStr =null;
 		Map map = new HashMap();
		int i = 0;  
		
		try { 
				connect("BRKR");  
				//begin();  
				
				if("03".equals(file_div.toString()) ){	//customer image
				   
				}else if("04".equals(file_div.toString()) ){  // item image
					
					sql.put(findQuery("pos-sql", "SEL_WAT_FILE_LIST"));
					sql.setString(++i, cmp_cd);   
					sql.setString(++i, sOrgCd);   
					sql.setString(++i, file_div);   
					sql.setString(++i, file_sub_div);
					
				}else if("05".equals(file_div.toString()) ){// campaign image
					
					sql.put(findQuery("pos-sql", "SEL_WAT_CPI_IMG_LIST"));
					sql.setString(++i, cmp_cd);   
					sql.setString(++i, sOrgCd);    
					sql.setString(++i, cmp_cd);   
					sql.setString(++i, sOrgCd);
					
				}else if("06".equals(file_div.toString()) ){// test mode image
					sql.put(findQuery("pos-sql", "SEL_WAT_TEST_IMG_LIST"));
					sql.setString(++i, cmp_cd);   
					sql.setString(++i, sOrgCd); 
				}else if("07".equals(file_div.toString()) ){// cdp-com image 
					
					sql.put(findQuery("pos-sql", "SEL_CDPCOM_BRAND_FILE_LST"));
					sql.setString(++i, cmp_cd);   
					sql.setString(++i, sOrgCd);  
					
					sql.setString(++i, cmp_cd);   
					sql.setString(++i, sOrgCd);
					
					sql.setString(++i, cmp_cd);   
					sql.setString(++i, sOrgCd);
					
					sql.setString(++i, cmp_cd);   
					sql.setString(++i, sOrgCd);
					
					sql.setString(++i, cmp_cd);   
					sql.setString(++i, sOrgCd);
					
					sql.setString(++i, cmp_cd);   
					sql.setString(++i, sOrgCd);
					
				}
 				list = executeQuery(sql);
 				
 				logger.info("[SQL info] " + sql.debug());	
				if  ( list.size() > 0) { 
					map = (Map<String, String>)list.get(0);  
					retStr = (String)map.get("FILE_NM"); 
 				}else{
					retStr= "";
				}
				
 		} catch(SQLException se) { 	
			retStr= "";
			logger.info("[SQL SUB ERROR 1 ] " + se.getMessage());	 

		} catch(Exception e) { 
			logger.info("[SQL SUB ERROR 2 ] " + e.getMessage());
			retStr= "";
		} finally {	 
			return list;
			//df.CommLogger("▶ 5: SetData END return: "+ret);				
		} 
	}
	
	
	/**
	 * generateTrlogData - 일자별 TRLOG 파일을 생성함 
	 * @param m 
	 * @param path : Path to generate TBL File(TBL파일 생성할 경로)
	 * @return
	 * @throws Exception
	 */
	private int generateTrlogData(Map<String, String> m, String path) throws Exception {
		StringBuffer sb = new StringBuffer();
		//MasterCrtExDAO dao = new MasterCrtExDAO();
		String fileName = (String)m.get("STOR_CD") + "_" + (String)m.get("SALE_DT") + "_" + "TRLOG.tbl";
		boolean flag = true;
		int max = 0;
		try {
			while(flag) {
				List<Object> list = null;
				
			//	list =  selectMaster(m, "SEL_TRLOG_DATA", max);
				if(list.size() > 0) {
					if(max > 0)
						sb.setLength(0);
					
					for(int i = 0;i < list.size();i++) {
						Map<String, String> map = (Map<String, String>)list.get(i);
						sb.append( (String)map.get("DEAL_DATA") + "@~" ) ;
					}
					if (max == 0)
					{
						// If there is result of inquiry, generate a file(조회된 결과가 있으면 파일 생성)
						if(sb.length()>0) {
							ZipUtil.createFileUTF16(sb, path, fileName, false);
							//logger.info("[comcd : "+(String)m.get("com_cd")+"][storecd : "+(String)m.get("store_cd")+"] Filename : "+fileName+" is created.");
						} else {
							ZipUtil.createFileUTF16(sb, path, fileName, false);
							//logger.info("[comcd : "+(String)m.get("com_cd")+"][storecd : "+(String)m.get("store_cd")+"] Filename : "+fileName+" is not created. There are no data.");
						}
					}
					else
					{
						// If there is result of inquiry, generate a file(조회된 결과가 있으면 파일 추가)
						ZipUtil.createFileUTF16(sb, path, fileName, true);
//						logger.info("[comcd : "+(String)m.get("com_cd")+"][storecd : "+(String)m.get("store_cd")+"] Filename : "+fileName+" is appended.");
					}					

					max++;
				}else {
					if( max == 0 ) {
						ZipUtil.createFileUTF16(sb, path, fileName, false);
//						logger.info("[comcd : "+(String)m.get("com_cd")+"][storecd : "+(String)m.get("store_cd")+"] Filename : "+fileName+" is appended.");
					}
					
					flag = false;
				}
			}
		}catch(Exception e) {
			logger.info("[ERROR]" + e);
			throw e;
		}
		return 0;
	}
	 
	
}
