/**
 * @(#)file    SignThreadBiz.java
 * @(#)author  DaeJin Lee
 * @(#)version 1.0
 * @(#)date    Jun 10, 2005
 * @(#)since   JDK 1.4.2
 *
 * Copyright (c) www.dcchem.co.kr, Inc.
 * All rights reserved.
 * This software is the proprietary information of dcchem, Inc.
 */
package kr.co.udapsoft.common.commonSign;

import java.sql.Connection;

import kr.co.hsnc.common.base.WAFLogger;
import kr.co.hsnc.common.logger.Logger;
import kr.co.hsnc.common.sql.Row;
import kr.co.hsnc.common.sql.RowImpl;
import kr.co.hsnc.common.sql.RowSet;
import kr.co.hsnc.common.sql.RowSetImpl;
import kr.co.hsnc.common.sql.WAFConnection;
import kr.co.hsnc.common.sql.WAFConnectionImpl;
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.util.ValueObject;

/**
 * 
 * @version 1.0
 * @author DaeJin Lee
 */
public class CommonSignThreadBiz {

    private WAFConnection conn = null;
    
    public CommonSignThreadBiz() {

        this.conn = new WAFConnectionImpl();        
        
    }

    /**
     * 전자결재 처리결과 수신 Biz
     */
    public void doBiz() throws Exception {

    	try {
    		RowSet rowSignInterface = getIFSignInfo();
    		setSign(rowSignInterface);
    	} catch(Exception se) {
    		WAFLogger.error(this.getClass().getName() + " --> setInsert() : " + se.getMessage());
    		WAFLogger.error(se);
    		throw se;
    	}
	}
    
    
    
    private RowSet getIFSignInfo() throws Exception{
    	Search search = new SearchImpl();
        RowSet rowSet = new RowSetImpl();
        
        StringBuffer sqlstr = new StringBuffer();       
        
        
        try {
        	System.out.println("쓰레드 시작-----------------------");
        	sqlstr.append(" SELECT  SIGN_INTERFACE_ID											\n");
        	sqlstr.append("         ,SIGN_DECI_CLASS											\n");
        	sqlstr.append("         ,APPROVAL_DATE												\n");
        	sqlstr.append("         ,APPROVAL_SABUN												\n");
        	sqlstr.append("         ,APPROVAL_USER												\n");
        	sqlstr.append("         ,SIGN_TYPE													\n");
        	sqlstr.append("         ,KEY_COL1													\n");
        	sqlstr.append("         ,KEY_COL2													\n");
        	sqlstr.append("         ,KEY_COL3													\n");
        	sqlstr.append("         ,KEY_COL4													\n");
        	sqlstr.append("         ,KEY_COL5													\n");
        	sqlstr.append("         ,ATTR_1														\n");
        	sqlstr.append("         ,ATTR_2														\n");
        	sqlstr.append("         ,ATTR_3														\n");
        	sqlstr.append("         ,ATTR_4														\n");
        	sqlstr.append("         ,ATTR_5														\n");
        	sqlstr.append("         ,DOC_ID														\n");
        	sqlstr.append("         ,SIGN_CLASS_CD												\n");
        	sqlstr.append("         ,B.ACCT_ID													\n");
        	sqlstr.append("         ,B.PSOSO AS DEPT_CD											\n");
        	sqlstr.append("         ,GET_DEPT_NM(B.PSOSO) AS DEPT_NM							\n");
        	sqlstr.append("         ,B.DEPART_DEPT_CD AS ACC_DEPT_CD							\n");
        	sqlstr.append("         ,B.DEPART_DEPT_NM AS ACC_DEPT_NM							\n");
        	sqlstr.append(" FROM    SIGN001T A													\n");
        	sqlstr.append("         ,PUB0120T B													\n");
        	sqlstr.append(" WHERE   ATTR_6 = 0													\n");
        	sqlstr.append(" AND     SIGN_DECI_CLASS IN ('12','13','14','22','23','24','25')		\n");
        	sqlstr.append(" AND     A.APPROVAL_SABUN = B.USER_SABUN(+)							\n");

            search.setStatement(sqlstr.toString());
            rowSet = search.execute();            
            
            
            System.out.println("rowSet = "+rowSet.size());
            System.out.println("쓰레드 종료-----------------------");
        }
        catch(WAFSQLException se) {
            Logger.err.println("SQL : \n" + se.getStatement());
            Logger.err.println("PARAM : \n" + se.getParameter());
            throw se;
       }
        finally {
            if( rowSet == null ) rowSet = new RowSetImpl();
            return rowSet;
        }
    }
    
    private void setSign(RowSet rowSignInterface){
    	String driverName = "";
    	String str_doc_state = "";
    	Row row = new RowImpl();
    	
    	System.out.println("rowSignInterface.size() = "+rowSignInterface.size());
    	
        for ( int i = 0 ; i < rowSignInterface.size() ; i ++ ) {
       	 
        	row = rowSignInterface.getRow(i);
        	
            try {
                conn.begin();
                if( row.get("SIGN_CLASS_CD").equals("") ) {
                    Logger.err.println("SIGN_CLASS_CD 정보가 없습니다..\\n");
                    continue;
                }
                
                // 결재진행상태 값을 가져온다.
                str_doc_state = row.get("SIGN_DECI_CLASS");
                
                System.out.println("str_doc_state = "+str_doc_state);
                
                // 상태별 Call 처리
                try {
                    ValueObject signDoc = new ValueObject();
                    
                    signDoc.set("SIGN_INTERFACE_ID",	row.get("SIGN_INTERFACE_ID"));
                    signDoc.set("SIGN_DECI_CLASS",		row.get("SIGN_DECI_CLASS"));
                    signDoc.set("APPROVAL_DATE",		row.get("APPROVAL_DATE"));
                    signDoc.set("APPROVAL_SABUN",		row.get("APPROVAL_SABUN"));
                    signDoc.set("APPROVAL_USER",		row.get("APPROVAL_USER"));
                    signDoc.set("SIGN_TYPE",			row.get("SIGN_TYPE"));
                    signDoc.set("KEY_COL1",				row.get("KEY_COL1"));
                    signDoc.set("KEY_COL2",				row.get("KEY_COL2"));
                    signDoc.set("KEY_COL3",				row.get("KEY_COL3"));
                    signDoc.set("KEY_COL4",				row.get("KEY_COL4"));
                    signDoc.set("KEY_COL5",				row.get("KEY_COL5"));
                    signDoc.set("ATTR_1",				row.get("ATTR_1"));
                    signDoc.set("ATTR_2",				row.get("ATTR_2"));
                    signDoc.set("ATTR_3",				row.get("ATTR_3"));
                    signDoc.set("ATTR_4",				row.get("ATTR_4"));
                    signDoc.set("ATTR_5",				row.get("ATTR_5"));
                    signDoc.set("ACCT_TYPE",			row.get("ATTR_5"));
                    signDoc.set("DOC_ID",				row.get("DOC_ID"));
                    signDoc.set("SIGN_CLASS_CD",		row.get("SIGN_CLASS_CD"));
                    signDoc.set("ACCT_ID",				row.get("ACCT_ID"));
                    signDoc.set("DEPT_CD",				row.get("DEPT_CD"));
                    signDoc.set("DEPT_NM",				row.get("DEPT_NM"));
                    signDoc.set("ACC_DEPT_CD",			row.get("ACC_DEPT_CD"));
                    signDoc.set("ACC_DEPT_NM",			row.get("ACC_DEPT_NM"));
                    driverName = getSignDriverName(row.get("SIGN_CLASS_CD"));
                    
                    System.out.println("driverName = "+driverName);
                    
                    
                    if(!"".equals(driverName)){
                    	CommonSignInterface driver = CommonSignManager.createSignDriver(driverName);
                    	
                    	if ( str_doc_state.equals("12") || str_doc_state.equals("13") ){ // 1차 반려
                    		driver.doFirstRejectSign(conn.getConnection(), signDoc);
                    		
                    	} else if ( str_doc_state.equals("14") ){ // 1차 결제 완료
                    		driver.doFirstFinishSign(conn.getConnection(), signDoc);
                    		
                    	} else if ( str_doc_state.equals("22") || str_doc_state.equals("23") ){ // 2차 결제 반려
                    		//driver.doRejectSign(conn.getConnection(), signDoc);  2017.04.27 수신부서에서 반려,회수하는 경우는 GW내 결재진행이므로 주석처리. 
                    		
                    	} else if ( str_doc_state.equals("25")){ // 2차 결제 반려
                    		driver.doRejectSign(conn.getConnection(), signDoc);
                    		
                    	} else if ( str_doc_state.equals("24") ){  // 완료
                    		driver.doFinishSign(conn.getConnection(), signDoc);
                    	}
                    	// 전자구매의 결재 인터페이스 테이블의 정보를 수정한다.
                    	updateSign001t(conn.getConnection(), signDoc);
                    }
                    
                }
                catch(Exception e) {
                    Logger.err.println(driverName + ".doXxxxSign() 실행중 오류가 발생 했습니다.\\n" + e.getMessage());
                    conn.setRollback();
                    throw e;
                }
            }
            catch(Exception e) {
                Logger.err.println("doBiz() 실행중 오류가 발생 했습니다.\\n" + e.getMessage());
                conn.setRollback();
            }
            finally {
                conn.end();
            }
        }
    }
    
    /**
	 * SIGN001T 상태값을 업데이트해준다.
	 * @param connection
	 * @param valueObject
	 * @throws Exception
	 */
	public void updateSign001t(Connection connection, ValueObject vo) throws Exception {
		Persistent persistent = new PersistentImpl(connection);
		StringBuffer sqlstr = null;
		try {
			sqlstr = new StringBuffer();
			
			sqlstr.append(" UPDATE  SIGN001T SET            					\n");
			sqlstr.append("         ATTR_6				= 1						\n");
			sqlstr.append(" WHERE   SIGN_INTERFACE_ID	= ?    					\n");
			
			
			
			persistent.setStatement(sqlstr.toString());
			persistent.addParameter(vo.get("SIGN_INTERFACE_ID"));
			persistent.execute();
		}
		catch(Exception e) {
			
			WAFLogger.error(this.getClass().getName() + " --> updateSign001t() : " + e.getMessage());
			WAFLogger.error("SQL : " + sqlstr);
			WAFLogger.error(e);
			throw e;
		}
	}
    
    
    public String getSignDriverName(String signClassCd) throws Exception{
    	Search search = new SearchImpl();
        RowSet rowSet = new RowSetImpl();
        StringBuffer sqlStr = new StringBuffer();
        String rtnStr = "";
        try {
        	sqlStr.append(" SELECT	DETAILSORTNM AS DRIVER_NAME		\n");
            sqlStr.append(" FROM	EBID_COM911T					\n");
            sqlStr.append(" WHERE	BASECD = 'DRAFT'				\n");
            sqlStr.append(" AND		DETAILNM = ?					\n");
            search.setStatement(sqlStr.toString());
            search.addParameter(signClassCd);
            rowSet = search.execute();
            
            if( rowSet != null && rowSet.size() > 0 ) {
            	
            	rtnStr = rowSet.getRow(0).get("DRIVER_NAME");
            	
            }
            
        }catch(WAFSQLException se) {
        	Logger.err.println("SQL : \n" + se.getStatement());
            Logger.err.println("PARAM : \n" + se.getParameter());
            throw se;
        }finally {
            if( rowSet == null ) rowSet = new RowSetImpl();
            return rtnStr;
        }
    }
    
    
}