/**
 * @(#)file    ContIntBiz.java
 * @(#)author  Kim Myung Ho
 * @(#)version 1.0
 * @(#)date    2014-07-15
 * @(#)since   JDK 1.4.2
 */
package kr.co.udapsoft.ebid.supplier.portal.common.guar.biz;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;

import oracle.toplink.internal.ox.StrBuffer;
import kr.co.hsnc.common.base.WAFLogger;
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.ValueObject;
import kr.co.udapsoft.common.code.CommCodeManager;
import kr.co.udapsoft.ebid.buyer.common.file.FileManager;
import kr.co.udapsoft.ebid.buyer.sycs.user.biz.UserCommon;

import com.udapsoft.modular.web.ibsheet7.IBSheet7Factory;
import com.udapsoft.modular.web.ibsheet7.util.IBSheet7Utils;
import com.udapsoft.waf.common.ui.InitCombo;
import com.udapsoft.waf.common.util.StringUtils;
import com.udapsoft.waf.system.Biz;
import com.udapsoft.waf.system.HandlerStorage;

import kr.co.hsnc.common.config.WAFConfig;




//전문건설 전송시 필요
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;

public class GuarPurErpBiz extends Biz {

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

	public void doBiz() throws Exception {
        ValueObject user = new ValueObject();
		boolean success = false;
		
		if(storage.compareEvent("")){
			ValueObject decryptParam = getDecryptParam(params);
			
			String validYn = "N";
			try {
        		long openTime = Long.parseLong(decryptParam.get("OPEN_TIME"));
        		long currTime = Long.parseLong(decryptParam.get("CURR_TIME"));
        		
        		//ERP에서 팝업을 띄운시간을 체크하여 유효성체크 (10분)
        		if( currTime - openTime < 10 && currTime - openTime >= 0 ) {
        			validYn = "Y";
        		}
        		
        	}catch (Exception e) {
        		//e.printStackTrace();
			}
			
			params.set("purContModId", decryptParam.get("PUR_CONT_MOD_ID"));
			if( decryptParam.get("PUR_CONT_MOD_ID").equals("") ) {
				validYn = "N";
			}
			params.set("warrGubun", "5");
			params.set("warrSeq", getWarrSeq(decryptParam.get("PUR_CONT_MOD_ID")));
			params.set("openTime", decryptParam.get("OPEN_TIME"));
			params.set("validYn", validYn);
			
			if( "Y".equals(validYn) ) {
				user = getWarrContValueObject(params);
				user.set("OldGuarOrganCode", getOldGuarInfo(user.get("PUR_CONT_ID")));
				storage.addValueObject("attFileList", getfilelist("GUARCONT_PUR_5_"+params.get("warrSeq"), params.get("purContModId"),"fileRow"));
			}else {
				storage.addValueObject("attFileList", new ValueObject());
			}
            
            storage.addValueObject("WarrContInfo", user);
            //첨부된 저장 파일
  
		}else if(storage.compareEvent("FORM_SAVE")){
			
			success = margeGuarInfoData(super.conn.getConnection(), params);	//보증정보 저장
			if(params.get("guarOnOffYn").equals("Y")){	//온라인 보증일경우
				success = makeGuarData(super.conn.getConnection(), params);	//보증 데이터 생성
				
				if(!success){	//전송 실패일 경우 상태값을 신청 대기 상태로 놓는다.
					params.set("gStatus", "04");
					WarrStatusUp(super.conn.getConnection(), params);
				}
			}
			super.storage.setSuccess(success);
			
		}else if(storage.compareEvent("FORM_DELETE")){
			
			if(params.get("guarOnOffYn").equals("Y")){	//온라인 보증일경우
				success = sendGuarData(super.conn.getConnection(), params, "CAN");	//온라인 보증 취소
				if(success){	//전송 성공일 경우 삭제처리
					success = deleteGuarInfoData(super.conn.getConnection(), params);	//보증정보 삭제
				}	
			}else{
				success = deleteGuarInfoData(super.conn.getConnection(), params);	//보증정보 삭제
			}
			super.storage.setSuccess(success);
		}
	         
	}
    /**
     * 첨부 파일
	 * @param 
	 * @param 
	 * @return ValueObject
	 */
	private ValueObject getfilelist(String filegb,String id,String returnid){
		ValueObject vo = new ValueObject();
		RowSet rowSet = FileManager.getFileList(filegb, id);
		String str="";
	        for(int i=0;i<rowSet.size();i++){
	        	Row row=rowSet.getRow(i);
	        	str += (i+1)+" : "+row.get("FILE_NAME")+" ("+ row.get("FILE_SIZE")+")";
	        	if(i+1!=rowSet.size()){
	        		str +="\r\n";
	        	}
	        }
	        vo.set(returnid, str);
		return vo;
	}
	
	/**
	 * 계약 상세 정보
	 * @param Params
	 * @return
	 */
	private ValueObject getDecryptParam(ValueObject param) {

		Search search = new SearchImpl();
        RowSet rowSet = new RowSetImpl();
        ValueObject valueobject = null;
        StrBuffer sqlstr = new StrBuffer();
        try{
        	sqlstr.append("SELECT	F_DECRYPT(?) AS PUR_CONT_MOD_ID						\n");
        	sqlstr.append("			,F_DECRYPT(?) AS OPEN_TIME							\n");
        	sqlstr.append("			,TO_CHAR(SYSDATE,'YYYYMMDDHH24MI')  AS CURR_TIME	\n");
        	sqlstr.append("FROM	DUAL													\n");
        	
			search.setStatement(sqlstr.toString());
			search.addParameter(params.get("purContModId"));
			search.addParameter(params.get("openTime"));
			
            rowSet = search.execute();
            
            if( rowSet != null && rowSet.size() > 0 ){
            	valueobject = RowSetUtility.getValueObject(rowSet.getRow(0));
            }
            	
        }catch(WAFSQLException se) {
        	super.doException(se);
            this.storage.setSuccess(false);
            this.storage.setMessage(se.getMessage());
            storage.setDetailMessage(se);
        }finally {
        	if( valueobject == null ) valueobject = new ValueObject();
            return valueobject;
        }
	}
	
	private ValueObject getWarrContValueObject(ValueObject param) {
		
		Search search = new SearchImpl();
		RowSet rowSet = new RowSetImpl();
		ValueObject valueobject = null;
		//   String sqlstr = "";
		StrBuffer sqlstr = new StrBuffer();
		try{
				
			sqlstr.append("  	SELECT 	\n");
			sqlstr.append("  	  A.PUR_CONT_MOD_ID	\n");
			sqlstr.append("  	  , NVL(B.GRTREQNO, 'M_' || A.PUR_CONT_MOD_ID ||'_'|| A.PUR_CONT_ID) AS GRTREQNO	\n");
			sqlstr.append("  	  , A.PUR_CONT_ID	\n");
			sqlstr.append("  	  , A.MOD_NO	\n");
			sqlstr.append("  	  , NVL(B.CAUSECODE, '10') AS CAUSECODE	\n");
			sqlstr.append("	      , F_GET_CODE_NAME('CAUSECODE',NVL(B.CAUSECODE, '10')) AS CAUSECODE_NM	\n");        	
			sqlstr.append("  	  , NVL(B.GUAR_STATUS, '02') AS GUAR_STATUS	\n");
			sqlstr.append("  	  , A.ORD_AMT	\n");
			sqlstr.append("  	  , A.CON_GUAR_AMT_RATE	\n");
			sqlstr.append("  	  , A.CON_GUAR_AMT	\n");
			sqlstr.append("  	  , NVL(B.WARR_WAMT, A.DEF_GUAR_AMT) AS WARR_WAMT	\n");
			sqlstr.append("  	  , NVL(B.WARR_WRATE, A.DEF_GUAR_AMT_RATE) AS WARR_WRATE	\n");
			sqlstr.append("  	  , NVL(B.GUAR_ONOFF_YN, 'N') AS GUAR_ONOFF_YN	\n");
			sqlstr.append("  	  , B.GUAR_ORGAN_CODE	\n");
			sqlstr.append("  	  , B.WARR_GOFFICE	\n");
			sqlstr.append("  	  , B.WARR_WGNO	\n");
			sqlstr.append("  	  , NVL(B.WARR_SDATE, TO_CHAR(A.ORD_START_DATE, 'YYYY-MM-DD')) AS WARR_SDATE	\n");
			sqlstr.append("  	  , NVL(B.WARR_EDATE, TO_CHAR(A.ORD_END_DATE, 'YYYY-MM-DD')) AS WARR_EDATE	\n");
			sqlstr.append("  	  , B.PAPERDATE	\n");
			sqlstr.append("	      , F_GET_CODE_NAME('GAUR_KIND','5') AS WARR_GUBUN_NM	\n");
			sqlstr.append("  	  , DECODE(WARR_GUBUN, '1', '002', '5', '003', '3', '004', '4', '005', '2', '006') AS GRTTYPE	\n");
			sqlstr.append("	      , F_GET_CODE_NAME('GUAR_STATUS', B.GUAR_STATUS) AS GUAR_STATUS_NM	\n");
			sqlstr.append("  	  , B.REJECTMENT	\n");
			sqlstr.append("  	  , A.CURRENCY_GB	\n");
			sqlstr.append("  	  , '' AS CONTSTATUS	\n");
			sqlstr.append("  	FROM PUR2000T A, CONT_PUR_WARR B	\n");
			sqlstr.append("  	WHERE A.PUR_CONT_MOD_ID = B.PUR_CONT_MOD_ID(+)	\n");
			sqlstr.append("  	    AND A.PUR_CONT_MOD_ID = '"+param.get("purContModId")+"'	\n");
			sqlstr.append("  	    AND B.WARR_GUBUN(+) = '5'	\n");
			sqlstr.append("  	    AND B.WARR_SEQ(+) = '"+param.get("warrSeq")+"'	\n");
			search.setStatement(sqlstr.toString());
			rowSet = search.execute();
			
			if( rowSet != null && rowSet.size() > 0 ){
				valueobject = RowSetUtility.getValueObject(rowSet.getRow(0));
			}
			
		}
		catch(WAFSQLException se) {
			super.doException(se);
			this.storage.setSuccess(false);
			this.storage.setMessage(se.getMessage());
			storage.setDetailMessage(se);
			//System.out.println(sqlstr.toString());
			//System.out.println("WAFSQLException : " + se.getMessage());
		}
		finally {
			
			if( valueobject == null ) valueobject = new ValueObject();
			//System.out.println("### valueobject size : " + valueobject.size());
			return valueobject;
		}
	}

	/**
     * 서명 완료
	 * @param connection
	 * @param valueObject
	 * @throws Exception
	 */
	public boolean ContStatusUp(Connection connection, ValueObject valueObject) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        StrBuffer sqlstr = new StrBuffer();
        try {
        	sqlstr.append("UPDATE PUR2000T SET  	\n");
        	sqlstr.append(" STATUS_CD = ?					\n");
        	sqlstr.append("WHERE PUR_CONT_MOD_ID = ?						\n");
            persistent.setStatement(sqlstr.toString());
            persistent.addParameter(valueObject.get("pStatusCD"));
            persistent.addParameter(valueObject.get("PUR_CONT_MOD_ID"));
            persistent.execute();

            return true;
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> updUser() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            //System.out.println("Exception : " + e.getMessage());
            throw e;
        }
    }	
	
	/**
     * 보증 정보 버장
	 * @param connection
	 * @param valueObject
	 * @throws Exception
	 */
	public boolean margeGuarInfoData(Connection connection, ValueObject valueObject) throws Exception {
		//System.out.println("valueObject : " + valueObject);
        Persistent persistent = new PersistentImpl(connection);
        StrBuffer sqlstr = new StrBuffer();
        try {
        	sqlstr.append("MERGE INTO CONT_PUR_WARR T1 USING (									\n");
        	sqlstr.append("          SELECT ? AS	PUR_CONT_MOD_ID	\n");
        	sqlstr.append("                ,? AS	WARR_GUBUN	\n");
        	sqlstr.append("                ,? AS	WARR_SEQ	\n");
        	sqlstr.append("                ,? AS	PUR_CONT_ID	\n");
        	sqlstr.append("                ,? AS	MOD_NO	\n");
        	sqlstr.append("                ,? AS	VIEW_DIV	\n");
        	sqlstr.append("                ,? AS	WARR_WAMT	\n");
        	sqlstr.append("                ,? AS	WARR_WRATE	\n");
        	sqlstr.append("                ,? AS	WARR_KAMT1	\n");
        	sqlstr.append("                ,? AS	WARR_KAMT2	\n");
        	sqlstr.append("                ,? AS	WARR_SDATE	\n");
        	sqlstr.append("                ,? AS	WARR_EDATE	\n");
        	sqlstr.append("                ,? AS	WARR_WGNO	\n");
        	sqlstr.append("                ,? AS	WARR_GOFFICE	\n");
        	sqlstr.append("                ,? AS	GUAR_ONOFF_YN	\n");
        	sqlstr.append("                ,? AS	GUAR_ORGAN_CODE	\n");
        	sqlstr.append("                ,? AS	CAUSECODE	\n");
        	sqlstr.append("                ,? AS	PAPERDATE	\n");
        	sqlstr.append("                ,? AS	GRTREQNO	\n");
        	sqlstr.append("                ,? AS	GUAR_STATUS	\n");
        	sqlstr.append("                ,? AS	PAYREQ_ID	\n");
        	sqlstr.append("		        FROM DUAL													\n");
        	sqlstr.append("		    ) T ON (T.PUR_CONT_MOD_ID = T1.PUR_CONT_MOD_ID AND T.WARR_GUBUN = T1.WARR_GUBUN AND T.WARR_SEQ = T1.WARR_SEQ)	\n");
        	sqlstr.append("		WHEN MATCHED THEN													\n");
        	sqlstr.append("		    UPDATE SET 				\n");
//        	sqlstr.append("                  T1.WARR_GUBUN	 =	T.WARR_GUBUN	\n");
//        	sqlstr.append("                , T1.WARR_SEQ	 =	T.WARR_SEQ	\n");
        	sqlstr.append("                  T1.VIEW_DIV	 =	T.VIEW_DIV	\n");
        	sqlstr.append("                , T1.WARR_WAMT	 =	T.WARR_WAMT	\n");
        	sqlstr.append("                , T1.WARR_WRATE	 =	T.WARR_WRATE	\n");
        	sqlstr.append("                , T1.WARR_KAMT1	 =	T.WARR_KAMT1	\n");
        	sqlstr.append("                , T1.WARR_KAMT2	 =	T.WARR_KAMT2	\n");
        	sqlstr.append("                , T1.WARR_SDATE	 =	T.WARR_SDATE	\n");
        	sqlstr.append("                , T1.WARR_EDATE	 =	T.WARR_EDATE	\n");
        	sqlstr.append("                , T1.WARR_WGNO	 =	T.WARR_WGNO	\n");
        	sqlstr.append("                , T1.WARR_GOFFICE	 =	T.WARR_GOFFICE	\n");
        	sqlstr.append("                , T1.GUAR_ONOFF_YN	 =	T.GUAR_ONOFF_YN	\n");
        	sqlstr.append("                , T1.GUAR_ORGAN_CODE	 =	T.GUAR_ORGAN_CODE	\n");
        	sqlstr.append("                , T1.CAUSECODE	 =	T.CAUSECODE	\n");
        	sqlstr.append("                , T1.PAPERDATE	 =	T.PAPERDATE	\n");
        	sqlstr.append("                , T1.GRTREQNO	 =	T.GRTREQNO	\n");
        	sqlstr.append("                , T1.GUAR_STATUS	 =	T.GUAR_STATUS	\n");
        	sqlstr.append("                , T1.PAYREQ_ID	 =	T.PAYREQ_ID	\n");
        	sqlstr.append("		WHEN NOT MATCHED THEN											\n");
        	sqlstr.append("			INSERT (T1.PUR_CONT_MOD_ID, T1.WARR_GUBUN, T1.WARR_SEQ, T1.PUR_CONT_ID, T1.MOD_NO, T1.VIEW_DIV, T1.WARR_WAMT, T1.WARR_WRATE, T1.WARR_KAMT1, T1.WARR_KAMT2, T1.WARR_SDATE, T1.WARR_EDATE, T1.WARR_WGNO, T1.WARR_GOFFICE, T1.GUAR_ONOFF_YN, T1.GUAR_ORGAN_CODE, T1.CAUSECODE, T1.PAPERDATE, T1.GRTREQNO, T1.GUAR_STATUS, T1.WARR_INDAY, T1.WARR_UPDAY, T1.PAYREQ_ID)	\n");
        	sqlstr.append("			VALUES (T.PUR_CONT_MOD_ID, T.WARR_GUBUN, T.WARR_SEQ, T.PUR_CONT_ID, T.MOD_NO, T.VIEW_DIV, T.WARR_WAMT, T.WARR_WRATE, T.WARR_KAMT1, T.WARR_KAMT2, T.WARR_SDATE, T.WARR_EDATE, T.WARR_WGNO, T.WARR_GOFFICE, T.GUAR_ONOFF_YN, T.GUAR_ORGAN_CODE, T.CAUSECODE, T.PAPERDATE, T.GRTREQNO, T.GUAR_STATUS, SYSDATE, SYSDATE, T.PAYREQ_ID)	\n");
            persistent.setStatement(sqlstr.toString());
            persistent.addParameter(valueObject.get("purContModId"));
            persistent.addParameter("5");
            persistent.addParameter(valueObject.get("WARRSEQ"));
            persistent.addParameter(valueObject.get("PUR_CONT_ID"));
            persistent.addParameter(valueObject.get("MOD_NO"));
            persistent.addParameter(valueObject.get("VIEWDIV"));
            persistent.addParameter(StringUtils.replace(valueObject.get("WARRWAMT"),",",""));
            persistent.addParameter(valueObject.get("WARRWRATE"));
            persistent.addParameter(StringUtils.replace(valueObject.get("WARRKAMT1"),",",""));
            persistent.addParameter(StringUtils.replace(valueObject.get("WARRKAMT2"),",",""));
            persistent.addParameter(StringUtils.replace(valueObject.get("DATESTART"),"-",""));
            persistent.addParameter(StringUtils.replace(valueObject.get("DATEEND"),"-",""));
            persistent.addParameter(valueObject.get("WARRWGNO"));
            persistent.addParameter(valueObject.get("WARRGOFFICEETC"));
            persistent.addParameter(valueObject.get("guarOnOffYn"));
            persistent.addParameter(valueObject.get("guarOrganCode"));
            persistent.addParameter(valueObject.get("CAUSECODE"));
            persistent.addParameter(StringUtils.replace(valueObject.get("PAPERDATE"),"-",""));
            persistent.addParameter(valueObject.get("GRTREQNO"));
            persistent.addParameter(valueObject.get("GUARSTATUS"));
            persistent.addParameter(valueObject.get("prepayId"));

//            persistent.addParameter(StringUtils.replace(valueObject.get("O_HP"),"-",""));
            
            persistent.execute();


            return true;
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> updUser() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            //System.out.println("Exception : " + e.getMessage());
            throw e;
        }
    }	
	/**
     * 보증 데이터 생성
	 * @param connection
	 * @param valueObject
	 * @throws Exception
	 */
	public boolean makeGuarData(Connection connection, ValueObject valueObject) throws Exception {

        Persistent persistent = new PersistentImpl(connection);

        CallableStatement cs = null;
        ValueObject rtnVo = new ValueObject();
        String sqlStr = "";
        try {
        	conn.begin();
        	sqlStr = "{call SP_GRT_DATA_CREATE(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}";
        	
        	//System.out.println("SQL : " + sqlStr); 
        	
            cs = super.conn.getConnection().prepareCall(sqlStr);
            cs.setString(1, valueObject.get("purContModId"));
            cs.setString(2, "M");
            cs.setString(3, valueObject.get("GRTREQNO"));
            cs.setString(4, valueObject.get("PUR_CONT_ID"));
            cs.setString(5, valueObject.get("MOD_NO"));
            cs.setString(6, valueObject.get("WARRSEQ"));
            cs.setString(7, "5");
            cs.setString(8, "0"+valueObject.get("guarOrganCode"));
            cs.setString(9, valueObject.get("CAUSECODE"));
            cs.setString(10, valueObject.get("prepayId"));
            cs.setString(11, null);
        	//System.out.println("1 : " + valueObject.get("purContModId")); 
        	//System.out.println("2 : " + "M"); 
        	//System.out.println("3 : " + valueObject.get("GRTREQNO")); 
        	//System.out.println("4 : " + valueObject.get("PUR_CONT_ID")); 
        	//System.out.println("5 : " + valueObject.get("MOD_NO")); 
        	//System.out.println("6 : " + valueObject.get("WARRSEQ")); 
        	//System.out.println("8 : " + "0"+valueObject.get("guarOrganCode")); 
        	//System.out.println("9 : " + valueObject.get("CAUSECODE")); 
        	//System.out.println("10 : " + valueObject.get("prepayId")); 

            cs.registerOutParameter(12, java.sql.Types.VARCHAR);
            cs.registerOutParameter(13, java.sql.Types.VARCHAR);
            cs.execute();
            rtnVo.set("O_ERRCODE",cs.getString(12));
            rtnVo.set("O_ERRMSG",cs.getString(13));            

            //온라인 보증 정보 전송
            return this.sendGuarData(connection, valueObject, "REQ");
         //   return true;

        }
        catch(Exception e) {
            super.doException(e);
            rtnVo.set("OUT_SUCCESS_CD",cs.getString(12));
            rtnVo.set("errMsg",cs.getString(13));
            super.conn.setRollback();
            this.storage.setSuccess(false);
            this.storage.setMessage(e.getMessage());
            return false;
        }
        finally {
            super.conn.end();
        }
    }	
	
	/**
	 * 보증정보 전송
	 * @param gs				GauceService
	 * @param sGuarOrganCode	보증기관코드
	 * @param sContNo			계약번호
	 * @param sContSubNo		계약순번
	 * @param sContRound		계약차수
	 * @param sBondSeq			
	 * @param sGrtType			보증종류코드
	 * @param sProcessCode
	 * @return
	 * @throws Exception
	 */
	public boolean sendGuarData(Connection connection, ValueObject gs, String sPCode) throws Exception
	{
		String 	offID			= "S2118141143";	// 	수신 보증기관 ID
		String 	orgID			= "C2148189369";	// 	송신 채권기관 ID
		String 	conRefNo 		= gs.get("GRTREQNO");	// 	계약번호
		String 	conSeqNo 		= "";		// 	계약차수 (2자리)
		String 	msgFuncCode 	= "53";		// 	운영구분 - 9 운영, 53 테스트
		String 	errMsg 			= "";
		String 	errCode 		= "";
		String	_sGrtType		= "";
		String sContChasu		= gs.get("MOD_NO");
		String sBondSeq			= gs.get("WARRSEQ");
		String sProcessCode		= sPCode;		// 진행구분 - REQ 신청, CAN 취소, APP 최종, DES 파기

		_sGrtType	=	"003";
		
		boolean	bSuccess	=	true;
		
		if(sContChasu.length() == 1)	conSeqNo	=	"0"	+	sContChasu;
		else							conSeqNo	=	sContChasu;
		
		if(sBondSeq.length() == 1)	sBondSeq	=	"0"	+	sBondSeq;
		else							sBondSeq	=	sBondSeq;

		
		//System.out.println("보증정보 전송(구매) sendGuarData");
		//System.out.println("orgID 			["+orgID+"]");
		//System.out.println("offID 			["+offID+"]");
		//System.out.println("conRefNo 		["+conRefNo+"]");
		//System.out.println("conSeqNo 		["+conSeqNo+"]");
		//System.out.println("_sGrtType 		["+_sGrtType+"]");
		//System.out.println("sBondSeq 		["+sBondSeq+"]");
		//System.out.println("msgFuncCode 	["+msgFuncCode+"]");
		//System.out.println("sProcessCode 	["+sProcessCode+"]");
		
		/*	전송 전문	*/
		String sendnStr =	"orgID=" + orgID + "&offID=" + offID + "&conRefNo=" + conRefNo + 
							"&conSeqNo=" + conSeqNo + "&grtType=" + _sGrtType + "&grtSeq=" + sBondSeq +
							"&msgFuncCode=" + msgFuncCode + "&processCode=" + sProcessCode;
		//System.out.println("sendnStr 	["+sendnStr+"]");
		
		URL 				targetURL	=	null;
		HttpURLConnection 	u			=	null;
		DataOutputStream 	os			=	null;
		InputStream 		ins			=	null;
		String guarUrl = WAFConfig.get("waf.guar.url");
		
		try {

			if(gs.get("guarOrganCode").equals("1")){
				targetURL = new URL(guarUrl + "/transure/TransureReqManager");
			}else{
				if(sPCode.equals("REQ")){
					targetURL = new URL(guarUrl + "/KICA_Linker/SendServlet");
				}else{
					targetURL = new URL(guarUrl + "/KICA_Linker/SendCancleServlet");
				}
			}
			
			u = (HttpURLConnection) targetURL.openConnection();
			u.setRequestMethod("POST"); 
			u.setDoOutput(true);
			u.setDoInput(true);
			
			os = new DataOutputStream(u.getOutputStream());
			os.write(sendnStr.getBytes());
			os.flush();
			
			ins = u.getInputStream(); 
			
			StringBuffer buff = new StringBuffer();
			
			int ch;
			
			while((ch = ins.read()) > 0) { 
				buff.append((char)ch);
			}
			String msg = buff.toString();
			msg = java.net.URLDecoder.decode(msg, "UTF-8" );
			//System.out.println("msg["+msg+"]");
			
			if(msg.indexOf("SA") > -1) 
			{
				//System.out.println("성공");
			} else 
			{
				if(msg.indexOf("SR") > -1) 
				{					
					bSuccess	=	false;
					errMsg 	= msg.substring(msg.indexOf("resResult") + "resResult".length() + 1);
					
					// 실패일 경우만 생성
					
					errCode = msg.substring(msg.indexOf("resCode") + "resCode".length() + 1);
					//System.out.println("실패 : " + errMsg +" / " + errCode);
				} else if (msg == null) 
				{
					bSuccess	=	false;
					errMsg 	= "TransureManager 서블릿 호출 오류 발생 1";
					errCode = "";
				} else 
				{
					bSuccess	=	false;
					errMsg 	= "TransureManager 서블릿 호출 오류 발생 2";
					errCode = "";
				}
		   }
			
		} catch (MalformedURLException e) {
			bSuccess	=	false;
			//System.out.println("[ERROR 1 "+this.getClass().toString()+".sendGuarData()] : "	+ e.toString());
			throw new MalformedURLException("[ERROR 1 "+this.getClass().toString()+".sendGuarData()] : "	+ e.toString());
		
		}catch (Exception e) {
			bSuccess	=	false;
			//System.out.println("[ERROR 2 "+this.getClass().toString()+".sendGuarData()] : "	+ e.toString());
			WAFLogger.error("[ERROR 1 "+this.getClass().toString()+".sendGuarData()] : "	+ e.toString());
		}
		this.storage.setMessage(errMsg);
		return	bSuccess;
	}
	/**
     * 전송 실패일경우 상태값을 04 신청 대기 상태로 놓는다.
	 * @param connection
	 * @param valueObject
	 * @throws Exception
	 */
	public boolean WarrStatusUp(Connection connection, ValueObject valueObject) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        StrBuffer sqlstr = new StrBuffer();
        try {
        	sqlstr.append("UPDATE CONT_PUR_WARR SET  	\n");
        	sqlstr.append(" GUAR_STATUS = ?					\n");
        	sqlstr.append("WHERE PUR_CONT_MOD_ID = ?						\n");
        	sqlstr.append(" AND WARR_GUBUN = '5'						\n");
        	sqlstr.append(" AND WARR_SEQ = ?						\n");
            persistent.setStatement(sqlstr.toString());
            persistent.addParameter(valueObject.get("gStatus"));
            persistent.addParameter(valueObject.get("purContModId"));
            persistent.addParameter(valueObject.get("warrSeq"));
            persistent.execute();

            return true;
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> updUser() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            //System.out.println("Exception : " + e.getMessage());
            throw e;
        }
    }	
	/**
     * 보증 정보 삭제
	 * @param connection
	 * @param valueObject
	 * @throws Exception
	 */
	public boolean deleteGuarInfoData(Connection connection, ValueObject valueObject) throws Exception {
		boolean bSuccess	=	true;
        Persistent persistent = new PersistentImpl(connection);
        StrBuffer sqlstr = new StrBuffer();
        try {
        	sqlstr.append("DELETE FROM CONT_PUR_WARR   	\n");
        	sqlstr.append("WHERE PUR_CONT_MOD_ID = ?						\n");
        	sqlstr.append(" AND WARR_GUBUN = '5'						\n");
        	sqlstr.append(" AND WARR_SEQ = ?						\n");
            persistent.setStatement(sqlstr.toString());
            persistent.addParameter(valueObject.get("purContModId"));
            persistent.addParameter(valueObject.get("warrSeq"));
            persistent.execute();

            bSuccess = true;
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> updUser() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            //System.out.println("Exception : " + e.getMessage());
            bSuccess	=	false;
    		this.storage.setMessage(e.getMessage());
        }
        return bSuccess;
    }	
	
    /**
     * 이전 보증 기관 조회
	 * @param 
	 * @param 
	 * @return ValueObject
	 */
	public String getOldGuarInfo(String purContid){

        Search search = new SearchImpl();
        RowSet listRowSet = null;
        StrBuffer sqlstr = new StrBuffer();
        ValueObject rowObject = null;
        String OldGuarOrganCode = "";
        
        try {
        	sqlstr.append(" 	SELECT GUAR_ORGAN_CODE	\n");
        	sqlstr.append(" 	  FROM CONT_PUR_WARR A	\n");
        	sqlstr.append("   WHERE 1=1								\n");
    		sqlstr.append("   	AND A.PUR_CONT_ID = '"+ purContid +"'			\n");
    		sqlstr.append("   	AND A.WARR_GUBUN =  '5'	\n");
    		sqlstr.append("   	AND A.MOD_NO =  0	\n");
    		sqlstr.append("   	AND A.GUAR_STATUS =  '09'	\n");
             
    		search.setStatement(sqlstr.toString());
            listRowSet = search.execute();
            if(listRowSet.size() != 0){
            	rowObject = RowSetUtility.getValueObject(listRowSet.getRow(0));
            	OldGuarOrganCode = rowObject.get("GUAR_ORGAN_CODE");
            }
            
		}catch(Exception e){
			e.printStackTrace();
		}finally{

			return OldGuarOrganCode;
		}
	}
	
	private String getWarrSeq(String purContModId) {
		
		Search search = new SearchImpl();
		RowSet rowSet = new RowSetImpl();
		StrBuffer sqlstr = new StrBuffer();
		String rtnStr = "";
		try{
			sqlstr.append("SELECT  NVL(										\n");
			sqlstr.append("            (									\n");
			sqlstr.append("            SELECT  WARR_SEQ						\n");
			sqlstr.append("            FROM    CONT_PUR_WARR				\n");
			sqlstr.append("            WHERE   PUR_CONT_MOD_ID = ?			\n");
			sqlstr.append("            AND     WARR_GUBUN = '5'				\n");
			sqlstr.append("            )									\n");
			sqlstr.append("            ,(									\n");
			sqlstr.append("            SELECT  NVL(MAX(WARR_SEQ),0) + 1		\n");
			sqlstr.append("            FROM    CONT_PUR_WARR				\n");
			sqlstr.append("            WHERE   PUR_CONT_MOD_ID = ?			\n");
			sqlstr.append("            )									\n");
			sqlstr.append("        )										\n");
			sqlstr.append("FROM    DUAL										\n");
			
			search.setStatement(sqlstr.toString());
			search.addParameter(purContModId);
			search.addParameter(purContModId);
			
			rowSet = search.execute();
			
			if( rowSet != null && rowSet.size() > 0 ){
				rtnStr = rowSet.getRow(0).get(0);
			}
			
		}catch(WAFSQLException se) {
			super.doException(se);
			this.storage.setSuccess(false);
			this.storage.setMessage(se.getMessage());
			storage.setDetailMessage(se);
		}finally {
			return rtnStr;
		}
	}
}