package ibase.webitm.ejb.mfg.adv;
import java.util.*; 
import java.sql.*;
import java.rmi.RemoteException;
import java.text.*;
import javax.ejb.SessionContext;
import javax.ejb.CreateException;
//import javax.ejb.SessionBean;
import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.TransIDGenerator;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.dis.StockUpdate;
import ibase.webitm.ejb.fin.FinCommon;														  
import ibase.webitm.ejb.fin.FinCommonInvAcct;
import ibase.webitm.utility.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3
public class WOMultipRcpConf extends ActionHandlerEJB implements  WOMultipRcpConfLocal , WOMultipRcpConfRemote //SessionBean 
{
    /*public void ejbCreate() throws RemoteException,CreateException{    
    }
    public void ejbRemove(){
        
    }
    public void ejbActivate(){
        
    }
    public void ejbPassivate(){
        
    }*/
    public void setSessionContext(SessionContext se){
        
    }
    public String confirm(String tranID,String xtraParams, String forcedFlag) throws RemoteException,ITMException
    {
        Connection conn = null;
        PreparedStatement pstmt = null,pstmt1 = null;
        ResultSet rs = null,rs1 = null;
        String sql = "";
        ConnDriver connDriver = null;
        String rcpDimension = "";
        long rcpNoArt = 0;
        long stkNoArt = 0;
        java.sql.Timestamp stkRetestDate = null;
        String acctCodeDr = "",cctrCodeDr = "",acctCodeCr = "",cctrCodeCr = "",workOrder="";
        String itemSer = "",itemStru = "";
        String errString = "",backFlushType = "",unitAlt = "",siteCodeHdr =  "";
	    double quantity=0,quantity1=0,sumQuantity=0,QuantityWO=0,remQuantity=0;
        Timestamp tranDate = null;
        HashMap stkUpdMap = null,hm;
		String itemCodenew="",returnString="",item_type="",item_ser="",loc_type ="";
		String itemCode="",locCode="",lotNo="",lotSl="",lineNo="",unit="",rcpConfirm = "";
        ITMDBAccessEJB itmDBAccessEJB = null;
        ArrayList arrayList =new ArrayList();
        FinCommon finCommon = null;
        GenericUtility genericUtility = null;
        FinCommonInvAcct finCommonInvAcct = null;
		int count=0;
        try{
            finCommon = new FinCommon();
            finCommonInvAcct = new FinCommonInvAcct();
            itmDBAccessEJB = new ITMDBAccessEJB();
			genericUtility = GenericUtility.getInstance();
            stkUpdMap = new HashMap();
           
            connDriver = new ConnDriver();
            conn = connDriver.getConnectDB("Driver");
            conn.setAutoCommit(false);
            sql = "select confirmed,site_code,tran_date,work_order,quantity from workorder_receipt where tran_id = '"+tranID+"'";
            System.out.println("SQL : "+sql);
			pstmt =  conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
            if(rs.next())
			{
                rcpConfirm = rs.getString("confirmed");
                siteCodeHdr = rs.getString("site_code");
                tranDate = rs.getTimestamp("tran_date"); 
				workOrder = rs.getString("work_order");
				quantity1 = rs.getDouble("quantity");
            }
            rs.close();
			pstmt.close();
			count=0;
//			sql ="select count(*)  from workorder_receipt where work_order ='"+workOrder+"' and "
//				  +" confirmed ='Y' "; 
//				System.out.println("sql-------------"+sql);
//
//				pstmt =  conn.prepareStatement(sql);
//				rs = pstmt.executeQuery();
//				if(rs.next())
//				{
//					count=rs.getInt(1);
//					
//				}
//				rs.close();
//				pstmt.close();
//				System.out.println("count-------------"+count);
//				if(count != 0)
//				{
//					
//					errString = itmDBAccessEJB.getErrorString("","VTWOCONF","BASE");
//					return errString;
//				}

			sql ="select sum(quantity)  from workorder_receipt where work_order ='"+workOrder+"' and "
				  +" confirmed ='Y' "; 
				System.out.println("sql-------------"+sql);

				pstmt =  conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					sumQuantity=rs.getDouble(1);
					
				}
				rs.close();
				pstmt.close();
				System.out.println("sumQuantity-------------"+sumQuantity);

				sql ="select quantity  from workorder where work_order ='"+workOrder+"' " ;
				 
				System.out.println("sql-------------"+sql);

				pstmt =  conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					QuantityWO=rs.getDouble(1);
					
				}
				rs.close();
				pstmt.close();
				System.out.println("QuantityWO-------------"+QuantityWO);

				remQuantity=QuantityWO-sumQuantity;
				if(remQuantity < quantity1)
				{
					
					errString = itmDBAccessEJB.getErrorString("","VTWOQUTY","BASE");
					return errString;
				}


            if(rcpConfirm != null && rcpConfirm.trim().equalsIgnoreCase("Y"))
			{
                System.out.println("The Selected ransaction is already confirmed..........");
                errString = itmDBAccessEJB.getErrorString("","VTCONF8","","",conn);
                return errString;
            }
			
            String acctCodeHdr = "",cctrCodeHdr = "";
            sql = "select item_code,loc_code,lot_no,lot_sl,line_no,quantity,unit from workorder_rcp_det  "
			      +" where tran_id = '"+tranID+"'";
			System.out.println("  sql................"+sql);
			pstmt =  conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
            while(rs.next())
			{	 
				itemCode = rs.getString("item_code");
                locCode = rs.getString("loc_code");
                lotNo = rs.getString("lot_no");
                lotSl = rs.getString("lot_sl");
                lineNo = rs.getString("line_no");
				quantity =rs.getDouble("quantity");
				unit =rs.getString("unit");
               	sql = "select item_ser from item where item_code = '"+itemCode+"'";
				System.out.println("SQL : "+sql);
				pstmt =  conn.prepareStatement(sql);
				rs1 = pstmt.executeQuery();
				if(rs1.next())
				{
					itemSer = rs1.getString("item_ser");
				}
				rs1.close();
				String acctCodeInv="";
				String cctrCodeInv="";
				System.out.println("itemSer-------------"+itemSer);
				String acctDetrType = finCommon.getFromAcctDetr(itemCode,itemSer,"STKINV", conn) ;
				System.out.println("acctDetrType.....STKINV........" + acctDetrType);
				if (acctDetrType != null && acctDetrType.trim().length() > 0)
				{
					acctCodeInv = acctDetrType.substring(0,acctDetrType.indexOf(","));
					cctrCodeInv = acctDetrType.substring(acctDetrType.indexOf(",")+1);
				}
				System.out.println("acctStr.....STKINV........" + acctCodeInv);
				System.out.println("acctStr.....STKINV........" + cctrCodeInv);
				stkUpdMap.put("site_code",siteCodeHdr);
              	stkUpdMap.put("item_code",itemCode);
				stkUpdMap.put("loc_code",locCode);
				stkUpdMap.put("lot_no",lotNo);
                stkUpdMap.put("lot_sl",lotSl);
				stkUpdMap.put("unit",unit);
                stkUpdMap.put("quantity",Double.toString(quantity));
				stkUpdMap.put("qty_stduom",Double.toString(quantity));
				stkUpdMap.put("tran_type","R");
				stkUpdMap.put("tran_date",tranDate); 
				stkUpdMap.put("tran_ser","W-RCP");	 
				stkUpdMap.put("tran_id",tranID);
				stkUpdMap.put("line_no",lineNo);
				stkUpdMap.put("rate",Double.toString(0));
				stkUpdMap.put("gross_rate",Double.toString(0));
				stkUpdMap.put("sitecode_mfg",siteCodeHdr);
				stkUpdMap.put("potency_perc",Double.toString(0));
				stkUpdMap.put("mfg_date",tranDate);
				stkUpdMap.put("acct_code_inv",acctCodeInv);
				stkUpdMap.put("cctr_code_inv",cctrCodeInv);
				stkUpdMap.put("rate_oh",Double.toString(0));
				stkUpdMap.put("acct_code_oh",acctCodeInv);
				stkUpdMap.put("cctr_code_oh",cctrCodeInv);
				stkUpdMap.put("dimension"," ");
				stkUpdMap.put("no_art",Double.toString(1));
				stkUpdMap.put("grade","LOC");
				stkUpdMap.put("batch_no",lotNo);
				StockUpdate stkUpd =  new StockUpdate();
				errString = stkUpd.updateStock(stkUpdMap,xtraParams,conn);
				System.out.println("Returning Result "+errString);
				stkUpd =  null;
				stkUpdMap.clear();                   
            }//while end (Issue)
            rs.close();
			pstmt.close();
            stkUpdMap.clear();
            
            if(errString !=null && errString.indexOf("Error") != -1)
			{
                System.out.println("Returning Result "+errString);
                conn.rollback();
                return errString;
            } 
            System.out.println("errString : "+errString);
	
                String empCodeAprv = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
                sql = "update workorder_receipt set confirmed = 'Y',conf_date = ? ,emp_code__aprv = ? where tran_id = '"+tranID+"' ";
                System.out.println("SQL : "+sql);
                pstmt = conn.prepareStatement(sql);
                pstmt.setTimestamp(1,new Timestamp(System.currentTimeMillis()));
                pstmt.setString(2,empCodeAprv);
                int upd = pstmt.executeUpdate();
                System.out.println("Receipt  Multi Confirm :: "+upd);
                if(upd > 0)
				{
                    conn.commit();
                    errString = itmDBAccessEJB.getErrorString("","VTDIST30","");
                    System.out.println("Receipt Multi Confirmed .."+errString);
                }
        }catch(ITMException ie)
		{
            System.out.println("ITMException : "+ie);
            try{conn.rollback();}catch(Exception t){}
            ie.printStackTrace();
            errString = itmDBAccessEJB.getErrorString("","VTDESNCONF","","",conn);
            System.out.println("Returnng String From RcpBackflushMultiConf :"+errString);
            return errString;
        }catch(Exception e){
            System.out.println("Exception in Confirm [RcpBackflushConfEJB]"+e);
            try{conn.rollback();}catch(Exception t){}
            e.printStackTrace();
            errString = itmDBAccessEJB.getErrorString("","VTDESNCONF","","",conn);
            System.out.println("Returnng String From RcpBackflushMultiConf :"+errString);
            return errString;
        }
		finally
		{
            try{
                stkUpdMap = null;
                if(rs != null){rs.close();rs = null;}
                if(rs1 != null){rs1.close();rs1 = null;}
				if(conn != null)
				{
					conn = null;
				}  
            }catch(Exception e){System.out.println("Exception : "+e);e.printStackTrace();}
        }
        System.out.println("Returnng String From RcpBackflushMultiConf :"+errString);
        return errString;
	}
}
	
