
/********************************************************
 Title : MSRTWiseCallAverageReport (Request Id: BI3DNOV001)
 Date  : 11/11/2013
 Developer: Swati Bade

 ********************************************************/

package ibase.dashboard.umpl.ejb;

import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;


/**
 * Session Bean implementation class MSRTerritorywiseCallAvg
 */
@Stateless

public class MSRTWiseCallAverageReport extends ValidatorEJB implements MSRTWiseCallAverageReportRemote, MSRTWiseCallAverageReportLocal {

    /**
     * Default constructor. 
     */
	StringBuffer xmlDataForTerr = null;
	String TerrLocation="";
	
    public MSRTWiseCallAverageReport() throws RemoteException, ITMException
    {
        // TODO Auto-generated constructor stub
    	String sql = "";
		ResultSet rs = null;		
		Connection conn = null;		
		PreparedStatement pstmt = null;
		ConnDriver connDriver = new ConnDriver();	   
	    String firstDateofMonth="";
	    String lstDateofMonth="";
	    Calendar cal=null;
	    SimpleDateFormat sdf=null;
	    List<String> terrLoc=new ArrayList<String>();
	    try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			//coding for generate  territory location combo box 
			sql=" select distinct EMP.hobby4 as Ter_code,STATION.DESCR AS Ter_desc "
				 +" from EMPLOYEE EMP ,Station "
				 +" where TRIM(EMP.HOBBY4) = TRIM(Station.Stan_Code)";
			pstmt = conn.prepareStatement(sql); 
			rs    = pstmt.executeQuery();
			xmlDataForTerr = new StringBuffer("<?xml version=\"1.0\"?><Root>");
			while(rs.next())
			{ 
				xmlDataForTerr.append("<Detail>");				
				xmlDataForTerr.append("<fld_value>").append("<![CDATA[" + checkNull(rs.getString("Ter_code"))+"]]>").append("</fld_value>");
				xmlDataForTerr.append("<descr>").append("<![CDATA[" + checkNull(rs.getString("Ter_desc"))+"]]>").append("</descr>");
				xmlDataForTerr.append("</Detail>");
			}
			xmlDataForTerr.append("</Root>");
			
			System.out.println("Territory Location Drop Down List=="+xmlDataForTerr);
			pstmt.close();
		    rs.close();
			pstmt = null;   					  
			rs = null;
		}
	    catch (Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		} finally
		{
			try
			{
				  if (conn != null)
			       {
				  	conn.close();
					conn = null;
			       }
					if (rs != null)
					{
						rs.close();
					    rs = null;
					}
					if (pstmt != null)
					{
						pstmt.close();
					    pstmt = null;
					}
				
			} catch (Exception d)
			{
				d.printStackTrace();
				throw new ITMException(d);
			}
		}
    	
    }
    
    public String getTerritoryLocXmlData() throws RemoteException, ITMException
	{
    	return xmlDataForTerr.toString();
	}
    
    public String getMSRWiseCallAvgDetail(String frmDate,String toDate,String territoryLoc) throws RemoteException,ITMException
	{
    	StringBuffer xmlData = null;
    	ResultSet rs = null;		
		PreparedStatement pstmt = null;
		Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		String sql="",territoryDescr="",prevTerritoyCode=null,tabSP="",tabName="",terrCode;
    	int count=0;
		
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			double doctorCalls=0.0,fldWrkngDays=0.0;
			System.out.println("territoryLoc-->"+territoryLoc);
			sql = 	" SELECT "
				   +" TAB1.SP,TAB1.Name, "
				   +" TAB1.Ter_code,TAB1.TERRITORY, "
				   +" SUM(TAB1.FIELD_WORKING_DAYS) FIELD_WORKING_DAYS, SUM(TAB1.DOCTOR_CALL) DOCTOR_CALL "
				   +" FROM( "
				   +" SELECT SM.SALES_PERS SP,S.SP_NAME Name,EMP.hobby4 as Ter_code,STATION.DESCR AS TERRITORY,0 AS IMPORTANT_DOCTOR_COVERED,0 AS CORE_DOCTOR_COVERED,COUNT(DISTINCT SM.EVENT_DATE) FIELD_WORKING_DAYS,0 AS DOCTOR_CALL,0 AS TC,0 AS IMPORTANT_DOCTORS_VISITED_ONCE,0 AS TARGET_DOCTORS,0 AS  CORE_DOCTORS_VISITED_TWICE " 
				   +" FROM STRG_MEET SM JOIN "
				   +" SALES_PERS S " 
				   +" ON SM.SALES_PERS = S.SALES_PERS "
				   +" INNER JOIN "
				   +" EMPLOYEE EMP  "
				   +" ON EMP.EMP_CODE = S.SALES_PERS "
				   +" Inner join "
				   +" Station on TRIM(EMP.HOBBY4) = TRIM(Station.Stan_Code) "
				   +" WHERE  "
				   +" SM.EVENT_DATE BETWEEN ? AND ? AND STRG_TYPE = 'D' "
				   +" AND S.ITEM_SER ='OTC'" +
				   "  AND TRIM(EMP.HOBBY4) in("+territoryLoc+") "
				   +" AND SM.EVENT_TYPE in (select activity_code from fieldactivity where activity_type='FW') "
				   +" GROUP BY SM.SALES_PERS, S.SP_NAME,EMP.hobby4,STATION.DESCR "
				   +" UNION ALL "
				   +" SELECT SM.SALES_PERS SP,S.SP_NAME Name,EMP.hobby4 as Ter_code,STATION.DESCR AS TERRITORY,0 AS IMPORTANT_DOCTOR_COVERED,0 AS CORE_DOCTOR_COVERED,0 AS FIELD_WORKING_DAYS,COUNT(*) DOCTOR_CALL,0 AS TC,0 AS IMPORTANT_DOCTORS_VISITED_ONCE,0 AS TARGET_DOCTORS,0 AS  CORE_DOCTORS_VISITED_TWICE " 
				   +" FROM STRG_MEET SM JOIN "
				   +" SALES_PERS S "
				   +" ON SM.SALES_PERS = S.SALES_PERS "
				   +" INNER JOIN "
				   +" EMPLOYEE EMP  "
				   +" ON EMP.EMP_CODE = S.SALES_PERS "
				   +" Inner join "
				   +" Station on TRIM(EMP.HOBBY4) = TRIM(Station.Stan_Code) "
				   +" WHERE  "
				   +" SM.EVENT_DATE BETWEEN ? AND ? AND STRG_TYPE = 'D' "
				   +" AND S.ITEM_SER ='OTC' "
				   +" AND TRIM(EMP.HOBBY4) in("+territoryLoc+")"
				   +" GROUP BY SM.SALES_PERS, S.SP_NAME,EMP.hobby4,STATION.DESCR)TAB1 "
				   +" GROUP BY TAB1.SP, TAB1.Name,TAB1.Ter_code,TAB1.TERRITORY "
				   +" ORDER BY TAB1.TERRITORY ";
			
			
			pstmt = conn.prepareStatement(sql); 
			pstmt.setString(1,frmDate);
		    pstmt.setString(2,toDate);
		    pstmt.setString(3,frmDate);
		    pstmt.setString(4,toDate);
			rs = pstmt.executeQuery();
			xmlData = new StringBuffer("<?xml version=\"1.0\"?><Root>");
			xmlData.append("<Detail>");	
			while(rs.next())
			{
				count++;
				terrCode=checkNull(rs.getString("Ter_code"));
				territoryDescr=checkNull(rs.getString("TERRITORY"));
				doctorCalls=Double.parseDouble(checkNull(rs.getString("DOCTOR_CALL")));
				fldWrkngDays=Double.parseDouble(checkNull(rs.getString("FIELD_WORKING_DAYS")));
				tabSP=checkNull(rs.getString("SP"));
				tabName=checkNull(rs.getString("Name"));
				
				prevTerritoyCode=prevTerritoyCode==null?"":prevTerritoyCode.trim();
				
				System.out.println("prevTerritoy:"+prevTerritoyCode+": terrCode:"+terrCode+": territoryDescr:"+territoryDescr);
				
				if(count>1 && (!((prevTerritoyCode).equals(terrCode.trim()))))
				{
					xmlData.append("</territory>");
					xmlData.append("<territory name='"+territoryDescr+"'>");	
					xmlData.append("<sp_code code='"+tabSP+"'>");	
					xmlData.append("<msr_name>").append("<![CDATA["+tabName+"]]>").append("</msr_name>");
					xmlData.append("<fld_working_days>").append("<![CDATA["+fldWrkngDays+"]]>").append("</fld_working_days>");
					xmlData.append("<doctor_call>").append("<![CDATA["+doctorCalls+"]]>").append("</doctor_call>");	
					xmlData.append("<call_avg>").append("<![CDATA["+(doctorCalls/fldWrkngDays)+"]]>").append("</call_avg>");
					xmlData.append("</sp_code>");
				}
				if(count>1 &&((prevTerritoyCode).equals(terrCode.trim())))
				{
				xmlData.append("<sp_code code='"+tabSP+"'>");	
				xmlData.append("<msr_name>").append("<![CDATA["+tabName+"]]>").append("</msr_name>");
				xmlData.append("<fld_working_days>").append("<![CDATA["+fldWrkngDays+"]]>").append("</fld_working_days>");
				xmlData.append("<doctor_call>").append("<![CDATA["+doctorCalls+"]]>").append("</doctor_call>");	
				xmlData.append("<call_avg>").append("<![CDATA["+(doctorCalls/fldWrkngDays)+"]]>").append("</call_avg>");
				xmlData.append("</sp_code>");
				}
				if(count==1 && (!(prevTerritoyCode).equals(terrCode.trim())))
				{
					xmlData.append("<territory name='"+territoryDescr+"'>");									
					xmlData.append("<sp_code code='"+tabSP+"'>");
					xmlData.append("<msr_name>").append("<![CDATA["+tabName+"]]>").append("</msr_name>");
					xmlData.append("<fld_working_days>").append("<![CDATA["+fldWrkngDays+"]]>").append("</fld_working_days>");
					xmlData.append("<doctor_call>").append("<![CDATA["+doctorCalls+"]]>").append("</doctor_call>");	
					xmlData.append("<call_avg>").append("<![CDATA["+(doctorCalls/fldWrkngDays)+"]]>").append("</call_avg>");
					xmlData.append("</sp_code>");
					
				}
				prevTerritoyCode=checkNull(rs.getString("Ter_code"));
				
				
			}
			if(count>0)
			{
				
				xmlData.append("</territory>");
			}
			xmlData.append("</Detail>");
			xmlData.append("</Root>");
			System.out.println("xml in ejb:"+xmlData.toString());
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (conn != null)
				{
					if (rs != null)
						rs.close();
					rs = null;
					if (pstmt != null)
						pstmt.close();
					pstmt = null;
					conn.close();
					conn = null;
				}
				conn = null;
			} catch (Exception d)
			{
				d.printStackTrace();
				System.out.println("Exception in :MSRTerritorywiseCallAvg:getMSRWiseCallAvgData:"+d.getMessage());
				throw new ITMException(d);
			}
		}
		return xmlData.toString();
	}
    
    
    private String checkNull(String input)
	{
		if (input == null)
		{
			input = "";
		} else
		{
			input = input.trim();
		}
		return input;
	}
    

}
