/**
 *
 * @(#)author  [OK]
 * @(#)version 1.0
 * @(#)date    2014-08-07
 * @(#)since   JDK 1.6.2
 *
 * Copyright (c) www.udapsoft.co.kr, Inc.
 * All rights reserved.
 */
package kr.co.udapsoft.ebid.buyer.payment.purchase.biz;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;

import kr.co.hsnc.common.base.WAFLogger;
import kr.co.hsnc.common.base.WAFMessages;
import kr.co.hsnc.common.config.WAFConfig;
import kr.co.hsnc.common.logger.Logger;
import kr.co.hsnc.common.sql.Row;
import kr.co.hsnc.common.sql.RowSet;
import kr.co.hsnc.common.sql.RowSetImpl;
import kr.co.hsnc.common.sql.WAFSQLException;
import kr.co.hsnc.common.sql.persistent.Persistent;
import kr.co.hsnc.common.sql.persistent.PersistentImpl;
import kr.co.hsnc.common.sql.search.Search;
import kr.co.hsnc.common.sql.search.SearchImpl;
import kr.co.hsnc.common.sql.util.RowSetUtility;
import kr.co.hsnc.common.util.StringUtil;
import kr.co.hsnc.common.util.ValueObject;
import kr.co.udapsoft.common.sender.MessageSend;
import kr.co.udapsoft.ebid.buyer.common.file.FileManager;
import oracle.toplink.internal.ox.StrBuffer;

import com.bea.common.security.service.SAML2PublishException.FileNotFoundException;
import com.udapsoft.modular.web.ibsheet7.IBSheet7Factory;
import com.udapsoft.waf.system.Biz;
import com.udapsoft.waf.system.HandlerStorage;

public class PayItemResultFileUpLoadBiz extends Biz {
	
	public PayItemResultFileUpLoadBiz(HandlerStorage storage) {
		super(storage);
	}

	public void doBiz() throws Exception {

		if(storage.compareEvent("SAVE_MRR_FILE")){
			
			String payReqId = params.get("payreqId");
			boolean success = createPDF(payReqId);
    		storage.setSuccess(success);

		}else if(storage.compareEvent("SAVE_CONT_COPY_FILE")){
			
			String payReqId = params.get("payreqId");
			boolean success = copyCont(payReqId);
    		storage.setSuccess(success);

		}
		
	}

	public boolean createPDF(String payReqId) throws Exception {
		HandlerStorage storage = new HandlerStorage();
    	
		ValueObject returnVO = getPayReqDetail(payReqId);
		//RowSet returnRowSet = getListRowSet(params.get("seq"));
		RowSet returnRowSet = getitemList(payReqId);
		//2016.6.22 MRR문서생성 수정 
		if (returnVO.get("CURRENCY_GB").equals("KRW")){ 
			if(returnRowSet.size() > 0) {
				PURCreatePDF2 purCreatePDF2 = new PURCreatePDF2();
				purCreatePDF2.doBiz(returnVO.get("dept_cd"), returnVO.get("dept_nm"), returnVO.get("corp_nm"), returnVO.get("ord_doc_no"), payReqId, returnVO.get("REQ_DATE"), storage.request);
				saveFileData(payReqId, returnVO.get("REQ_DATE"), returnVO.get("ord_doc_no"));
			}
		}
		else
		{
			PURCreatePDF3 purCreatePDF3 = new PURCreatePDF3(); 
			purCreatePDF3.doBiz(returnVO.get("dept_cd"), returnVO.get("dept_nm"), returnVO.get("corp_nm"), returnVO.get("ord_doc_no"), payReqId, returnVO.get("PUR_CONT_ID"), returnVO.get("REQ_DATE"),returnVO.get("CURRENCY_GB"),returnVO.getInt("digit"), storage.request);
			saveFileData(payReqId, returnVO.get("REQ_DATE"), returnVO.get("ord_doc_no"));
		}
		return true;
	}
	
	public ValueObject getPayReqDetail(String payReqId) throws Exception {               
        
        Search search = new SearchImpl();
        RowSet listRowSet = null;
        StringBuffer sql = new StringBuffer();
		ValueObject vo = null;
        
        try {
        	sql.append("	SELECT B.DEPT_CD DEPT_CD                  												\n");
        	sql.append("		 , B.DEPT_NAME DEPT_NM                												\n");
        	sql.append("		 , (SELECT CORP_KOR FROM SUPP_INFO WHERE CORP_ID = B.CORP_ID) AS CORP_NM            \n");
        	sql.append("		 , B.ORD_DOC_NO                    													\n");
        	sql.append("		 , TO_CHAR(TO_DATE(A.TAX_DY, 'YYYYMMDD'), 'YYYY-MM-DD') AS REQ_DATE                 \n");
        	sql.append("		, A.PUR_CONT_ID                      												\n");
        	sql.append("		, B.CURRENCY_GB                     												\n");//2016.6.22 외화 추가 
        	sql.append("		, F_GET_CURRENCY_DIGIT(B.CURRENCY_GB) AS DIGIT                   				    \n");
        	sql.append("		, A.PAY_DIV										                   				    \n");//2021.5.10 대금구분 추가
        	sql.append("	FROM PUR1100T  A   , PUR1000T B      													\n");
        	sql.append("	WHERE A.PUR_CONT_ID = B.PUR_CONT_ID 													\n");
        	sql.append("	 AND A.PAYREQ_ID  = ?  																	\n");
        	
        	
            search.setStatement(sql.toString());
            search.addParameter(payReqId);
            WAFLogger.debug(sql.toString());
            listRowSet = search.execute();
            
			if(listRowSet.size()>0){
				vo = RowSetUtility.getValueObject(listRowSet.getRow(0));
			}
			
		}catch(Exception e){
			WAFLogger.error("SQL : " + search.getStatement());
            WAFLogger.error(e);
		}finally{
			if( vo == null) vo = new ValueObject();
		}
		return vo;
    }
	
	
	/**
     *@param ValueObject
     *@return RowSet
     *기   능 : 대금신청 아이템 내역을 조회한다.
     *@author OK
     *@version 2014. 7. 28.
     *@since JDK1.7
     */
    public RowSet getitemList(String payReqId) {
    	
        Search search = new SearchImpl();
        RowSet listRowSet = null;
        String sqlstr = "";
        
        try {
        	sqlstr += " 																			\n"
        			+ " SELECT																		\n"
        			+ " 		A.MATERIAL_CD,														\n"
        			+ " 		A.STOCK_NO,															\n"
        			+ " 		A.ITEM_QTY AS STOCK_QTY,											\n"
        			+ " 		A.ITEM_PRI AS STOCK_PRI,  -- pmm_payreq_item.item_pri				\n"
        			+ " 		A.ITEM_AMT AS STOCK_AMT,  -- pmm_payreq_item.item_amt				\n"
        			+ " 		A.EXC_PRI,    -- pmm_payreq_item.exc_pri							\n"
        			+ " 		A.EXC_AMT,    -- pmm_payreq_item.exc_amt							\n"
        			+ " 		A.GUBUN																\n"
        			+ " FROM  PMM_PAYREQ_ITEM A												\n"
        			+ " WHERE A.PAYREQ_ID = '"+payReqId+"'										\n"
        			;
        	search.setStatement(sqlstr);
        	WAFLogger.debug(sqlstr);
            listRowSet = search.execute();
            
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> getitemList() : " + e.getMessage());
            WAFLogger.error("SQL : " + search.getStatement());
            WAFLogger.error(e);
            return null;
        }
        finally {

            if( listRowSet == null ) listRowSet = new RowSetImpl();
            return listRowSet;
        }
    }
    
    private boolean saveFileData(String payreq_id, String req_date, String ord_doc_no)throws Exception{
		try {
			File fileObj = null;
			String fileName = "";
			String baseCd = "PUR_PAY_FILE";
			
			ValueObject voFileNm = new ValueObject();
			
			String req_date2 = req_date.replaceAll("-", "");
			req_date2 = req_date2.substring(0, 6);
			
			Connection conn = super.conn.getConnection();
			String yyyyMM = (new java.text.SimpleDateFormat ("yyyyMM")).format (new java.util.Date());
			
			
			String fileConnGB = "PURCHASE_"+payreq_id;
			
			// ID = 160 = MRR
			String fileId = getFileID(conn);
			
			addFileMap(conn, fileId, fileConnGB, "160", "F", "");
			
//			String path = StringUtil.replace(WAFConfig.get("waf.repository.path") + "/"+yyyyMM, "/", File.separator);
			String path = StringUtil.replace(WAFConfig.get("waf.repository.path") + "/payment/purchase/"+payreq_id, "/", File.separator);
        	
    		int tempFileCnt = 0;
    		File fileExist = new File(path);
    		File fileList[] = fileExist.listFiles();
    		for(File tempFile : fileList) {
    			if(tempFile.isFile()) {
    				if(tempFile.getName().indexOf(ord_doc_no+"_"+req_date2) > -1) {
    					tempFileCnt++;
    				}
    			}
    		}
    		
    		
    		voFileNm = getNewFileName(conn, "160", baseCd);	// MRR
    		
    		
    		if(tempFileCnt == 1 ) {
    			fileObj = new File(path+"/"+ord_doc_no+"_"+req_date2+".pdf");
    			fileName	=	ord_doc_no+"_"+req_date2+".pdf";
    		} else if (tempFileCnt > 1) {
    			--tempFileCnt;
    			fileObj = new File(path+"/"+ord_doc_no+"_"+req_date2+"_"+tempFileCnt+".pdf");
    			fileName	=	ord_doc_no+"_"+req_date2+".pdf";
    		}
    		
    		fileName = voFileNm.get("FILE_NUM") +". "+ voFileNm.get("DETAILNM") +"_" + fileName;
    		
             //첨부파일 연결하기
    		addFile(conn, fileObj, fileName, fileId);
    		return true;
		} catch (Exception e) {
			super.doException(e);
            conn.setRollback();
            storage.setMessage(e.getMessage());
            storage.setDetailMessage(e);
            return false;
            
		}
	}
    
	/**
     * 파일맵을 추가한다.
	 * @param connection
	 * @return
	 * @throws Exception
	 */
    private String getFileID(Connection connection) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        try {

            sqlstr = " SELECT PUB0500T_S.NEXTVAL AS FILE_ID \n"
                   + " FROM   DUAL                          \n" ;

            persistent.setStatement(sqlstr);

            return persistent.query().getRow(0).get("FILE_ID");
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> getFileID() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            storage.setDetailMessage(e);
            throw e;
        }
    }
    
    //변경차수 추가
    private void addFileMap(Connection connection, String fileID, String fileGB, String ID, String addGB, String modNo) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        int ACCT_ID = 0;
        if(storage.getUser() != null) ACCT_ID = storage.getUser().getInt("ACCT_ID");
        try {

            sqlstr = " INSERT INTO PUB0510T "
                   + " ( FILE_MAP_ID, FILE_ID, O_FILE_GB, O_ID, FILE_GB, ID, OPEN_CORP_YN, USE_CON_YN, ADD_GB, MOD_NO, " //변경차수 추가
                   + "   CRE_BY, CRE_DATE ) "
                   + " VALUES "
                   + " ( PUB0510T_S.NEXTVAL, ?, ?, ?, ?, ?, ?, ?, ?, ?, "
                   + "   ?, TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') ) " ;

            persistent.setStatement(sqlstr);

            persistent.addParameter(fileID);
            persistent.addParameter(fileGB);
            persistent.addParameter(ID);
            persistent.addParameter(fileGB);
            persistent.addParameter(ID);
            persistent.addParameter("N");
            persistent.addParameter("Y");
            persistent.addParameter(addGB);
            persistent.addParameter(modNo); //변경차수 추가
            persistent.addParameter(ACCT_ID);

            persistent.execute();
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> addFile() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            storage.setDetailMessage(e);
            throw e;
        }
    }
    
    private void addFile(Connection connection, File file, String fileName, String FileId) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        int ACCT_ID = 0;
        if(storage.getUser() != null) ACCT_ID = storage.getUser().getInt("ACCT_ID");

        try {

            sqlstr = " INSERT INTO PUB0500T "
                   + " ( FILE_ID, REAL_FILE_NAME, FILE_NAME, FILE_PATH, FILE_EXT,  "
                   + "   FILE_SIZE, MINE_TYPE, CONTENT_TYPE, CONTENT_DISP, SUB_MINE_TYPE,  "
                   + "   CRE_BY, CRE_DATE ) "
                   + " VALUES "
                   + " ( ?, ?, ?, ?, ?, "
                   + "   ?, ?, ?, ?, ?, "
                   + "   ?, TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') ) " ;

            persistent.setStatement(sqlstr);

            String defaultDir = WAFConfig.get("waf.repository.path");
            String path = StringUtil.replace( StringUtil.replace(file.getPath(), "\\", "/"), "/" + file.getName(), "");
            path = path.substring(defaultDir.length(), path.length());
            
            ///payment/purchase/30659

            String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length());

            fileName = StringUtil.replace( fileName, "\\", "/");
            fileName = fileName.substring( fileName.lastIndexOf("/") + 1, fileName.length());

            persistent.addParameter(FileId);
            persistent.addParameter(file.getName());
            persistent.addParameter(fileName);
            persistent.addParameter(path);
            persistent.addParameter(ext);
            
            persistent.addParameter((int)file.length());
            persistent.addParameter("");
            persistent.addParameter(file.getName());
            persistent.addParameter("");
            persistent.addParameter("");

            persistent.addParameter(ACCT_ID);

            persistent.execute();
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> addFile() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            storage.setDetailMessage(e);
            throw e;
        }
    }
    
    private ValueObject getNewFileName( Connection connection, String file_cd, String baseCd) {

		 Persistent persistent = new PersistentImpl(connection);
		 String sqlstr = "";
		 ValueObject vo = new ValueObject();
		 
     try {
     	
         sqlstr = 	" SELECT DETAILNM						" +
         				" 		 ,CHG_CODE02	FILE_NUM				" +
      	   			" FROM EBID_COM911T							"+
      	   			" WHERE BASECD = ?				 		"+
      	   			" AND DETAILCD = ?						" ;

         persistent.setStatement(sqlstr);
         persistent.addParameter(baseCd);
         persistent.addParameter(file_cd);
         RowSet rowset = persistent.query();
         
         if( rowset != null && rowset.size() > 0 ){
         	vo = RowSetUtility.getValueObject(rowset.getRow(0));
         }
     }
     catch(Exception e) {

         WAFLogger.error(this.getClass().getName() + " --> getFileMapID() : " + e.getMessage());
         WAFLogger.error("SQL : " + persistent.getStatement());
         WAFLogger.error(e);
     }
     finally {

         if( vo == null ) vo = new ValueObject();
     }
     
     return vo;
    }

    public boolean copyCont(String payReqId) throws Exception {
		HandlerStorage storage = new HandlerStorage();
    	
		ValueObject returnVO = getPayReqDetail(payReqId);
		RowSet returnRowSet = getContList(payReqId, returnVO.get("PAY_DIV"));
		System.out.println("returnRowSet.size() : "+returnRowSet.size());
		//2021.4.27 계약서문서복사 
		if(returnRowSet.size() > 0) {
			for (int i = 0; i < returnRowSet.size(); i++) {
				Row row=returnRowSet.getRow(i);
				saveContFileData(payReqId, row.get("PUR_CONT_MOD_ID"), row.get("UNIQUE_FILE_NAME"), row.get("FILE_PATH"), row.get("FILE_EXT"), row.get("FILE_SIZE"), row.get("FILE_NAME"));
			}
		}
		return true;
	}
    
    public RowSet getContList(String payReqId, String payDiv) {
    	
        Search search = new SearchImpl();
        RowSet listRowSet = null;
        String sqlstr = "";
        
        try {
        	sqlstr += " 															\n"
        			+ " SELECT														\n"
        			+ " 		PUR_CONT_MOD_ID,									\n"
        			+ " 		UNIQUE_FILE_NAME,									\n"
        			+ " 		FILE_PATH,											\n"
        			+ " 		FILE_EXT,  											\n"
        			+ " 		FILE_SIZE,  										\n"
        			+ " 		FILE_NAME    										\n"
        			+ " FROM  CONT_PUR_FILE											\n";
        	if(payDiv.equals("1")){	//납품성 일 경우 최종 계약서 정보만
        		sqlstr += " WHERE PUR_CONT_MOD_ID IN(SELECT PUR_CONT_MOD_ID FROM PUR1100T WHERE PAYREQ_ID = '"+payReqId+"')								\n";
        	}else{	//설치성(계획분할) 일 경우 모든 계약서 정보 포함
        		sqlstr += " WHERE PUR_CONT_MOD_ID IN(SELECT PUR_CONT_MOD_ID	FROM PUR2000T WHERE PUR_CONT_ID IN(SELECT PUR_CONT_ID FROM PUR1100T WHERE PAYREQ_ID = '"+payReqId+"'))								\n";
        	}
        	search.setStatement(sqlstr);
        	WAFLogger.debug(sqlstr);
            listRowSet = search.execute();
            
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> getContList() : " + e.getMessage());
            WAFLogger.error("SQL : " + search.getStatement());
            WAFLogger.error(e);
            return null;
        }
        finally {

            if( listRowSet == null ) listRowSet = new RowSetImpl();
            return listRowSet;
        }
    }
    
    private boolean saveContFileData(String payreq_id, String pur_cont_mod_id, String unique_file_name, String file_path, String file_ext, String file_size, String file_name)throws Exception{
		try {
			File fileObj = null;
			String fileName = "";
			Connection conn = super.conn.getConnection();
			String fileConnGB = "PURCHASE_"+payreq_id;
			
			// ID = 230 = 계약서
			String fileId = getFileID(conn);	//PUB0500T_S.NEXTVAL
			addFileMap(conn, fileId, fileConnGB, "230", "F", "");
			//첨부파일 연결하기(db)
			String newPath = "/payment/purchase/"+payreq_id;
			addContFile(conn, fileId, pur_cont_mod_id, unique_file_name, newPath, file_ext, file_size, file_name);
			//실제 첨부파일 복사하기
			String path = "/cont/"+file_path;
			copyFile(payreq_id, path, unique_file_name);    		
    		return true;
		} catch (Exception e) {
			super.doException(e);
            conn.setRollback();
            storage.setMessage(e.getMessage());
            storage.setDetailMessage(e);
            return false;
            
		}
	}
    
    private void addContFile(Connection connection, String FileId, String pur_cont_mod_id, String unique_file_name, String file_path, String file_ext, String file_size, String file_name) throws Exception {
        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        int ACCT_ID = 0;
        if(storage.getUser() != null) ACCT_ID = storage.getUser().getInt("ACCT_ID");

        try {

            sqlstr = " INSERT INTO PUB0500T "
                   + " ( FILE_ID, REAL_FILE_NAME, FILE_NAME, FILE_PATH, FILE_EXT, FILE_SIZE,  "
                   + "   CRE_BY, CRE_DATE ) "
                   + " VALUES "
                   + " ( ?, ?, ?, ?, ?, ?,"
                   + "   ?, TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') ) " ;

            persistent.setStatement(sqlstr);
            
            persistent.addParameter(FileId);
            persistent.addParameter(unique_file_name);
            persistent.addParameter(file_name);
            persistent.addParameter(file_path);
            persistent.addParameter(file_ext);
            persistent.addParameter(file_size);
            
            persistent.addParameter(ACCT_ID);

            persistent.execute();
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> addFile() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            storage.setDetailMessage(e);
            throw e;
        }
    }    
    
    private void copyFile(String payreq_id, String file_path, String unique_file_name) throws Exception {
    	String oriFileInfo  = StringUtil.replace(WAFConfig.get("waf.repository.path") + file_path+unique_file_name, "/", File.separator);
    	String copyFileInfo = StringUtil.replace(WAFConfig.get("waf.repository.path") + "/payment/purchase/"+payreq_id+"/"+unique_file_name, "/", File.separator);
    	String copyFilePath = StringUtil.replace(WAFConfig.get("waf.repository.path") + "/payment/purchase/"+payreq_id, "/", File.separator);

    	File dir = new File(copyFilePath);
    	if(dir.exists() == false) dir.mkdir();

    	File oriFile = new File(oriFileInfo);
        File copyFile = new File(copyFileInfo);

        try {
        	FileInputStream fis = new FileInputStream(oriFile); //읽을파일
            FileOutputStream fos = new FileOutputStream(copyFile); //복사할파일
            int fileByte = 0; 
            // fis.read()가 -1 이면 파일을 다 읽은것
            while((fileByte = fis.read()) != -1) {
                fos.write(fileByte);
            }
            //자원사용종료
            fis.close();
            fos.close();

        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }    
}
