package ibase.webitm.ejb.dis;


import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.TransIDGenerator;
import ibase.webitm.ejb.*;

import java.rmi.RemoteException;
import java.sql.*;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
//import java.util.Date;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@javax.ejb.Stateless
public class CenvatCrCapitalPrc extends ProcessEJB implements CenvatCrCapitalPrcLocal,CenvatCrCapitalPrcRemote //SessionBean 
{

	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	DistCommon discommon = new DistCommon();
	
	int noRows = 0;
	
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;
		System.out.println("getData(xmlString,xmlString2,windowName,xtraParams CALLEDRohan..."+ xmlString);
		try
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				System.out.println("XML String :"+xmlString);
				headerDom = genericUtility.parseString(xmlString); 				
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				System.out.println("XML String :"+xmlString2);
				detailDom = genericUtility.parseString(xmlString2); 				
			}
			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :CenVatCrCapitalPrc :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			rtrStr = e.getMessage();
		}
		return rtrStr; 
	}
	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String siteCode = "";
		String acctPrd = "";
		String prcDate = "";
		String errCode = "";
		String errString = "";
		String getDataSql= "" ;
		String resultString = "";
		StringBuffer retTabSepStrBuff = new StringBuffer();
		String dataCntSql = "";
		String acctPrdSql = "";
		
		java.util.Date processDate = null;
		java.util.Date dateCheck = null;
		
		int count = 0;
		
		noRows = 0;
		
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		
		Connection conn = null;
		try
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
		
			
			siteCode = genericUtility.getColumnValue("site_code",headerDom);
			if ( siteCode == null || siteCode.trim().length() == 0 )
			{
				siteCode = "";
				System.out.println("Site Code From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTNULSITE","","",conn);
				return errString;
			}
			System.out.println(" SITE CODE ::"+ siteCode);
			
			acctPrd = genericUtility.getColumnValue("acct_period",headerDom);
			if ( acctPrd == null || acctPrd.trim().length() == 0 )
			{
				acctPrd = "";
				System.out.println(" Period is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTNULLPRD","","",conn);
				return errString;
			} 
			System.out.println(" PERIOD ::"+ acctPrd);
			
			prcDate = genericUtility.getColumnValue("process_date",headerDom);
         	if ( prcDate == null || prcDate.trim().length() == 0 )
			{
         		prcDate = "";
				System.out.println(" Proecss Date is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTNULLPRC","","",conn);
				return errString;
			}
         	acctPrdSql = "SELECT COUNT(*) AS COUNT FROM PERIOD WHERE ACCT_PRD = ? ";
			pstmt = conn.prepareStatement(acctPrdSql);
			
			pstmt.setString(1,acctPrd);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				count = rs.getInt("COUNT");
			}
			if(count == 0)
			{
				errString = itmDBAccessEJB.getErrorString("","VTINVLDPRD","","",conn);
				return errString;
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
         	String applDateFmt = genericUtility.getApplDateFormat();
			DateFormat dtFormat = new SimpleDateFormat(applDateFmt);
			processDate = dtFormat.parse(prcDate);
			
			java.sql.Date processSqlDate = new java.sql.Date(processDate.getTime());     
			
			String year = acctPrd.substring(2, 4);
			String chkDate = "01/04/"+year;
			dateCheck = dtFormat.parse(chkDate);
			
			if (dateCheck.after(processDate))
			 {
				 resultString = itmDBAccessEJB.getErrorString("","VTNTVALDAT","","",conn);
				 return resultString;
			 }
			//to check all row select.start
			
	
			dataCntSql = "SELECT COUNT(*) AS COUNT FROM CENVAT_CR_CAPITAL WHERE CONFIRMED = ? " 
					+" AND SITE_CODE = ? AND PROCESS_YEAR = ? AND CASE WHEN PROCESS IS NULL THEN 'N' ELSE PROCESS end <> 'Y' ORDER BY BAL_GROUP ";
			pstmt = conn.prepareStatement(dataCntSql);
			
			pstmt.setString(1,"Y");
			pstmt.setString(2,siteCode);
			pstmt.setString(3,acctPrd);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				noRows = rs.getInt("COUNT");
			}
			
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			//to check all row select.end
			getDataSql = "SELECT TRAN_ID,TRAN_DATE,BAL_GROUP,REF_SER,REF_ID,REF_DATE,CONFIRMED,"
					+" DRCR_FLAG,PARTY_REF,NET_AMT,TAX_AMT,SITE_CODE,SUPP_CODE,TAX_CODE,"
					+" REF_DOC_NO,REF_DOC_DATE,SR_NO,BAL_GROUP__ADJ,ADJ_AMT,CR_AMT,CHG_DATE,CHG_USER,CHG_TERM"
					+" FROM CENVAT_CR_CAPITAL WHERE CONFIRMED = ? " 
					+" AND SITE_CODE = ? AND PROCESS_YEAR = ? AND CASE WHEN PROCESS IS NULL THEN 'N' ELSE PROCESS end <> 'Y' ORDER BY BAL_GROUP ";
			pstmt = conn.prepareStatement(getDataSql);
			
			pstmt.setString(1,"Y");
			pstmt.setString(2,siteCode);
			pstmt.setString(3,acctPrd);
			rs = pstmt.executeQuery();
			if(rs.next())
			{	
			
				do
				{
					retTabSepStrBuff.append(checkNull(rs.getString("TRAN_ID"))).append("\t");
					retTabSepStrBuff.append(rs.getDate("TRAN_DATE")).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("BAL_GROUP"))).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("REF_SER"))).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("REF_ID"))).append("\t");
					retTabSepStrBuff.append(rs.getDate("REF_DATE")).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("CONFIRMED"))).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("DRCR_FLAG"))).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("PARTY_REF"))).append("\t");
					retTabSepStrBuff.append(rs.getDouble("NET_AMT")).append("\t");
					retTabSepStrBuff.append(rs.getDouble("TAX_AMT")).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("SITE_CODE"))).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("SUPP_CODE"))).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("TAX_CODE"))).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("REF_DOC_NO"))).append("\t");
					retTabSepStrBuff.append(rs.getDate("REF_DOC_DATE")).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("SR_NO"))).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("BAL_GROUP__ADJ"))).append("\t");
					retTabSepStrBuff.append(rs.getDouble("ADJ_AMT")).append("\t");
					retTabSepStrBuff.append(rs.getDouble("CR_AMT")).append("\t");
					retTabSepStrBuff.append(rs.getDate("CHG_DATE")).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("CHG_USER"))).append("\t");
					retTabSepStrBuff.append(checkNull(rs.getString("CHG_TERM"))).append("\t");
							
					retTabSepStrBuff.append("\n");
					
				}while(rs.next());
				resultString = retTabSepStrBuff.toString();
				System.out.println("ResultString....." + resultString);
				pstmt.clearParameters();	
			}
			else
			{
				errCode ="VTNOTREC";
			}
			if (!errCode.equals(""))
			{
				resultString = itmDBAccessEJB.getErrorString("", errCode, "", "", conn);
				System.out.println("resultString: "+resultString);
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			
		}
		catch (SQLException e)
		{
			System.out.println("SQLException :CenVatCrCapitalPrc :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		catch (Exception e)
		{
			System.out.println("Exception :CenVatCrCapitalPrc :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{
			
			try
			{
				if(conn != null)
				{		
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				throw new ITMException(e);
			}
		}		
		return resultString;	

	}
	//Process method
	public String process() throws RemoteException,ITMException
	{
		
		return "";
	}
	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String retStr = "";
		Document detailDom = null;
		Document headerDom = null;
		
		GenericUtility genericUtility = GenericUtility.getInstance();
		
		try
		{	
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString); 
				System.out.println("headerDom" + headerDom);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2); 
				System.out.println("detailDom" + detailDom);
			}
									
		    retStr = process(headerDom, detailDom, windowName, xtraParams);
		    
		}
		catch (Exception e)
		{
			System.out.println("Exception :CenVatCrCapitalPrc :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			retStr = e.getMessage();
			throw new ITMException(e);
		}
		return retStr;
		
	}
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		
		String errString = "";
		String balPrd = "";
		String balGrp = "";
		String siteCode = "";
		String finEntity = "";
		String childNodeName = "";
		String prcDate = "";
		String adjAmount = "";
		String netAmount = "";
		String crAmount = "";
		String taxAmount = "";
		String insetSql ="";
		String chgUser = "";
		String chgTerm = "";
		String currBalprd = "";
		String prd = "";
		String dateStr = "";
		String tranIdProc = "";
		String tranIdCr = "";
		String docType = "";
		String balType = "";
		String refSer = "";
		String drCr = "";
		String taxChap = "";
		String itemCode = "";
		String suppCode = "";
		String exeRef = "";
		String suppSiteCode = "";
		String tranSiteCode = "";
		String transtranType = "";
		String chapHead = "";
		String lotNo = "";
		String invoiceNo = "";
		String taxCode = "";
		String lotSl =  "";
		String matCate =  "";
		String refId =  "";
		String refLine =  "";
		String tranType =  "";
		String balGrpAdj =  "";
		String sqlCp = "";
		String srNo = "";
		String delimiter = ":";
		String chktax = "";
		String chkbalPrd = "";
		String updateTaxBal = "";
		String processYear = "";
		String sqlFinEntity = "";
		String insertTaxPrc = "";
		String updateSql = "";
		
		PreparedStatement pstmtUpdate = null;
		PreparedStatement pstmttax = null;
		PreparedStatement pstmtCapital = null;
		PreparedStatement pstmtbalPrd = null;
		PreparedStatement pstmtFinEntity = null;
		PreparedStatement pstmt = null;
		PreparedStatement pstmtTaxPrc = null;
		PreparedStatement pstmtUpdateCr = null;
		
		ResultSet rsTax = null;
		ResultSet rsCapital = null;
		ResultSet rsFin = null;

		Double addlExcise = 0.0;
		Double qtyReq = 0.0;
		Double closeStk = 0.0;
		
		java.util.Date processDate = null;
		
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		
		int parentNodeListLength = 0;
		int childNodeListLength = 0;
		int date = 0;
		int month=0;
		int year=0;
		int recordcnt = 0;
		int balcnt = 0;
		
		double adjAmt = 0.0;
		double netAmt = 0.0;
		double crAmt = 0.0;
		double taxAmt = 0.0;

		
		Calendar cal = Calendar.getInstance();
		
		HashMap<String,String> balGroupMap = new HashMap<String,String>();
		ResultSet rs = null;
				
		NodeList parentNodeList = null;
		
		Connection conn = null;
		
		try
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;
			
			prcDate = genericUtility.getColumnValue("process_date",headerDom);
			chgUser = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" );
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
			siteCode = checkNull(genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginSiteCode" ));
			
			String applDateFmt = genericUtility.getApplDateFormat();
			DateFormat dtFormat = new SimpleDateFormat(applDateFmt);
			
			processDate = dtFormat.parse(prcDate);
			java.util.Date utilDate = new java.util.Date();
			
			java.sql.Date chgDate = new java.sql.Date(utilDate.getTime());
			java.sql.Date processSqlDate = new java.sql.Date(processDate.getTime());     
			
			
			//calculating balance period.start
			java.sql.Date tranDate = processSqlDate;
			cal.setTime(tranDate);
			date=cal.get(Calendar.DATE);
			month=cal.get(Calendar.MONTH);
			year=cal.get(Calendar.YEAR);
			dateStr= new Integer(year).toString()+"-"+(new java.text.DecimalFormat( "00" )).format( month + 1)+"-"+(new java.text.DecimalFormat( "00" )).format( date );
			System.out.println("dateStr:::["+dateStr+"]");
			System.out.println("timestamp dateStr :::["+dateStr+" 00:00:00.0]");
		 	Timestamp currTranDate = java.sql.Timestamp.valueOf(dateStr+" 00:00:00.0");
			prd = (currTranDate.toString()).substring(0,currTranDate.toString().indexOf(" "));
			String FltStr[] = prd.split("-");
			currBalprd = FltStr[0]+FltStr[1]+FltStr[2];
			System.out.println("currBalPeriod::::::::::::["+currBalprd+"]");
			//calculating balance period.end
					
			parentNodeList = detailDom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength(); 
			
			System.out.println("noRows***"+noRows+"parentNodeListLength***"+parentNodeListLength);
			
			if(noRows != parentNodeListLength )
			{		
				errString = itmDBAccessEJB.getErrorString("","VTNTSELECT","","",conn);
				return errString;	
			}
			else
			{
				
				refId = getTranId("t_transfer_refId",siteCode,conn);
			}
			
			for (int selectedRow = 0; selectedRow < parentNodeListLength; selectedRow++)
			{
				parentNode = parentNodeList.item(selectedRow);
				
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				
				for (int childRow = 0; childRow < childNodeListLength; childRow++)
				{
					childNode = childNodeList.item(childRow);
					childNodeName = childNode.getNodeName();
					
					if (childNodeName.equals("tran_id"))
					{
						tranIdCr = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("bal_group"))
					{
						balGrp = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("adj_amt"))
					{
						adjAmount = childNode.getFirstChild().getNodeValue();
						
					}
					if (childNodeName.equals("net_amt"))
					{
						netAmount = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("cr_amt"))
					{
						crAmount = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("tax_amt"))
					{
						taxAmount = childNode.getFirstChild().getNodeValue();
					}
					
				}
				//Adding to hashmap.start
				if(!balGroupMap.containsKey(balGrp))
				{
					balGroupMap.put(balGrp, adjAmount+":"+netAmount+":"+crAmount+":"+taxAmount+":"+tranIdCr);
				}
				else
				{
					String amtStr = balGroupMap.get(balGrp);
					String[] amtArray;
				    amtArray = amtStr.split(delimiter);
				
				    adjAmt = Double.parseDouble(amtArray[0]) + Double.parseDouble(adjAmount);
					netAmt = Double.parseDouble(amtArray[1]) + Double.parseDouble(netAmount);
					crAmt = Double.parseDouble(amtArray[2]) + Double.parseDouble(crAmount);
					taxAmt = Double.parseDouble(amtArray[3]) + Double.parseDouble(taxAmount);

					balGroupMap.put(balGrp,String.valueOf(adjAmt)+":"+String.valueOf(netAmt)+":"+String.valueOf(crAmt)+":"+String.valueOf(taxAmt)+":"+amtArray[4]);
					
				}
			}//
			//to get fin entity.start
			
			sqlFinEntity = "SELECT FIN_ENTITY FROM SITE WHERE SITE_CODE = ?";
			pstmtFinEntity = conn.prepareStatement(sqlFinEntity);
			pstmtFinEntity.setString(1,siteCode);
			rsFin = pstmtFinEntity.executeQuery();
			if(rsFin.next())
			{
				finEntity = checkNull(rsFin.getString("FIN_ENTITY"));
			}
			if(rsFin != null)
			{
				rsFin.close();
				rsFin = null;
			}
			if(pstmtFinEntity != null)
			{
				pstmtFinEntity.close();
				pstmtFinEntity = null;
			}
			//to get fin entity.end
			sqlCp = "SELECT DOC_TYPE, BAL_TYPE,BAL_PRD, REF_SER, DRCR_FLAG,TAX_CHAP, ITEM_CODE, SITE_CODE, QTY_RECD, SUPP_CODE, EXC_REF,"
					  +" CLOSING_STOCK, SITE_CODE__SUPP, SITE_CODE__TRAN, TRAN_TYPE_TRANSACTION,CHAP_HEADING, LOT_NO, INVOICE_NO,"
					  +" TAX_CODE,REF_DOC_NO, REF_DOC_DATE, LOT_SL, MATERIAL_CATEGORY, REF_ID,REF_DATE,REF_LINE,TRAN_TYPE,"
					  +" BAL_GROUP__ADJ, ADDL_EXCISE,PROCESS_YEAR FROM CENVAT_CR_CAPITAL WHERE TRAN_ID = ? ";
			pstmtCapital = conn.prepareStatement(sqlCp);
			
			insetSql = "INSERT INTO TAX_PROCESS_BAL (BAL_GROUP, BAL_PRD, DR_AMT, CR_AMT, CHG_DATE, CHG_USER, CHG_TERM, "
					 +" ACCT_PRD, FIN_ENTITY, SITE_CODE) VALUES (?,?,?,?,?,?,?,?,?,?)";				
			pstmt = conn.prepareStatement(insetSql);
			
			chkbalPrd = "SELECT COUNT(*) AS CNT FROM TAX_PROCESS_BAL WHERE BAL_GROUP = ? AND BAL_PRD = ? AND ACCT_PRD = ?"
					 +" AND FIN_ENTITY = ? AND SITE_CODE = ?";
			pstmtbalPrd = conn.prepareStatement(chkbalPrd);
			
			chktax = "SELECT COUNT(*) AS COUNT FROM TAX_PROCESS_BAL WHERE BAL_GROUP = ?  AND ACCT_PRD = ?"
					 +" AND FIN_ENTITY = ? AND SITE_CODE = ?";
			pstmttax = conn.prepareStatement(chktax);
			
			insertTaxPrc = "INSERT INTO TAX_PROCESSED (TRAN_ID, TRAN_DATE, BAL_GROUP, DOC_TYPE, BAL_TYPE, BAL_PRD, REF_SER, DRCR_FLAG, " +
			        " NET_AMT, DR_AMT, CR_AMT, TAX_CHAP, ITEM_CODE, SITE_CODE, QTY_RECD, SUPP_CODE, EXC_REF, CLOSING_STOCK, " +
			        " SITE_CODE__SUPP, SITE_CODE__TRAN, TRAN_TYPE_TRANSACTION, PROCESS_YN, CHAP_HEADING, LOT_NO, TAX_AMT, " +
			        " INVOICE_NO, TAX_CODE, CHG_DATE, CHG_USER, CHG_TERM,LOT_SL, MATERIAL_CATEGORY, " +
			        " REF_ID,REF_LINE,REF_DATE,TRAN_TYPE, SR_NO,BAL_GROUP__ADJ, ADJ_AMT, ADDL_EXCISE ) " +
			        " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			
			pstmtTaxPrc = conn.prepareStatement(insertTaxPrc);
			
			
			updateTaxBal = "UPDATE TAX_PROCESS_BAL SET CR_AMT = CR_AMT + ? WHERE BAL_GROUP = ? AND BAL_PRD = ? AND ACCT_PRD = ? "
						   +" AND FIN_ENTITY = ? AND SITE_CODE = ? ";
			pstmtUpdate = conn.prepareStatement(updateTaxBal);
			
			
			//srNo = getUniqueKey(conn, "t_tax_process_sr_no", prcDate,siteCode,"",balType,balPrd,refSer,drCr,docType,refId,itemCode,taxCode,suppCode,taxChap,matCate);
			//System.out.println("Only one serial no is generate***"+srNo);
			//Changed by Rohan on 12-1-13 To genrate unique serial no irrespective of group
			boolean isSerialGen = false;
			for (String keyBalGrp : balGroupMap.keySet())
			{

				String str = balGroupMap.get(keyBalGrp);
				String[] amtArrayIns;
				amtArrayIns = str.split(delimiter);
				adjAmt = Double.parseDouble(amtArrayIns[0]);
				netAmt = Double.parseDouble(amtArrayIns[1]);
				crAmt = Double.parseDouble(amtArrayIns[2]);
				taxAmt = Double.parseDouble(amtArrayIns[3]);
				tranIdCr = amtArrayIns[4];
				/*	
				sqlCp = "SELECT DOC_TYPE, BAL_TYPE, REF_SER, DRCR_FLAG,TAX_CHAP, ITEM_CODE, SITE_CODE, QTY_RECD, SUPP_CODE, EXC_REF,"
						  +" CLOSING_STOCK, SITE_CODE__SUPP, SITE_CODE__TRAN, TRAN_TYPE_TRANSACTION,CHAP_HEADING, LOT_NO, INVOICE_NO,"
						  +" TAX_CODE,REF_DOC_NO, REF_DOC_DATE, LOT_SL, MATERIAL_CATEGORY, REF_ID,REF_DATE,REF_LINE,TRAN_TYPE,"
						  +" BAL_GROUP__ADJ, ADDL_EXCISE FROM CENVAT_CR_CAPITAL WHERE TRAN_ID = ? ";
				pstmtCapital = conn.prepareStatement(sqlCp);
				*/
		
				pstmtCapital.setString(1, tranIdCr);
				rsCapital = pstmtCapital.executeQuery();
				if(rsCapital.next())
				{
					docType = checkNull(rsCapital.getString("DOC_TYPE"));
					balType = checkNull(rsCapital.getString("BAL_TYPE"));
					balPrd = checkNull(rsCapital.getString("BAL_PRD"));
					refSer = checkNull(rsCapital.getString("REF_SER"));
					drCr = checkNull(rsCapital.getString("DRCR_FLAG"));
					taxChap = checkNull(rsCapital.getString("TAX_CHAP"));
					itemCode = checkNull(rsCapital.getString("ITEM_CODE"));
					qtyReq = rsCapital.getDouble("QTY_RECD");
					suppCode = checkNull(rsCapital.getString("SUPP_CODE"));
					exeRef = checkNull(rsCapital.getString("EXC_REF"));
					closeStk = rsCapital.getDouble("CLOSING_STOCK");
					suppSiteCode = checkNull(rsCapital.getString("SITE_CODE__SUPP"));
					tranSiteCode = checkNull(rsCapital.getString("SITE_CODE__TRAN"));
					transtranType = checkNull(rsCapital.getString("TRAN_TYPE_TRANSACTION"));
					chapHead = checkNull(rsCapital.getString("CHAP_HEADING"));
					lotNo = checkNull(rsCapital.getString("LOT_NO"));
					invoiceNo = checkNull(rsCapital.getString("INVOICE_NO"));
					taxCode = checkNull(rsCapital.getString("TAX_CODE"));
					//refDocNo = checkNull(rsCapital.getString("REF_DOC_NO"));
					//refDocDate = rsCapital.getDate("REF_DOC_DATE");
					lotSl =  checkNull(rsCapital.getString("LOT_SL"));
					matCate =  checkNull(rsCapital.getString("MATERIAL_CATEGORY"));
					//refDate = rsCapital.getDate("REF_DATE");
					//refId =  checkNull(rsCapital.getString("REF_ID"));
					refLine =  checkNull(rsCapital.getString("REF_LINE"));
					tranType =  checkNull(rsCapital.getString("TRAN_TYPE"));
					balGrpAdj =  checkNull(rsCapital.getString("BAL_GROUP__ADJ"));
					addlExcise = rsCapital.getDouble("ADDL_EXCISE");
					processYear = checkNull(rsCapital.getString("PROCESS_YEAR"));
				}
				pstmtCapital.clearParameters();
				if(rsCapital != null)
				{
					rsCapital.close();
					rsCapital = null;
				}
		
			    //inserting data into tax process bal.start
				//opening balance insert.start
				/*
				insetSql = "INSERT INTO TAX_PROCESS_BAL (BAL_GROUP, BAL_PRD, DR_AMT, CR_AMT, CHG_DATE, CHG_USER, CHG_TERM, "
						 +" ACCT_PRD, FIN_ENTITY, SITE_CODE) VALUES (?,?,?,?,?,?,?,?,?,?)";				
				pstmt = conn.prepareStatement(insetSql);
				*/
				/*
				chktax = "SELECT COUNT(*) AS COUNT FROM TAX_PROCESS_BAL WHERE BAL_GROUP = ?  AND ACCT_PRD = ?"
						 +" AND FIN_ENTITY = ? AND SITE_CODE = ?";
				pstmttax = conn.prepareStatement(chktax);
				*/
				
				pstmttax.setString(1, keyBalGrp);
				pstmttax.setString(2,processYear);//balance group
				pstmttax.setString(3, finEntity);												//balance period
				pstmttax.setString(4,siteCode);															//debit amount
				rsTax = pstmttax.executeQuery();
				if(rsTax.next())
				{
					recordcnt = rsTax.getInt("COUNT");
					
				}
				
				pstmttax.clearParameters();
				if(rsTax != null)
				{
					rsTax.close();
					rsTax = null;
				}
				if(recordcnt > 0)
				{
					//only update SQL
					/*
					updateTaxBal = "UPDATE TAX_PROCESS_BAL SET CR_AMT = CR_AMT + ? WHERE BAL_GROUP = ? AND BAL_PRD = ? AND ACCT_PRD = ? "
				   +" AND FIN_ENTITY = ? AND SITE_CODE = ? ";
					pstmtUpdate = conn.prepareStatement(updateTaxBal);
					*/
					pstmtUpdate.setDouble(1,adjAmt);
					pstmtUpdate.setString(2,keyBalGrp);
					pstmtUpdate.setString(3, "ZZZZZZ  ");
					pstmtUpdate.setString(4,processYear);
					pstmtUpdate.setString(5,finEntity);
					pstmtUpdate.setString(6,siteCode);
					pstmtUpdate.executeUpdate();
					
				}
				else
				{	
					pstmt.setString(1, keyBalGrp);												//balance group
					pstmt.setString(2, "000000  ");												//balance period
					pstmt.setDouble(3, 0.0);															//debit amount
					pstmt.setDouble(4, 0.0);
					pstmt.setDate(5, chgDate);	//change date
					pstmt.setString(6, chgUser);
					pstmt.setString(7, chgTerm);												//change terminal number
					pstmt.setString(8,processYear);												//accounting year
					pstmt.setString(9,finEntity);													//fin entity
					pstmt.setString(10,siteCode);												//site code
					
					pstmt.executeUpdate();
					pstmt.clearParameters();
					//opening balance insert.end
					//closing balance insert.start
					pstmt.setString(1, keyBalGrp);
					pstmt.setString(2, "ZZZZZZ  ");
					pstmt.setDouble(3, 0.0);
					pstmt.setDouble(4, adjAmt);
					pstmt.setDate(5, chgDate);	
					pstmt.setString(6, chgUser);
					pstmt.setString(7, chgTerm);
					pstmt.setString(8,processYear);	
					pstmt.setString(9,finEntity);
					pstmt.setString(10,siteCode);
					pstmt.executeUpdate();
					pstmt.clearParameters();
					//closing balance insert.start
				}
				/*
				chkbalPrd = "SELECT COUNT(*) AS CNT FROM TAX_PROCESS_BAL WHERE BAL_GROUP = ? AND BAL_PRD = ? AND ACCT_PRD = ?"
						 +" AND FIN_ENTITY = ? AND SITE_CODE = ?";
				pstmtbalPrd = conn.prepareStatement(chkbalPrd);
				*/
		
				pstmtbalPrd.setString(1, keyBalGrp);
				pstmtbalPrd.setString(2,currBalprd);//balance group
				pstmtbalPrd.setString(3,processYear);
				pstmtbalPrd.setString(4, finEntity);												//balance period
				pstmtbalPrd.setString(5,siteCode);															//debit amount
				rsTax = pstmtbalPrd.executeQuery();
				if(rsTax.next())
				{
					balcnt = rsTax.getInt("CNT");
					
				}
				
				if(rsTax != null)
				{
					rsTax.close();
					rsTax = null;
				}
				if(balcnt > 0)
				{
					//update only
					pstmtUpdate.setDouble(1,adjAmt);
					pstmtUpdate.setString(2,keyBalGrp);
					pstmtUpdate.setString(3, currBalprd);
					pstmtUpdate.setString(4,processYear);
					pstmtUpdate.setString(5,finEntity);
					pstmtUpdate.setString(6,siteCode);
					pstmtUpdate.executeUpdate();
				}
				else
				{	
					pstmt.setString(1, keyBalGrp);
					pstmt.setString(2,currBalprd);
					pstmt.setDouble(3, 0.0);
					pstmt.setDouble(4, adjAmt);
					pstmt.setDate(5, chgDate);	
					pstmt.setString(6, chgUser);
					pstmt.setString(7, chgTerm);
					pstmt.setString(8,processYear);	
					pstmt.setString(9,finEntity);
					pstmt.setString(10,siteCode);
					pstmt.executeUpdate();
					pstmt.clearParameters();
				}
				
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				//inserting data into tax process bal.end
				
				//tax.start
				/*
				insertTaxPrc = "INSERT INTO TAX_PROCESSED (TRAN_ID, TRAN_DATE, BAL_GROUP, DOC_TYPE, BAL_TYPE, BAL_PRD, REF_SER, DRCR_FLAG, " +
						        " NET_AMT, DR_AMT, CR_AMT, TAX_CHAP, ITEM_CODE, SITE_CODE, QTY_RECD, SUPP_CODE, EXC_REF, CLOSING_STOCK, " +
						        " SITE_CODE__SUPP, SITE_CODE__TRAN, TRAN_TYPE_TRANSACTION, PROCESS_YN, CHAP_HEADING, LOT_NO, TAX_AMT, " +
						        " INVOICE_NO, TAX_CODE, CHG_DATE, CHG_USER, CHG_TERM, REF_DOC_NO, REF_DOC_DATE, LOT_SL, MATERIAL_CATEGORY, " +
						        " REF_ID,REF_DATE,REF_LINE,TRAN_TYPE, SR_NO,BAL_GROUP__ADJ, ADJ_AMT, ADDL_EXCISE ) " +
						        " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				pstmtTaxPrc = conn.prepareStatement(insertTaxPrc);
				*/
				//getTranId
				
				//Changed by Rohan on 12/06/12 for bug fixing
				/*
				
				srNo = getTranId("t_tax_process_sr_no",siteCode,conn);
				*/
				tranIdProc = getUniqueKey(conn, "T_tax_processed", prcDate,siteCode,keyBalGrp,balType,balPrd,refSer,drCr,docType,refId,itemCode,taxCode,suppCode,taxChap,matCate);
				//Changed by Rohan on 12-1-12 To genrate unique serial no irrespective of group
				//srNo = getUniqueKey(conn, "t_tax_process_sr_no", prcDate,siteCode,keyBalGrp,balType,balPrd,refSer,drCr,docType,refId,itemCode,taxCode,suppCode,taxChap,matCate);
				if(!isSerialGen)
				{
					srNo = getUniqueKey(conn, "t_tax_process_sr_no", prcDate,siteCode,keyBalGrp,balType,balPrd,refSer,drCr,docType,refId,itemCode,taxCode,suppCode,taxChap,matCate);
					isSerialGen = true;
				}
				pstmtTaxPrc.setString(1, tranIdProc);//transaction id
				pstmtTaxPrc.setDate(2,processSqlDate);
				pstmtTaxPrc.setString(3,keyBalGrp);		//balance group
				pstmtTaxPrc.setString(4, docType);		//document type
				pstmtTaxPrc.setString(5, balType);			//balance type
				pstmtTaxPrc.setString(6, balPrd);			//balance period
				pstmtTaxPrc.setString(7, refSer);			//referance series
				pstmtTaxPrc.setString(8, drCr);		//dr / cr flag
				pstmtTaxPrc.setDouble(9, netAmt);			//net amount
				pstmtTaxPrc.setDouble(10, 0.0);			//debit amount
				pstmtTaxPrc.setDouble(11, crAmt);			//credit amount
				pstmtTaxPrc.setString(12, taxChap);		//tax chapter
				pstmtTaxPrc.setString(13, itemCode);	//item code
				pstmtTaxPrc.setString(14, siteCode);		//site code
				pstmtTaxPrc.setDouble(15, qtyReq);		//quantity received
				pstmtTaxPrc.setString(16, suppCode);	//supplier code
				pstmtTaxPrc.setString(17, exeRef);			//exc referance
				pstmtTaxPrc.setDouble(18, closeStk);	//closing stock
				pstmtTaxPrc.setString(19, suppSiteCode);	//site code supplier
				pstmtTaxPrc.setString(20, tranSiteCode);	//site code transaction
				pstmtTaxPrc.setString(21, transtranType);	//tran type transaction
				pstmtTaxPrc.setString(22, "Y");	//confirmation flag
				pstmtTaxPrc.setString(23, chapHead);	//chapter heading
				pstmtTaxPrc.setString(24, lotNo);				//lot number
				pstmtTaxPrc.setDouble(25, taxAmt);			//tax amount
				pstmtTaxPrc.setString(26, invoiceNo);		//invoice number
				pstmtTaxPrc.setString(27, taxCode);			//tax code
				pstmtTaxPrc.setDate(28, chgDate);			//change date
				pstmtTaxPrc.setString(29, chgUser);			//change user
				pstmtTaxPrc.setString(30, chgTerm);			//change terminal number
				//pstmtTaxPrc.setString(31, refId);		//referance document number
				//pstmtTaxPrc.setDate(32, processSqlDate);	//referance document date
				pstmtTaxPrc.setString(31, lotSl);		//lot sl
				pstmtTaxPrc.setString(32, matCate);		//material category
				pstmtTaxPrc.setString(33, refId);		//Ref Id
				pstmtTaxPrc.setString(34, refLine);		//referance line number
				pstmtTaxPrc.setDate(35, processSqlDate);				//Ref Date
				pstmtTaxPrc.setString(36, tranType);			//Tran Type
				pstmtTaxPrc.setString(37, srNo);
				pstmtTaxPrc.setString(38, balGrpAdj);			//bal group adj
				pstmtTaxPrc.setDouble(39, adjAmt);			//adj amt
				pstmtTaxPrc.setDouble(40, addlExcise);	// 06-01-2006 manoharan new column
				
				pstmtTaxPrc.executeUpdate();
				pstmtTaxPrc.clearParameters();
				//tax.end
				
				//UPDATING FLAG OF CENVAT.start
				updateSql = "UPDATE CENVAT_CR_CAPITAL SET PROCESS = ? WHERE BAL_GROUP = ? AND PROCESS_YEAR = ? AND CONFIRMED = ?";
				pstmtUpdateCr = conn.prepareStatement(updateSql);
				pstmtUpdateCr.setString(1,"Y");
				pstmtUpdateCr.setString(2,keyBalGrp);
				pstmtUpdateCr.setString(3,processYear);
				pstmtUpdateCr.setString(4,"Y");
				pstmtUpdateCr.executeUpdate();
				pstmtUpdateCr.clearParameters();
			}	
			
		}
		catch(Exception e)
		{
			if ( conn != null && ! conn.isClosed() )
			{
				conn.rollback();
			}
			e.printStackTrace();
			System.out.println("Exception :CenVatCrCapitalPrc :process(String xmlString2, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			errString = e.getMessage();
			//return errString ;
			throw e;
		}
		finally
		{
			System.out.println("Closing Connection....");
			try
			{
				if(pstmtUpdateCr != null)
				{
					pstmtUpdateCr.close();
					pstmtUpdateCr = null;
				}
				
				if(pstmtTaxPrc != null)
				{
					pstmtTaxPrc.close();
					pstmtTaxPrc = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(pstmtUpdate != null)
				{
					pstmtUpdate.close();
					pstmtUpdate = null;
				}
				if(pstmtbalPrd != null)
				{
					pstmtbalPrd.close();
					pstmtbalPrd = null;
				}
				if(pstmttax != null)
				{
					pstmttax.close();
					pstmttax = null;
				}
				if(pstmtCapital != null)
				{
					pstmtCapital.close();
					pstmtCapital = null;
				}
				
				if (errString == null || errString.trim().length() == 0)
				{
					conn.commit();
					errString="VTCOMPLETE";
					errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
					return errString;
				}
				else
				{
					System.out.println("errString.indexOf(<Errors>)---------------"+errString.indexOf("<Errors>"));
					if(errString.indexOf("<Errors>") == -1 )
					{
						if( errString.trim().length() > 0)
						{
							System.out.println("Inside Block for ErrOr Not Found---------------");
							errString="VTPRCESERR";
							errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
						}
					}
					
					return errString;

				}
				
				
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				return errString ;
			
			}
			
			
		}
	}
	private String checkNull( String input )
	{
		if( input == null )
		{
			input = "";
		}
		return input;
	}
	
	private String getTranId(String windowName,String siteCode,Connection conn) throws ITMException
	{
		String keyStringQuery = "";
		String xmlValues = "";
		String tranId = "";
		ResultSet rSet = null ;
		PreparedStatement pstmt = null;
		//CommonConstants commonConstants = new CommonConstants();

		java.sql.Timestamp currDate = null;

		try
		{
			
			keyStringQuery = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ?";
	    	
	    	pstmt = conn.prepareStatement(keyStringQuery);
	    	pstmt.setString(1,windowName);
	    	rSet = pstmt.executeQuery();	    	
			String tranSer1 = "";
			String keyString = "";
			String keyCol = "";
			if (rSet.next())
			{
				keyString = rSet.getString("KEY_STRING");
				keyCol = rSet.getString("TRAN_ID_COL");
				tranSer1 = rSet.getString("REF_SER");
			}
			SimpleDateFormat sdfAppl = new SimpleDateFormat(genericUtility.getApplDateFormat());

			currDate = new java.sql.Timestamp(System.currentTimeMillis());
			String currDateStr = sdfAppl.format(currDate);			
			System.out.println("keyString :"+keyString);
			System.out.println("keyCol :"+keyCol);
			System.out.println("tranSer1 :"+tranSer1);
			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues +		"<tran_id></tran_id>";
			xmlValues = xmlValues +		"<site_code>" + siteCode + "</site_code>";
			xmlValues = xmlValues +		"<desp_date>" + currDateStr + "</desp_date>"; 
			xmlValues = xmlValues +		"<tran_date>" + currDateStr + "</tran_date>"; 
			xmlValues = xmlValues + "</Detail1></Root>";
			System.out.println("xmlValues  :["+xmlValues+"]");
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
			//crating new ID
			tranId = tg.generateTranSeqID(tranSer1, keyCol, keyString, conn);
			
			if(rSet != null)
			{
				rSet.close();
				rSet=null;
			}	
			if(pstmt != null)
			{
				pstmt.close();
				pstmt=null;
			}			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{	
				if(rSet != null)
				{
					rSet.close();
					rSet=null;
				}	
				if(pstmt != null)
				{
					pstmt.close();
					pstmt=null;
				}				
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return checkNull( tranId);
	}
	
	private String getUniqueKey(Connection con, String winName, String tranDate,String siteCode,String balGrp,String balType,String balPrd,String refSer,String drCr,
			String docType,String refId,String itemCode,String taxCode,String suppCode,String taxChap,String matCate )throws ITMException
	{
		String uniqueKey = null;
		String xmlValues = "";
		try
		{
			System.out.println("Generating Primary Key ..........."+tranDate);
		
			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues + "<sr_no><![CDATA[]]></sr_no>";
			xmlValues = xmlValues +"<site_code><![CDATA[" + siteCode + "]]></site_code>";
			xmlValues = xmlValues +"<tran_date><![CDATA[" + tranDate + "]]></tran_date>";
			
			// to generate sr_no based on any of the value.start
			xmlValues = xmlValues +"<bal_group><![CDATA[" + balGrp + "]]></bal_group>";
			xmlValues = xmlValues +"<bal_type><![CDATA[" + balType + "]]></bal_type>";
			xmlValues = xmlValues +"<bal_prd><![CDATA[" + balPrd + "]]></bal_prd>";
			xmlValues = xmlValues +"<ref_ser><![CDATA[" + refSer + "]]></ref_ser>";
			xmlValues = xmlValues +"<drcr_flag><![CDATA[" + drCr + "]]></drcr_flag>";
			xmlValues = xmlValues +"<bal_group__adj><![CDATA[" + balGrp + "]]></bal_group__adj>";
			
			xmlValues = xmlValues +"<doc_type><![CDATA[" + docType + "]]></doc_type>";
			xmlValues = xmlValues +"<ref_id><![CDATA[" + refId + "]]></ref_id>";
			
			xmlValues = xmlValues +"<item_code><![CDATA[" + itemCode + "]]></item_code>";
			xmlValues = xmlValues +"<tax_code><![CDATA[" + taxCode + "]]></tax_code>";
			xmlValues = xmlValues +"<supp_code><![CDATA[" + suppCode + "]]></supp_code>";
			xmlValues = xmlValues +"<tax_chap><![CDATA[" + taxChap + "]]></tax_chap>";
			xmlValues = xmlValues +"<material_category><![CDATA[" + matCate+ "]]></material_category>";
			
			// to generate sr_no based on any of the value.end

            xmlValues = xmlValues +"</Detail1></Root>";



			Statement stmt = null;
			ResultSet rSet = null;

			String keyStringQuery = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = '" + winName +"' ";
			stmt = con.createStatement();
			rSet = stmt.executeQuery(keyStringQuery);

			String tranSer = null;
			String keyString = null;
			String keyCol = null;
			if(rSet.next())
			{
				keyString = rSet.getString("KEY_STRING");
				keyCol = rSet.getString("TRAN_ID_COL");
				tranSer = rSet.getString("REF_SER");
				
			}
			rSet.close();
			rSet = null; 
			stmt.close();
			stmt = null;
			CommonConstants commonConstants = new CommonConstants();
		
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", commonConstants.DB_NAME);
			uniqueKey = tg.generateTranSeqID(tranSer, keyCol, keyString, con);
			System.out.println("Generated tran_id........" + uniqueKey);
		}
		catch(Exception e)
		{
			System.out.println("Exception : getUniqueKey :==>\n"+e);
			uniqueKey = null;
			throw new ITMException(e);
		}
		//System.out.println("Generated Primary Key :"+uniqueKey);
		return uniqueKey;
	}



}
