package ibase.webitm.ejb.dis;

import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.BaseLogger;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.fin.*;
import ibase.webitm.ejb.mfg.MfgCommon;
import ibase.utility.E12GenericUtility;
import ibase.utility.UserInfoBean;
import ibase.webitm.utility.ITMException;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.rmi.RemoteException;
import java.sql.*;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.naming.InitialContext;

import org.w3c.dom.*;




public class ReqForQuotationWiz extends ValidatorEJB{
	static int domID = 1;

	@Override
	public String itemChanged() throws RemoteException, ITMException
	{
		BaseLogger.log("3", getUserInfo(), null,"In ReqForQuotationWiz itemChanged1");
		

		return "";
	}


	public String wfValData(String xmlString, String xmlString1,String xmlString2, String objContext, String editFlag, String xtraParams, String formName) throws RemoteException,ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errString = "";
		try
		{
			System.out.println("wfValData DOM1:StrgBrandActWiz ["+xmlString+"]");
			System.out.println("wfValData DOM2:StrgBrandActWiz ["+xmlString1+"]");
			System.out.println("wfValData DOM3:StrgBrandActWiz ["+xmlString2+"]");
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				dom = parseString(xmlString);
			}
			else
			{
				System.out.println("xmlstring is null StrgBrandActWiz Validation");
			}
			if(xmlString1 != null && xmlString1.trim().length()!=0)
			{
				dom1 = parseString(xmlString1);
			}
			else
			{
				System.out.println("xmlstring1 is null StrgBrandActWiz Validation");
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				dom2 = parseString(xmlString2);
			}
			else
			{
				System.out.println("xmlstring2 is null StrgBrandActWiz Validation");
			}
			System.out.println("Before call valdata StrgBrandActWiz");
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams,formName);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [StrgBrandActWiz Validation][wfValData(String xmlString)] : ==>\n"+e.getMessage());
		}
		return (errString);
	}
	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams, String formName) throws RemoteException,ITMException
	{
		E12GenericUtility genericUtility = new ibase.utility.E12GenericUtility();

		String userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
		String logincode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
		String errString = "";

		int currentFormNo = 0;
		
		NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = "";
		String columnValue = "";
		Connection connectionObject = null;
		PreparedStatement pstmt = null;
		ResultSet rSet = null ;
		ResultSet rs = null ;

		String propDateValue = "";
		int firstMonth = 01;
		int lastMonth = 12;
		ITMDBAccessEJB itmDBAccessLocal = null;
		int noOfChilds = 0;
		ArrayList prdList = new ArrayList();
		String paramValue="";
		
		try
		{
			connectionObject = getConnection();
			AppConnectParm appConnect = new AppConnectParm();
			Properties p = appConnect.getProperty();
			itmDBAccessLocal = new ITMDBAccessEJB();
			String sql="";
			
			System.out.println("wfValData objContext StrgBrandActWiz::  ["+objContext+"]");
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			switch ( currentFormNo )
			{
			
			
			case 1:
			{
				if( errString.indexOf( "<Errors>" ) == -1 )
				{
					parentList = dom.getElementsByTagName("Detail"+ currentFormNo);
					int parentNodeListLength = parentList.getLength();
					for (int prntCtr = 0; prntCtr < parentNodeListLength; prntCtr++ )
					{
						parentNode = parentList.item(prntCtr);
						childList = parentNode.getChildNodes();
						noOfChilds = childList.getLength();
						for (int ctr = 0; ctr < noOfChilds; ctr++)
						{
							childNode = childList.item(ctr);
							if( childNode.getNodeType() != Node.ELEMENT_NODE )
							{
								continue;
							}

							if ( childNode != null && childNode.getFirstChild() != null )
							{
								columnValue = childNode.getFirstChild().getNodeValue();
							}
							childNodeName = childNode.getNodeName();
							BaseLogger.log("3", null, null, "ReqForQuotationWiz childNodeName [" + childNodeName + "]");

							if( childNodeName.equalsIgnoreCase("cust_code") )
							{
								String custCode = checkNull(genericUtility.getColumnValue("cust_code", dom));
								BaseLogger.log("3", null, null, "ReqForQuotationWiz custCode wfValData case 1 [" + custCode + "]");
								String checkCustCodeSql = "select count(cust_code) as custCodeCount from customer where cust_code = ?";
								PreparedStatement checkCustCodePs = connectionObject.prepareStatement(checkCustCodeSql);
								checkCustCodePs.setString(1, custCode);
								ResultSet checkCustCodeRs = checkCustCodePs.executeQuery();
								while(checkCustCodeRs.next()) {
									int custCodeCont = checkCustCodeRs.getInt("custCodeCount");
									BaseLogger.log("3", null, null, "ReqForQuotationWiz custCode wfValData case 1 custCodeCont::[" + custCodeCont + "]");
	                                if(custCodeCont<=0) {
								        errString = getErrorString("cust_code", "VTCUST1", userId);
								        break;
	                                }
									
								}
								if(checkCustCodeRs != null)
								{
									checkCustCodeRs.close();
									checkCustCodeRs = null;
								}
								if(checkCustCodePs != null)
								{
									checkCustCodePs.close();
									checkCustCodePs = null;
								}
							}
							
							if( childNodeName.equalsIgnoreCase("site_code") )
							{
								String siteCode = checkNull(genericUtility.getColumnValue("site_code", dom));
								BaseLogger.log("3", null, null, "ReqForQuotationWiz siteCode wfValData case 1 [" + siteCode + "]");
								String checkSiteCodeSql = "select count(site_code) as siteCodeCount from site where site_code = ?";
								PreparedStatement checkSiteCodePs = connectionObject.prepareStatement(checkSiteCodeSql);
								checkSiteCodePs.setString(1, siteCode);
								ResultSet checkSiteCodeRs = checkSiteCodePs.executeQuery();
								while(checkSiteCodeRs.next()) {
									int siteCodeCont = checkSiteCodeRs.getInt("siteCodeCount");
									BaseLogger.log("3", null, null, "ReqForQuotationWiz siteCode wfValData case 1 siteCodeCont::[" + siteCodeCont + "]");
	                                if(siteCodeCont<=0) {
								        errString = getErrorString("site_code", "VTSITCD1", userId);
								        break;
	                                }
									
								}
								if(checkSiteCodeRs != null)
								{
									checkSiteCodeRs.close();
									checkSiteCodeRs = null;
								}
								if(checkSiteCodePs != null)
								{
									checkSiteCodePs.close();
									checkSiteCodePs = null;
								}
							}
							
							
							if( childNodeName.equalsIgnoreCase("item_ser") )
							{
								String itemSerStr = checkNull(genericUtility.getColumnValue("item_ser", dom));
								BaseLogger.log("3", null, null, "ReqForQuotationWiz itemSerStr wfValData case 1 [" + itemSerStr + "]");
								   if (itemSerStr != null && itemSerStr.length() > 0) {
			                            String[] itemSerArr = itemSerStr.split(",");
			                            for (String itemSer : itemSerArr) {
			    							BaseLogger.log("3", null, null, "ReqForQuotationWiz item_ser wfValData case 1 itemSer [" + itemSer + "]");

			                                sql = "SELECT count(1) FROM itemser WHERE item_ser = ?";
			                                pstmt = connectionObject.prepareStatement(sql);
			                                pstmt.setString(1, itemSer.trim());
			                                rs = pstmt.executeQuery();
			                                long count = 0;
			                                if (rs.next()) {
			                                    count = rs.getLong(1);
			                                }
			                                rs.close();
			                                rs = null;
			                                pstmt.close();
			                                pstmt = null;
			                                if (count == 0) {
										        errString = getErrorString("item_ser", "VTITEMSER1", userId);
			                                    break;
			                                }
			                                
			                            }
			                        }

									if(pstmt != null)
									{
										pstmt.close();
										pstmt = null;
									}
									if(rs != null)
									{
										rs.close();
										rs = null;
									}
							}
							
						}//end of inner for loop
					}//end of first for loop
				}
				break;
			}
				case 2:
				{
				if( errString.indexOf( "<Errors>" ) == -1 )
				{
					parentList = dom.getElementsByTagName("Detail"+ currentFormNo);
					int parentNodeListLength = parentList.getLength();
					for (int prntCtr = 0; prntCtr < parentNodeListLength; prntCtr++ )
					{
						parentNode = parentList.item(prntCtr);
						childList = parentNode.getChildNodes();
						noOfChilds = childList.getLength();
						for (int ctr = 0; ctr < noOfChilds; ctr++)
						{
							childNode = childList.item(ctr);
							if( childNode.getNodeType() != Node.ELEMENT_NODE )
							{
								continue;
							}

							if ( childNode != null && childNode.getFirstChild() != null )
							{
								columnValue = childNode.getFirstChild().getNodeValue();
							}
							childNodeName = childNode.getNodeName();
							BaseLogger.log("3", null, null, "ReqForQuotationWiz childNodeName [" + childNodeName + "]");

							if( childNodeName.equalsIgnoreCase("item_code") )
							{
								String itemCode = checkNull(genericUtility.getColumnValue("item_code", dom));
								BaseLogger.log("3", null, null, "ReqForQuotationWiz itemCode wfValData case 1 [" + itemCode + "]");
								String checkItemCodeSql = "select count(item_code) as itemCodeCount from item where cust_code = ?";
								PreparedStatement checkItemCodePs = connectionObject.prepareStatement(checkItemCodeSql);
								checkItemCodePs.setString(1, itemCode);
								ResultSet checkItemCodeRs = checkItemCodePs.executeQuery();
								while(checkItemCodeRs.next()) {
									int itemCodeCont = checkItemCodeRs.getInt("itemCodeCount");
									BaseLogger.log("3", null, null, "ReqForQuotationWiz itemCode wfValData case 1 itemCodeCont::[" + itemCodeCont + "]");
	                                if(itemCodeCont<=0) {
								        errString = getErrorString("item_code", "STKVALITNE", userId);
								        break;
	                                }
									
								}
								if(checkItemCodeRs != null)
								{
									checkItemCodeRs.close();
									checkItemCodeRs = null;
								}
								if(checkItemCodePs != null)
								{
									checkItemCodePs.close();
									checkItemCodePs = null;
								}
							}
							
							
							if( childNodeName.equalsIgnoreCase("ptr_flag") )
							{
								String ptrFlag = checkNull(genericUtility.getColumnValue("ptr_flag", dom));
								String competitorRate = checkNull(genericUtility.getColumnValue("competitor_rate", dom));
								String competitorItem = checkNull(genericUtility.getColumnValue("competitor_item", dom));
								String competitorName = checkNull(genericUtility.getColumnValue("competitor_name", dom));
								BaseLogger.log("3", null, null, "ReqForQuotationWiz ptrFlag wfValData [" + ptrFlag + "]");
								BaseLogger.log("3", null, null, "ReqForQuotationWiz competitorRate wfValData [" + competitorRate + "]");
								BaseLogger.log("3", null, null, "ReqForQuotationWiz competitorItem wfValData [" + competitorItem + "]");
								BaseLogger.log("3", null, null, "ReqForQuotationWiz competitorNane wfValData [" + competitorName + "]");


								if (ptrFlag.equalsIgnoreCase("N") || ptrFlag.trim().isEmpty()) {
								    BaseLogger.log("3", null, null, "ReqForQuotationWiz in condition ptrFlag wfValData::: [" + ptrFlag + "]");

								    // Check if any of the competitor fields are null or blank
								    if ((competitorRate == null || competitorRate.trim().isEmpty()) 
								            || (competitorItem == null || competitorItem.trim().isEmpty()) 
								            || (competitorName == null || competitorName.trim().isEmpty())) { 
								        BaseLogger.log("3", null, null, "ReqForQuotationWiz in competitor details null [" + ptrFlag + "]");
								        errString = getErrorString("ptr_flag", "COMPDETM", userId);
								        BaseLogger.log("3", null, null, "ReqForQuotationWiz in competitor details null errString:: [" + errString + "]");
								        break;
								    }
								}

							}//end of Sales_pers Validation
						}//end of inner for loop
					}//end of first for loop
				}//end of errorstring
				break;
			}
		}//end of validation of first form
			
		}//end of Try block wfvalData
		catch(Exception e)
		{
			e.printStackTrace();
			errString = "";
			errString = genericUtility.createErrorString( e ) ;
			String messageValue="",message = "";

			if( errString.indexOf("<Errors>")!=-1 )
			{
				if( errString.length() > 0 )
				{
					String msgDescr = errString.substring(errString.indexOf("<description>")+("<description>").length(),errString.indexOf("</description>"));
					messageValue = msgDescr.substring(msgDescr.indexOf("<![CDATA[")+("<![CDATA[").length(),msgDescr.indexOf("]"));
					String messageDescr = errString.substring(errString.indexOf("<message>")+("<message>").length(),errString.indexOf("</message>"));
					message = messageDescr.substring(messageDescr.indexOf("<![CDATA[")+("<![CDATA[").length(),messageDescr.indexOf("]"));

					System.out.println("errorMessage==>"+messageValue);
					StringBuffer valueXmlErrorString = new StringBuffer( "<?xmlversion=\"1.0\"?>\r\n<Root>\r\n<Header>\r\n<Errors>\r\n" );
					valueXmlErrorString.append("<error id=\"INVDATA\" type=\"E\" column_name=\"\">");
					valueXmlErrorString.append("<message><![CDATA[").append(message).append("]]></message>\r\n");
					valueXmlErrorString.append("<description><![CDATA[").append(messageValue).append("]]></description>\r\n");
					valueXmlErrorString.append("<type>E</type>\r\n");
					valueXmlErrorString.append("<option></option>\r\n");
					valueXmlErrorString.append("<time></time>\r\n");
					valueXmlErrorString.append("<alarm></alarm>\r\n");
					valueXmlErrorString.append("<source></source>\r\n");
					valueXmlErrorString.append("<trace>Error : NO DATA</trace>\r\n");
					valueXmlErrorString.append("<redirect>1</redirect>\r\n");
					valueXmlErrorString.append("</error>\r\n");
					valueXmlErrorString.append("</Errors>\r\n");
					valueXmlErrorString.append("</Header>\r\n");
					valueXmlErrorString.append( "</Root>\r\n" );
					System.out.println( "\n****valueXmlErrorString :" + valueXmlErrorString.toString() + ":********" );
					errString =valueXmlErrorString.toString();
				}

			}
		}//end of catch after try in wfvaldata
		finally
		{

			try
			{
				
				if(rSet !=null)
				{
					rSet.close();
					rSet = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if( connectionObject != null && ! connectionObject.isClosed() )
				{
					connectionObject.close();
					connectionObject = null;
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception  :StrgBrandActWiz wfvalData :==>\n"+e.getMessage());
				errString = "";
				errString = genericUtility.createErrorString( e ) ;
				System.out.println( "errString ::" +errString + ":" );
				String messageValue="",message = "";

				if( errString.indexOf("<Errors>")!=-1 )
				{
					if( errString.length() > 0 )
					{
						String msgDescr = errString.substring(errString.indexOf("<description>")+("<description>").length(),errString.indexOf("</description>"));
						messageValue = msgDescr.substring(msgDescr.indexOf("<![CDATA[")+("<![CDATA[").length(),msgDescr.indexOf("]"));
						String messageDescr = errString.substring(errString.indexOf("<message>")+("<message>").length(),errString.indexOf("</message>"));
						message = messageDescr.substring(messageDescr.indexOf("<![CDATA[")+("<![CDATA[").length(),messageDescr.indexOf("]"));

						System.out.println("errorMessage==>"+messageValue);
						StringBuffer valueXmlErrorString = new StringBuffer( "<?xmlversion=\"1.0\"?>\r\n<Root>\r\n<Header>\r\n<Errors>\r\n" );
						valueXmlErrorString.append("<error id=\"INVDATA\" type=\"E\" column_name=\"\">");
						valueXmlErrorString.append("<message><![CDATA[").append(message).append("]]></message>\r\n");
						valueXmlErrorString.append("<description><![CDATA[").append(messageValue).append("]]></description>\r\n");
						valueXmlErrorString.append("<type>E</type>\r\n");
						valueXmlErrorString.append("<option></option>\r\n");
						valueXmlErrorString.append("<time></time>\r\n");
						valueXmlErrorString.append("<alarm></alarm>\r\n");
						valueXmlErrorString.append("<source></source>\r\n");
						valueXmlErrorString.append("<trace>Error : NO DATA</trace>\r\n");
						valueXmlErrorString.append("<redirect>1</redirect>\r\n");
						valueXmlErrorString.append("</error>\r\n");
						valueXmlErrorString.append("</Errors>\r\n");
						valueXmlErrorString.append("</Header>\r\n");
						valueXmlErrorString.append( "</Root>\r\n" );
						System.out.println( "\n****valueXmlErrorString :" + valueXmlErrorString.toString() + ":********" );
						errString =valueXmlErrorString.toString();

					}
				}
			}
		}//end of finally block of wfvalData
		System.out.println("errString wfvalData ["+errString+"]");
		return errString;
	}//End WfValData
	
	@Override
	public String itemChanged(String xmlCurrFrmString, String xmlHdrFrmString, String xmlAllFrmString, String objContext, String currentColumn, String editFlag, String xtraParams, String formName) throws RemoteException, ITMException
	{
		BaseLogger.log("3", getUserInfo(), null,"In ReqForQuotationWiz itemChanged2");
		BaseLogger.log("3", getUserInfo(), null,"DEBUG currentColumn RAW = [" + currentColumn + "]");
		BaseLogger.log("3", getUserInfo(), null,"DEBUG currentColumn trimmed = [" + 
		    (currentColumn == null ? "null" : currentColumn.trim()) + "]");
		BaseLogger.log("3", getUserInfo(), null,"DEBUG currentColumn length = " + 
		    (currentColumn == null ? 0 : currentColumn.length()));
		Document currDom = null;
		Document hdrDom = null;
		Document allDom = null;

		String errString = null;

		E12GenericUtility genericUtility = new E12GenericUtility();

		try
		{
			if (xmlCurrFrmString != null && xmlCurrFrmString.trim().length()!=0)
			{
				currDom = genericUtility.parseString(xmlCurrFrmString); 
			}
			if (xmlHdrFrmString != null && xmlHdrFrmString.trim().length()!=0)
			{
				hdrDom = genericUtility.parseString(xmlHdrFrmString); 
			}
			if (xmlAllFrmString != null && xmlAllFrmString.trim().length()!=0)
			{
				allDom = genericUtility.parseString(xmlAllFrmString); 
			}
			System.out.println("xmlCurrFrmString--------"+xmlCurrFrmString);
			System.out.println("xmlHdrFrmString--------"+xmlHdrFrmString);
			System.out.println("xmlAllFrmString--------"+xmlAllFrmString);
			errString = itemChanged( currDom, hdrDom, allDom, objContext, currentColumn, editFlag, xtraParams, formName );
			System.out.println ( "ErrString :" + errString);
		}
		catch (Exception e)
		{
			System.out.println ( "Exception : QCResultEntryWizIC:default_ItemChanged(String,String):" + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
			throw new ITMException(e);
		}
		System.out.println ( "returning from QCResultEntryWizIC default_Itemchanged" );
		return errString;
	}	




//	public String itemChanged( Document currDom, Document hdrDom, Document allDom, String objContext, String currentColumn, String editFlag, String xtraParams ) throws RemoteException,ITMException
//	{
//		BaseLogger.log("3", getUserInfo(), null,"In ReqForQuotationWiz itemChanged3");
//		BaseLogger.log("3", getUserInfo(), null,"DEBUG currentColumn RAW = [" + currentColumn + "]");
//		BaseLogger.log("3", getUserInfo(), null,"DEBUG currentColumn trimmed = [" + 
//		    (currentColumn == null ? "null" : currentColumn.trim()) + "]");
//		BaseLogger.log("3", getUserInfo(), null,"DEBUG currentColumn length = " + 
//		    (currentColumn == null ? 0 : currentColumn.length()));
//		String retValue = "";
//		try
//		{
//			retValue = default_ItemChanged( currDom, hdrDom, allDom,  objContext, currentColumn, editFlag, xtraParams );
//		} 
//		catch (Exception e) 
//		{
//			e.printStackTrace();
//			throw new ITMException(e);
//		}
//		return retValue;
//
//	}	
	
	public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams, String formName) throws RemoteException,ITMException
	{
		String returnStr="";
		try
		{

			returnStr = defaultDataWiz(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams, formName);
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return returnStr;
	}
	

	private String defaultDataWiz( Document dom, Document dom1, Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams, String formName  ) throws RemoteException,ITMException
	{

		
		ResultSet rs = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		PreparedStatement psSiteCustomer = null;
		PreparedStatement psCustomer = null;
		PreparedStatement psPriceList = null;
		PreparedStatement psFinEntity = null;
		String sql = "";
		String userId = "";
		String currDate = "";
		String chgTerm ="";
		String priceList = "";
		int rate= 0;
		String finEntity = "";
		String propDateValue = "";
		String [] temp = new String [10];
		StringBuffer valueXmlString = new StringBuffer();
		int currentFormNo = 0;
		List<String> itemCodeList = new ArrayList<>();
		E12GenericUtility genericUtility = new ibase.utility.E12GenericUtility();
		try
		{
			
			InetAddress ownIP=InetAddress.getLocalHost();
			chgTerm = ownIP.getHostAddress();
			conn = getConnection();
			 UserInfoBean userInfo = getUserInfo(); 

			String siteCode = checkNull(userInfo.getSiteCode());
			userId = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" );
			BaseLogger.log("0", null,userId,"case 1---------itemDefault------gsb start");
			BaseLogger.log("0", null,userId,"defaultDataWiz siteCode: "+siteCode);

			DateFormat dtFormat = new SimpleDateFormat(getApplDateFormat());
			java.util.Date date = Calendar.getInstance().getTime();
			currDate = dtFormat.format( date );
			
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.MONTH, -1);
			Date result = cal.getTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			
			String prevPrd = String.valueOf(sdf.format(result));	
			String curPrd = String.valueOf(sdf.format(date));
			String curDate = curPrd.substring(curPrd.length()-2,curPrd.length());
			prevPrd = prevPrd.substring(0,prevPrd.length()-2);	
			curPrd = curPrd.substring(0,curPrd.length()-2);
			System.out.println("previous Period....::"+prevPrd+"....current Prd code....::"+curPrd+"...current Date...::"+curDate);

			if( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}
			valueXmlString = new StringBuffer( "<?xml version=\"1.0\"?>\r\n<Root>\r\n<Header>\r\n<editFlag>" );
			valueXmlString.append( editFlag ).append( "</editFlag>\r\n</Header>\r\n<Errors>\r\n</Errors>\r\n" );
			
			switch(currentFormNo){
				case 1:
				if( currentColumn.equalsIgnoreCase( "itm_default" ))
				{

					BaseLogger.log("0", null,userId,"case 1---------itemDefault------gsb-----");

					valueXmlString.append( "<Detail"+ objContext+" domID='"+ 1 +"' objContext = '"+currentFormNo+"' objName=\"qc_resentry_wiz\" selected=\"N\">\r\n" );
					valueXmlString.append( "<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"tran_id\"/>\r\n" );
					valueXmlString.append( "<tran_id/>" );
					valueXmlString.append("<tran_date protect = '1'>").append("<![CDATA[" + currDate + "]]>").append("</tran_date>");
					valueXmlString.append("</Detail"+objContext+">");

				}//end of itmdefault case1
				if (currentColumn.equalsIgnoreCase( "item_ser" )) 
				{
				    String itemSerDescr = "";
				    String itemSerForIC = checkNull(genericUtility.getColumnValue("item_ser", dom, "1"));

				    BaseLogger.log("0", null, userId, "case 1::: item_ser");
				    System.out.println("case 1---------itemSerForIC05M------[" + itemSerForIC + "]");

				    if(itemSerForIC != null && itemSerForIC.trim().length() > 0)
				    {
				        String[] itemSerArr = itemSerForIC.split(",");

				        String itemSerSql = "select descr from itemser where item_ser = ?";
				        
				        try (PreparedStatement itemSerPs = conn.prepareStatement(itemSerSql))
				        {
				            for(String itemSer : itemSerArr)
				            {
				                itemSerPs.setString(1, itemSer.trim());

				                try (ResultSet itemSerRs = itemSerPs.executeQuery())
				                {
				                    if(itemSerRs.next())
				                    {
				                        if(itemSerDescr.length() > 0)
				                        {
				                            itemSerDescr += ", ";
				                        }
				                        itemSerDescr += checkNull(itemSerRs.getString("descr"));
				                    }
				                }
				            }
				        }
				    }

				    valueXmlString.append("<descr><![CDATA[" + itemSerDescr + "]]></descr>\n");
				}
				
                      if (currentColumn.equalsIgnoreCase( "cust_code" )) {

					
					BaseLogger.log("0", null,userId,"case 1---------custCodeForIC::------]");

					String custCodeForIC = checkNull(genericUtility.getColumnValue("cust_code",dom,"1"));

					String custName = "",addr1="", addr2="", addr3="";
					BaseLogger.log("0", null,userId,"case 1---------custCodeForIC------[" +custCodeForIC + "]");



					String custNameSql = "select cust_name, addr1 , addr2 , addr3 from customer where cust_code = ?";
					PreparedStatement custNamePs = conn.prepareStatement(custNameSql);
					custNamePs.setString(1, custCodeForIC);
					ResultSet custNameRs = custNamePs.executeQuery();
					while(custNameRs.next()) {
						custName = custNameRs.getString("cust_name");
						addr1 = custNameRs.getString("addr1");
						addr2 = custNameRs.getString("addr2");
						addr3 = custNameRs.getString("addr3");

					}
					valueXmlString.append( "<Detail"+ objContext+" domID='"+ 1 +"' objContext = '"+currentFormNo+"' objName=\"qc_resentry_wiz\" selected=\"N\">\r\n" );
					valueXmlString.append( "<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"tran_id\"/>\r\n" );
					valueXmlString.append("<cust_name>").append("<![CDATA[" + custName + "]]>").append("</cust_name>");
					valueXmlString.append("<addr1>").append("<![CDATA[" + addr1 + "]]>").append("</addr1>");
					valueXmlString.append("<addr2>").append("<![CDATA[" + addr2 + "]]>").append("</addr2>");
					valueXmlString.append("<addr3>").append("<![CDATA[" + addr3 + "]]>").append("</addr3>");
					valueXmlString.append("</Detail"+objContext+">");

					if (custNameRs != null)
					{
						custNameRs.close();
						custNameRs = null;
					}
					if (custNamePs != null)
					{
						custNamePs.close();
						custNamePs = null;
					}
				
				}
                      break;
                      
                      
				case 2:
					if ("itm_default".equalsIgnoreCase(currentColumn.trim())) {
						int domId = 0;
						int lineNo = 0;
						String custCode = checkNull(genericUtility.getColumnValue("cust_code", dom1));
						String itemSer = checkNull(genericUtility.getColumnValue("item_ser",dom1,"1"));
						BaseLogger.log("3", null, null, "ReqForQuotationWiz in itm default ");
						//Management rate block[Start]
						String finEntityQuery = "select fin_entity from site where site_code = ?";
						psFinEntity = conn.prepareStatement(finEntityQuery);
						psFinEntity.setString(1, siteCode);
						rs = psFinEntity.executeQuery();
						if(rs.next()) {
							finEntity = checkNull(rs.getString("fin_entity"));
						}
						BaseLogger.log("3", null, null, "ReqForQuotationWiz in itm default finEntity:: "+finEntity);

						rs.close();
						psFinEntity.close();
						
						// Now, use finEntity to fetch VAR_VALUE from finparm
						String varValueQuery = "select VAR_VALUE from finparm where ADDL_VALUE = ?";
						PreparedStatement psVarValue = conn.prepareStatement(varValueQuery);
						psVarValue.setString(1, finEntity);
						ResultSet rsVarValue = psVarValue.executeQuery();
						String varValue = null;
						if (rsVarValue.next()) {
						    varValue = checkNull(rsVarValue.getString("VAR_VALUE"));
						}
						BaseLogger.log("3", null, null, "ReqForQuotationWiz in itm default varValue:: " + varValue);

						// Clean up the result set and prepared statement for the varValue query
						rsVarValue.close();
						psVarValue.close();

						// Finally, use varValue to fetch the rate from pricelist
						String rateQuery = "select rate from pricelist where price_list = ?";
						PreparedStatement psRate = conn.prepareStatement(rateQuery);
						psRate.setString(1, varValue);
						ResultSet rsRate = psRate.executeQuery();
						int MngmntAprvRate = 0;
						if (rsRate.next()) {
							MngmntAprvRate = rsRate.getInt("rate");
						}
						BaseLogger.log("3", null, null, "ReqForQuotationWiz in itm default MngmntAprvRate:: " + MngmntAprvRate);

						// Clean up the result set and prepared statement for the rate query
						rsRate.close();
						psRate.close();
						
						
						int pts = 0;
						int ptd = 0;

						/* Fetch PTS */
						String ptsSql = 
						        "SELECT pl.rate " +
						        "FROM pricelist pl " +
						        "WHERE pl.price_list = ( " +
						        "   SELECT fp.var_value " +
						        "   FROM finparm fp " +
						        "   WHERE fp.var_name = 'RFQ_PTS' " +
						        "   AND fp.addl_value = (SELECT fin_entity FROM site WHERE site_code = ?) " +
						        ")";

						PreparedStatement psPts = conn.prepareStatement(ptsSql);
						psPts.setString(1, siteCode);
						ResultSet rsPts = psPts.executeQuery();

						if (rsPts.next()) {
						    BigDecimal ptsRate = rsPts.getBigDecimal("rate");
						    pts = (ptsRate != null) ? ptsRate.intValue() : 0;
						}


						/* Fetch PTD */
						String ptdSql = 
						        "SELECT pl.rate " +
						        "FROM pricelist pl " +
						        "WHERE pl.price_list = ( " +
						        "   SELECT fp.var_value " +
						        "   FROM finparm fp " +
						        "   WHERE fp.var_name = 'RFQ_PTD' " +
						        "   AND fp.addl_value = (SELECT fin_entity FROM site WHERE site_code = ?) " +
						        ")";

						PreparedStatement psPtd = conn.prepareStatement(ptdSql);
						psPtd.setString(1, siteCode);
						ResultSet rsPtd = psPtd.executeQuery();

						if (rsPtd.next()) {
						    BigDecimal ptdRate = rsPtd.getBigDecimal("rate");
						    ptd = (ptdRate != null) ? ptdRate.intValue() : 0;
						}

						BaseLogger.log("3", null, null,
						        "ReqForQuotationWiz in itm default pts:: " + pts + " ptd:: " + ptd);

						//PTR calculation start
					    String siteCustomerQuery = 
						        "SELECT PRICE_LIST FROM SITE_CUSTOMER " +
						        "WHERE SITE_CODE = ? AND CUST_CODE = ?";

						    psSiteCustomer = conn.prepareStatement(siteCustomerQuery);
						    psSiteCustomer.setString(1, siteCode);
						    psSiteCustomer.setString(2, custCode);

						    rs = psSiteCustomer.executeQuery();

						    if (rs.next()) {
						        priceList = rs.getString("PRICE_LIST");
						    }

						    rs.close();
						    psSiteCustomer.close();

						    // Step 2: If not found in SITE_CUSTOMER, fetch from CUSTOMER
						    if (priceList == null || priceList.trim().isEmpty()) {

						        String customerQuery =
						            "SELECT PRICE_LIST FROM CUSTOMER WHERE CUST_CODE = ?";

						        psCustomer = conn.prepareStatement(customerQuery);
						        psCustomer.setString(1, custCode);

						        rs = psCustomer.executeQuery();

						        if (rs.next()) {
						            priceList = rs.getString("PRICE_LIST");
						        }

						        rs.close();
						        psCustomer.close();
						    }

						    // Step 3: Fetch RATE from PRICELIST table
						    if (priceList != null && !priceList.trim().isEmpty()) {

						        String priceListQuery =
						            "SELECT RATE FROM PRICELIST WHERE PRICE_LIST = ?";

						        psPriceList = conn.prepareStatement(priceListQuery);
						        psPriceList.setString(1, priceList);

						        rs = psPriceList.executeQuery();

						        if (rs.next()) {
						            rate = rs.getInt("RATE");
						        }

						        rs.close();
						        psPriceList.close();
						    }
							BaseLogger.log("3", null, null, "ReqForQuotationWiz in itm default ptr:: " + rate);

						    if(itemSer != null && itemSer.trim().length() > 0)
							{
							    String[] itemSerArr = itemSer.split(",");

							    // Build dynamic IN clause
							    StringBuilder sqlForItemCode = new StringBuilder();
							    sqlForItemCode.append("SELECT item_code FROM item WHERE item_ser IN (");

							    for(int i = 0; i < itemSerArr.length; i++)
							    {
							    	sqlForItemCode.append("?");
							        if(i < itemSerArr.length - 1)
							        {
							        	sqlForItemCode.append(",");
							        }
							    }
							    sqlForItemCode.append(")");

							    PreparedStatement ItemCodesPs = conn.prepareStatement(sqlForItemCode.toString());

							    // Bind values
							    for(int i = 0; i < itemSerArr.length; i++)
							    {
							    	ItemCodesPs.setString(i + 1, itemSerArr[i].trim());
							    }

							     rs = ItemCodesPs.executeQuery();

							    while(rs.next())
							    {
							        itemCodeList.add(rs.getString("item_code"));
							    }

							    rs.close();
							    ItemCodesPs.close();
							}
						    
						    
						    for (String itemCode : itemCodeList)
							{
								domId++;
								lineNo++;
							    System.out.println("Item Code: " + itemCode);
							    valueXmlString.append( "<Detail"+ objContext+" domID='"+domId  +"' objContext = '"+currentFormNo+"' objName=\"rfq_wiz\" selected=\"N\">\r\n" );
								valueXmlString.append( "<attribute selected=\"Y\" updateFlag=\"A\" pkNames=\"tran_id:line_no\"/>\r\n" );
								valueXmlString.append( "<tran_id/>" );
                                valueXmlString.append("<line_no><![CDATA[").append(lineNo).append("]]></line_no>");
								valueXmlString.append("<item_code><![CDATA[").append(itemCode).append("]]></item_code>");
								valueXmlString.append("<rate_apprv>").append("<![CDATA["+MngmntAprvRate+"]]>").append("</rate_apprv>\r\n");
								valueXmlString.append("<ptd>").append("<![CDATA["+ptd+"]]>").append("</ptd>\r\n");
								valueXmlString.append("<pts>").append("<![CDATA["+pts+"]]>").append("</pts>\r\n");
								valueXmlString.append("<ptr>").append("<![CDATA["+rate+"]]>").append("</ptr>\r\n");
								valueXmlString.append("</Detail"+objContext+">");

							}

						//PTR calculation end
						   
							

						//Management rate block[End]
					}
					if ("ptr_flag".equalsIgnoreCase(currentColumn.trim())) {
						String ptrFlag = checkNull(genericUtility.getColumnValue("ptr_flag", dom));

						BaseLogger.log("3", null, null, "ReqForQuotationIC in ptr_flag ");
						String custCode = checkNull(genericUtility.getColumnValue("cust_code", dom1));

						BaseLogger.log("3", null, null, "ReqForQuotationWiz in ptr_flat condition:: "+ptrFlag);
						BaseLogger.log("3", null, null, "ReqForQuotationWiz in ptr_flat condition siteCode:: "+siteCode);
						BaseLogger.log("3", null, null, "ReqForQuotationWiz in ptr_flat condition custCode:: "+custCode);

						if(ptrFlag.equalsIgnoreCase("Y")) {
						   String rateStr = checkNull(genericUtility.getColumnValue("ptr", dom));	
						   
							BaseLogger.log("3", getUserInfo(), null, "Final RATE : " + rate);
							
							valueXmlString.append( "<Detail"+ objContext+" domID='"+ 1 +"' objContext = '"+currentFormNo+"' objName=\"qc_resentry_wiz\" selected=\"N\">\r\n" );
							valueXmlString.append( "<attribute selected=\"Y\" updateFlag=\"A\"  pkNames=\"tran_id:line_no\"/>\r\n" );
							valueXmlString.append("<rate_quot protect='1'>").append("<![CDATA["+rateStr+"]]>").append("</rate_quot>\r\n");
							valueXmlString.append("</Detail"+objContext+">");

							
						}else if(ptrFlag.equalsIgnoreCase("N")) {
							
							valueXmlString.append( "<Detail"+ objContext+" domID='"+ 1 +"' objContext = '"+currentFormNo+"' objName=\"rfq_wiz\" selected=\"N\">\r\n" );
							valueXmlString.append( "<attribute selected=\"Y\" updateFlag=\"A\"  pkNames=\"tran_id:line_no\"/>\r\n" );
							valueXmlString.append("<rate_quot protect='0'>").append("<![CDATA[]]>").append("</rate_quot>\r\n");
							valueXmlString.append("</Detail"+objContext+">");

						}
					}
					if ("rate_quot".equalsIgnoreCase(currentColumn.trim())) {
						BaseLogger.log("3", null, null, "ReqForQuotationWiz in rate_quot ::");
						String rateQuot = genericUtility.getColumnValue("rate_quot", dom);
						String rateApprv = checkNull(genericUtility.getColumnValue("rate_apprv", dom));
						String ratePtr = checkNull(genericUtility.getColumnValue("ptr", dom));

						BaseLogger.log("3", null, null, "ReqForQuotationWiz in rate_quot:: "+rateQuot+" rateApprv::"+rateApprv+ " ratePtr::"+ratePtr);
						

						if (!rateQuot.isEmpty() && !rateApprv.isEmpty()) {
						    BigDecimal rateApprvVal = new BigDecimal(rateApprv);
						    BigDecimal rateQuotVal = new BigDecimal(rateQuot);
						    BigDecimal ratePtrVal = new BigDecimal(ratePtr);

							BaseLogger.log("3", null, null, "ReqForQuotationIC after conversion rateQuotVal:: "+rateQuotVal+" rateApprvVal::"+rateApprvVal);

						    
						    
						    //added condition when ptr and rate_quot is same direct approval without management
							
							  if (ratePtrVal.compareTo(rateQuotVal) == 0) { 
								  BaseLogger.log("3", null, null,
							  "in ratePtrVal == rateQuotVal condition"); 
								  String detail1Xml =
							  "<Detail1><mgmnt_apprv><![CDATA[N]]></mgmnt_apprv><wf_status><![CDATA[A]]></wf_status></Detail1>";
							  
							  int pos = valueXmlString.indexOf("</header>");
							  
							  if (pos != -1) { pos += "</header>".length(); // move after </header>
							  valueXmlString.insert(pos, detail1Xml); }
							  
							  BaseLogger.log("3", null, null,
							  "in rateApprvVal greater condition updatedXml ::"+valueXmlString); }
							 
						    
						    
						    if (rateApprvVal.compareTo(rateQuotVal) > 0) {
						        BaseLogger.log("3", null, null, "in rateApprvVal greater condition");
						        String detail1Xml = "<Detail1><mgmnt_apprv><![CDATA[Y]]></mgmnt_apprv><wf_status><![CDATA[P]]></wf_status></Detail1>";

						        int pos = valueXmlString.indexOf("</header>");

						        if (pos != -1) {
						            pos += "</header>".length();   // move after </header>
						            valueXmlString.insert(pos, detail1Xml);
						        }

						        BaseLogger.log("3", null, null, "in rateApprvVal greater condition updatedXml ::"+valueXmlString);

						        
						    }
						}


					}
					break;
                      
		}
                      
				
				//end sales_pers 
			
		}//end try itemchange
		catch(Exception e)
		{
			System.out.println("Exception :StrgBrandactwiz :defaultDataWiz(Document,String):" + e.getMessage() + ":" );
			valueXmlString = valueXmlString.append( genericUtility.createErrorString( e ) );
		}//end catch itemchange
		finally
		{

			try
			{
				if(rs !=null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if( conn != null && ! conn.isClosed() )
				{
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				System.out.println("Exception :StrgBrandactwiz :defaultDataWiz :==>\n"+e.getMessage());
				throw new ITMException(e);
			}
		}
		valueXmlString.append( "</Root>\r\n" );
		System.out.println(" ReqForQuotationWiz valueXmlString :==>\n"+valueXmlString.toString());

		return valueXmlString.toString();
	}
	private String getDomID(Document dom2,String objContext)
	{
		Node elementName = null, parentNode = null;
		NodeList elementList = null;
		Element elementAttr = null;
		String objName = "";
		elementList = dom2.getElementsByTagName("Detail"+objContext);
		elementName = elementList.item(0);
		if (elementName!=null && ("Detail"+objContext).equalsIgnoreCase(elementName.getNodeName()))
		{
			NamedNodeMap etlAttributes = elementName.getAttributes();
			if (etlAttributes!=null)
			{
				if (etlAttributes.getNamedItem("domID")!=null)
				{
					objName = etlAttributes.getNamedItem("domID").getNodeValue();
				}
			}
		}
		return objName;
	}
	
	
	
	private String checkNull( String inputVal )
	{
		if ( inputVal == null )
		{
			inputVal = "";
		}
		return inputVal;
	}	
}
