/**
 * @(#)file    ChgItemAddBiz.java
 * @(#)author  Choi hoon seok
 * @(#)version 1.0
 * @(#)date    2022-07-29
 * @(#)since   JDK 1.6.9
 */
package kr.co.udapsoft.ebid.buyer.cont.purchase.biz;


import java.sql.Connection;

import kr.co.hsnc.common.base.WAFLogger;
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 oracle.toplink.internal.ox.StrBuffer;

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

   
public class ChgItemAddBiz extends Biz {

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

	public void doBiz() throws Exception {
        ValueObject user = new ValueObject();
        ValueObject valueObject = new ValueObject();
        ValueObject valueObject2 = new ValueObject();
        ValueObject valueObject3 = new ValueObject();
        int chk_cnt = 0;
		boolean success = false;
		
		//변경 내역
		if(storage.compareEvent("")){
			
		}else if(storage.compareEvent("ITEM_ADD_SAVE")){
			valueObject  = chk_item_cnt(conn.getConnection(),params);
			valueObject2 = chk_pmm_cnt(conn.getConnection(),params);
			valueObject3 = chk_same_item(conn.getConnection(),params);
			chk_cnt      = Integer.parseInt(valueObject.get("CNT"));
			int chk_pmm  = Integer.parseInt(valueObject2.get("CNT"));
//			System.out.println("chk_cnt : "+chk_cnt);
//			System.out.println("chk_pmm : "+chk_pmm);
			String chk_itemCd = valueObject3.get("MATERIAL_CD");
	        params.set("login_user", storage.getUser().get("ACCT_ID"));
	        
	        if(chk_cnt > 0){
	        	super.storage.setSuccess(false);
				super.storage.setMessage("추가품목은 1개만 등록 가능합니다.");
	        }else{
	        	if( chk_itemCd.equals("") || chk_itemCd.equals(null) || chk_itemCd.equals(params.get("MATERIAL_CD")) ){	//기존에 등록된 mat_cd와 동일한 품목을 추가했는지 확인
	        		if(chk_pmm == 0){	//동일한 DEMANDED_ID값에 엮여있는 변경계약정보(PUR_CONT_MOD_ID)가 1개만 남아있는 경우
		        		addDemItemSave(conn.getConnection(),params);
			        }
		        	success = addItemSave(conn.getConnection(),params);
	        	}else{
	        		super.storage.setSuccess(false);
					super.storage.setMessage("다른 계약서에 추가된 품목정보와 일치하지 않습니다.");
	        	}
	        }
	        storage.setSuccess(success);			
		}else if(storage.compareEvent("ITEM_ADD_DEL")){
			valueObject = chk_item_cnt(conn.getConnection(),params);
			valueObject2 = chk_item_cnt2(conn.getConnection(),params);
			chk_cnt = Integer.parseInt(valueObject.get("CNT"));
			int chk_cnt2 = Integer.parseInt(valueObject2.get("CNT"));
//			System.out.println("chk_cnt : "+chk_cnt);
//			System.out.println("chk_cnt2 : "+chk_cnt2);
	        params.set("login_user", storage.getUser().get("ACCT_ID"));
	        if(chk_cnt == 0){
	        	super.storage.setSuccess(false);
				super.storage.setMessage("삭제할 추가품목이 없습니다.");
	        }else{
	        	if(chk_cnt2 == 1){	//동일한 DEMANDED_ID값에 엮여있는 변경계약정보(PUR_CONT_MOD_ID)가 1개만 남아있는 경우
	        		addDemItemDel(conn.getConnection(),params);
		        }
	        	success = addItemDel(conn.getConnection(),params);
	        }
	        storage.setSuccess(success);			
		}
	}
	
	private ValueObject chk_item_cnt(Connection connection, ValueObject valueObject){
		Search search = new SearchImpl();
		RowSet rowSet = new RowSetImpl();
		ValueObject valueobject = null;
		StrBuffer sqlstr = new StrBuffer();
		try{
			sqlstr.append("	SELECT NVL(COUNT(*),0) as CNT FROM CONT_PUR_ITEM WHERE PUR_CONT_MOD_ID = '"+valueObject.get("PUR_CONT_MOD_ID")+"' AND ITEM_ADD_YN = 'Y'	\n");
	    	search.setStatement(sqlstr.toString());
			rowSet = search.execute();
//			System.out.println(sqlstr);
			
			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 chk_pmm_cnt(Connection connection, ValueObject valueObject){
		Search search = new SearchImpl();
		RowSet rowSet = new RowSetImpl();
		ValueObject valueobject = null;
		StrBuffer sqlstr = new StrBuffer();
		try{
			sqlstr.append("	SELECT NVL(COUNT(*),0) as CNT 		\n");
			sqlstr.append("	  FROM PMM_DEMANDED_ITEM 			\n");
			sqlstr.append("	WHERE DEMANDED_ID = '"+valueObject.get("DEMANDED_ID")+"' 	\n");
			sqlstr.append("	  AND ITEM_ADD_YN = 'Y'	\n");
	    	search.setStatement(sqlstr.toString());
//	    	System.out.println(sqlstr);
			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 chk_same_item(Connection connection, ValueObject valueObject){
		Search search = new SearchImpl();
		RowSet rowSet = new RowSetImpl();
		ValueObject valueobject = null;
		StrBuffer sqlstr = new StrBuffer();
		try{
			sqlstr.append("SELECT MATERIAL_CD FROM CONT_PUR_ITEM WHERE     PUR_CONT_MOD_ID IN (SELECT PUR_CONT_MOD_ID FROM pur2000t WHERE dem_id = '"+valueObject.get("DEMANDED_ID")+"') AND ITEM_ADD_YN = 'Y'	\n");
	    	search.setStatement(sqlstr.toString());
//	    	System.out.println(sqlstr);
			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 chk_item_cnt2(Connection connection, ValueObject valueObject){
		Search search = new SearchImpl();
		RowSet rowSet = new RowSetImpl();
		ValueObject valueobject = null;
		StrBuffer sqlstr = new StrBuffer();
		try{
			sqlstr.append("	SELECT COUNT(*) AS CNT 																		\n");
			sqlstr.append("	FROM CONT_PUR_ITEM																		\n");
			sqlstr.append("	WHERE PUR_CONT_MOD_ID IN(SELECT PUR_CONT_MOD_ID FROM PUR2000T WHERE DEM_ID = '"+valueObject.get("DEMANDED_ID")+"' )		\n"); 
			sqlstr.append("	AND ITEM_ADD_YN = 'Y'																	\n");
	    	search.setStatement(sqlstr.toString());
//	    	System.out.println(sqlstr);
			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;
		}
    }

	public void addDemItemSave(Connection connection, ValueObject valueObject){
		Persistent persistent = new PersistentImpl(connection);
        StrBuffer sqlstr = new StrBuffer();
        try {
        	sqlstr.append("	INSERT INTO PMM_DEMANDED_ITEM(ITEM_SEQ, DEMANDED_ID, MATERIAL_CD, DEMANDED_QTY, CONT_PRI,DEMANDED_PRI, DEMANDED_AMT, SHIPPING_QTY, YM_REQU, NO_REQU,SQ_REQU,ITEM_ADD_YN)	\n");
        	sqlstr.append("   VALUES( PMM_DEMANDED_ITEM_S.NEXTVAL,?,?,1,0,1,1,1,		\n");
        	sqlstr.append("   		  (SELECT MAX(YM_REQU) FROM PMM_DEMANDED_ITEM WHERE DEMANDED_ID = ?),	\n");
        	sqlstr.append("   		  (SELECT MAX(NO_REQU) FROM PMM_DEMANDED_ITEM WHERE DEMANDED_ID = ?),	\n");
        	sqlstr.append("   		  (SELECT LPAD(TO_NUMBER(MAX(SQ_REQU))+1,3,0) FROM PMM_DEMANDED_ITEM WHERE DEMANDED_ID = ?),		\n");
        	sqlstr.append("   		  'Y'	)	\n");
            persistent.setStatement(sqlstr.toString());
            persistent.addParameter(valueObject.get("DEMANDED_ID"));
            persistent.addParameter(valueObject.get("MATERIAL_CD"));
            persistent.addParameter(valueObject.get("DEMANDED_ID"));
            persistent.addParameter(valueObject.get("DEMANDED_ID"));
            persistent.addParameter(valueObject.get("DEMANDED_ID"));
//            System.out.println(sqlstr);
            persistent.execute();
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> addDemItemSave() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
        }
    }
	
	public boolean addItemSave(Connection connection, ValueObject valueObject){
		Persistent persistent = new PersistentImpl(connection);
        StrBuffer sqlstr = new StrBuffer();
        try {
        	sqlstr.append("	INSERT INTO CONT_PUR_ITEM(PUR_CONT_MOD_ID, MATERIAL_CD, PUR_CONT_ID, ITEM_NAME, ITEM_UNIT,ITEM_QTY, ITEM_PRICE, ITEM_AMT, CRE_BY, CRE_DATE,ITEM_ADD_YN)	\n");
        	sqlstr.append("   VALUES(?,?,?,     	\n");
        	sqlstr.append("   (SELECT DETAILNM FROM EBID_COM911T WHERE BASECD = 'ADD_ITEM_CD' AND DETAILCD = ?),     	\n");
        	sqlstr.append("   '01',1,1,1,?,SYSDATE,'Y')     	\n");
            persistent.setStatement(sqlstr.toString());
            persistent.addParameter(valueObject.get("PUR_CONT_MOD_ID"));
            persistent.addParameter(valueObject.get("MATERIAL_CD"));
            persistent.addParameter(valueObject.get("PUR_CONT_ID"));
            persistent.addParameter(valueObject.get("MATERIAL_CD"));
            persistent.addParameter(valueObject.get("login_user"));
//            System.out.println(sqlstr);
            persistent.execute();
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> itemAddSave() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            return false;
        }
        return true;
    }
	
	public boolean addItemDel(Connection connection, ValueObject valueObject){
		Persistent persistent = new PersistentImpl(connection);
        StrBuffer sqlstr = new StrBuffer();
        try {
        	sqlstr.append("	DELETE CONT_PUR_ITEM												\n");
        	sqlstr.append("  WHERE PUR_CONT_MOD_ID = '"+valueObject.get("PUR_CONT_MOD_ID")+"'   \n");
        	sqlstr.append("    AND ITEM_ADD_YN ='Y'     										\n");
            persistent.setStatement(sqlstr.toString());
//            System.out.println(sqlstr);
            persistent.execute();
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> itemAddSave() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            return false;
        }
        return true;
    }
	
	public boolean addDemItemDel(Connection connection, ValueObject valueObject){
		Persistent persistent = new PersistentImpl(connection);
        StrBuffer sqlstr = new StrBuffer();
        try {
        	sqlstr.append("DELETE PMM_DEMANDED_ITEM									\n");
        	sqlstr.append("WHERE DEMANDED_ID = '"+valueObject.get("DEMANDED_ID")+"' \n");
        	sqlstr.append("AND ITEM_ADD_YN = 'Y'   									\n");
            persistent.setStatement(sqlstr.toString());
            persistent.execute();
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> addDemItemDel() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            return false;
        }
        return true;
    }
	
	/**
	 * 품목 리스트
	 * @param Params
	 * @return
	 * 
	 */
	private RowSet getContItemList(ValueObject ValueObject) {

		Search search = new SearchImpl();
        RowSet rowSet = new RowSetImpl();

        StrBuffer sqlstr = new StrBuffer();
        try{
        	sqlstr.append(" SELECT PUR_CONT_ID, PUR_CONT_MOD_ID, DEM_ID					\n");
        	sqlstr.append("   FROM PUR2000T												\n");
        	sqlstr.append(" WHERE PUR_CONT_MOD_ID = '"+params.get("PUR_CONT_MOD_ID")+"'	\n");
			search.setStatement(sqlstr.toString());
            rowSet = search.execute();
        }
        catch (WAFSQLException se) {
            super.doException(se);
            this.storage.setSuccess(false);
            this.storage.setMessage(se.getMessage());
            storage.setDetailMessage(se);
            WAFLogger.error("SQL : " + sqlstr);
        }
        finally {    
            if(rowSet == null){
            	rowSet = new RowSetImpl();
            }
        }
        //WAFLogger.debug("### rowSet size : " + rowSet.size());
        
        return rowSet;
	}
	
}


