/**
 * @(#)file    SuccessBidSaveStatusBiz.java
 * @(#)author  chj
 * @(#)version 1.0
 * @(#)date    2015-02-26
 * @(#)since   JDK 1.6
 */
package kr.co.udapsoft.ebid.buyer.bid.purchase.biz;



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.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 oracle.toplink.internal.ox.StrBuffer;

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

   
public class SuccessBidSaveStatusBiz extends Biz {

	public SuccessBidSaveStatusBiz(HandlerStorage storage) {
		super(storage);
	}
	ValueObject rtnVo = new ValueObject();
	public void doBiz() throws Exception {
		boolean success = false;
		
		if(storage.compareEvent("SAVE_BID_STATUS")){//낙찰
        	success = BidmasterStatusUpdate(params);
        }
		
		super.storage.setSuccess(success);
	}
	
	
	/**
     * 유찰 업데이트 
	 * @param valueObject
	 * @param event
	 * @return
	 */
	public boolean BidmasterStatusUpdate(ValueObject valueObject) {
		conn.begin(); 
		StrBuffer sqlstr = new StrBuffer();
		StrBuffer sqlstr2 = new StrBuffer();
		StrBuffer sqlstr3 = new StrBuffer();
		StrBuffer sqlstr4 = new StrBuffer();
        try {
        	
        	Persistent persistent = new PersistentImpl(conn.getConnection());
        	Persistent persistent2 = new PersistentImpl(conn.getConnection());
        	Persistent persistent3 = new PersistentImpl(conn.getConnection());
        	Persistent persistent4 = new PersistentImpl(conn.getConnection());
        	
        	
        	/*낙찰 상태로 변경*/
            sqlstr.append("UPDATE BID_MASTER		\n");
        	sqlstr.append("SET STATUS_CD = ?			\n");
        	sqlstr.append(",UPD_BY = ?					\n");
        	sqlstr.append(",UPD_DATE = SYSDATE		\n");
        	sqlstr.append("WHERE BID_NO = ?			\n");
        	sqlstr.append("AND BID_DEG = ?			\n");
        	
        	/*도급금액, 실행예산, 구매예산 UPDATE */
        	sqlstr2.append("				UPDATE BID_SUPP A                                                                                                       \n");
        	sqlstr2.append("				SET PUR_AMT = (SELECT NVL(PUR_AMT,0 ) FROM BID_MASTER WHERE BID_NO = A.BID_NO AND BID_DEG = A.BID_DEG)                   \n");
        	sqlstr2.append("				    ,  CONT_AMT  = (SELECT NVL(CONT_AMT,0 ) FROM BID_MASTER WHERE BID_NO = A.BID_NO AND BID_DEG = A.BID_DEG)             \n");
        	sqlstr2.append("				    , ACT_AMT = (SELECT NVL(ACT_AMT,0 ) FROM BID_MASTER WHERE BID_NO = A.BID_NO AND BID_DEG = A.BID_DEG)                 \n");
        	sqlstr2.append("				    , CON_REMARK = (SELECT CON_REMARK FROM BID_MASTER WHERE BID_NO = A.BID_NO AND BID_DEG = A.BID_DEG)                 \n");
        	sqlstr2.append("				WHERE BID_NO = ?                                                                                                        \n");
        	sqlstr2.append("				AND   BID_DEG = ?																										\n");

        	/*계약번호 미리 채번 */
        	sqlstr3.append("				UPDATE BID_SUPP A                                                                                                       \n");
        	sqlstr3.append("				SET CONF_NO = ?                   																						\n");
        	sqlstr3.append("				  , BID_STATUS_CD = '15'                   																				\n");
        	sqlstr3.append("				WHERE BID_NO = ?                                                                                                        \n");
        	sqlstr3.append("				AND   BID_DEG = ?																										\n");
        	sqlstr3.append("				AND   VENDOR_CD = ?																										\n");
        	
        	/*분할발주가 아닌경우 SELECT_QTY에 QTY UPDATE*/
        	sqlstr4.append("				UPDATE BID_SUPP_ESTI                                                                                                    \n");
        	sqlstr4.append("				SET SELECT_QTY = QTY                   																						\n");
        	sqlstr4.append("				WHERE BID_NO = ?                                                                                                        \n");
        	sqlstr4.append("				AND   BID_DEG = ?																										\n");
        	sqlstr4.append("				AND   VENDOR_CD = ?																										\n");
        	
        	
        	
        	
            persistent.setStatement(sqlstr.toString());
            persistent.addParameter("15");
            persistent.addParameter(storage.getUser().get("ACCT_ID"));
            persistent.addParameter(valueObject.get("BID_NO"));
            persistent.addParameter(valueObject.get("BID_DEG"));
            persistent.execute();
            

            persistent2.setStatement(sqlstr2.toString());
            persistent2.addParameter(valueObject.get("BID_NO"));
            persistent2.addParameter(valueObject.get("BID_DEG"));
            persistent2.execute();
            
            
            RowSet rowSet = getVendor(valueObject.get("BID_NO"), valueObject.get("BID_DEG"));
            
            
            for(int i =0; i <rowSet.size(); i++){
            	Row row = rowSet.getRow(i);
            	if(!row.get("DIV_CONT_YN").equals("Y")){
            		
            		persistent4.setStatement(sqlstr4.toString());
            		
            		persistent4.addParameter(valueObject.get("BID_NO"));
            		persistent4.addParameter(valueObject.get("BID_DEG"));
            		persistent4.addParameter(row.get("VENDOR_CD"));
            		persistent4.execute();
            		
            		persistent4.clearParameters();
            		
            	}
                persistent3.setStatement(sqlstr3.toString());
                persistent3.addParameter(row.get("ORD_DOC_NO"));
                persistent3.addParameter(valueObject.get("BID_NO"));
                persistent3.addParameter(valueObject.get("BID_DEG"));
                persistent3.addParameter(row.get("VENDOR_CD"));
                persistent3.execute();
                
                persistent3.clearParameters();
            	
            }
            
            
            return true;
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> BidmasterStatusUpdate() : " + e.getMessage());
            WAFLogger.error(e);
            conn.setRollback();
            storage.setDetailMessage(e);
            return false;
        }
        finally {
        	
            conn.end();
        }
    }
	
	
	private RowSet getVendor(String bidNo , String bidDeg){
		Search search = new SearchImpl();
		RowSet rowSet = null;
		StringBuffer sqlstr = new StringBuffer();
		
		try{
			//2018.06.08 수정. 단가계약 업체선정 하나일때도 계약번호 끝에 알파벳 추가 || DECODE(DIV_PO_YN, 'Y',  CHR(ASCII('@')+RANK)  , '')
			sqlstr.append("	      SELECT  CASE WHEN CNT > 1 THEN ORD_DOC_NO || CHR(ASCII('@')+RANK)                                                                             \n");
			sqlstr.append("	                                ELSE ORD_DOC_NO || DECODE(DIV_PO_YN, 'Y',  CHR(ASCII('@')+RANK)  , '') END  ORD_DOC_NO -- 발주계약번호   				\n");
			sqlstr.append("	            ,VENDOR_CD                                                                                                                              \n");
			sqlstr.append("	            ,DIV_PO_YN -- 단가계약여부                                                                                                                 													\n");
			sqlstr.append("	            ,DIV_CONT_YN -- 분할발주 여부                                                                                                                													\n");
			sqlstr.append("	            ,CNT -- 입찰공고별 낙찰업체수                                                                                                              													\n");
			sqlstr.append("	            ,RANK -- 순위                                                                                                                              														\n");
			sqlstr.append("	            ,NVL(PAY_DIV,1) PAY_DIV -- 납품/설치 구분                                                                                                  											\n");
			sqlstr.append("	          FROM(                                                                                                                                     \n");
			sqlstr.append("	                    SELECT 'PO-'||REPLACE(REPLACE(REPLACE(REPLACE(B.DEMANDED_NO,'MR_',''),'WR_'),'MR-',''),'WR-','') ORD_DOC_NO -- 발주계약번호               \n");
			sqlstr.append("	                         ,A.VENDOR_CD                                                                                                               \n");
			sqlstr.append("	                         ,DIV_PO_YN -- 단가계약여부                                                                                                      											\n");
			sqlstr.append("	                         ,DIV_CONT_YN -- 분할발주 여부                                                                                                      											\n");
			sqlstr.append("	                         ,COUNT(A.BID_NO) OVER(PARTITION BY A.BID_NO, A.BID_DEG) CNT                                                                \n");
			sqlstr.append("	                         ,RANK() OVER(PARTITION BY A.BID_NO, A.BID_DEG ORDER BY A.VENDOR_CD) RANK                                                   \n");
			sqlstr.append("	                         ,B.PAY_DIV                                                                                                                 \n");
			sqlstr.append("	                    FROM BID_SUPP A,                                                                                                                \n");
			sqlstr.append("	                                BID_MASTER B                                                                                                        \n");
			sqlstr.append("	                    WHERE A.BID_NO = B.BID_NO                                                                                                       \n");
			sqlstr.append("	                    AND A.BID_DEG = B.BID_DEG                                                                                                       \n");
			sqlstr.append("	                    AND A.BID_NO = '"+bidNo+"'                                                                                                      \n");
			sqlstr.append("	                    AND A.BID_DEG = '"+bidDeg+"'                                                                                                    \n");
			sqlstr.append("	                    AND A.SUCC_YN = 'Y'                                                                                                             \n");
			sqlstr.append("	     			)																																	\n");
			
			 search.setStatement(sqlstr.toString());
			 rowSet = search.execute();
		}
		catch(Exception e){
			 WAFLogger.error(this.getClass().getName() + " --> getVendor() : " + e.getMessage());
	            WAFLogger.error("SQL : " + search.getStatement());
	            WAFLogger.error(e);
		}finally{
			if(rowSet == null) rowSet = new RowSetImpl();
			return rowSet;
		}
		
		
	}
}