/**
 *
 * @(#)author  [Youngmi Im]
 * @(#)version 1.0
 * @(#)date    May 10, 2007
 * @(#)since   JDK 1.4.2
 *
 * Copyright (c) www.hwenc.co.kr, Inc.
 * All rights reserved.
 * This software is the proprietary information of Hanwha E&C, Inc.
 */
 package kr.co.udapsoft.ebid.buyer.payment.outside.biz;


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

import kr.co.hsnc.common.base.WAFLogger;
import kr.co.hsnc.common.base.WAFMessages;
import kr.co.hsnc.common.sql.RowSet;
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.sender.MessageSend;
import kr.co.udapsoft.ebid.buyer.bid.purchase.biz.InterfacePurERPiU;

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

	public void doBiz() throws Exception {

		RowSet listRowSet = null; 
		boolean success = false;
		
		if (storage.compareEvent("")) {
			
			WAFLogger.debug("prepayId="+params.get("prepayId"));
			WAFLogger.debug("pageDiv="+params.get("pageDiv"));
			
			//기존 등록된 반려사유 조회
			ValueObject rejectionData = getRejectionData(params);
			storage.addValueObject("rejectionData", rejectionData);	
			
			
		}  else if(storage.compareEvent("SAVE_DATA")){	
			
			
			//구매기성 반려 (조달 PUR1100T 삭제후 ERPIU업데이트)
			if( params.get("pageDiv").equals("2") || params.get("pageDiv").equals("20") ) { //2 구매납품 20 입고계획
				success = rejectionPur1100tData(params); 
			//업체 반려  params.get("pageDiv").equals("21")
			}else {
				success = rejectionData(params); 
			}
			
			
			//success = true;
			
			String resUserName = params.get("resUserName");			//계약 담당자명
			String resHp = params.get("resHp").replaceAll("-", "");	//계약 담당자 핸드폰번호
			String resEmail = params.get("resEmail");				//계약 담당자 이메일
			String resDivision = params.get("resDivision");	

			String hp = params.get("hp").replaceAll("-", "");	//업체 담당자 핸드폰번호
			String eMail = params.get("eMail");					//업체 담당자 이메일
        	String memberName = params.get("memberName");		//업체명
        	String userName = params.get("userName");			//업체 담당자명
        	String deptName = params.get("deptName");			//현장명
        	String conDocNo = params.get("conDocNo");			//계약번호
        	String buildName = params.get("buildName");			//계약명

        	String rtnReason = params.get("rtnReason");				//반려사유
        	
        	if(params.get("pageDiv").equals("0") || params.get("pageDiv").equals("3")){	//선급금반려
				//SMS
		      	MessageSend messageSend = new MessageSend(storage);
		      	String recvAddress = hp;
	        	String smsContent = WAFMessages.getMessage("Prepayments.Information.Request");
	        	WAFLogger.debug(smsContent);
	        	messageSend.sendSMS(recvAddress, storage.getUser().get("USER_PHONE"), storage.getUser().get("ACCT_ID"), smsContent);  //2015.9.21 resHp
				
	        	//E-Mail
	        	MessageSend mailSend = new MessageSend(storage);
	        	StringBuffer mailContent = new StringBuffer();
        	
            	mailContent.append(memberName+ "님이 서명한 선급금 신청 내용에 정정 사항이 있어 알려드립니다. </BR>");
            	mailContent.append("협력업체포탈시스템에서 선급금의 정정 사유 확인하시고 정정후 다시 서명하시기 바랍니다. </BR>");
            	mailContent.append("<font style='width:auto; font-size:12px; line-height:18px; padding:5px; text-align:left;'>");
            	mailContent.append("</BR>");
            	mailContent.append("1.프로젝트: "+deptName+"</BR>");
            	mailContent.append("2.계약번호: "+conDocNo+"</BR>");
            	mailContent.append("3.계약명: " +buildName+"</BR>");
            	mailContent.append("4.수정요청사유: " +rtnReason+"</BR>");
            	mailContent.append("5.계약담당자: "+resDivision+"/" +resUserName+"(연락처 :"+resHp+")</BR>");
            	mailContent.append("</font>");
            	messageSend.sendEmail(eMail, resEmail, "선급금정보 수정요청 메일입니다.", "선급금정보 수정요청 메일입니다.", mailContent);
        	}else if(params.get("pageDiv").equals("21")){ //대금반려
				//SMS
		      	MessageSend messageSend = new MessageSend(storage);
		      	String recvAddress = hp;
	        	String smsContent = WAFMessages.getMessage("Billing.Information.Request");
	        	WAFLogger.debug(smsContent);
	        	messageSend.sendSMS(recvAddress, storage.getUser().get("USER_PHONE"), storage.getUser().get("ACCT_ID"), smsContent); //2015.9.21 선급반려 resHp
	        	
	        	//E-Mail
	        	MessageSend mailSend = new MessageSend(storage);
	        	StringBuffer mailContent = new StringBuffer();
        	
            	mailContent.append(memberName+ "님이 서명한 대금 신청 내용에 정정 사항이 있어 알려드립니다. </BR>");
            	mailContent.append("협력업체포탈시스템에서 대금의 정정 사유 확인하시고 정정후 다시 서명하시기 바랍니다. </BR>");
            	mailContent.append("<font style='width:auto; font-size:12px; line-height:18px; padding:5px; text-align:left;'>");
            	mailContent.append("</BR>");
            	mailContent.append("1.프로젝트: "+deptName+"</BR>");
            	mailContent.append("2.계약번호: "+conDocNo+"</BR>");
            	mailContent.append("3.계약명: " +buildName+"</BR>");
            	mailContent.append("4.수정요청사유: " +rtnReason+"</BR>");
            	mailContent.append("5.계약담당자: "+resDivision+"/" +resUserName+"(연락처 :"+resHp+")</BR>");
            	mailContent.append("</font>");
            	messageSend.sendEmail(eMail, resEmail, "대금정보 수정요청 메일입니다.", "대금정보 수정요청 메일입니다.", mailContent);
            	
        	}else{
        		
        	}
			
        	storage.setSuccess(success);
		
		}
	}

    /**
     *@param ValueObject
     *@return ValueObject
     *기   능 : 반려사유조회
     *@author OK
     *@version 2014. 6. 30.
     *@since JDK1.7
     */
    public ValueObject getRejectionData(ValueObject Params) {
        Search search = new SearchImpl();
        RowSet listRowSet = null;
        StringBuffer sql = new StringBuffer();
        ValueObject rowObject = null;
        
        String tableName = "SUB1030T";
        
        if(params.get("pageDiv").equals("0")){	//0:선급, 1:기성
        	tableName = "SUB1030T";
        }else if(params.get("pageDiv").equals("1")){
        	tableName = "SUB1040T";
        }
        
        try {
      	  	sql.append("	SELECT PREPAY_ID,  --기성ID										\n");
      	  	sql.append(" 	       RTN_REASON,         --반려사유								\n");
      	  	sql.append(" 	       to_char(to_date(RTN_DATE, 'yyyymmdd'), 'yyyy-mm-dd') AS RTN_DATE, 	--반류일자						\n");
      	  	sql.append(" 	       RTN_EMPNO,          --반려사사번							\n");
      	  	sql.append(" 	       RTN_EMPNM           --반려자명								\n");
      	  	sql.append(" 	from "+tableName+"												\n");
      	  	sql.append("	WHERE PREPAY_ID = '"+ params.get("prepayId") +"' -- 기성ID			\n"); 
      	
      	  	search.setStatement(sql.toString());
      	  WAFLogger.debug(sql.toString());
      	  	
            listRowSet = search.execute();
            rowObject = RowSetUtility.getValueObject(listRowSet.getRow(0));
            
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> getRejectionpData() : " + e.getMessage());
            WAFLogger.error("SQL : " + search.getStatement());
            WAFLogger.error(e);
            return null;
        }
        finally {

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

	/**
	 * Persistent 를 이용한 반려 처리
	 * @param params
	 * @return
	 * * 경영정보에서 협력업체에 반려 처리한다.
	 * @param connection
	 * @param pgmName
	 * @param screenName
	 * @param systemCode
	 * @throws Exception
	 */
	private boolean rejectionData(ValueObject params) {
		
		Persistent persistent_u = null;
		String sqlstr_u = "";
	
        String tableName = "SUB1030T";
        
        if(params.get("pageDiv").equals("0")){	//0:선급, 1:기성, 2:대금(납품,설치), 3:대금(선급금)
        	tableName = "SUB1030T";
			sqlstr_u = " UPDATE  "+tableName+"   													\n"
					+ " SET    STATUS_CD    			= '91'      ,									\n"
					+ "        SIGN_DT  				= null    , 					            \n"
					+ "        RTN_REASON  				= ?       , 					            \n"
					+ "        RTN_DATE  				= TO_CHAR(sysdate, 'yyyymmdd') ,	        \n"
					+ "        RTN_EMPNO  				= ?		  , 					            \n"
					+ "        RTN_EMPNM  				= ?		  , 					            \n"
					+ "        UPD_BY      				= ?       , 					            \n"
					+ "        UPD_DATE    				= sysdate									\n"
					+ " WHERE  PREPAY_ID      			= ?        									\n" ;
        }else if(params.get("pageDiv").equals("1")){
        	tableName = "SUB1040T";
			sqlstr_u = " UPDATE  "+tableName+"   													\n"
					+ " SET    STATUS_CD    			= '91'     ,									\n"
					+ "        SIGN_DT  				= null    , 					            \n"
					+ "        SUPP_SIGN_DT				= null    , 					            \n"
					+ "        RTN_REASON  				= ?       , 					            \n"
					+ "        RTN_DATE  				= TO_CHAR(sysdate, 'yyyymmdd') ,	        \n"
					+ "        RTN_EMPNO  				= ?		  , 					            \n"
					+ "        RTN_EMPNM  				= ?		  , 					            \n"
					+ "        UPD_BY      				= ?       , 					            \n"
					+ "        UPD_DATE    				= sysdate									\n"
					+ " WHERE  PREPAY_ID      			= ?        									\n" ;
        }else if(params.get("pageDiv").equals("2")){	//납품
        	tableName = "PUR1100T";
        	
        	/*
			sqlstr_u = " UPDATE  "+tableName+"   													\n"
					+ " SET    REQ_STATUS    			= 99      ,									\n"
					+ "        SIGN_DATA  				= null    , 					            \n"
					+ "        SUPP_SIGN_DT				= null    , 					            \n"
					+ "        RTN_REASON  				= ?       , 					            \n"
					+ "        RTN_DATE  				= TO_CHAR(sysdate, 'yyyymmdd') ,	        \n"
					+ "        RTN_EMPNO  				= ?		  , 					            \n"
					+ "        RTN_EMPNM  				= ?		  , 					            \n"
					+ "        UPD_BY      				= ?       , 					            \n"
					+ "        UPD_DATE    				= sysdate									\n"
					+ " WHERE  PAYREQ_ID      			= ?        									\n";
        	 */
        }else if(params.get("pageDiv").equals("20")){	//현장
        	tableName = "PUR1100T";
        	/*
			sqlstr_u = " UPDATE  "+tableName+"   													\n"
					+ " SET    REQ_STATUS    			= 98      ,									\n"
					+ "        SIGN_DATA  				= null    , 					            \n"
					+ "        SUPP_SIGN_DT				= null    , 					            \n"
					+ "        RTN_REASON  				= ?       , 					            \n"
					+ "        RTN_DATE  				= TO_CHAR(sysdate, 'yyyymmdd') ,	        \n"
					+ "        RTN_EMPNO  				= ?		  , 					            \n"
					+ "        RTN_EMPNM  				= ?		  , 					            \n"
					+ "        UPD_BY      				= ?       , 					            \n"
					+ "        UPD_DATE    				= sysdate									\n"
					+ " WHERE  PAYREQ_ID      			= ?        									\n";
        	 */        	
        }else if(params.get("pageDiv").equals("21")){  //설치
        	tableName = "PUR1100T";
        	
			sqlstr_u = " UPDATE  "+tableName+"   													\n"
					+ " SET    REQ_STATUS    			= '02'    ,									\n"
					+ "        SIGN_DATA  				= null    , 					            \n"
					+ "        SUPP_SIGN_DT				= null    , 					            \n"
					+ "        RTN_REASON  				= ?       , 					            \n"
					+ "        RTN_DATE  				= TO_CHAR(sysdate, 'yyyymmdd') ,	        \n"
					+ "        RTN_EMPNO  				= ?		  , 					            \n"
					+ "        RTN_EMPNM  				= ?		  , 					            \n"
					+ "        UPD_BY      				= ?       , 					            \n"
					+ "        UPD_DATE    				= sysdate									\n"
					+ " WHERE  PAYREQ_ID      			= ?        									\n";
			              	
        }else if(params.get("pageDiv").equals("3")){
        	tableName = "PUR1030T";
			sqlstr_u = " UPDATE  "+tableName+"   													\n"
					+ " SET    PREPAY_PROC_GB  			= '91'      ,									\n"
					+ "        SIGN_DATA  				= null    , 					            \n"
					+ "        SUPP_SIGN_DT				= null    , 					            \n"
					+ "        RTN_REASON  				= ?       , 					            \n"
					+ "        RTN_DATE  				= TO_CHAR(sysdate, 'yyyymmdd') ,	        \n"
					+ "        RTN_EMPNO  				= ?		  , 					            \n"
					+ "        RTN_EMPNM  				= ?		  , 					            \n"
					+ "        UPD_BY      				= ?       , 					            \n"
					+ "        UPD_DATE    				= sysdate									\n"
					+ " WHERE  PREPAY_ID      			= ?        									\n" ;
        	
        }
        
		try {
			
			//외주_기성정보
			String prepayId					= params.get("prepayId");				//기성ID
			//String statusCd					= "91";									//기성상태값 : 작성상태(01),기성신청요청(02), 기성신청(03), 기성완료(10), 반려(91)
			String userId					= storage.getUser().get("USER_ID");		//로그인사용자
			int userNum						= params.getInt("USER_ID");				//로그인사용자
			String rtnDate					= params.get("rtnDate");				//반려일
			String rtnReason				= params.get("rtnReason1");				//반려사유
			
			conn.begin();
			
			persistent_u = new PersistentImpl(super.conn.getConnection());
			
			persistent_u.setStatement(sqlstr_u);
			
			//persistent_u.addParameter(statusCd);
			persistent_u.addParameter(rtnReason);
			persistent_u.addParameter(userNum);
			persistent_u.addParameter(userId);
			persistent_u.addParameter(userNum);
			persistent_u.addParameter(prepayId);
			
			WAFLogger.debug(sqlstr_u);
			WAFLogger.debug(persistent_u.getParameters());
			
			persistent_u.execute();
			persistent_u.clearParameters();
			
			return true;
		}
		catch(Exception e) {
			super.doException(e);
			super.storage.setMessage(e.getMessage());
			super.storage.setDetailMessage(e);
			super.conn.setRollback();
			return false;
		}
		finally {
			super.conn.end();
		}	
	}
	
	private boolean rejectionPur1100tData(ValueObject params) {
		
		Persistent persistent = null;
		StringBuffer sqlstr = new StringBuffer();
		
		try {
			//외주_기성정보
			String prepayId					= params.get("prepayId");				//기성ID
			String userId					= storage.getUser().get("USER_ID");		//로그인사용자
			int userNum						= params.getInt("USER_ID");				//로그인사용자
			String rtnDate					= params.get("rtnDate");				//반려일
			String rtnReason				= params.get("rtnReason1");				//반려사유
			
			conn.begin();
			persistent = new PersistentImpl(super.conn.getConnection());
			
			sqlstr.append("DELETE	FROM PUR1100T WHERE PAYREQ_ID = ?	\n");
			persistent.setStatement(sqlstr.toString());
			persistent.addParameter(prepayId);
			persistent.execute();
			persistent.clearParameters();
			
			sqlstr = new StringBuffer();
			sqlstr.append("DELETE	FROM ETEC_ERPIF.PUR1100T WHERE PAYREQ_ID = ?	\n");
			persistent.setStatement(sqlstr.toString());
			persistent.addParameter(prepayId);
			persistent.execute();
			persistent.clearParameters();
			
			// 구매납품인 경우 ERP 반려시 상세내역 삭제 2019.11.04 추가
			if(params.get("pageDiv").equals("2")){
				sqlstr = new StringBuffer();
				sqlstr.append("DELETE	FROM PMM_PAYREQ_ITEM WHERE PAYREQ_ID = ?	\n");
				persistent.setStatement(sqlstr.toString());
				persistent.addParameter(prepayId);
				persistent.execute();
				persistent.clearParameters();
				
				sqlstr = new StringBuffer();
				sqlstr.append("DELETE	FROM ETEC_ERPIF.PMM_PAYREQ_ITEM WHERE PAYREQ_ID = ?	\n");
				persistent.setStatement(sqlstr.toString());
				persistent.addParameter(prepayId);
				persistent.execute();
				persistent.clearParameters();
			}
			
			InterfacePurERPiU.updateBuiltReject(params, storage.getUser().get("USER_SABUN"), storage.getUser().get("USER_NAME"));
			
			return true;
		}catch(Exception e) {
			super.doException(e);
			super.storage.setMessage(e.getMessage());
			super.storage.setDetailMessage(e);
			super.conn.setRollback();
			return false;
		}finally {
			super.conn.end();
		}	
	}
	
}
