/**
 *
 * @(#)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 oracle.toplink.internal.ox.StrBuffer;
import kr.co.hsnc.common.base.WAFLogger;
import kr.co.hsnc.common.sql.RowSet;
import kr.co.hsnc.common.sql.WAFConnectionImpl;
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.ValueObject;
import kr.co.udapsoft.ebid.buyer.bid.purchase.biz.InterfacePurERPiU;

import com.udapsoft.waf.system.Biz;
import com.udapsoft.waf.system.HandlerStorage;

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

	public void doBiz() throws Exception {

		WAFLogger.debug("분계유형 처리");
		
		if(storage.compareEvent("")){
			
/*			//분계유형
			ValueObject contInfo = getContInfo(params);
            storage.addValueObject("ContInfo", contInfo);*/
		    
		}else if(storage.compareEvent("SAVE_GUA")){
			
			WAFLogger.debug("[PayItemBiz] SAVE_GUA");
			
			Persistent persistent_i = null;
			Persistent persistent_u = null;
			String sqlstr_i = "";
			String sqlstr_u = "";
	        StrBuffer sqlstr = new StrBuffer();
	        
			try {
			
				//String taxMethodCd				= params.get("chk_info");			//세금계산서발행방법
				//String taxDy					= params.get("date1");					//작성일자(증빙일자)
				//String taxChargNm				= params.get("userName");				//담당자명
				//String taxChargHp				= params.get("hp");						//담당자 핸드폰번호
				//String taxChargEmail			= params.get("eMail");					//담당자 이메일

				//분계유형
				String acctGb					= params.get("acct_gb");				//분계유형
				String guaGb					= params.get("proof_cd");				//
				String payGroup					= params.get("pay_group");				//
				String paymentTerms				= params.get("payment_terms_id");		//
				String userId					= storage.getUser().get("ACCT_ID");		//로그인사용자
				
				String pKey						= params.get("pKey");					//
				
				conn.begin();
				
				persistent_u = new PersistentImpl(super.conn.getConnection());
				sqlstr_u = " UPDATE PUR1100T	      														\n"
			              + " SET    --TAX_METHOD_CD    			= ?       , 					            \n"
			              + "        --TAX_DY 					= ?       , 					            \n"
			              + "        --TAX_CHARG_NM				= ?       , 					            \n"
			              + "        --TAX_CHARG_HP				= ?       , 					            \n"
			              + "        --TAX_CHARG_EMAIL			= ?       , 					            \n"
						  + "	     ACCT_GB      				= ?       , 					            \n"
						  + "        PAY_GROUP      			= ?       , 					            \n"
						  + "        GUA_GB      				= ?       , 					            \n"
						  + "        PAYMENT_TERMS      		= ?       , 					            \n"
						  + "        UPD_BY      				= ?       , 					            \n"
			              + "        UPD_DATE    				= sysdate									\n"
			              + " WHERE  PAYREQ_ID      			= ?        									\n" ;
				  
				persistent_u.setStatement(sqlstr_u);
					
				//persistent_u.addParameter(taxMethodCd);
				//persistent_u.addParameter(taxDy.replaceAll("-", ""));
				//persistent_u.addParameter(taxChargNm);
				//persistent_u.addParameter(taxChargHp);
				//persistent_u.addParameter(taxChargEmail);
				
				//분계유형
				persistent_u.addParameter(acctGb);
				persistent_u.addParameter(payGroup);
				persistent_u.addParameter(guaGb);
				persistent_u.addParameter(paymentTerms);
				persistent_u.addParameter(userId);				
				persistent_u.addParameter(pKey);
				persistent_u.execute();
				persistent_u.clearParameters();

				//2019.09.18 start 분개유형 PAYMENT 수정(ERP에서 전표생성시 계약데이터 기준으로 생성하기 때문에 계약마스터, ERP 계약테이블 업데이트) 
	        	sqlstr.append("UPDATE PUR2000T SET  	\n");
	        	sqlstr.append(" 	  PAY_GROUP  =  '"+ params.get("pay_group") +"' 	\n");	
	        	sqlstr.append(" 	 , PAYMENT_TERMS  =  '"+ params.get("payment_terms_id") +"' 	\n");	
	        	sqlstr.append("WHERE PUR_CONT_MOD_ID = ?						\n");
	        	persistent_u.setStatement(sqlstr.toString());  
	        	persistent_u.addParameter(params.get("subContModId"));
	        	persistent_u.execute();
	        	persistent_u.clearParameters();
	        	
	        	sqlstr.reset();
	        	
	        	sqlstr.append("UPDATE PUR1000T SET  	\n");
	        	sqlstr.append(" 	  PAY_GROUP  =  '"+ params.get("pay_group") +"' 	\n");	
	        	sqlstr.append(" 	 , PAYMENT_TERMS  =  '"+ params.get("payment_terms_id") +"' 	\n");	
	        	sqlstr.append("WHERE PUR_CONT_ID = ?						\n");
	        	persistent_u.setStatement(sqlstr.toString());  
	        	persistent_u.addParameter(params.get("purContId"));
	        	persistent_u.execute();
	        	persistent_u.clearParameters();

	        	sqlstr.reset();
	        	
	        	ValueObject erpVO = new ValueObject();
	        	erpVO.set("PAYMENT_TERMS", params.get("payment_terms_id"));
	        	erpVO.set("PUR_CONT_MOD_ID", params.get("subContModId"));
	        		        	
	            //2019.05.16 ERP계약자료 업데이트
	            WAFConnectionImpl erpConn = new WAFConnectionImpl();
				try {
					erpConn.setDataSource("jdbc/erpiu");
					erpConn.begin();
					InterfacePurERPiU.updateErpContPayment(erpConn.getConnection(),erpVO);
				}catch(Exception e) {
					super.conn.setRollback();
					erpConn.setRollback();
					throw e;
				}finally {
					erpConn.close();
				}
				//2019.09.18 end
				
				super.storage.setSuccess(true);
			}			
	        catch(Exception e) {
	            super.doException(e);
	            super.storage.setMessage(e.getMessage());
	            super.storage.setDetailMessage(e);
	            super.conn.setRollback();
	        	super.storage.setSuccess(false);
	        }
	        finally {
	        	super.conn.end();
	        }
		
		}else if(storage.compareEvent("SAVE_SEGUM")){
			
			WAFLogger.debug("[PayItemBiz] SAVE_SEGUM");
			
			Persistent persistent_i = null;
			Persistent persistent_u = null;
			String sqlstr_i = "";
			String sqlstr_u = "";

			try {
			
				String taxMethodCd				= params.get("chk_info");				//세금계산서발행방법
				String taxDy					= params.get("date1");					//작성일자(증빙일자)
				String taxChargNm				= params.get("userName");				//담당자명
				String taxChargHp				= params.get("hp");						//담당자 핸드폰번호
				String taxChargEmail			= params.get("eMail");					//담당자 이메일

				//분계유형
				//String acctGb					= params.get("acct_gb");				//분계유형
				//String guaGb					= params.get("proof_cd");				//
				//String payGroup					= params.get("pay_group");				//
				//String paymentTerms				= params.get("payment_terms");			//
				int userId						= params.getInt("USER_ID");		//로그인사용자
				
				String pKey				= params.get("pKey");			//
				
				conn.begin();
				
				persistent_u = new PersistentImpl(super.conn.getConnection());
				sqlstr_u = " UPDATE PUR1100T	      														\n"
			              + " SET    TAX_METHOD_CD    			= ?       , 					            \n"
			              + "        TAX_DY 					= ?       , 					            \n"
			              + "        TAX_CHARG_NM				= ?       , 					            \n"
			              + "        TAX_CHARG_HP				= ?       , 					            \n"
			              + "        TAX_CHARG_EMAIL			= ?       , 					            \n"
						  + "	     --ACCT_GB      				= ?       , 					        \n"
						  + "        --PAY_GROUP      			= ?       , 					            \n"
						  + "        --GUA_GB      				= ?       , 					            \n"
						  + "        --PAYMENT_TERMS      		= ?       , 					            \n"
						  + "        UPD_BY      				= ?       , 					            \n"
			              + "        UPD_DATE    				= sysdate									\n"
			              + " WHERE  PAYREQ_ID      			= ?        									\n" ;
				  
				persistent_u.setStatement(sqlstr_u);
					
				persistent_u.addParameter(taxMethodCd);
				persistent_u.addParameter(taxDy.replaceAll("-", ""));
				persistent_u.addParameter(taxChargNm);
				persistent_u.addParameter(taxChargHp);
				persistent_u.addParameter(taxChargEmail);
				
				//분계유형
				//persistent_u.addParameter(acctGb);
				//persistent_u.addParameter(payGroup);
				//persistent_u.addParameter(guaGb);
				//persistent_u.addParameter(paymentTerms);
				persistent_u.addParameter(userId);
				
				persistent_u.addParameter(pKey);
					
				WAFLogger.debug(sqlstr_u);
				WAFLogger.debug(persistent_u.getParameters());
					
				persistent_u.execute();
				persistent_u.clearParameters();

				super.storage.setSuccess(true);
			}			
	        catch(Exception e) {
	            super.doException(e);
	            super.storage.setMessage(e.getMessage());
	            super.storage.setDetailMessage(e);
	            super.conn.setRollback();
	        	super.storage.setSuccess(false);
	        }
	        finally {
	        	super.conn.end();
	        }
		
		}
	}
	
    /**
     *@param ValueObject
     *@return ValueObject
     *기   능 : 대금신청 상세(구매 중도금,잔금)
     *@author OK
     *@version 2014. 8. 07.
     *@since JDK1.7
     */
    public ValueObject getContInfo(ValueObject Params) {
        Search search = new SearchImpl();
        RowSet listRowSet = null;
        String sqlstr = "";
        ValueObject rowObject = null;
        
        try {

        	sqlstr += " SELECT 			  								  																						\n"
        			+ "     A.PUR_CONT_ID	                			  																						\n"
					+ "     ,B.ACCT_GB       																													\n"
					+ "     ,B.GUA_GB       																													\n"
					+ "     ,B.PAY_GROUP       																													\n"
					+ "     ,B.PAYMENT_TERMS       																												\n"
					+ "     ,B.PAY_ITEM ||'-'|| B.COST_CODE ||'-'|| B.COST_TYPE AS PAY_ITEM      																	\n"
					+ "     ,B.PAY_ITEM ||'-'|| B.COST_CODE ||'-'|| B.COST_TYPE ||'(' || F_GET_PAY_ITEM_EST_DESC(B.PAY_ITEM,B.COST_CODE,B.COST_TYPE,A.DEPT_CD)||')' AS PAY_ITEM_NM	      										\n"
					+ "     ,(SELECT AC_UNIT_CD FROM ACZ10100V Z WHERE  Z.DEPT_CD = A.DEPT_CD) AS  AC_UNIT_CD		      										\n"
        			+ " FROM PUR1000T A, 																														\n"
        			+ "      (SELECT B1.*																														\n"
        			+ "      FROM PUR1100T B1,																													\n"
        			+ "      (SELECT PUR_CONT_ID, MAX(DEPOSIT_SEQ) AS MAX_DEPOSIT_SEQ FROM PUR1100T GROUP BY PUR_CONT_ID) B2									\n"
        			+ "      WHERE 1=1																															\n"
        			+ "      AND B1.PUR_CONT_ID = B2.PUR_CONT_ID																								\n"
        			+ "      AND B1.DEPOSIT_SEQ = B2.MAX_DEPOSIT_SEQ																							\n"
        			+ "      ) B, 																																\n"
        			+ "      PUR1030T C																															\n"
        			+ " WHERE 1=1																																\n"
        			+ " AND A.PUR_CONT_ID = B.PUR_CONT_ID																										\n"
        			//+ " AND A.PUR_CONT_ID = C.PUR_CONT_ID																										\n";
        			+ " AND A.PUR_CONT_ID = C.PUR_CONT_ID(+)																									\n";

        	sqlstr += " AND A.PUR_CONT_ID = '"+ params.get("purContId") +"'																						\n";
        	
            search.setStatement(sqlstr);
            WAFLogger.debug(sqlstr);
            listRowSet = search.execute();
            rowObject = RowSetUtility.getValueObject(listRowSet.getRow(0));
            
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> getPrePayment() : " + e.getMessage());
            WAFLogger.error("SQL : " + search.getStatement());
            WAFLogger.error(e);
            return null;
        }
        finally {

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