/**
 * @(#)file    PaySignFormBiz.java
 * @(#)author  OK
 * @(#)version 1.0
 * @(#)date    2014.09.04
 * @(#)since   JDK 1.6.24
 *
 * Copyright (c) www.udapsoft.co.kr, Inc.
 */
package kr.co.udapsoft.ebid.buyer.common.slipSign.biz;

import java.sql.Connection;

import kr.co.hsnc.common.base.WAFLogger;
import kr.co.hsnc.common.config.WAFConfig;
import kr.co.hsnc.common.sql.RowSet;
import kr.co.hsnc.common.sql.RowSetImpl;
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;
import kr.co.udapsoft.common.util.NetUtil;

import com.udapsoft.modular.core.util.StringUtils;
import com.udapsoft.waf.system.Biz;
import com.udapsoft.waf.system.HandlerStorage;

public class AdvSignFormBiz extends Biz {

	public AdvSignFormBiz(HandlerStorage storage) {
        super(storage);
    }

    public void doBiz() throws Exception {

        boolean isSuccess = procSign(storage.getParams(), storage.getUser());
        storage.setSuccess(isSuccess);
        
    }

    private boolean procSign(ValueObject params, ValueObject user) {

        String signClassCd = params.get("SIGN_CLASS_CD");
        String slip_dept = params.get("slip_dept");
        String slip_dt = params.get("slip_dt");
        String acct_type = params.get("acct_type");

        String if_id = getInterFacePk();

/*        
		String tmp_slip_payreq = params.get("tmpslip_payreq"); //ID
        String tmp_slip_deposit_cd = params.get("tmpslip_deposit_cd"); //지급차수
        String tmp_slip_deposit_seq = params.get("tmpslip_deposit_seq"); //지급구분
*/        
		String tmpslip_prepayId = params.get("tmpslip_prepayId"); 	//
        String tmpslip_subContModId = params.get("tmpslip_subContModId"); //
        
        if( "".equals(signClassCd) ) {
            storage.setMessage("'SIGN_CLASS_CD' 정보가 없습니다.");
            return false;
        }

        // 결재문서 생성
        String uri = params.get("uri");
        
        if( "".equals(uri) ) {
            storage.setMessage("[" + signClassCd + "]에 해당하는 URI 정보가 없습니다.");
            return false;
        }
        
        
        //String dupCnt = getDupCnt(signClassCd, tmp_slip_payreq, tmp_slip_deposit_cd, tmp_slip_deposit_seq);
        String dupCnt = getDupCnt1(signClassCd, tmpslip_prepayId, tmpslip_subContModId);
        
        if( !"0".equals(dupCnt) ){
        	storage.setMessage("이미 결재중인 대금입니다.");
            return false;
        }
        
        
        uri = StringUtils.replace(uri,"^","&"); // 

        //String url = getServerDomain();
        String url = WAFConfig.get("waf.ServerURL");
        if("".equals(url)) url = storage.getCurrentDoamin();
        
        if( url.substring(url.length()-1).equals("/") )
            url = url.substring(0, url.length()-1);
        url += uri;
        

        String body = NetUtil.getHttpPage(url);
        

        try {
            conn.begin();
            
            /*try {
            	ValueObject vo = new ValueObject();
            	vo.set("CRE_BY",	user.get("ACCT_ID"));
            	vo.set("PAYREQ_ID",	tmp_slip_no);
            	
            	updatePaySign(conn.getConnection(), vo);
                
            }catch(Exception e) {
            	WAFLogger.debug(e);
                storage.setMessage("결재 인터페이스 데이터 생성중 오류가 발생 했습니다.\\n" + e.getMessage());
                throw e;
            }*/
            
            try {
            	ValueObject vo = new ValueObject();
            	vo.set("SIGN_INTERFACE_ID",	if_id);
            	vo.set("SIGN_CLASS_CD", signClassCd);
            	vo.set("KEY_COL1", tmpslip_subContModId);
            	vo.set("KEY_COL2", tmpslip_prepayId);
            	vo.set("KEY_COL3", slip_dept);
            	vo.set("KEY_COL4", slip_dt);
            	vo.set("CRE_BY", user.get("ACCT_ID"));
            	vo.set("ACCT_TYPE", acct_type);
            	
                insertInterfaceTable(conn.getConnection(), vo);
                
            }catch(Exception e) {
            	WAFLogger.error(e);
                storage.setMessage("결재 인터페이스 데이터 생성중 오류가 발생 했습니다.\\n" + e.getMessage());
                throw e;
            }
            
        }
        catch(Exception e) {
            conn.setRollback();
            return false;
        }
        finally{
            conn.end();
        }
        
        // 결재정보 세팅
        ValueObject signInfo = new ValueObject();
        signInfo.set("ORGID",  "EBID");
        signInfo.set("ORGKEY", if_id);
        signInfo.set("COMID",  "TEC");
        signInfo.set("FORMID", signClassCd);
        signInfo.set("BODY",   body);
        signInfo.set("EMPNO",  storage.getUser().get("USER_SABUN"));
        
        storage.addValueObject("SignInfo", signInfo);

        return true;
    }
    
    /**
     * 2011 09 30 인터페이스용 시퀀스를 가저온다
     */
    private String getInterFacePk() {
    	
    	Search search = new SearchImpl();
    	RowSet rowSet = new RowSetImpl();
    	StringBuffer sqlstr = new StringBuffer();
    	
    	String rtnStr = "";
    	
    	try {
    		
    		sqlstr.append(" SELECT	SLIP_INTERFACE_S.NEXTVAL AS IF_ID		\n ");
    		sqlstr.append(" FROM	DUAL  										\n ");
    		
    		
    		search.setStatement(sqlstr);            
    		rowSet = search.execute();
    		
    		if(rowSet != null && rowSet.size() > 0 ) {
    			rtnStr = rowSet.getRow(0).get("IF_ID");
    		}
    		
    	}
    	catch (Exception e) {
            super.doException(e);
            this.storage.setSuccess(false);
            this.storage.setMessage(e.getMessage());
            storage.setDetailMessage(e);
    	}
    	
    	return rtnStr;
    }
    
    /**
     * 
     */
    private String getDupCnt1(String signClassCd, String tmpslip_prepayId, String tmpslip_subContModId) {
    	
    	Search search = new SearchImpl(); 
    	RowSet rowSet = new RowSetImpl();
    	StringBuffer sqlstr = new StringBuffer();
    	
    	ValueObject user = storage.getUser();
    	
    	String rtnStr = "";
    	
    	try {
    		
    		sqlstr.append(" SELECT  COUNT(*) AS CNT                                                                   	\n");
    		sqlstr.append(" FROM    SIGN001T                                                                     	\n");
    		sqlstr.append("	WHERE SIGN_CLASS_CD = '"+signClassCd+"'														\n");
    		sqlstr.append("	AND KEY_COL1 = '"+tmpslip_subContModId+"'	 												\n");
    		sqlstr.append("	AND KEY_COL2 = '"+tmpslip_prepayId+"' 														\n");
    		sqlstr.append("	AND ATTR_6  = '0'  																			\n");
    		sqlstr.append("	AND CRE_BY = '"+user.get("acct_id")+"'														\n");
    		
    		WAFLogger.debug(sqlstr.toString());
    		search.setStatement(sqlstr);
    		rowSet = search.execute();
    		if(rowSet != null && rowSet.size() > 0 ) {
    			rtnStr = rowSet.getRow(0).get("CNT");
    		}
    		
    	}
    	catch (Exception e) {
            super.doException(e);
            this.storage.setSuccess(false);
            this.storage.setMessage(e.getMessage());
            storage.setDetailMessage(e);
    	}
    	
    	return rtnStr;
    }
    
    /**
     * 
     */
    private String getDupCnt(String signClassCd, String tmp_slip_payreq, String tmp_slip_deposit_cd, String tmp_slip_deposit_seq) {
    	
    	Search search = new SearchImpl();
    	RowSet rowSet = new RowSetImpl();
    	StringBuffer sqlstr = new StringBuffer();
    	
    	ValueObject user = storage.getUser();
    	
    	String rtnStr = "";
    	
    	try {
    		
    		sqlstr.append(" SELECT  COUNT(*) AS CNT                                                                   	\n");
    		sqlstr.append(" FROM    SIGN001T                                                                          	\n");
    		sqlstr.append("	WHERE SIGN_CLASS_CD = '"+signClassCd+"'														\n");
    		sqlstr.append("	AND KEY_COL1 = "+tmp_slip_payreq+"	 														\n");
    		sqlstr.append("	AND KEY_COL2 = "+tmp_slip_deposit_cd+" 														\n");
    		sqlstr.append("	AND KEY_COL3 = "+tmp_slip_deposit_seq+"														\n");
    		sqlstr.append("	AND NVL(ATTR_6, '100') = '100'																\n");
    		sqlstr.append("	AND CRE_BY NOT IN ("+user.get("acct_id")+")													\n");
    		
    		search.setStatement(sqlstr);
    		rowSet = search.execute();
    		
    		if(rowSet != null && rowSet.size() > 0 ) {
    			rtnStr = rowSet.getRow(0).get("CNT");
    		}
    		
    	}
    	catch (Exception e) {
            super.doException(e);
            this.storage.setSuccess(false);
            this.storage.setMessage(e.getMessage());
            storage.setDetailMessage(e);
    	}
    	
    	return rtnStr;
    }
    
    /**
	 * updatePaySign 결재상태값을 바꾼다 테이블에 값을 저장한다
	 * @param connection
	 * @param valueObject
	 * @throws Exception
	 */
	public void updatePaySign(Connection connection, ValueObject vo) throws Exception {
		
		Persistent persistent = new PersistentImpl(connection);
		StringBuffer sqlstr = null;
		try {
			sqlstr = new StringBuffer();
			
			sqlstr.append(" UPDATE  PUR1100T SET				\n");
			sqlstr.append("         REQ_STATUS	= 2				\n");
			sqlstr.append("        	,UPD_BY	= ?					\n");
			sqlstr.append("        	,UPD_DATE	= SYSDATE		\n");
			sqlstr.append(" WHERE	PAYREQ_ID = ?				\n");
			
			persistent.setStatement(sqlstr.toString());
			persistent.addParameter(vo.get("CRE_BY"));
			persistent.addParameter(vo.get("PAYREQ_ID"));
			
			WAFLogger.debug(vo.get("PAYREQ_ID"));
			WAFLogger.debug(sqlstr);
			
			persistent.execute();
			
		}
		catch(Exception e) {
			
			WAFLogger.error(this.getClass().getName() + " --> insertInterfaceTable() : " + e.getMessage());
			WAFLogger.error("SQL : " + sqlstr);
			WAFLogger.error(e);
			throw e;
		}
	}
    
	
	/**
	 * insertInterfaceTable 인터페이스 테이블에 값을 저장한다
	 * @param connection
	 * @param valueObject
	 * @throws Exception
	 */
	public void insertInterfaceTable(Connection connection, ValueObject vo) throws Exception {
		
		Persistent persistent = new PersistentImpl(connection);
		StringBuffer sqlstr = null;
		try {
			sqlstr = new StringBuffer();
			
			sqlstr.append(" INSERT INTO  SIGN001T (		\n");
			sqlstr.append("         SIGN_INTERFACE_ID			\n");
			sqlstr.append("         ,SIGN_CLASS_CD				\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("         ,SIGN_DECI_DATE				\n");
			sqlstr.append("         ,SIGN_TYPE					\n");
			sqlstr.append("         ,ATTR_5						\n");
			sqlstr.append("         ,CRE_BY						\n");
			sqlstr.append("         ,CRE_DATE					\n");
			sqlstr.append("         ) VALUES (					\n");
			sqlstr.append("          ?							\n");
			sqlstr.append("         ,?							\n");
			sqlstr.append("         ,?							\n");
			sqlstr.append("         ,?							\n");
			sqlstr.append("         ,?							\n");
			sqlstr.append("         ,?							\n");
			sqlstr.append("         ,SLIP_NO_S.NEXTVAL			\n");
			sqlstr.append("         ,SYSDATE					\n");
			sqlstr.append("         ,'1'						\n");
			sqlstr.append("         ,?							\n");
			sqlstr.append("         ,?							\n");
			sqlstr.append("         ,SYSDATE					\n");
			sqlstr.append("         )							\n");
			
			persistent.setStatement(sqlstr.toString());
			persistent.addParameter(vo.get("SIGN_INTERFACE_ID"));
			persistent.addParameter(vo.get("SIGN_CLASS_CD"));
			persistent.addParameter(vo.get("KEY_COL1"));
			persistent.addParameter(vo.get("KEY_COL2"));
			persistent.addParameter(vo.get("KEY_COL3"));
			persistent.addParameter(vo.get("KEY_COL4"));
			persistent.addParameter(vo.get("ACCT_TYPE"));
			persistent.addParameter(vo.get("CRE_BY"));
			
			persistent.execute();
			
		}
		catch(Exception e) {
			
			WAFLogger.error(this.getClass().getName() + " --> insertInterfaceTable() : " + e.getMessage());
			WAFLogger.error("SQL : " + sqlstr);
			WAFLogger.error(e);
			throw e;
		}
	}

	/**
     * Server에 도메인을 리턴한다.
     * ex> http://www.sample.co.kr:80/
     * ex> http://www.sample.co.kr:80/contextName/
     * @return
     */
    private String getServerDomain() {
        return super.storage.request.getScheme() + "://" + 
               super.storage.request.getServerName() + ":" + 
               super.storage.request.getServerPort() + "/" +
               super.storage.request.getContextPath();
    }
    
}
