package com.bankaudit.rest.process.dao;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.persistence.Column;
import javax.persistence.Id;

import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.ResultTransformer;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;

import com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.dao.AbstractDao;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.dto.EntityAuditDataDto;
import com.bankaudit.dto.process.AuditDto;
import com.bankaudit.dto.process.AuditObservationDto;
import com.bankaudit.dto.process.AuditRatingComplianceScoreDto;
import com.bankaudit.model.MaintAuditTypeDesc;
import com.bankaudit.model.MaintEntity;
import com.bankaudit.model.RiskScorePercentage;
import com.bankaudit.model.User;
import com.bankaudit.process.model.AuditActionItem;
import com.bankaudit.process.model.AuditObservation;
import com.bankaudit.process.model.AuditObservationReportReviewCapture;
import com.bankaudit.process.model.AuditObservationReportReviewCaptureWrk;
import com.bankaudit.process.model.AuditRating;
import com.bankaudit.process.model.AuditSchedule;
import com.bankaudit.process.model.AuditScheduleStagesStatusHst;
import com.bankaudit.process.model.AuditTeam;
import com.bankaudit.process.model.RiskSummaryDtls;
import com.bankaudit.rest.process.service.AuditProcessVService;
import com.bankaudit.rest.process.service.AuditRatingComplianceScoreService;
import com.bankaudit.rest.process.service.AuditScheduleStagesStatusHstService;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.MaintAuditTypeDescService;
import com.bankaudit.service.MaintEntityService;
import com.bankaudit.service.MaintHolidayService;
import com.bankaudit.service.SequenceAppenderService;
import com.bankaudit.util.BankAuditUtil;

/*MaintEntityDataEffect */
@Repository("myAuditsDao")
public class MyAuditsDaoImpl extends AbstractDao implements MyAuditsDao{
	
	@Autowired
	BusinessDateService businessDateService;
		
	@Autowired
	AuditProcessVService auditProcessVService;
	
	@Autowired(required=true)
	AuditObservationDao auditObservationDao;
	
	@Autowired
    SequenceAppenderService sequenceAppenderService;
	
	@Autowired
    ReportDao reportDao;
	
	@Autowired
    MaintEntityService maintEntityService;
	
	@Autowired
	AuditScheduleDao auditScheduleDao; 
	
	@Autowired
	MaintHolidayService maintHolidayService;
	
	@Autowired
	MaintAuditTypeDescService maintAuditTypeDescService;
	
	@Autowired
	AuditScheduleStagesStatusHstService auditScheduleStagesStatusHstService;
	 
	@Lazy
	@Autowired
	AuditRatingComplianceScoreService auditRatingComplianceScoreService;
	
	static final Logger logger = Logger.getLogger(MyAuditsDaoImpl.class);
	
	@SuppressWarnings("unchecked")
	@Override
	public DataTableResponse getMuAuditsList(int legalEntityCode,String userId, String search, Integer orderColumn,
			String orderDirection, Integer page, Integer size, String roleId,
			LocalDate financialYear, String auditTypeCode, List<LocalDate>  financialYearStrtEndList) { // Added to filter the records based on Financial Year and AuditType

		Session session = getSession();
		session.setDefaultReadOnly(true);

		logger.info("Inside getMuAuditsList .."+userId +" :: "+roleId);
		/********************** This block is to retrieve the User details --> UserId and UserName **************************/
		StringBuilder queryString0=new StringBuilder(// " Select concat(u.firstName , ' ' , u.lastName) as firstName, u.userId "
				 " FROM User u WHERE u.legalEntityCode =:legalEntityCode ");
		
		Query query1=session.createQuery(queryString0.toString()).setParameter("legalEntityCode", legalEntityCode);
		
		List lst = query1.list();
		HashMap<String, String> userDtls = new HashMap<String, String>();
		for ( Iterator iter = lst.iterator(); iter.hasNext(); ) {
			User usr = (User) iter.next();
			if(usr.getUserId().equalsIgnoreCase(userId))
				userDtls.put(usr.getUserId(), "Me"); // for the same User we are stamping as "You"
			else userDtls.put(usr.getUserId(), (usr.getFirstName()==null?"":usr.getFirstName()) 
											+ (usr.getMiddleName()==null?"":(" "+usr.getMiddleName())) 
											+ (usr.getLastName()==null?"":(" "+usr.getLastName())) );	
		}
		logger.info("userId is .... "+ userId+" serach:: "+search +" legal entity code:: "+legalEntityCode);
		logger.info("User details val is .... "+ userDtls);
		/******************** User Retrieval logic, Ends here ********************************/
		
		/***************** Logic to retrieve duration and No. of Audits from general parameter table and  ****
		 ***************** 	comparing both to find out the minimum, Starts here 	      ********************/
		Date businessDate =businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		logger.info("businessDate .... "+ businessDate);
		StringBuilder queryString2=new StringBuilder( " select nd.auditsInInterval,nads.noAudits from " 
				+ " ( select count(*) as auditsInInterval from audit_schedule ash, audit_team atm " 
				+ "	where ash.plan_id=atm.plan_id and ash.audit_id = atm.audit_id and ash.legal_entity_code=atm.legal_entity_code and atm.user_id=:userId " 
				+ "          and (ash.schedule_start_date between :businessDate and " 
				+ "				ADDDATE(:businessDate, INTERVAL (select g.value from general_parameter g where key_1='AUDITOR_VISIBILITY' AND key_2='DAYS' AND g.legal_entity_code=ash.legal_entity_code ) DAY))  ) as nd, " 
				+ " ( select g.value as noAudits from general_parameter g where g.key_1='AUDITOR_VISIBILITY' AND g.key_2='NO_OF_AUDITS' AND g.legal_entity_code=:legalEntityCode) as nads "  
				); 
		//(select g.value from GeneralParameter g where g.key1='AUDITOR_VISIBILITY' AND g.key2='DAYS' AND g.legalEntityCode=:legalEntityCode) 
		
		Query query2lst=session.createSQLQuery(queryString2.toString())
				.setParameter("legalEntityCode", legalEntityCode).setParameter("userId", userId)
				.setParameter("businessDate", businessDate);
		
		Object obj = query2lst.uniqueResult();
		int auidtsDisplay = 100;
		try{
			if(obj != null  && ((Object[])obj).length > 0)
			{
				int auditsInInterval  =Integer.parseInt( ((Object[])obj)[0].toString());
				int  noOfAudit=Integer.parseInt( ((Object[])obj)[1].toString());
				logger.info("auditsInInterval .... "+ auditsInInterval +" noOfAudit.... "+noOfAudit);
				if(auditsInInterval > noOfAudit) auidtsDisplay=noOfAudit;
				else auidtsDisplay = auditsInInterval;
			}
		}catch(Exception e) {
			logger.info("Exception occured ....");
		}
		logger.info("auidtsDisplay .... "+auidtsDisplay);
		/******************** Logic for no of Audits, Ends here ********************************/
			
		/***************** Logic to retrieve the Visible Audits, which are in Planned state. Based on the above Output ****/
		logger.info("businessDate .... "+ businessDate);
		StringBuilder queryString3=new StringBuilder( " select audit_id from audit_schedule s "
				+ "	where legal_entity_code=:legalEntityCode and audit_status in ('AP') " 
				+ "		and audit_id in(select t.audit_id from audit_team t where t.legal_entity_code=s.legal_entity_code and t.user_id=:userId) " 
				+ "	order by schedule_start_date asc limit :auidtsDisplay "); 
		
		List visibleAuditList=session.createNativeQuery(queryString3.toString())
				.setParameter("legalEntityCode", legalEntityCode).setParameter("userId", userId)
				.setParameter("auidtsDisplay", auidtsDisplay).list();
		logger.info("visibleAuditList .... "+visibleAuditList);
		if(visibleAuditList != null && visibleAuditList.size() < 1) visibleAuditList.add("NoAudit"); // If the Audit visibility is 0, then we are passing NoAudit
		/******************** Logic for Visible Audits, Ends here ********************************/
		
		/************************** ********************************************/
		/*StringBuilder queryString4=new StringBuilder( " select user_role_id from user_role_mapping where legal_entity_code=:legalEntityCode and user_id=:userId limit 1"); 
		String roleId=(String)session.createNativeQuery(queryString4.toString())
				.setParameter("legalEntityCode", legalEntityCode).setParameter("userId", userId)
				.uniqueResult();*/
		logger.info("roleId .... "+roleId);
		List<String> maintEntities = null;
		if(roleId != null && (roleId.equalsIgnoreCase("G1") || roleId.equalsIgnoreCase("G6"))) {
			maintEntities=maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode,"user",userId);
			logger.info("maintEntities .... "+maintEntities);
		}
		
		/****************************** ****************************************/
		
		// Logic added to filter the Records based on Financial Year and Audit Type
		logger.info("financial Year :: "+ financialYear +" auditTypeCode :: "+auditTypeCode +" financial Year StartEnd:: "+ financialYearStrtEndList);
		
		boolean isDeptAsRMD =false;
		isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, "", userId);
		
		DataTableResponse dataTableResponse=new DataTableResponse();
		try {
		//StringBuilder queryString=new StringBuilder(" from AuditSchedule where legalEntityCode =:legalEntityCode ");
		StringBuilder queryString=new StringBuilder("select sch as auditSchedule, " 
				+ " legalEntityCode,"
				+ "(select concat(auditTypeCode , '-' , auditTypeDesc) from MaintAuditTypeDesc at where at.auditTypeCode=sch.auditTypeCode and at.legalEntityCode= sch.legalEntityCode ) as auditTypeCode,"
				
				+ "planId,auditId, "
				//+ " (Select concat(unitCode , '-' , unitName) from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitId,  "
				+ " (Select  unitName from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitName,  "
				+ " (Select g.description from  MaintEntity e,GeneralParameter g where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=e.unitType) as unitType, "
				
				+ " (Select c.criticalityDesc from  MaintEntity e,MaintCriticality c where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =c.legalEntityCode and e.uCriticality=c.criticalityCode and c.criticalityOfType='Entity') as uCriticality, "
				
				//+ " (Select concat(u.firstName , ' ' , u.lastName) from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
				+ " (Select t.userId from  AuditTeam t where t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
				
				+" duration," //Code to comment //+ " (Select p.duration from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as duration, "
				+" frequency," //Code to comment //+ " (Select p.frequency from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as frequency, "
				//+ " (select tm.auditTypeCode,GROUP_CONCAT(tm.name) from (Select t.auditTypeCode,t.planId, t.auditId, concat(u.firstName , ' ' , u.lastName) as name from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='T') tm where  GROUP BY tm.auditTypeCode  ) as teamMember "
				+ " (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus) as auditStatus, "
				
				//+ " (Select concat(u.userId , '-' , u.firstName, ' ',u.middleName,' ',u.lastName) from  User u where u.legalEntityCode =sch.legalEntityCode and u.userId=sch.maker) as maker "
				+ " (Select concat(u.userId , '-' , ifnull(u.firstName,''), ' ',ifnull(u.middleName,''),' ',ifnull(u.lastName,'') ) "
				+ " from  User u where u.legalEntityCode =sch.legalEntityCode and u.userId=sch.maker) as maker "
								
				//+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='N' and o.reviewStatus='R' ) as responseReject "
				//+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='C' and o.submissionStatus='A') as complianceCount "
				//+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='NA' and o.submissionStatus='A') as notApplicableCount "
				+" ,0,0,0 "  // No need to calculate responseReject, Compliance, NA
				//+ " , auditStatus "
				+ ", (Select g.value from GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='AUDIT_EARLY_START' and g.key2='EARLY_START_ALLOWED') as earlyStartAllowed "
				+ ", (Select g.value from GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='AUDIT_OFFSET_DAYS' and g.key2='AUDIT_OFFSET_DAYS') as auditOffsetDays " 
				+ ", (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.observationStatus) as auditStatusTemp " // This result to stamp in Audit status in the Observation status is AE i.e Audit Reported
				+ ", (select group_concat(t.userId) from AuditTeam t where t.legalEntityCode=sch.legalEntityCode AND t.auditId=sch.auditId AND t.userType='M' ) AS teamMember "
				+" ,   sch.reportStatus " // Report review status added for BaaSDOS implementation 
				+ ",  (Select concat(sch.reportStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='REPORT_STATUS' and g.value=sch.reportStatus) as reportStatusDesc " // Report review status desc added for BaaSDOS implementation 
								
			 	+ " , (Select concat(sch.status , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode "
				+ " and g.key1='STATUS' and g.key2='STATUS' and g.value=sch.status) as authStatus "  
				+ ", (Select  g.description from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='REPORT_STATUS' and g.value=sch.reportStatus) as reportStatusDescOnly " // to get the Report Status on 13Dec24					
				+ ", (Select  (CASE WHEN sch.auditStatus ='AI' and sch.observationStatus='AE' then 'Exited' "
				+ " 		ELSE  g.description END) as Desc from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and "
				+ "  		g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus) as auditStatusDescOnly "  // To get the Audit status description on 13Dec24
				
				+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode "
				//+ " and sch.legalEntityCode=t.legalEntityCode and t.auditId=sch.auditId and t.userId=:userId"
				// + " and  IFNULL(auditStatus,'NotNull') not in ('AD','AU','DRP','UP') "
				// Condition added to get the Assessments, For processing check with AuitTeam table till AC audit status , for View check with User table from AC audit status
				+ " and  ( (sch.auditId IN (SELECT t.auditId FROM AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userId=:userId  ) "
				+ "           AND IFNULL(auditStatus,'NotNull') IN ('AP','AI','AS','AR','AW','AC') )" );   // 'AW','AC' included to show the Inspections after Closure as well to the Inspectors
				//+ "        OR ( (sch.unitId IN  (SELECT u.unitCode FROM User u WHERE u.unitCode=sch.unitId and  u.legalEntityCode =sch.legalEntityCode and u.userId=:userId) ) "
				//+ "			  AND  IFNULL(auditStatus,'NotNull') IN ('AW','AC')  )   " );
				if(roleId != null && (roleId.equalsIgnoreCase("G1") || roleId.equalsIgnoreCase("G6"))) {
					queryString.append(" OR (sch.unitId IN (:maintEntities) AND  IFNULL(auditStatus,'NotNull') IN ('AP','AI','AS','AR','AW','AC')) ");
				}else if(roleId != null && !(roleId.equalsIgnoreCase("G2") || roleId.equalsIgnoreCase("G8"))){
					queryString.append(" OR ( (sch.unitId IN  (SELECT u.unitCode FROM User u WHERE u.unitCode=sch.unitId and  u.legalEntityCode =sch.legalEntityCode and u.userId=:userId) ) "
							+ " AND  IFNULL(auditStatus,'NotNull') IN ('AW','AC')  ) ");
				}
				queryString.append(" ) ");
				
				// Financial Year and Audit Type filter added for filtering
				if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
					queryString.append(" AND  sch.auditTypeCode =:auditTypeCode "); 
				}if(financialYear !=null) {
					LocalDate fYStartDt = financialYearStrtEndList.get(0);
					LocalDate fYearEndDt = financialYearStrtEndList.get(1);
					logger.info("fYStartDt :: "+fYStartDt+" fYEndDt :: "+fYearEndDt);
					//queryString.append(" And (sch.scheduleStartDate between :fYStartDt and :fYearEndDt )");
					queryString.append(" AND (sch.scheduleStartDate between '"+fYStartDt+"' AND '"+fYearEndDt+"' )");
				}
				
			// Condition end here
				/*if(!isDeptAsRMD) {
					queryString.append(" and  sch.auditTypeCode IN (SELECT asgm.auditTypeCode FROM MaintEntityAuditSubgroupMapping as asgm WHERE asgm.legalEntityCode=sch.legalEntityCode and asgm.mappingType='U' and asgm.id =:userId )"); // To show the Assessments to which the Assessor Mapped (Department mapping)
				}*/
				//if(visibleAuditList !=null && visibleAuditList.s)
				//+ " and (sch.auditId  IN :visibleAuditList  OR auditStatus in ('AI','AS','AR','AC','AU','UP','AD','AW')) " //commented to remove Visibility cond, Condition included to get the Audits as per the Visibility logic maintained in general parameter.
						
				
				logger.info("Before the qry....");
		
		if(!BankAuditUtil.isEmptyString(search)){
			queryString=queryString.append(" and ( "
					+ " sch.auditTypeCode IN (SELECT a.auditTypeCode FROM MaintAuditTypeDesc a  WHERE a.legalEntityCode=sch.legalEntityCode AND (a.auditTypeDesc LIKE :search OR a.auditTypeCode LIKE :search)) "
					+ " or planId like :search "
					+ " or auditId like :search "
					//+ " or unitId like :search "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m WHERE m.legalEntityCode=sch.legalEntityCode AND (m.unitName LIKE :search or m.unitCode LIKE :search )) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,GeneralParameter g WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=m.unitType and g.description LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintCriticality c WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =c.legalEntityCode and m.uCriticality=c.criticalityCode and c.criticalityOfType='Entity' and  c.criticalityDesc LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintAuditParameter p WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =p.legalEntityCode and m.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and  p.duration LIKE :search) "
					+ " or sch.auditId IN (SELECT t.auditId FROM User u,AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.legalEntityCode =u.legalEntityCode and t.userId=u.userId and (t.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or DATE_FORMAT(sch.scheduleStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.scheduleEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.lastAuditDate, '%d %b %Y') LIKE :search "
					+ " or sch.maker IN (SELECT u.userId FROM User u WHERE u.legalEntityCode =sch.legalEntityCode and (u.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus and g.description LIKE :search) "
					+ " or sch.reportStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' and g.key2='REPORT_STATUS' and g.value=sch.reportStatus and g.description LIKE :search) "
					// + " or teamMember like :search "
					+ " or sch.auditId IN (select t.auditId from AuditTeam t, User u where t.legalEntityCode=sch.legalEntityCode AND t.auditId=sch.auditId AND t.userType='M' AND t.legalEntityCode=u.legalEntityCode AND t.userId=u.userId "
					+ "						AND sch.unitId=u.unitCode AND (u.firstName like :search OR u.middleName like :search OR u.lastName like :search OR u.userId like :search )) "
					
					//+ " ) "
					
						+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' "
						+ " and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus "
						+ " and (g.description LIKE :search or g.value LIKE :search)"
						+ " and   ( sch.observationStatus !='AE'  ) "
						+ " ) "
						
						+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' "
						+ " and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus "
						+ " and (g.description LIKE :search or g.value LIKE :search)"
						+ " and   ( sch.observationStatus  ='AE' and sch.auditStatus='AW'  ) "
						+ " ) " 
						
						+ "  " );
						
						if((search.length()==2 && search.toUpperCase().startsWith("EX") )
						|| (search.length()==3 && search.toUpperCase().startsWith("EXI"))
						|| (search.length()==4 && search.toUpperCase().startsWith("EXIT"))
						|| ((search.length()==5 || search.length()==6) && search.toUpperCase().startsWith("EXITE")) ){
							queryString.append("Or (sch.auditStatus='AI' and sch.observationStatus='AE' ) )");
						}	
						else{
							queryString.append(" )" );
							if(search.toUpperCase().startsWith("INI")){
								queryString.append("and  ( sch.auditStatus='AI' and (sch.observationStatus is null or sch.observationStatus='' ) )");
							}
						}
					/*queryString.append(" )" );*/
		}
		
		/*queryString=queryString.append("  ORDER BY FIELD(auditStatus, 'AI','P','AP','AS','AC','AU') asc ");*/
		String[] columns={
				"auditTypeCode",
				"(auditId *1 ), (planId *1 )", //"CAST(planId AS Integer),CAST(auditId AS Integer) "
				"unitType",
				"(unitId * 1) ",  //"unitId",
				"uCriticality",
				"duration",
				"lastAuditDate",//last audit date actually 
				"sch.scheduleStartDate",
				"sch.scheduleEndDate",
				"sch.actualStartDate",
				"sch.actualEndDate",
				"teamLead", // Team Lead
				// "sch.maker", // Team Member
				"sch.maker",
				"reportStatusDescOnly" , // "sch.reportStatus",
				"auditStatusDescOnly", // "sch.auditStatus"
				"unitName",  
				"financialYear"
		};

		/*if(orderColumn!=null
				&& !BankAuditUtil.isEmptyString(orderDirection)){
			queryString=queryString.append(" order by ").append(columns[orderColumn]).append(" ").append(orderDirection);
		}*/
		logger.info(" orderColumn **.... "+ orderColumn +"  orderDirection ...."+ orderDirection );
		if(orderColumn != null && orderColumn == -1 && !BankAuditUtil.isEmptyString(orderDirection)){ // -1 send for the first time from the UI during landing page.
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc  "); // The code modified to get the records in the order of Status on landing page, the sequence is  Initiated, Planned, Submitted, Respond, Reviewed, Closed
		}else if(orderColumn!=null && !BankAuditUtil.isEmptyString(orderDirection)){
			if(orderColumn==0) {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection).append(" , FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc ,(auditId *1 ) asc  ");
			}else {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection);
			}
		}else {
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc  ");
		}
		
		logger.info("queryString .... "+ queryString.toString());
		
		Query query=(Query) session.createQuery(queryString.toString())				
				.setResultTransformer(new ResultTransformer() {
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						AuditSchedule auditSchedule=null;
						//System.out.println("tuple[0] ...."+tuple[0]);
						if(tuple[0]!=null){
							auditSchedule=(AuditSchedule)tuple[0];
							/* session.evict(maintEntity);*/
							
							if(tuple[1]!=null){
								auditSchedule.setLegalEntityCode(Integer.parseInt(tuple[1].toString()));								
							}
							if(tuple[2]!=null){
								auditSchedule.setAuditTypeCode(tuple[2].toString());
							}
							
							if(tuple[3]!=null){
								auditSchedule.setPlanId(tuple[3].toString());
							}
							
							if(tuple[4]!=null){
								auditSchedule.setAuditId(tuple[4].toString());
							}
							if(tuple[5]!=null){
								String unitCodeName=tuple[5].toString();
								//auditSchedule.setUnitId(unitCodeName);
								//auditSchedule.setUnitName(unitCodeName.substring(unitCodeName.indexOf('-')+1));
								auditSchedule.setUnitId(auditSchedule.getUnitId()+"-"+unitCodeName);
								auditSchedule.setUnitName(unitCodeName);
							}
							if(tuple[6]!=null){
								auditSchedule.setUnitType(tuple[6].toString());
							}
							if(tuple[7]!=null){
								auditSchedule.setuCriticality(tuple[7].toString());
							}
							if(tuple[8]!=null){ 
									String teamLead = userDtls.get(tuple[8].toString());
									auditSchedule.setTeamLead(teamLead.equalsIgnoreCase("Me")?"Me":tuple[8].toString()+"-"+teamLead);
								 
								//auditSchedule.setTeamLead(tuple[8].toString()+"-"+userDtls.get(tuple[8].toString()));
								//auditSchedule.setTeamLead(userDtls.get(tuple[8].toString()));
							}
							if(tuple[9]!=null){
								auditSchedule.setDuration(tuple[9].toString());
							}
							if(tuple[10]!=null){
								auditSchedule.setFrequency(tuple[10].toString());
							}
							if(tuple[11]!=null){
								if("P".equalsIgnoreCase(tuple[11].toString()))auditSchedule.setAuditStatus("AP"); // temp purpose as in few earlier records the Planned status is reflecting as "P"
								else if("AE".equalsIgnoreCase(auditSchedule.getObservationStatus())) auditSchedule.setAuditStatus(tuple[18] !=null ?tuple[18].toString() :tuple[11].toString() );
								else auditSchedule.setAuditStatus(tuple[11].toString());
							}
							if(tuple[12]!=null){
								auditSchedule.setMaker(tuple[12].toString());
							}
							if(tuple[13]!=null && auditSchedule.getRespondedFindings() != null){
								auditSchedule.setResponseReject(Integer.parseInt(tuple[13].toString()));
								auditSchedule.setRespondedFindings(auditSchedule.getRespondedFindings()- (Integer.parseInt(tuple[13].toString()))); // Included to find out the Responded Observations
							}else auditSchedule.setResponseReject(0);
							
							if(tuple[14]!=null){
								auditSchedule.setComplianceCount(Integer.parseInt(tuple[14].toString()));
							}else auditSchedule.setComplianceCount(0);
							
							if(tuple[15]!=null){
								auditSchedule.setNotApplicableCount(Integer.parseInt(tuple[15].toString()));
							}else auditSchedule.setNotApplicableCount(0);
							
							if(tuple[16]!=null){
								auditSchedule.setEarlyStartAllowed(tuple[16].toString());
							}else auditSchedule.setEarlyStartAllowed("Y");
							
							if(tuple[17]!=null){
								auditSchedule.setAuditOffsetDays(Integer.parseInt(tuple[17].toString()));
							}else auditSchedule.setAuditOffsetDays(0);
							
							if(tuple[19]!=null){
								String teamMembers="";
								String[] members = tuple[19].toString().split(",");
								for (String member: members) {
									teamMembers+=member+"-"+userDtls.get(member)+",";
								}
								auditSchedule.setTeamMember(teamMembers.substring(0,teamMembers.length()-1));
							}
							
							if(tuple[20]!=null) auditSchedule.setReportStatus(tuple[20].toString());
							if(tuple[21]!=null) auditSchedule.setReportStatusDesc(tuple[21].toString());
							
							if(tuple[22]!=null) auditSchedule.setStatus(tuple[22].toString());
							
							/*int tmSize =auditSchedule.getAuditTeams().size()-1;
							String teamMember="";
							System.out.println("Audit Id .... "+ auditSchedule.getAuditId()+" tmSize .."+tmSize);
							for( AuditTeam adtTm: auditSchedule.getAuditTeams() ) {
								
								adtTm.setUserId(adtTm.getUserId()+"-"+userDtls.get(adtTm.getUserId()));
								
								if(!"L".equalsIgnoreCase(adtTm.getUserType())) teamMember +=adtTm.getUserId() + ",";
								System.out.println("teamMember .... "+ teamMember);
							}if(tmSize >0 ) auditSchedule.setTeamMember(teamMember.substring(0,teamMember.lastIndexOf(",")));*/
							//System.out.println("Team member .... "+auditSchedule.getTeamMember());
							//System.out.println("Team size ...."+auditSchedule.getAuditTeams().size());
							
						}
						return auditSchedule;
					}
			@Override
			public List transformList(List collection) {
				return collection;
			}
		})		
				.setParameter("legalEntityCode",legalEntityCode).setParameter("userId",userId); //.setParameter("visibleAuditList", visibleAuditList);
		if(roleId != null && (roleId.equalsIgnoreCase("G1") || roleId.equalsIgnoreCase("G6"))) 
			query.setParameter("maintEntities", maintEntities);
		if(!BankAuditUtil.isEmptyString(search)){
			query.setParameter("search", "%"+search+"%");
		}
		
		if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
			query.setParameter("auditTypeCode", auditTypeCode);
		}
		
		logger.info("page :: "+page +"size :: "+ size);
		List<AuditSchedule> tmpAuditSchedule =query.list(); 
		Long totalRecords=null;
		try {
			totalRecords = (long)tmpAuditSchedule.size();
		}catch(Exception e) {
			totalRecords = (long)0;
		}
		List<AuditSchedule> auditSchedule=query.setFirstResult((page*size)).setMaxResults(size).list();
		
		logger.info("Bfr size tmpAuditSchedule is .... "+tmpAuditSchedule.size()+" totalRecords:: "+ totalRecords);
		
		/*int i=0;
		for(AuditSchedule adSch:auditSchedule){
			System.out.println("Inside adSch ...");
			if("A2".equalsIgnoreCase(adSch.getAuditId()));
			else 	tmpAuditSchedule.add(adSch);
			System.out.println("after the call");
			
		}
		System.out.println("size tmpAuditSchedule .... "+tmpAuditSchedule);*/
		
		
		dataTableResponse.setData(auditSchedule);
		dataTableResponse.setRecordsTotal(totalRecords);
		dataTableResponse.setRecordsFiltered(totalRecords);
		
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return dataTableResponse;
	
	}

	@Override
	public AuditSchedule getAuditByPlanIdAndAuditId(int legalEntityCode, String auditTypeCode, String planId,
			String auditId) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		
		AuditSchedule auditSchedule = null;
		logger.info("getAuditByPlanIdAndAuditId .."+auditTypeCode +" :: "+ auditId );
		try {
			//StringBuilder queryString=new StringBuilder(" from AuditSchedule where legalEntityCode =:legalEntityCode ");
			StringBuilder queryString=new StringBuilder("select sch as auditSchedule, " 
					+ " legalEntityCode,"
					+ "(select concat(auditTypeCode , '-' , auditTypeDesc) from MaintAuditTypeDesc at where at.auditTypeCode=sch.auditTypeCode and at.legalEntityCode= sch.legalEntityCode ) as auditTypeCode,"
					
					+ "planId,auditId, "
					+ " (Select concat(unitCode , '-' , unitName) from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitId,  "
					
					+ " (Select g.description from  MaintEntity e,GeneralParameter g where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=e.unitType) as unitType, "
					
					+ " (Select c.criticalityDesc from  MaintEntity e,MaintCriticality c where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =c.legalEntityCode and e.uCriticality=c.criticalityCode and c.criticalityOfType='Entity') as uCriticality, "
					
					+ " (Select concat(u.firstName , ' ' , u.lastName) from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
					
					+ "  duration," //+ " (Select p.duration from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as duration, "
					+ "  frequency, "//+ " (Select p.frequency from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as frequency, "
					//+ " (select tm.auditTypeCode,GROUP_CONCAT(tm.name) from (Select t.auditTypeCode,t.planId, t.auditId, concat(u.firstName , ' ' , u.lastName) as name from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='T') tm where  GROUP BY tm.auditTypeCode  ) as teamMember "
					+ " (Select prevAuditId from  AuditSchedule sch1 where sch1.legalEntityCode =sch.legalEntityCode and sch1.auditId=sch.prevAuditId ) as prevPrevAuditId, " // Included to get the Previous to previous Audit Id
					+ " (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus) as auditStatus "
					+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='N' and o.reviewStatus='R') as responseReject "
					+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='C' and o.submissionStatus='A') as complianceCount "
					+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='NA' and o.submissionStatus='A') as notApplicableCount "
					+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode  and auditId=:auditId "); /* and planId=:planId */
			System.out.println("Before the qry....");
			
			Query query=(Query) session.createQuery(queryString.toString())				
					.setResultTransformer(new ResultTransformer() {
						@Override
						public Object transformTuple(Object[] tuple, String[] aliases) {
							AuditSchedule auditSchedule=null;
							System.out.println("tuple[0] ...."+tuple[0]);
							if(tuple[0]!=null){
								auditSchedule=(AuditSchedule)tuple[0];
								/* session.evict(maintEntity);*/
								
								if(tuple[1]!=null){
									auditSchedule.setLegalEntityCode(Integer.parseInt(tuple[1].toString()));								
								}
								if(tuple[2]!=null){
									auditSchedule.setAuditTypeCode(tuple[2].toString());
								}
								
								if(tuple[3]!=null){
									auditSchedule.setPlanId(tuple[3].toString());
								}
								
								if(tuple[4]!=null){
									auditSchedule.setAuditId(tuple[4].toString());
								}
								if(tuple[5]!=null){
									auditSchedule.setUnitId(tuple[5].toString());
								}
								if(tuple[6]!=null){
									auditSchedule.setUnitType(tuple[6].toString());
								}
								if(tuple[7]!=null){
									auditSchedule.setuCriticality(tuple[7].toString());
								}
								if(tuple[8]!=null){
									auditSchedule.setTeamLead(tuple[8].toString());
								}
								if(tuple[9]!=null){
									auditSchedule.setDuration(tuple[9].toString());
								}
								if(tuple[10]!=null){
									auditSchedule.setFrequency(tuple[10].toString());
								}
								if(tuple[11]!=null)	auditSchedule.setPrevPrevAuditId(tuple[11].toString()); // Included to get the Previous to previous Audit Id
								
								if(tuple[12]!=null)	auditSchedule.setAuditStatus(tuple[12].toString()); 
								
								if(tuple[13]!=null && auditSchedule.getRespondedFindings() != null){
									auditSchedule.setResponseReject(Integer.parseInt(tuple[13].toString()));
									auditSchedule.setRespondedFindings(auditSchedule.getRespondedFindings()- (Integer.parseInt(tuple[13].toString()))); // Included to find out the Responded Observations
								}else auditSchedule.setResponseReject(0);
								
								if(tuple[14]!=null){
									auditSchedule.setComplianceCount(Integer.parseInt(tuple[14].toString()));
								}else auditSchedule.setComplianceCount(0);
								
								if(tuple[15]!=null){
									auditSchedule.setNotApplicableCount(Integer.parseInt(tuple[15].toString()));
								}else auditSchedule.setNotApplicableCount(0);
								
								// int tmSize =auditSchedule.getAuditTeams().size();
								//Calculating target end date
								Date actualStartDate = auditSchedule.getActualStartDate();
								String durationStr = auditSchedule.getDuration();
								int duration = Integer.parseInt(durationStr==null || durationStr.equals("")?0+"":auditSchedule.getDuration());
								 
								if(actualStartDate!=null){
									Calendar targetEndDate =new GregorianCalendar();
									targetEndDate.setTime(actualStartDate);
									targetEndDate.add(Calendar.DATE, duration-1);								
									//auditSchedule.setTargetEndDate(new Timestamp(targetEndDate.getTimeInMillis()));
									
									if(duration >0){
										duration =  maintHolidayService.getNumberOfBusinessDaysBetweenDates(legalEntityCode, auditSchedule.getUnitId().split("-")[0],
												 actualStartDate,  targetEndDate.getTime()) - duration ;
										targetEndDate.add(Calendar.DATE, duration);
									}
											
									auditSchedule.setTargetEndDate(new Timestamp(targetEndDate.getTimeInMillis()));								 
								}
								 
							}
							return auditSchedule;
						}
				@Override
				public List transformList(List collection) {
					return collection;
				}
			})      .setParameter("legalEntityCode",legalEntityCode)
					//.setParameter("planId",planId)
					.setParameter("auditId",auditId);
			
			 auditSchedule=(AuditSchedule)query.uniqueResult(); 

		}catch(Exception e) {
			e.printStackTrace(System.out);
		}return auditSchedule; 
	}

	@Override
	public void updateMyAuditStatus(AuditSchedule auditSchedule) {
		Session session = getSession();
		String unitHead =null;
		try {
			String auditId=auditSchedule.getAuditId();
			String auditStatus =auditSchedule.getAuditStatus();
			String observationStatus =auditSchedule.getObservationStatus();
			Date auditDate = auditSchedule.getBusinessdateTimestamp();
			Date reportDate = auditSchedule.getReportDate();
			Date schStartDate = auditSchedule.getScheduleStartDate();
			String auditerId =auditSchedule.getAuditerId(); 
			String asdRating=null, asdRatingPrc=null, effRating=null, effRatingPrc=null, ratingOvrrdRmrk=null;
			String actionItemStatus  = auditSchedule.getActionItemStatus();
			if("AS".equalsIgnoreCase(observationStatus)){
				asdRating = auditSchedule.getAssessedRating();
				asdRatingPrc = auditSchedule.getAssessedRiskPrcntg();
				effRating = auditSchedule.getEffectiveRating();
				effRatingPrc = auditSchedule.getEffectiveRiskPrcntg();
				ratingOvrrdRmrk = auditSchedule.getRatingOverrideRemarks();
			}
			String reportStatus =auditSchedule.getReportStatus();  // Included for BaaSDOS
			String reportLanguage =auditSchedule.getReportLanguage();
			
			logger.info("updateMyAuditStatus auditStatus:: "+ auditStatus + " observationStatus ::"+observationStatus+ " auditDate:: "+auditDate +" auditerId:: "+auditerId +" reportStatus:: "+ reportStatus);
			
			AuditSchedule audSch1= (AuditSchedule)session.get(AuditSchedule.class,auditSchedule);
			logger.info("audSch1 from Table auditStatus  :: "+ audSch1.getAuditStatus() +" obsSts :: "+ audSch1.getObservationStatus());
			
			
			if("AI".equalsIgnoreCase(auditStatus) && observationStatus == null)
			{
				// Logic to get the Unit Head
				StringBuilder queryString=new StringBuilder(" from MaintEntity e  "
						+ " where e.legalEntityCode =:legalEntityCode and e.unitCode =:unitId ");
				
				Query qry=session.createQuery(queryString.toString())
						.setParameter("legalEntityCode", auditSchedule.getLegalEntityCode())
						.setParameter("unitId", auditSchedule.getUnitId());
				MaintEntity mntEnt =(MaintEntity)qry.uniqueResult();
				unitHead = mntEnt.getUnitHeadUser();
				logger.info("unitHead:: "+ unitHead);
				
				// Logic to get the PreviousAuditId and Assessedrating // May comment this => as we will get PrevAudit details during Audit Submit "AS" , refer below code
				/*String prevAuditId=null; String prevAuditAssedratingPrc=null;
				StringBuilder prvAuditDtls=new StringBuilder(" SELECT audit_id, assessed_risk_prcntg FROM audit_schedule "
						+ " WHERE actual_end_date IS not null  AND audit_type_code=:auditTypeCode "
						+ " 	AND legal_entity_code=:legalEntityCode AND unit_id=:unitId  "
						+ " ORDER BY actual_end_date desc limit 1");
				
				Query prvAuditDtlsQry=session.createNativeQuery(prvAuditDtls.toString())
						.setParameter("legalEntityCode", auditSchedule.getLegalEntityCode())
						.setParameter("unitId", auditSchedule.getUnitId())
						.setParameter("auditTypeCode", auditSchedule.getAuditTypeCode());
				
				Object prvObj = prvAuditDtlsQry.uniqueResult();
				logger.info("prvObj .."+prvObj +" prvAuditDtls.."+prvAuditDtls );
				try{
					if(prvObj != null  && ((Object[])prvObj).length > 0)
					{
						prevAuditId  = ((Object[])prvObj)[0].toString();
						// prevAuditAssedratingPrc=  ((Object[])prvObj)[1].toString();
						logger.info("AI prevAuditId.... "+ prevAuditId +" prevAuditAssedratingPrc.... "+prevAuditAssedratingPrc);
					}
				}catch(Exception e) {
					e.printStackTrace(System.out);
				}*/
				
				//For BaaSDOS implementation, Logic to get the PreviousAuditId and Serial no
				String prevAuditId=null; int auditSerialNo=1;
				/*StringBuilder prvAuditDtls=new StringBuilder(" select audit_id, audit_serial_no from audit_schedule  "
						+ " where audit_type_code=:auditTypeCode and legal_entity_code=:legalEntityCode and unit_id=:unitId " // Need to uncomment when one Unit mapped to multiple Inspection type
						+ " 	and  audit_serial_no in (select ifnull(max(audit_serial_no),0) as max_sl_no from audit_schedule "
						+ "									 where legal_entity_code=:legalEntityCode  and audit_type_code=:auditTypeCode and unit_id=:unitId) " // Need to uncomment when one Unit mapped to multiple Inspection type
						+ " order by schedule_end_date limit 1 "); */
				
				
				// Logic to combine the Inspection types (DCCB & DCCBE) (StCB & StCBE), to get the Previous Audit Id
				List<String> auditTypeCodeLst=null;
				auditTypeCodeLst = new ArrayList<String>();
				if(auditSchedule.getAuditTypeCode().contains(BankAuditConstant.INSPECTION_TYPE_DCCB_CONTAIN)){
					auditTypeCodeLst.add(BankAuditConstant.INSPECTION_TYPE_DCCB);
					auditTypeCodeLst.add(BankAuditConstant.INSPECTION_TYPE_DCCBEI);
				}else if(auditSchedule.getAuditTypeCode().contains(BankAuditConstant.INSPECTION_TYPE_StCB_CONTAIN)){
					auditTypeCodeLst.add(BankAuditConstant.INSPECTION_TYPE_StCBI);
					auditTypeCodeLst.add(BankAuditConstant.INSPECTION_TYPE_StCBEI);
				}else {
					auditTypeCodeLst.add(auditSchedule.getAuditTypeCode());
				}
				logger.info("auditTypeCodeLst .. "+ auditTypeCodeLst);
				
				StringBuilder prvAuditDtls=new StringBuilder(" select audit_id, audit_serial_no from audit_schedule  "
						+ " where audit_type_code in :auditTypeCodeLst and legal_entity_code=:legalEntityCode and unit_id=:unitId " // Need to uncomment when one Unit mapped to multiple Inspection type
						+ " 	and  audit_serial_no in (select ifnull(max(audit_serial_no),0) as max_sl_no from audit_schedule "
						+ "									 where legal_entity_code=:legalEntityCode and audit_type_code in :auditTypeCodeLst and unit_id=:unitId) " // Need to uncomment when one Unit mapped to multiple Inspection type
						+ " order by schedule_end_date limit 1 ");
					
				Query prvAuditDtlsQry=session.createNativeQuery(prvAuditDtls.toString())
						.setParameter("legalEntityCode", auditSchedule.getLegalEntityCode())
						.setParameter("unitId", auditSchedule.getUnitId())
						.setParameter("auditTypeCodeLst", auditTypeCodeLst);  // Need to uncomment when one Unit mapped to multiple Inspection type 
				
				Object prvObj = prvAuditDtlsQry.uniqueResult();
				logger.info("prvObj .."+prvObj +" prvAuditDtls.."+prvAuditDtls );
				try{
					if(prvObj != null  && ((Object[])prvObj).length > 0)
					{
						prevAuditId  = (((Object[])prvObj)[0]!=null?((Object[])prvObj)[0].toString():null);
						auditSerialNo  = (((Object[])prvObj)[1]!=null?(Integer.parseInt(((Object[])prvObj)[1].toString())):0);
						logger.info("AI prevAuditId.... "+ prevAuditId +" serialNo.... "+auditSerialNo);
						auditSerialNo += 1;						
					}logger.info(" serialNo final .... "+auditSerialNo);
				}catch(Exception e) {
					e.printStackTrace(System.out);
				}// end here
				
				//For BaaSDOS implementation, Logic to get the Financial year end date
				Date fn_year=null;
				Object fyObj=session.createNativeQuery("select DATE_SUB(get_financial_year_endDate_forDate(:legalEntityCode, :schStartDate),INTERVAL 1 Year)")
						.setParameter("legalEntityCode", auditSchedule.getLegalEntityCode())
						.setParameter("schStartDate", auditSchedule.getScheduleStartDate()).getSingleResult();
				
				logger.info("fyObj .."+fyObj);
				try{
					if(fyObj != null )
						audSch1.setFinancialYear((Date)fyObj);
						logger.info("FY year.... "+audSch1.getFinancialYear());
				}catch(Exception e) {
					e.printStackTrace(System.out);
				}// end here
				
				audSch1.setActualStartDate(auditDate);
				audSch1.setUnitHead(unitHead);
				if(!auditId.equalsIgnoreCase(prevAuditId))  // Cond added so that current and previous Audit Id's not the same, on 09May24
					audSch1.setPrevAuditId(prevAuditId);
				//audSch1.setPrevAssessedRiskPrcntg(prevAuditAssedratingPrc);
				audSch1.setAuditSerialNo(auditSerialNo);
				audSch1.setReportStatus(reportStatus);
				audSch1.setReportLanguage(reportLanguage);
				audSch1.setAuditerId(audSch1.getMaker());
				
				MaintAuditTypeDesc maintAuditTypeDesc = maintAuditTypeDescService.getMaintAuditTypeDesc(auditSchedule.getLegalEntityCode(), auditSchedule.getAuditTypeCode()); 
				audSch1.setIoFlexibility(maintAuditTypeDesc.getIoFlexibility());
				
				//Save action/ticketing/broadcast item from maintActionItem to auditActionItem on initiation
				saveAuditActionItem(audSch1.getLegalEntityCode(), audSch1.getAuditTypeCode(), audSch1.getAuditId());
				
				AuditScheduleStagesStatusHst auditScheduleStagesStatusHst = new AuditScheduleStagesStatusHst();
				auditScheduleStagesStatusHst.setStagesStatus(auditStatus);
				auditScheduleStagesStatusHst.setCode(auditStatus);
				auditScheduleStagesStatusHst.setActionType(BankAuditConstant.ACTION_TYPE_INSPECTION);
				auditScheduleStagesStatusHstService.saveAuditStagesStatus(audSch1, auditScheduleStagesStatusHst);
				
			}else if("AP".equalsIgnoreCase(auditStatus)) {
				audSch1.setActualStartDate(null);
				audSch1.setUnitHead(unitHead);
			}/*else if("AS".equalsIgnoreCase(auditStatus)) {
				audSch1.setActualEndDate(auditDate);
				audSch1.setAuditerId(auditerId);
			}*/
			else if("AE".equalsIgnoreCase(observationStatus) && "AI".equalsIgnoreCase(auditStatus)) { // Audit Exit Date
				audSch1.setReportDate(reportDate);
				AuditScheduleStagesStatusHst auditScheduleStagesStatusHst = new AuditScheduleStagesStatusHst();
				auditScheduleStagesStatusHst.setStagesStatus(observationStatus);
				auditScheduleStagesStatusHst.setCode(observationStatus);
				auditScheduleStagesStatusHst.setActionType(BankAuditConstant.ACTION_TYPE_INSPECTION);
				auditScheduleStagesStatusHstService.saveAuditStagesStatus(audSch1, auditScheduleStagesStatusHst);
			}else if("AE".equalsIgnoreCase(observationStatus) && "AS".equalsIgnoreCase(auditStatus)) { // Audit Exit Date
				audSch1.setActualEndDate(auditDate);
				audSch1.setAuditerId(auditerId);
				audSch1.setObservationStatus("AS"); // for BAAS implementation
				AuditScheduleStagesStatusHst auditScheduleStagesStatusHst = new AuditScheduleStagesStatusHst();
				auditScheduleStagesStatusHst.setStagesStatus(audSch1.getObservationStatus());
				auditScheduleStagesStatusHst.setCode(audSch1.getObservationStatus());
				auditScheduleStagesStatusHst.setActionType(BankAuditConstant.ACTION_TYPE_INSPECTION);
				auditScheduleStagesStatusHstService.saveAuditStagesStatus(audSch1, auditScheduleStagesStatusHst);
			}else if("AS".equalsIgnoreCase(observationStatus) && "AS".equalsIgnoreCase(auditStatus)) { // Audit Submitted Date
				// If the Auditor want to Submit the Audit with out Exiting the Audit, then need to insert ActualEndDate & AuditorId
				if(audSch1.getActualEndDate() == null) audSch1.setActualEndDate(auditDate);  
				if(audSch1.getAuditerId() == null) audSch1.setAuditerId(auditerId);
				//logic, end here
				
				/* Not requeired for BaaSDOS 
				// The logic to retrieve the Previous AuditId, RiskScorePerc & Rating improvements 
				System.out.println("Bfr making call previousAuditDetails....");
				String previousAuditIdArr= auditProcessVService.previousAuditDetails(audSch1.getLegalEntityCode(), audSch1.getAuditTypeCode(), audSch1.getUnitId(), audSch1.getAuditId());
				System.out.println("previousAuditIdArr...."+previousAuditIdArr);
				
				if(!BankAuditUtil.isEmptyString(previousAuditIdArr)){
					String previousAuditId= previousAuditIdArr.substring(0, previousAuditIdArr.indexOf(','));
					String prevAssedPcntg=null; 
					int ratingImprv =0; 
					
					StringBuilder queryString=new StringBuilder( " SELECT  a.audit_id, r.rating_internal, a.assessed_risk_prcntg  "
							+ " FROM risk_score_percentage r, audit_schedule a "
							+ " WHERE "
							+ "     r.legal_entity_code = a.legal_entity_code "
							+ "         AND a.audit_id in ( :currAuditId, :previousAuditId) "
							+ "         AND r.legal_entity_code =:legalEntityCode "
							+ "         AND r.audit_type_code = a.audit_type_code "
							+ "         AND IFNULL(a.assessed_risk_prcntg, :asdRatingPrc) > r.minimun_per "
							+ "         AND IFNULL(a.assessed_risk_prcntg, :asdRatingPrc) <= r.maximum_per ");
					
					Query qry=session.createNativeQuery(queryString.toString())
							.setParameter("legalEntityCode", auditSchedule.getLegalEntityCode())
							.setParameter("currAuditId", audSch1.getAuditId())
							.setParameter("previousAuditId", previousAuditId)
							.setParameter("asdRatingPrc", asdRatingPrc);
					
					List ls = qry.list();
					logger.info("ls .. "+ ls.size()+" LE::"+auditSchedule.getLegalEntityCode() +" AuditId ::"+audSch1.getAuditId()+" previousAuditId::"+previousAuditId+" asdRatingPrc::"+asdRatingPrc);
					Iterator iterator = ls.iterator();
					while (iterator.hasNext()) {
						Object[] obj = (Object[])iterator.next();
						System.out.println(obj[0]+" :: "+obj[1]+" :: "+obj[2]);
						if(obj != null && audSch1.getAuditId().equalsIgnoreCase(obj[0].toString())){
							ratingImprv += Integer.parseInt(obj[1].toString());
						}else{
							ratingImprv -= Integer.parseInt(obj[1].toString());
							prevAssedPcntg = obj[2].toString();
						}
					}		
					logger.info("previousAuditId::"+previousAuditId+" ratingImprv::"+ratingImprv+" prevAssedPcntg::"+prevAssedPcntg);
					audSch1.setPrevAuditId(previousAuditId);
					audSch1.setPrevAssessedRiskPrcntg(prevAssedPcntg);
					audSch1.setRatingImprovement(ratingImprv+"");
					
				}	
				// The logic, ends here
				BaaSDOS comment */
				
				audSch1.setReportDate(auditDate);
				//audSch1.setAssessedRating(asdRating);
				//audSch1.setAssessedRiskPrcntg(asdRatingPrc);
				//audSch1.setEffectiveRating(effRating);
				//audSch1.setEffectiveRiskPrcntg(effRatingPrc);
				audSch1.setRatingOverrideRemarks(ratingOvrrdRmrk);
			}
			
			audSch1.setAuditStatus(auditStatus);
			audSch1.setObservationStatus(observationStatus);
			audSch1.setActionItemStatus(actionItemStatus);
			session.update(audSch1);
			session.flush();
		
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
	}	
	
	@Override
	public void updateAuditScheduleCounts(AuditSchedule auditSchedule) {
		
		Session session=getSession();
		
		session.createQuery("update AuditSchedule "
				+ " set totalFindings =:totalFindings , "
				+ "  openFindings =:openFindings , "
				+ "  rectifiedFindings =:rectifiedFindings , "
				+ "  closedFindings =:closedFindings , "
				+ "  respondedFindings =:respondedFindings  "
				+ " where "
				+ " legalEntityCode =:legalEntityCode "
				+ " and auditTypeCode =:auditTypeCode "
				+ " and planId =:planId "
				+ " and auditId =:auditId ")
		.setParameter("legalEntityCode", auditSchedule.getLegalEntityCode())
		.setParameter("auditTypeCode", auditSchedule.getAuditTypeCode())
		.setParameter("planId", auditSchedule.getPlanId())
		.setParameter("auditId", auditSchedule.getAuditId())
		.setParameter("totalFindings", auditSchedule.getTotalFindings())
		.setParameter("openFindings", auditSchedule.getOpenFindings())
		.setParameter("rectifiedFindings", auditSchedule.getRectifiedFindings())
		.setParameter("closedFindings", auditSchedule.getClosedFindings())
		.setParameter("respondedFindings", auditSchedule.getRespondedFindings())
		.executeUpdate();
		
		
	}	
	
	@Override
	public void updateAuditTeamStatus(AuditSchedule auditSchedule) {
		logger.info("auditSchedule .. "+ auditSchedule.getLegalEntityCode() +" :: "+auditSchedule.getAuditTypeCode()+" :: "+ auditSchedule.getPlanId() +" :: "+ auditSchedule.getAuditId() );
		Session session=getSession();
		String teamMaker=auditSchedule.getTeamMaker();
		Date teamMakerTimeStamp=auditSchedule.getTeamMakerTimestamp();
		String teamChecker=auditSchedule.getTeamChecker();
		Date teamCheckerTimeStamp=auditSchedule.getTeamCheckerTimestamp();
		String teamAuthRejRemarks= auditSchedule.getTeamAuthRejRemarks();
		String teamStatus= auditSchedule.getTeamStatus();
		try {
			AuditSchedule audSch1= (AuditSchedule)session.get(AuditSchedule.class,auditSchedule);
			if("U".equalsIgnoreCase(teamStatus)) {
				audSch1.setTeamMaker(teamMaker);
				audSch1.setTeamMakerTimestamp(teamMakerTimeStamp);
			}else {
				audSch1.setTeamChecker(teamChecker);
				audSch1.setTeamCheckerTimestamp(teamCheckerTimeStamp);
				audSch1.setTeamAuthRejRemarks(teamAuthRejRemarks);
			}audSch1.setTeamStatus(teamStatus);
			session.update(audSch1);
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
				
	}	
	
	@Override
	public List getAuditsForDashboard(int legalEntityCode,String userId,String role,String period,String fromDate,String toDate) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		
		AuditSchedule auditSchedule = null;
		List myAuditsLst= null; 
		//StringBuilder queryString=new StringBuilder(" from AuditSchedule where legalEntityCode =:legalEntityCode ");
		StringBuilder queryString=new StringBuilder(" select t.audit_type_code,t.audit_type_desc,audit_status,sch.cnt from "
					+ " maint_audit_type_desc t left join "
					+ " (select s.audit_type_code,audit_status,s.legal_entity_code,count(*) as cnt from audit_schedule s, audit_team tm where s.legal_entity_code =3 "
					+ " and s.legal_entity_code=tm.legal_entity_code "
					+ " and s.audit_id=tm.audit_id and s.plan_id=tm.plan_id and tm.user_id=:userId group by s.audit_type_code,s.audit_status) as sch "
					+ " on sch.legal_entity_code=t.legal_entity_code and sch.audit_type_code=t.audit_type_code where t.legal_entity_code=:legalEntityCode"
					+ " order by t.audit_type_code ");
			System.out.println("Before the qry....");
			
			Query query2lst=session.createSQLQuery(queryString.toString())
					.setParameter("legalEntityCode", legalEntityCode).setParameter("userId", userId);
			
			List myAuditsLst1 = query2lst.list();
			System.out.println("after executing obj.... "+ myAuditsLst1.size());
			try{
				myAuditsLst = new ArrayList<>();
				List audits = new ArrayList<>();
				String tempAuditTypeCode=""; String tempAuditDesc="";
				HashMap map =new HashMap();int cntr=1; int adtlstSize=myAuditsLst1.size();
				for ( Iterator iter = myAuditsLst1.iterator(); iter.hasNext(); ) {
					
					Object[] obj = (Object[]) iter.next();
						String auditCode=obj[0].toString(); 
						String auditDesc=obj[1].toString(); 
						String auditStatus=obj[2]+"";
						String auditCnt=obj[3]+"";
						
						if(tempAuditTypeCode.equals("") || tempAuditTypeCode.equals(auditCode)){
							if(obj[2] != null)map.put(auditStatus+"",auditCnt);
						}else{
							audits.add(0,tempAuditTypeCode+"_"+tempAuditDesc);
							if(!map.containsKey("AP")) map.put("AP","0");
							if(!map.containsKey("AI")) map.put("AI","0");
							if(!map.containsKey("AS")) map.put("AS","0");
							if(!map.containsKey("AR")) map.put("AR","0");
							if(!map.containsKey("AC")) map.put("AC","0");
							//map.remove("null_");
							audits.add(1,map);
							
							myAuditsLst.add(audits);
														
							audits = new ArrayList();
							map =new HashMap();
							if(obj[2] != null)map.put(auditStatus+"_",auditCnt);
						}
						if(cntr==adtlstSize){
							audits.add(0,obj[0].toString()+"_"+obj[1].toString());
							if(!map.containsKey("AP")) map.put("AP","0");
							if(!map.containsKey("AI")) map.put("AI","0");
							if(!map.containsKey("AS")) map.put("AS","0");
							if(!map.containsKey("AR")) map.put("AR","0");
							if(!map.containsKey("AC")) map.put("AC","0");
							audits.add(1,map);
							myAuditsLst.add(audits);
							
						}else{
							tempAuditTypeCode=auditCode;
							tempAuditDesc=auditDesc;
						}cntr++;
						
						//String auditStatus=obj[2].toString();
						System.out.println("auditCode is .... "+ obj[0] +" auditStatus ...." +obj[2]+" .... "+ obj[1]);
					}
				System.out.println("myAuditsLst .... "+myAuditsLst);
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return myAuditsLst; 
	}
	
	@Override
	public List getRatingAndObsCntGrpSGrpwiseByAuditId(int legalEntityCode, String auditTypeCode, String planId,String auditId) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		List myAuditSummarylst = new ArrayList();
		
		/*StringBuilder queryString=new StringBuilder(" select fn.audit_id,fn.mapping_id,fn.audit_group_code,fn.aduit_group_desc,fn.aduit_grp_wght,fn.audit_sub_group_code,fn.aduit_subgroup_desc,fn.aduit_subgrp_wght,"
				+ " fn.activity_code,fn.activity_score,fn.process_code,fn.process_score,fn.finding_code,fn.finding_score,fn.obs_yes_no, o.observation_id,o.compliance_category "
				+ " from ( "
				+ " select h.audit_id,am.mapping_id,am.audit_group_code,"
				+ " (select g.audit_group_name from maint_audit_group g where g.legal_entity_code=am.legal_entity_code and "
				+ " g.audit_type_code=am.audit_type_code and g.audit_group_code = am.audit_group_code) as aduit_group_desc,"
				+ " (select g.weightage from risk_score_audit_grp g where g.legal_entity_code=am.legal_entity_code  "
				+ " and g.audit_type_code=am.audit_type_code and g.audit_group_code = am.audit_group_code ) as aduit_grp_wght, "
				+ " am.audit_sub_group_code,"
				+ " (select g.audit_sub_group_name from maint_audit_subgroup g where g.legal_entity_code=am.legal_entity_code and "  
				+ "  g.audit_type_code=am.audit_type_code and g.audit_sub_group_code=am.audit_sub_group_code and g.audit_group_code = am.audit_group_code) as aduit_subgroup_desc,"
				+ " (select g.weightage from risk_score_audit_subgrp g where g.legal_entity_code=am.legal_entity_code  "
				+ " and g.audit_type_code=am.audit_type_code and g.audit_sub_group_code=am.audit_sub_group_code and g.audit_group_code = am.audit_group_code ) as aduit_subgrp_wght, "
				+ " am.activity_code,(select c.score from maint_audit_activity a, maint_criticality c where c.criticality_of_type='Activity' and c.legal_entity_code=a.legal_entity_code  "
				+ " and a.a_criticality=c.criticality_code and am.activity_code=a.activity_code and a.legal_entity_code=am.legal_entity_code) as activity_score, "
				+ " am.process_code,(select c.score from maint_audit_process p, maint_criticality c where c.criticality_of_type='Process' and c.legal_entity_code=p.legal_entity_code  "
				+ " and p.p_criticality=c.criticality_code and am.process_code=p.process_code and p.legal_entity_code=am.legal_entity_code) as process_score, "
				+ " am.finding_code,(select c.score from maint_audit_finding f, maint_criticality c where c.criticality_of_type='Finding' and c.legal_entity_code=f.legal_entity_code  "
				+ " and f.f_criticality=c.criticality_code and am.finding_code=f.finding_code and f.legal_entity_code=am.legal_entity_code) as finding_score, "
				+ " (select if(count(*)>0,'Y','N') from audit_observation o where o.legal_entity_code=h.legal_entity_code and o.mapping_id=am.mapping_id and o.audit_id=h.audit_id) as obs_yes_no "
				+ " from activity_process_finding_mapping am, audit_schedule h "
				+ "  where h.legal_entity_code=:legalEntityCode "
				+ " and am.legal_entity_code=h.legal_entity_code and h.audit_id=:auditId ) fn  "
				+ " left join audit_observation o on o.legal_entity_code=:legalEntityCode and o.audit_id=fn.audit_id and o.mapping_id =fn.mapping_id "
				+ "  order by audit_group_code,audit_sub_group_code ");*/
			StringBuilder queryString=new StringBuilder(" SELECT  "
					+ "     fn.*, o.observation_id, o.compliance_category, o.submission_status,o.response_status,o.review_status "  // o.submission_status,o.response_status,o.review_status -- included on 16Apr18
							//		16					17						18						19				20
					+ " FROM "
					+ "     (SELECT h.audit_id,am.mapping_id,am.audit_group_code, "			// 3
					+ " 			(select g.audit_group_name from maint_audit_group g  "
					+ " 				where g.legal_entity_code=am.legal_entity_code and g.audit_type_code=am.audit_type_code   "
					+ " 						AND g.audit_group_code = am.audit_group_code) as aduit_group_desc, "		//4
					+ "             (SELECT g.weightage FROM risk_score_audit_grp g "
					+ "                 WHERE g.legal_entity_code = am.legal_entity_code AND g.audit_type_code = am.audit_type_code "
					+ "                         AND g.audit_group_code = am.audit_group_code) AS aduit_grp_wght, "			//5
					+ "             am.audit_sub_group_code, "								//6
					+ "             (select g.audit_sub_group_name from maint_audit_subgroup g  "
					+ " 				where g.legal_entity_code=am.legal_entity_code and g.audit_type_code=am.audit_type_code  "
					+ " 						AND g.audit_sub_group_code=am.audit_sub_group_code and g.audit_group_code = am.audit_group_code) as aduit_subgroup_desc, "		//7
					+ "             (SELECT g.weightage  FROM risk_score_audit_subgrp g "
					+ "                 WHERE g.legal_entity_code = am.legal_entity_code AND g.audit_type_code = am.audit_type_code "
					+ "                         AND g.audit_sub_group_code = am.audit_sub_group_code "
					+ "                         AND g.audit_group_code = am.audit_group_code) AS aduit_subgrp_wght, "		//8
					+ "             am.activity_id, "										//9
					+ "             (SELECT c.score FROM maint_audit_activity a, maint_criticality c "
					+ "                 WHERE c.criticality_of_type = 'Activity' AND c.legal_entity_code = a.legal_entity_code "
					+ "                         AND a.a_criticality = c.criticality_code AND am.activity_id = a.activity_id "
					+ "                         AND a.legal_entity_code = am.legal_entity_code) AS activity_score, "		//10
					+ "             am.process_id, "										//11
					+ "             (SELECT c.score FROM maint_audit_process p, maint_criticality c "
					+ "                 WHERE c.criticality_of_type = 'Process' AND c.legal_entity_code = p.legal_entity_code "
					+ "                         AND p.p_criticality = c.criticality_code AND am.process_id = p.process_id "
					+ "                         AND p.legal_entity_code = am.legal_entity_code) AS process_score, "			//12
					+ "             am.finding_id, "										//13
					+ "             (SELECT c.score FROM maint_audit_finding f, maint_criticality c "
					+ "                 WHERE c.criticality_of_type = 'Finding' AND c.legal_entity_code = f.legal_entity_code "
					+ "                         AND f.f_criticality = c.criticality_code AND am.finding_id = f.finding_id "
					+ "                         AND f.legal_entity_code = am.legal_entity_code) AS finding_score, "			//14
					+ "             (SELECT IF(COUNT(*) > 0, 'Y', 'N') FROM audit_observation o "
					+ "                 WHERE o.legal_entity_code = h.legal_entity_code AND o.mapping_id = am.mapping_id  "
					+ "                 AND o.audit_id = h.audit_id AND o.submission_status='A') AS obs_yes_no "  	//15 // AND o.submission_status='A'  -- included on 16Apr18
					//+ "             , h.audit_type_code "  // added to include AuditType as well // then commented as qry sequence issue coming for Logic
					/*+"				,(SELECT COUNT(*) FROM audit_observation o where o.legal_entity_code = h.legal_entity_code AND o.plan_id=h.plan_id AND o.audit_id=h.audit_id and o.compliance_category='N' and o.submission_status='A' ) as open_findings "		
					+"				,(SELECT COUNT(*) FROM audit_observation o where o.legal_entity_code = h.legal_entity_code AND o.plan_id=h.plan_id AND o.audit_id=h.audit_id and o.compliance_category='N' and o.response_status='A' ) as responded_findings "	
					+"				,(SELECT COUNT(*) FROM audit_observation o where o.legal_entity_code = h.legal_entity_code AND o.plan_id=h.plan_id AND o.audit_id=h.audit_id and o.compliance_category='N' and o.review_status='A' ) as closed_findings "*/		
					+ "     FROM "
					+ "         activity_process_finding_mapping am, audit_schedule h "
					+ "     WHERE "
					+ "         h.legal_entity_code = :legalEntityCode "
					+ "             AND am.legal_entity_code = h.legal_entity_code "
					+ "             AND h.audit_id = :auditId AND am.audit_type_code=h.audit_type_code AND am.entity_status='A' ) fn "
					+ "         LEFT JOIN "
					+ "     audit_observation o ON o.legal_entity_code = :legalEntityCode "
					+ "         AND o.audit_id = fn.audit_id "
					+ "         AND o.mapping_id = fn.mapping_id AND o.submission_status='A' "  // AND o.submission_status='A' -- included on 16Apr18
					//+ " 		AND o.audit_type_code=fn.audit_type_code "
					+ " ORDER BY audit_group_code , audit_sub_group_code , activity_id ,process_id,finding_id "
					+ " ");
			System.out.println("Before the qry....");
			
			Query query2lst=session.createSQLQuery(queryString.toString())
					.setParameter("legalEntityCode", legalEntityCode).setParameter("auditId", auditId);
			
			List qrylst = query2lst.list();
			System.out.println("after executing obj.... "+ qrylst.size());
			
			List myAuditGrpSubGrpsLst = new ArrayList();
			List myAuditGrpsLst= null;
			myAuditGrpsLst = new ArrayList();
			List auditSubGrplst = new ArrayList();// List nclist = new ArrayList();
			String tempAuditGrp="";String tempAuditSubGrp="";String tempAuditGrpDesc="";String tempAuditSubGrpDesc="";
			int asgCnt=1;int c=0; int nc=0; int grpCmpl=0; int grpNcmpl=0; int compRating=0; int nonCompRating=0; 
			int na=0; int grpNa=0; int sub=0; int rsp=0; int rvw=0;
			int agWtg=1; int asgWtg=1; int actScr=1; int prcScr=1; int fndScr=1;
			double nonCompRatingDbl=0, compRatingDbl=0;
			int obsCnt=0;
			HashMap<String,String> sgMap =new HashMap<String,String>(); HashMap<String,String> gMap= new HashMap<String,String>();
			try{
				
				int rsltSize=qrylst.size();
				for ( Iterator iter = qrylst.iterator(); iter.hasNext(); ) {
					
					Object[] obj = (Object[]) iter.next();
						String auditGrpCode=obj[2].toString();
						String auditGrpDesc=obj[3].toString();
						String auditSubGrpCode=obj[5].toString(); 
						String auditSubGrpDesc=obj[6].toString();
						String cmpVal=((obj[16] != null) ?obj[16].toString() : "");
						String subSts=((obj[17] != null) ?obj[17].toString() : "");
						String rspSts=((obj[18] != null) ?obj[18].toString() : "");
						String rvwSts=((obj[19] != null) ?obj[19].toString() : "");
						//String auditComplianceCategory=obj[14];
						String auditCnt=obj[3]+"";
						logger.info("obsYorN .."+obj[14] +" cnt.." +obsCnt);
						obsCnt=((obj[14] != null) ?(obj[14].toString().equals("Y") ? obsCnt+1 :obsCnt) : obsCnt+0);
						// logger.info("obsCnt .."+obj[14] +" cnt.." +obsCnt);
						
						System.out.println("audit_group_code:: "+auditGrpCode );
						System.out.println();
						if(tempAuditGrp.equals("") || tempAuditGrp.equals(auditGrpCode)){
							if(tempAuditSubGrp.equals("") || tempAuditSubGrp.equals(auditSubGrpCode)){
								if(obj[16] !=null){
									if("N".equalsIgnoreCase(obj[16].toString())){ // Non Compliance code modified to N from NC
										nc++; grpNcmpl++;   
										if("A".equalsIgnoreCase(rvwSts)){
											rvw++;
										}else if("A".equalsIgnoreCase(rspSts)){
											rsp++;
										}else{
											sub++;
										}
									}else if("C".equalsIgnoreCase(obj[16].toString())) {
										c++; grpCmpl++;
									}else {na++; grpNa++;}
								}
							}else{
								sgMap.put("AUDIT_SUBGROUP_CODE", tempAuditSubGrp);
								sgMap.put("AUDIT_SUBGROUP_DESC", tempAuditSubGrpDesc);
								sgMap.put("COMPLIANCE", c+"");
								sgMap.put("NON_COMPLIANCE", nc+"");
								sgMap.put("NON_COMPLIANCE_CAP", sub+"");
								sgMap.put("NON_COMPLIANCE_RES", rsp+"");
								sgMap.put("NON_COMPLIANCE_RVW", rvw+"");
								sgMap.put("NOT_APPLICABLE", na+"");
								auditSubGrplst.add(sgMap);sgMap= new HashMap<String,String>();
								c=0;nc=0;na=0;rvw=0;rsp=0;sub=0;
								if(obj[16] !=null){
									if("N".equalsIgnoreCase(obj[16].toString())){
										nc++; grpNcmpl++;
										if("A".equalsIgnoreCase(rvwSts)){
											rvw++;
										}else if("A".equalsIgnoreCase(rspSts)){
											rsp++;
										}else{
											sub++;
										}
									}else if("C".equalsIgnoreCase(obj[16].toString())) {
										c++; grpCmpl++;
									}else {na++; grpNa++;}
								}
							}//System.out.println("auditSubGrplst .... "+ auditSubGrplst );
							
							tempAuditSubGrp = auditSubGrpCode;
							tempAuditSubGrpDesc=auditSubGrpDesc;
						}else{
							//if(asgCnt >0){
							sgMap.put("AUDIT_SUBGROUP_CODE", tempAuditSubGrp);
							sgMap.put("AUDIT_SUBGROUP_DESC", tempAuditSubGrpDesc);
							sgMap.put("COMPLIANCE", c+"");
							sgMap.put("NON_COMPLIANCE", nc+"");
							sgMap.put("NON_COMPLIANCE_CAP", sub+"");
							sgMap.put("NON_COMPLIANCE_RES", rsp+"");
							sgMap.put("NON_COMPLIANCE_RVW", rvw+"");
							sgMap.put("NOT_APPLICABLE", na+"");
							auditSubGrplst.add(sgMap);sgMap= new HashMap<String,String>();
							c=0;nc=0;na=0; rvw=0;rsp=0;sub=0;
							//}asgCnt=0;
							
							gMap.put("AUDIT_GROUP_CODE", tempAuditGrp );
							gMap.put("AUDIT_GROUP_DESC", tempAuditGrpDesc );
							gMap.put("COMPLIANCE", grpCmpl+"" );
							gMap.put("NON_COMPLIANCE", grpNcmpl+"" );
							gMap.put("NOT_APPLICABLE", grpNa+"");
							myAuditGrpsLst.add(gMap);
							myAuditGrpsLst.add(auditSubGrplst);
							
							myAuditGrpSubGrpsLst.add(myAuditGrpsLst);
							gMap = new HashMap();
							auditSubGrplst = new ArrayList();
							myAuditGrpsLst = new ArrayList();
							
							grpCmpl=0; grpNcmpl=0;c=0;nc=0; grpNa=0; na=0; rvw=0;rsp=0;sub=0;
							tempAuditSubGrp = auditSubGrpCode;
							tempAuditSubGrpDesc=auditSubGrpDesc;   // added this line as missed out earlier.
							if(obj[16] !=null){
								if("N".equalsIgnoreCase(obj[16].toString())){ 
									nc++; grpNcmpl++;
									if("A".equalsIgnoreCase(rvwSts)){
										rvw++;
									}else if("A".equalsIgnoreCase(rspSts)){
										rsp++;
									}else{
										sub++;
									}
								}else if("C".equalsIgnoreCase(obj[16].toString())) {
									c++; grpCmpl++;
								}else {na++; grpNa++;}
							}
						}
						//System.out.println("myCompletelst .... "+ resultset1.getString("audit_group_code")+" :::: "+myCompletelst );
						tempAuditGrp = auditGrpCode;
						tempAuditGrpDesc = auditGrpDesc;
						if(asgCnt==rsltSize){
							sgMap.put("AUDIT_SUBGROUP_CODE", auditSubGrpCode);
							sgMap.put("AUDIT_SUBGROUP_DESC", auditSubGrpDesc);
							sgMap.put("COMPLIANCE", c+"");
							sgMap.put("NON_COMPLIANCE", nc+"");
							sgMap.put("NON_COMPLIANCE_CAP", sub+"");
							sgMap.put("NON_COMPLIANCE_RES", rsp+"");
							sgMap.put("NON_COMPLIANCE_RVW", rvw+"");
							sgMap.put("NOT_APPLICABLE", na+"");
							auditSubGrplst.add(sgMap);
							
							gMap.put("AUDIT_GROUP_CODE", auditGrpCode );
							gMap.put("AUDIT_GROUP_DESC", auditGrpDesc);
							gMap.put("COMPLIANCE", grpCmpl+"" );
							gMap.put("NON_COMPLIANCE", grpNcmpl+"" );
							gMap.put("NOT_APPLICABLE", grpNa+"");
							myAuditGrpsLst.add(gMap);
							myAuditGrpsLst.add(auditSubGrplst);
							
							myAuditGrpSubGrpsLst.add(myAuditGrpsLst);
						}
						asgCnt++;
						
						// Block to calculate the Rating score
						agWtg = ( obj[4] != null )?Integer.parseInt(obj[4].toString()):1;
						asgWtg = ( obj[7] != null )?Integer.parseInt(obj[7].toString()):1;
						actScr = ( obj[9] != null )?Integer.parseInt(obj[9].toString()):1;
						prcScr = ( obj[11] != null )?Integer.parseInt(obj[11].toString()):1;
						fndScr = ( obj[13] != null )?Integer.parseInt(obj[13].toString()):1;
						
						//System.out.println("AG::" +obj[2]  +" AGdesc::"+obj[3] +" AGWg::"+obj[4] +" ASG:: "+obj[5] +" ASGDesc::"+obj[6] +" ASGWg::"+obj[7] +"ActId::" +obj[8]  +" ActScr::"+obj[9] +" PrcId::"+obj[10] +" PrcScr:: "+obj[11] +" FnId::"+obj[12] +" FnScr::"+obj[13]);
						//System.out.println(obj[2] +"=>"+ obj[4] +", "+ obj[5]+"=>"+obj[7] +", "+obj[8]+"=>"+obj[9]+", "+obj[10]+"=>"+obj[11]+", "+obj[12]+"=>"+obj[13]);
						
						if(obj[16] !=null && "N".equalsIgnoreCase(obj[16].toString())){ // Logic to be rewritten based on NA
							nonCompRating = nonCompRating +(agWtg *asgWtg * actScr* prcScr*fndScr); 
							//nonCompRatingDbl = nonCompRatingDbl + ( ((double)agWtg/100) * ((double)asgWtg/100) * actScr * prcScr * fndScr);
						}else {
							compRating = compRating +(agWtg *asgWtg * actScr* prcScr*fndScr); 
							//compRatingDbl = compRatingDbl +( ((double)agWtg/100) * ((double)asgWtg/100) * actScr * prcScr * fndScr);
						}
						
						//						
						System.out.println("nonCompRating is .... "+ nonCompRating +" compRating ...." +compRating );
						//System.out.println("nonCompRatingDbl is .... "+ nonCompRatingDbl +" compRatingDbl ...." +compRatingDbl );
					}
				System.out.println("myAuditGrpSubGrpsLst .... "+myAuditGrpSubGrpsLst);
				//double assessedRatingPrc = Math.round((double)nonCompRating /(compRating+nonCompRating)*100);
				//double assessedRatingPrcDbl = Math.round((double)nonCompRatingDbl /(compRatingDbl+nonCompRatingDbl)*100);
				
				double assessedRatingPrc_NC = Math.round((double)nonCompRating /(compRating+nonCompRating)*100);
				double assessedRatingPrc = 100 - assessedRatingPrc_NC; // The Rating compliance is ( 1- NC/NC+C)
				
				String assessedRiskRating =null;
				try {
					System.out.println("assessedRatingPrc .... "+ assessedRatingPrc );
					logger.info("assessedRatingPrc_NC .... "+ assessedRatingPrc_NC +" assessedRatingPrc.... "+assessedRatingPrc);
					StringBuilder queryString0=new StringBuilder(// " Select concat(u.firstName , ' ' , u.lastName) as firstName, u.userId "
							 " from RiskScorePercentage rskPrc  "
							+ " where "
							+ " rskPrc.legalEntityCode =:legalEntityCode and rskPrc.auditTypeCode =:auditTypeCode "
							+ " and (rskPrc.minimunPer <= CEIL(:ratingPercentage) and rskPrc.maximumPer > CEIL(:ratingPercentage))"
							);
					
					Query query1=session.createQuery(queryString0.toString())
							.setParameter("legalEntityCode", legalEntityCode).setParameter("auditTypeCode", auditTypeCode)
							.setParameter("ratingPercentage", (100- Math.round((double)nonCompRating/(compRating+nonCompRating)*100)));
							
					RiskScorePercentage rskPrcntg = (RiskScorePercentage)query1.uniqueResult();
					System.out.println("rskPrcntg .... "+rskPrcntg +" :: "+rskPrcntg.getRiskCategoryDesc());
					assessedRiskRating =rskPrcntg.getRiskCategoryDesc();
					
				}catch(Exception e) {
					e.printStackTrace(System.out);
					assessedRiskRating ="Rating Not Defined";
				}
				logger.info("obsCnt .."+obsCnt);
				HashMap< String, String> mapRating = new HashMap<String, String>();
				mapRating.put("ASSESSED_RISK", assessedRatingPrc+"");
				mapRating.put("ASSESSED_RATING", assessedRiskRating+"");
				mapRating.put("OBSERVATION_CNT", obsCnt+"");
				myAuditSummarylst.add(mapRating);
				myAuditSummarylst.add(myAuditGrpSubGrpsLst);
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return myAuditSummarylst; 
	}

	@Override
	public Map<String, String> getObsRespRvwCnt(int legalEntityCode, String auditTypeCode, String planId,String auditId) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		HashMap< String, String> mapProcessCnt = new HashMap();
		logger.info("Inside getObsRespRvwCnt ...."+ legalEntityCode +" AuditCode.." + auditTypeCode +" PlanId.." +planId +" AuditId.." +auditId);
		try {
			StringBuilder queryString=new StringBuilder(" SELECT  "
					+"		(SELECT COUNT(*) FROM audit_observation o where o.legal_entity_code = h.legal_entity_code AND o.plan_id=h.plan_id AND o.audit_id=h.audit_id and o.compliance_category='N' and o.submission_status='A' ) as open_findings "
					+"		,(SELECT COUNT(*) FROM audit_observation o where o.legal_entity_code = h.legal_entity_code AND o.plan_id=h.plan_id AND o.audit_id=h.audit_id and o.compliance_category='N' and o.response_status='A' ) as responded_findings "
					+"		,(SELECT COUNT(*) FROM audit_observation o where o.legal_entity_code = h.legal_entity_code AND o.plan_id=h.plan_id AND o.audit_id=h.audit_id and o.compliance_category='N' and o.review_status='A' ) as closed_findings "
					+"    FROM audit_schedule h "
					+"    WHERE "
					+"         h.legal_entity_code = :legalEntityCode AND h.audit_type_code=:auditTypeCode"
					+"         AND h.plan_id=:planId AND h.audit_id = :auditId  ");
			logger.info("Before the qry....");
			
			Query queryCnt=session.createSQLQuery(queryString.toString())
					.setParameter("legalEntityCode", legalEntityCode).setParameter("auditTypeCode", auditTypeCode)
					.setParameter("planId", planId).setParameter("auditId", auditId);
			
			Object obj = queryCnt.uniqueResult();
			int obsCnt = 0; int rspCnt =0; int rvwCnt=0; String rspSubmit ="No"; String rvwSubmit ="No";
			try{
				if(obj != null  && ((Object[])obj).length > 0)
				{
					obsCnt  =Integer.parseInt( ((Object[])obj)[0].toString());
					rspCnt =Integer.parseInt( ((Object[])obj)[1].toString());
					rvwCnt  =Integer.parseInt( ((Object[])obj)[2].toString());
					logger.info("obsCnt .... "+ obsCnt +" respCnt.... "+rspCnt +" rvwCnt.... "+rvwCnt);
				}
				if(rspCnt == obsCnt ) rspSubmit ="Yes";
				if(rvwCnt == obsCnt ) rvwSubmit ="Yes";
			}catch(Exception e) {
				System.out.println("Exception occured ....");
			}
				mapProcessCnt.put("NC_OBSERVATION_CNT", obsCnt+"");
				mapProcessCnt.put("RESPONSE_CNT", rspCnt+"");
				mapProcessCnt.put("REVIEW_CNT", rvwCnt+"");
				//mapProcessCnt.put("RESPONSE_SUBMIT", rspSubmit); // to be uncommented
				//mapProcessCnt.put("REVIEW_SUBMIT", rvwSubmit); // to be uncommented
				
				mapProcessCnt.put("RESPONSE_SUBMIT", "Yes");	// to be commented, had fix for demo
				mapProcessCnt.put("REVIEW_SUBMIT", "Yes");  // to be commented, had fix for demo
				
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return mapProcessCnt; 
	}
	
	@Override
	public DataTableResponse getAdHocAuditsForAuditor(int legalEntityCode, String userId, String search, Integer orderColumn, String orderDirection, Integer page, Integer size,
			LocalDate financialYear, String auditTypeCode, List<LocalDate>  financialYearStrtEndList) { // Added to filter the records based on Financial Year and AuditType

		Session session = getSession();
		session.setDefaultReadOnly(true);

		/********************** This block is to retrieve the User details --> UserId and UserName **************************/
		StringBuilder queryString0=new StringBuilder(// " Select concat(u.firstName , ' ' , u.lastName) as firstName, u.userId "
				 " from User u  "
				+ " where "
				+ " u.legalEntityCode =:legalEntityCode "
				);
		
		Query query1=session.createQuery(queryString0.toString())
				.setParameter("legalEntityCode", legalEntityCode);
		
		List lst = query1.list();
		HashMap<String, String> userDtls = new HashMap<String, String>();
		for ( Iterator iter = lst.iterator(); iter.hasNext(); ) {
			User usr = (User) iter.next();
			if(usr.getUserId().equalsIgnoreCase(userId))
				userDtls.put(usr.getUserId(), "Me"); // for the same User we are stamping as "You"
			else userDtls.put(usr.getUserId(), usr.getFirstName()+" "+usr.getMiddleName()+" "+usr.getLastName());	
		}
		System.out.println("userId is .... "+ userId+" serach:: "+search +" legal entity code:: "+legalEntityCode);
		System.out.println("User details val is .... "+ userDtls);
		/******************** User Retrieval logic, Ends here ********************************/
		
		/***************** Logic to retrieve duration and No. of Audits from general parameter table and  ****
		 ***************** 	comparing both to find out the minimum, Starts here 	      ********************/
		Date businessDate =businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		System.out.println("businessDate .... "+ businessDate);
		//userId="4468"; // for temp purpose, need to be commented
		StringBuilder queryString2=new StringBuilder( " select nd.auditsInInterval,nads.noAudits from " 
				+ " ( select count(*) as auditsInInterval from audit_schedule ash, audit_team atm " 
				+ "	where ash.plan_id=atm.plan_id and ash.audit_id = atm.audit_id and ash.legal_entity_code=atm.legal_entity_code and atm.user_id=:userId " 
				+ "          and (ash.schedule_start_date between :businessDate and " 
				+ "				ADDDATE(:businessDate, INTERVAL (select g.value from general_parameter g where key_1='AUDITOR_VISIBILITY' AND key_2='DAYS' AND g.legal_entity_code=ash.legal_entity_code ) DAY))  ) as nd, " 
				+ " ( select g.value as noAudits from general_parameter g where g.key_1='AUDITOR_VISIBILITY' AND g.key_2='NO_OF_AUDITS' AND g.legal_entity_code=:legalEntityCode) as nads; "  
				); 
		//(select g.value from GeneralParameter g where g.key1='AUDITOR_VISIBILITY' AND g.key2='DAYS' AND g.legalEntityCode=:legalEntityCode) 
		
		Query query2lst=session.createSQLQuery(queryString2.toString())
				.setParameter("legalEntityCode", legalEntityCode).setParameter("userId", userId)
				.setParameter("businessDate", businessDate);
		
		Object obj = query2lst.uniqueResult();
		int auidtsDisplay = 100;
		try{
			if(obj != null  && ((Object[])obj).length > 0)
			{
				int auditsInInterval  =Integer.parseInt( ((Object[])obj)[0].toString());
				int  noOfAudit=Integer.parseInt( ((Object[])obj)[1].toString());
				System.out.println("auditsInInterval .... "+ auditsInInterval +" noOfAudit.... "+noOfAudit);
				if(auditsInInterval > noOfAudit) auidtsDisplay=noOfAudit;
				else auidtsDisplay = auditsInInterval;
			}
		}catch(Exception e) {
			System.out.println("Exception occured ....");
		}
		logger.info("auidtsDisplay .... "+auidtsDisplay);
		/******************** Logic for no of Audits, Ends here ********************************/
		
		// Logic added to filter the Records based on Financial Year and Audit Type
		logger.info("financial Year :: "+ financialYear +" auditTypeCode :: "+auditTypeCode +" financial Year StartEnd:: "+ financialYearStrtEndList);
				
			
		DataTableResponse dataTableResponse=new DataTableResponse();
		try {
		//StringBuilder queryString=new StringBuilder(" from AuditSchedule where legalEntityCode =:legalEntityCode ");
		StringBuilder queryString=new StringBuilder("select sch as auditSchedule, " 
				+ " legalEntityCode,"
				+ "(select concat(auditTypeCode , '-' , auditTypeDesc) from MaintAuditTypeDesc at where at.auditTypeCode=sch.auditTypeCode and at.legalEntityCode= sch.legalEntityCode ) as auditTypeCode,"
				
				+ "planId,auditId, "
				//+ " (Select concat(unitCode , '-' , unitName) from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitId,  "
				+ " (Select unitName from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitName,  "
				
				+ " (Select g.description from  MaintEntity e,GeneralParameter g where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=e.unitType) as unitType, "
				
				+ " (Select c.criticalityDesc from  MaintEntity e,MaintCriticality c where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =c.legalEntityCode and e.uCriticality=c.criticalityCode and c.criticalityOfType='Entity') as uCriticality, "
				
				//+ " (Select concat(u.firstName , ' ' , u.lastName) from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
				+ " (Select t.userId from  AuditTeam t where t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
				
				+ " duration, "//+ " (Select p.duration from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as duration, "
				+ " frequency, "//+ " (Select p.frequency from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as frequency, "
				//+ " (select tm.auditTypeCode,GROUP_CONCAT(tm.name) from (Select t.auditTypeCode,t.planId, t.auditId, concat(u.firstName , ' ' , u.lastName) as name from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='T') tm where  GROUP BY tm.auditTypeCode  ) as teamMember "
				+ " (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus) as auditStatus, "
				+ " (Select concat(u.userId , '-' , u.firstName, ' ',u.middleName,' ',u.lastName) from  User u where u.legalEntityCode =sch.legalEntityCode and u.userId=sch.maker) as maker "
				+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='N' and o.reviewStatus='R' ) as responseReject "
				+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='C' and o.submissionStatus='A') as complianceCount "
				+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='NA' and o.submissionStatus='A') as notApplicableCount "
				//+ " , auditStatus "
				+ ", (select GROUP_CONCAT(t.userId)  from  AuditTeam t    where  t.auditId=sch.auditId and t.legalEntityCode = sch.legalEntityCode and t.userType='M'     ) as teamMember "
				
				+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode "
				//+ " and sch.legalEntityCode=t.legalEntityCode and t.auditId=sch.auditId and t.userId=:userId"
				+ " and   IFNULL(auditStatus,'NotNull') not in ('AD','AU','DRP','UP','AP') "
				+ " and  ((sch.auditId IN (SELECT t.auditId FROM AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userId=:userId  )) "
				//+ " or  (sch.auditId IN (SELECT d.auditId FROM AuditAdhocDocument d, AuditAdhocReport r WHERE d.id=r.documentId and d.auditId=sch.auditId and d.legalEntityCode =r.legalEntityCode and d.legalEntityCode =sch.legalEntityCode and r.targetUser=:userId  )) "  // This part for Repotee
				+ " ) "
		);
		
		// Financial Year and Audit Type filter added for filtering
		if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
			queryString.append(" and  sch.auditTypeCode =:auditTypeCode "); 
		}if(financialYear !=null) {
			LocalDate fYStartDt = financialYearStrtEndList.get(0);
			LocalDate fYearEndDt = financialYearStrtEndList.get(1);
			logger.info("fYStartDt :: "+fYStartDt+" fYEndDt :: "+fYearEndDt);
			queryString.append(" And (sch.scheduleStartDate between '"+fYStartDt+"' and '"+fYearEndDt+"' )");
			//queryString.append(" And (sch.scheduleStartDate between :fYStartDt and :fYearEndDt )");
		}
		
		logger.info("Before the qry....");
		
		if(!BankAuditUtil.isEmptyString(search)){
			queryString=queryString.append(" and ( "
					+ " sch.auditTypeCode IN (SELECT a.auditTypeCode FROM MaintAuditTypeDesc a  WHERE a.legalEntityCode=sch.legalEntityCode AND a.auditTypeDesc LIKE :search) "
					+ " or planId like :search "
					+ " or auditId like :search "
					//+ " or unitId like :search "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m WHERE m.legalEntityCode=sch.legalEntityCode AND (m.unitName LIKE :search or m.unitCode LIKE :search )) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,GeneralParameter g WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=m.unitType and g.description LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintCriticality c WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =c.legalEntityCode and m.uCriticality=c.criticalityCode and c.criticalityOfType='Entity' and  c.criticalityDesc LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintAuditParameter p WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =p.legalEntityCode and m.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and  p.duration LIKE :search) "
					+ " or sch.auditId IN (SELECT t.auditId FROM User u,AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.legalEntityCode =u.legalEntityCode and t.userId=u.userId and (t.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or DATE_FORMAT(sch.scheduleStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.scheduleEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.lastAuditDate, '%d %b %Y') LIKE :search "
					+ " or sch.maker IN (SELECT u.userId FROM User u WHERE u.legalEntityCode =sch.legalEntityCode and (u.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus and g.description LIKE :search) "
					+ " ) "
					// + " )"
					);
		}
		
		/*queryString=queryString.append("  ORDER BY FIELD(auditStatus, 'AI','P','AP','AS','AC','AU') asc ");*/
		String[] columns={
				"auditTypeCode",
				"(planId *1 ),(auditId *1 )", //"CAST(planId AS Integer),CAST(auditId AS Integer) "
				"unitType",
				"(unitId * 1) ",  //"unitId",
				"uCriticality",
				"duration",
				"lastAuditDate",//last audit date actually 
				"sch.scheduleStartDate",
				"sch.scheduleEndDate",
				"sch.actualStartDate",
				"sch.actualEndDate",
				"teamLead", // Team Lead
				// "sch.maker", // Team Member
				"sch.maker",
				"sch.auditStatus",
				"unitName",  
				"financialYear"
		};

		/*if(orderColumn!=null
				&& !BankAuditUtil.isEmptyString(orderDirection)){
			queryString=queryString.append(" order by ").append(columns[orderColumn]).append(" ").append(orderDirection);
		}*/
		logger.info("orderColumn **.... "+ orderColumn +"  orderDirection ...."+ orderDirection );
		if(orderColumn != null && orderColumn == -1 && !BankAuditUtil.isEmptyString(orderDirection)){ // -1 send for the first time from the UI during landing page.
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc  "); // The code modified to get the records in the order of Status on landing page, the sequence is  Draft, Reject, Unauth, Modify, Auth
		}else if(orderColumn!=null && !BankAuditUtil.isEmptyString(orderDirection)){
			if(orderColumn==0) {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection).append(" , FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc ,(auditId *1 ) asc  ");
			}else {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection);
			}
		}else {
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc  ");
		}
		System.out.println("queryString .... "+ queryString.toString());
		
		Query query=(Query) session.createQuery(queryString.toString())				
				.setResultTransformer(new ResultTransformer() {
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						AuditSchedule auditSchedule=null;
						//System.out.println("tuple[0] ...."+tuple[0]);
						if(tuple[0]!=null){
							auditSchedule=(AuditSchedule)tuple[0];
							/* session.evict(maintEntity);*/
							
							if(tuple[1]!=null){
								auditSchedule.setLegalEntityCode(Integer.parseInt(tuple[1].toString()));								
							}
							if(tuple[2]!=null){
								auditSchedule.setAuditTypeCode(tuple[2].toString());
							}
							
							if(tuple[3]!=null){
								auditSchedule.setPlanId(tuple[3].toString());
							}
							
							if(tuple[4]!=null){
								auditSchedule.setAuditId(tuple[4].toString());
							}
							if(tuple[5]!=null){
								//String unitCodeName=tuple[5].toString();
								//auditSchedule.setUnitId(unitCodeName);
								//auditSchedule.setUnitName(unitCodeName.substring(unitCodeName.indexOf('-')+1));
								auditSchedule.setUnitId(auditSchedule.getUnitId()+"-"+tuple[5].toString());
								auditSchedule.setUnitName(tuple[5].toString());
							}
							if(tuple[6]!=null){
								auditSchedule.setUnitType(tuple[6].toString());
							}
							if(tuple[7]!=null){
								auditSchedule.setuCriticality(tuple[7].toString());
							}
							if(tuple[8]!=null){
								String teamLead = userDtls.get(tuple[8].toString());
								auditSchedule.setTeamLead(teamLead.equalsIgnoreCase("Me")?"Me":tuple[8].toString()+"-"+teamLead);
								//auditSchedule.setTeamLead(userDtls.get(tuple[8].toString()));
							}
							if(tuple[9]!=null){
								auditSchedule.setDuration(tuple[9].toString());
							}
							if(tuple[10]!=null){
								auditSchedule.setFrequency(tuple[10].toString());
							}
							if(tuple[11]!=null){
								if("P".equalsIgnoreCase(tuple[11].toString()))auditSchedule.setAuditStatus("AP");
								else auditSchedule.setAuditStatus(tuple[11].toString());
							}
							if(tuple[12]!=null){
								auditSchedule.setMaker(tuple[12].toString());
							}
							if(tuple[13]!=null && auditSchedule.getRespondedFindings() != null){
								auditSchedule.setResponseReject(Integer.parseInt(tuple[13].toString()));
								auditSchedule.setRespondedFindings(auditSchedule.getRespondedFindings()- (Integer.parseInt(tuple[13].toString()))); // Included to find out the Responded Observations
							}else auditSchedule.setResponseReject(0);
							
							if(tuple[14]!=null){
								auditSchedule.setComplianceCount(Integer.parseInt(tuple[14].toString()));
							}else auditSchedule.setComplianceCount(0);
							
							if(tuple[15]!=null){
								auditSchedule.setNotApplicableCount(Integer.parseInt(tuple[15].toString()));
							}else auditSchedule.setNotApplicableCount(0);
							
							if(tuple[16]!=null){ 
								String teamMembers="";
								String[] members = tuple[16].toString().split(",");
								for (String member: members) {
									teamMembers+=member+"-"+userDtls.get(member)+",";
								}
								auditSchedule.setTeamMember(teamMembers.substring(0,teamMembers.length()-1));								 
							}
							/*int tmSize =0;
							try {
								logger.info("getAuditTeams .. "+auditSchedule.getAuditTeams());
								if(auditSchedule.getAuditTeams()!=null)tmSize=auditSchedule.getAuditTeams().size()-1;
							}catch(Exception e) {tmSize =0;}String teamMember="";
							logger.info("Audit Id .... "+ auditSchedule.getAuditId()+" tmSize .."+tmSize);*/
							/*for( AuditTeam adtTm: auditSchedule.getAuditTeams() ) {
								
								adtTm.setUserId(adtTm.getUserId()+"-"+userDtls.get(adtTm.getUserId()));
								
								if(!"L".equalsIgnoreCase(adtTm.getUserType())) teamMember +=adtTm.getUserId() + ",";
								System.out.println("teamMember .... "+ teamMember);
							}*/
							/*if(tmSize >0 ) auditSchedule.setTeamMember(teamMember.substring(0,teamMember.lastIndexOf(",")));
							System.out.println("Team member .... "+auditSchedule.getTeamMember());*/
							//System.out.println("Team size ...."+auditSchedule.getAuditTeams().size());
						}
						return auditSchedule;
					}
			@Override
			public List transformList(List collection) {
				return collection;
			}
		})		
				.setParameter("legalEntityCode",legalEntityCode).setParameter("userId",userId);

		if(!BankAuditUtil.isEmptyString(search)){
			query.setParameter("search", "%"+search+"%");
		}
		
		if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
			query.setParameter("auditTypeCode", auditTypeCode);
		}
		
		logger.info("page :: "+page +"size :: "+ size);
		List<AuditSchedule> tmpAuditSchedule =query.list(); 
		Long totalRecords=null;
		try {
			totalRecords = (long)tmpAuditSchedule.size();
		}catch(Exception e) {
			totalRecords = (long)0;
		}
		List<AuditSchedule> auditSchedule=query.setFirstResult((page*size)).setMaxResults(size).list();
		
		System.out.println("Bfr size tmpAuditSchedule is .... "+tmpAuditSchedule.size()+" totalRecords:: "+ totalRecords);
		
		/*int i=0;
		for(AuditSchedule adSch:auditSchedule){
			System.out.println("Inside adSch ...");
			if("A2".equalsIgnoreCase(adSch.getAuditId()));
			else 	tmpAuditSchedule.add(adSch);
			System.out.println("after the call");
			
		}
		System.out.println("size tmpAuditSchedule .... "+tmpAuditSchedule);*/
		
		
		dataTableResponse.setData(auditSchedule);
		dataTableResponse.setRecordsTotal(totalRecords);
		dataTableResponse.setRecordsFiltered(totalRecords);
		
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return dataTableResponse;
	
	}
	
	
	@Override
	public String chkAuditEarlyStartAllowed(AuditSchedule auditSchedule) {

		Session session=getSession();
		String earlyStartAllowedYesORNo ="Y";
		logger.info("LE:: "+ auditSchedule.getLegalEntityCode() + " Audit ID:: "+auditSchedule.getAuditId() + " Bsns Date::" + auditSchedule.getBusinessdateTimestamp() + "Audit Type:: "+ auditSchedule.getAuditTypeCode());
		try {
			StringBuilder queryStr1=new StringBuilder("");
			queryStr1.append(" SELECT  ");
			queryStr1.append(" (CASE ");
			queryStr1.append("     WHEN  a.schedule_start_date > (select  b.business_date from business_date b where b.legal_entity_code= :legalEntityCode )  AND g.value='N' ");  //:businessDate
			queryStr1.append(" 			THEN 'N' ");
			queryStr1.append("     ELSE 'Y' ");
			queryStr1.append(" END) AS `early_start_allow`  ");
			queryStr1.append(" from audit_schedule a left outer join general_parameter g  ");
			queryStr1.append(" on a.legal_entity_code=g.legal_entity_code  ");
			queryStr1.append(" AND g.key_1 ='AUDIT_EARLY_START' AND g.key_2='EARLY_START_ALLOWED' ");
			queryStr1.append(" where  a.legal_entity_code= :legalEntityCode and audit_id= :auditId and audit_type_code = :auditTypeCode ");
			
			Query query=session.createSQLQuery(queryStr1.toString());
			query.setParameter("legalEntityCode", auditSchedule.getLegalEntityCode());
			query.setParameter("auditId",auditSchedule.getAuditId());
			//query.setParameter("businessDate", auditSchedule.getBusinessdateTimestamp());
			query.setParameter("auditTypeCode", auditSchedule.getAuditTypeCode());
			logger.info("chkAuditEarlyStartAllowed QRY is :: "+ query);
	
			earlyStartAllowedYesORNo = query.uniqueResult().toString();
			logger.info("earlyStartAllowedYesORNo QRY is :: "+ earlyStartAllowedYesORNo);
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		return earlyStartAllowedYesORNo;
	}

	@Override
	public DataTableResponse getAdHocAuditsForManagement(int legalEntityCode, String userId, String search, Integer orderColumn, String orderDirection, Integer page, Integer size,
			LocalDate financialYear, String auditTypeCode, List<LocalDate>  financialYearStrtEndList) { // Added to filter the records based on Financial Year and AuditType	

		logger.info("Inside getAdHocAuditsForManagement ..");
		Session session = getSession();
		session.setDefaultReadOnly(true);

		/********************** This block is to retrieve the User details --> UserId and UserName **************************/
		StringBuilder queryString0=new StringBuilder(// " Select concat(u.firstName , ' ' , u.lastName) as firstName, u.userId "
				 " from User u where u.legalEntityCode =:legalEntityCode ");
		
		Query query1=session.createQuery(queryString0.toString())
				.setParameter("legalEntityCode", legalEntityCode);
		
		List lst = query1.list();
		HashMap<String, String> userDtls = new HashMap<String, String>();
		for ( Iterator iter = lst.iterator(); iter.hasNext(); ) {
			User usr = (User) iter.next();
			if(usr.getUserId().equalsIgnoreCase(userId))
				userDtls.put(usr.getUserId(), "Me"); // for the same User we are stamping as "You"
			else userDtls.put(usr.getUserId(), usr.getFirstName()+" "+usr.getMiddleName()+" "+usr.getLastName());	
		}
		logger.info("userId is .... "+ userId+" serach:: "+search +" legal entity code:: "+legalEntityCode);
		logger.info("User details val is .... "+ userDtls);
		/******************** User Retrieval logic, Ends here ********************************/
		
		/***************** Logic to retrieve duration and No. of Audits from general parameter table and  ****
		 ***************** 	comparing both to find out the minimum, Starts here 	      ********************/
		Date businessDate =businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		System.out.println("businessDate .... "+ businessDate);
		//userId="4468"; // for temp purpose, need to be commented
		StringBuilder queryString2=new StringBuilder( " select nd.auditsInInterval,nads.noAudits from " 
				+ " ( select count(*) as auditsInInterval from audit_schedule ash, audit_team atm " 
				+ "	where ash.plan_id=atm.plan_id and ash.audit_id = atm.audit_id and ash.legal_entity_code=atm.legal_entity_code and atm.user_id=:userId " 
				+ "          and (ash.schedule_start_date between :businessDate and " 
				+ "				ADDDATE(:businessDate, INTERVAL (select g.value from general_parameter g where key_1='AUDITOR_VISIBILITY' AND key_2='DAYS' AND g.legal_entity_code=ash.legal_entity_code ) DAY))  ) as nd, " 
				+ " ( select g.value as noAudits from general_parameter g where g.key_1='AUDITOR_VISIBILITY' AND g.key_2='NO_OF_AUDITS' AND g.legal_entity_code=:legalEntityCode) as nads; "  
				); 
		//(select g.value from GeneralParameter g where g.key1='AUDITOR_VISIBILITY' AND g.key2='DAYS' AND g.legalEntityCode=:legalEntityCode) 
		
		Query query2lst=session.createSQLQuery(queryString2.toString())
				.setParameter("legalEntityCode", legalEntityCode).setParameter("userId", userId)
				.setParameter("businessDate", businessDate);
		
		Object obj = query2lst.uniqueResult();
		int auidtsDisplay = 100;
		try{
			if(obj != null  && ((Object[])obj).length > 0)
			{
				int auditsInInterval  =Integer.parseInt( ((Object[])obj)[0].toString());
				int  noOfAudit=Integer.parseInt( ((Object[])obj)[1].toString());
				System.out.println("auditsInInterval .... "+ auditsInInterval +" noOfAudit.... "+noOfAudit);
				if(auditsInInterval > noOfAudit) auidtsDisplay=noOfAudit;
				else auidtsDisplay = auditsInInterval;
			}
		}catch(Exception e) {
			System.out.println("Exception occured ....");
		}
		logger.info("auidtsDisplay .... "+auidtsDisplay);
		/******************** Logic for no of Audits, Ends here ********************************/
			
		// Logic added to filter the Records based on Financial Year and Audit Type
		logger.info("financial Year :: "+ financialYear +" auditTypeCode :: "+auditTypeCode +" financial Year StartEnd:: "+ financialYearStrtEndList);
				
		DataTableResponse dataTableResponse=new DataTableResponse();
		try {
		//StringBuilder queryString=new StringBuilder(" from AuditSchedule where legalEntityCode =:legalEntityCode ");
		StringBuilder queryString=new StringBuilder("select sch as auditSchedule, " 
				+ " legalEntityCode,"
				+ "(select concat(auditTypeCode , '-' , auditTypeDesc) from MaintAuditTypeDesc at where at.auditTypeCode=sch.auditTypeCode and at.legalEntityCode= sch.legalEntityCode ) as auditTypeCode,"
				
				+ "planId,auditId, "
				//+ " (Select concat(unitCode , '-' , unitName) from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitId,  "
				+ " (Select unitName from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitName,  " //5
				
				+ " (Select g.description from  MaintEntity e,GeneralParameter g where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=e.unitType) as unitType, "
				
				+ " (Select c.criticalityDesc from  MaintEntity e,MaintCriticality c where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =c.legalEntityCode and e.uCriticality=c.criticalityCode and c.criticalityOfType='Entity') as uCriticality, "
				
				//+ " (Select concat(u.firstName , ' ' , u.lastName) from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
				+ " (Select t.userId from  AuditTeam t where t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
				
				+ " duration, " //+ " (Select p.duration from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as duration, "
				+ " frequency," //+ " (Select p.frequency from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as frequency, "
				//+ " (select tm.auditTypeCode,GROUP_CONCAT(tm.name) from (Select t.auditTypeCode,t.planId, t.auditId, concat(u.firstName , ' ' , u.lastName) as name from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='T') tm where  GROUP BY tm.auditTypeCode  ) as teamMember "
				+ " (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus) as auditStatus, "
				+ " (Select concat(u.userId , '-' , u.firstName, ' ',u.middleName,' ',u.lastName) from  User u where u.legalEntityCode =sch.legalEntityCode and u.userId=sch.maker) as maker "
				+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='N' and o.reviewStatus='R' ) as responseReject "
				+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='C' and o.submissionStatus='A') as complianceCount "
				+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='NA' and o.submissionStatus='A') as notApplicableCount "
				//+ " , auditStatus "
				+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode "
				//+ " and sch.legalEntityCode=t.legalEntityCode and t.auditId=sch.auditId and t.userId=:userId"
				+ " and   IFNULL(auditStatus,'NotNull') not in ('AD','AU','DRP','UP','AP') "
				//+ " and  sch.auditId IN (SELECT t.auditId FROM AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userId=:userId  ) "
				+ " and  sch.auditId IN (SELECT d.auditId FROM AuditAdhocDocument d WHERE d.auditId=sch.auditId and d.legalEntityCode =sch.legalEntityCode and d.status='A' and d.id IN  "
				+ "  (SELECT r.documentId FROM AuditAdhocReport r WHERE r.documentId=d.id and r.legalEntityCode =d.legalEntityCode and r.legalEntityCode =sch.legalEntityCode and r.status='A' and r.targetUser=:userId  ))  "
				);
		
		// Financial Year and Audit Type filter added for filtering
				if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
					queryString.append(" and  sch.auditTypeCode =:auditTypeCode "); 
				}if(financialYear !=null) {
					LocalDate fYStartDt = financialYearStrtEndList.get(0);
					LocalDate fYearEndDt = financialYearStrtEndList.get(1);
					logger.info("fYStartDt :: "+fYStartDt+" fYEndDt :: "+fYearEndDt);
					queryString.append(" And (sch.scheduleStartDate between '"+fYStartDt+"' and '"+fYearEndDt+"' )");
					//queryString.append(" And (sch.scheduleStartDate between :fYStartDt and :fYearEndDt )");
				}
				
		logger.info("Before the qry....");
		
		if(!BankAuditUtil.isEmptyString(search)){
			queryString=queryString.append(" and ( "
					+ " sch.auditTypeCode IN (SELECT a.auditTypeCode FROM MaintAuditTypeDesc a  WHERE a.legalEntityCode=sch.legalEntityCode AND a.auditTypeDesc LIKE :search) "
					+ " or planId like :search "
					+ " or auditId like :search "
					//+ " or unitId like :search "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m WHERE m.legalEntityCode=sch.legalEntityCode AND (m.unitName LIKE :search or m.unitCode LIKE :search )) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,GeneralParameter g WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=m.unitType and g.description LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintCriticality c WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =c.legalEntityCode and m.uCriticality=c.criticalityCode and c.criticalityOfType='Entity' and  c.criticalityDesc LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintAuditParameter p WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =p.legalEntityCode and m.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and  p.duration LIKE :search) "
					+ " or sch.auditId IN (SELECT t.auditId FROM User u,AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.legalEntityCode =u.legalEntityCode and t.userId=u.userId and (t.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or DATE_FORMAT(sch.scheduleStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.scheduleEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.lastAuditDate, '%d %b %Y') LIKE :search "
					+ " or sch.maker IN (SELECT u.userId FROM User u WHERE u.legalEntityCode =sch.legalEntityCode and (u.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus and g.description LIKE :search) "
					+ " ) "
					// + " )"
					);
		}
		
		/*queryString=queryString.append("  ORDER BY FIELD(auditStatus, 'AI','P','AP','AS','AC','AU') asc ");*/
		String[] columns={
				"auditTypeCode",
				"(planId *1 ),(auditId *1 )", //"CAST(planId AS Integer),CAST(auditId AS Integer) "
				"unitType",
				"(unitId * 1) ",  //"unitId",
				"uCriticality",
				"duration",
				"lastAuditDate",//last audit date actually 
				"sch.scheduleStartDate",
				"sch.scheduleEndDate",
				"sch.actualStartDate",
				"sch.actualEndDate",
				"teamLead", // Team Lead
				// "sch.maker", // Team Member
				"sch.maker",
				"sch.auditStatus",
				"unitName",  
				"financialYear"
		};

		/*if(orderColumn!=null
				&& !BankAuditUtil.isEmptyString(orderDirection)){
			queryString=queryString.append(" order by ").append(columns[orderColumn]).append(" ").append(orderDirection);
		}*/
		System.out.println("orderColumn **.... "+ orderColumn +"  orderDirection ...."+ orderDirection );
		if(orderColumn != null && orderColumn == -1 && !BankAuditUtil.isEmptyString(orderDirection)){ // -1 send for the first time from the UI during landing page.
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc  "); // The code modified to get the records in the order of Status on landing page, the sequence is  Initiated, Planned, Submitted, Respond, Reviewed, Closed
		}else if(orderColumn!=null && !BankAuditUtil.isEmptyString(orderDirection)){
			if(orderColumn==0) {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection).append(" , FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc ,(auditId *1 ) asc  ");
			}else {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection);
			}
		}else {
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc  ");
		}
		
		System.out.println("queryString .... "+ queryString.toString());
		
		Query query=(Query) session.createQuery(queryString.toString())				
				.setResultTransformer(new ResultTransformer() {
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						AuditSchedule auditSchedule=null;
						//System.out.println("tuple[0] ...."+tuple[0]);
						if(tuple[0]!=null){
							auditSchedule=(AuditSchedule)tuple[0];
							/* session.evict(maintEntity);*/
							
							if(tuple[1]!=null){
								auditSchedule.setLegalEntityCode(Integer.parseInt(tuple[1].toString()));								
							}
							if(tuple[2]!=null){
								auditSchedule.setAuditTypeCode(tuple[2].toString());
							}
							
							if(tuple[3]!=null){
								auditSchedule.setPlanId(tuple[3].toString());
							}
							
							if(tuple[4]!=null){
								auditSchedule.setAuditId(tuple[4].toString());
							}
							if(tuple[5]!=null){
								//String unitCodeName=tuple[5].toString();
								//auditSchedule.setUnitId(unitCodeName);
								//auditSchedule.setUnitName(unitCodeName.substring(unitCodeName.indexOf('-')+1));
								auditSchedule.setUnitId(auditSchedule.getUnitId()+"-"+tuple[5].toString());
								auditSchedule.setUnitName(tuple[5].toString());
							}
							if(tuple[6]!=null){
								auditSchedule.setUnitType(tuple[6].toString());
							}
							if(tuple[7]!=null){
								auditSchedule.setuCriticality(tuple[7].toString());
							}
							if(tuple[8]!=null){
								//auditSchedule.setTeamLead(tuple[8].toString()+"-"+userDtls.get(tuple[8].toString()));
								auditSchedule.setTeamLead(userDtls.get(tuple[8].toString()));
							}
							if(tuple[9]!=null){
								auditSchedule.setDuration(tuple[9].toString());
							}
							if(tuple[10]!=null){
								auditSchedule.setFrequency(tuple[10].toString());
							}
							if(tuple[11]!=null){
								if("P".equalsIgnoreCase(tuple[11].toString()))auditSchedule.setAuditStatus("AP");
								else auditSchedule.setAuditStatus(tuple[11].toString());
							}
							if(tuple[12]!=null){
								auditSchedule.setMaker(tuple[12].toString());
							}
							if(tuple[13]!=null && auditSchedule.getRespondedFindings() != null){
								auditSchedule.setResponseReject(Integer.parseInt(tuple[13].toString()));
								auditSchedule.setRespondedFindings(auditSchedule.getRespondedFindings()- (Integer.parseInt(tuple[13].toString()))); // Included to find out the Responded Observations
							}else auditSchedule.setResponseReject(0);
							
							if(tuple[14]!=null){
								auditSchedule.setComplianceCount(Integer.parseInt(tuple[14].toString()));
							}else auditSchedule.setComplianceCount(0);
							
							if(tuple[15]!=null){
								auditSchedule.setNotApplicableCount(Integer.parseInt(tuple[15].toString()));
							}else auditSchedule.setNotApplicableCount(0);
							
							
							int tmSize =0;
							String teamMember="";
							try {
								logger.info("getAuditTeams .. "+auditSchedule.getAuditTeams());
								if(auditSchedule.getAuditTeams()!=null)tmSize=auditSchedule.getAuditTeams().size()-1;
							}catch(Exception e) {tmSize =0;}
							logger.info("Audit Id .... "+ auditSchedule.getAuditId()+" tmSize .."+tmSize);
							/*for( AuditTeam adtTm: auditSchedule.getAuditTeams() ) {
								
								adtTm.setUserId(adtTm.getUserId()+"-"+userDtls.get(adtTm.getUserId()));
								
								if(!"L".equalsIgnoreCase(adtTm.getUserType())) teamMember +=adtTm.getUserId() + ",";
								System.out.println("teamMember .... "+ teamMember);
							}*/
							if(tmSize >0 ) auditSchedule.setTeamMember(teamMember.substring(0,teamMember.lastIndexOf(",")));
							System.out.println("Team member .... "+auditSchedule.getTeamMember());
							//System.out.println("Team size ...."+auditSchedule.getAuditTeams().size());
						}
						return auditSchedule;
					}
			@Override
			public List transformList(List collection) {
				return collection;
			}
		})		
				.setParameter("legalEntityCode",legalEntityCode).setParameter("userId",userId);

		if(!BankAuditUtil.isEmptyString(search)){
			query.setParameter("search", "%"+search+"%");
		}
		
		if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
			query.setParameter("auditTypeCode", auditTypeCode);
		}
		
		logger.info("page :: "+page +"size :: "+ size);
		List<AuditSchedule> tmpAuditSchedule =query.list(); 
		Long totalRecords=null;
		try {
			totalRecords = (long)tmpAuditSchedule.size();
		}catch(Exception e) {
			totalRecords = (long)0;
		}
		List<AuditSchedule> auditSchedule=query.setFirstResult((page*size)).setMaxResults(size).list();
		
		System.out.println("Bfr size tmpAuditSchedule is .... "+tmpAuditSchedule.size()+" totalRecords:: "+ totalRecords);
		
		/*int i=0;
		for(AuditSchedule adSch:auditSchedule){
			System.out.println("Inside adSch ...");
			if("A2".equalsIgnoreCase(adSch.getAuditId()));
			else 	tmpAuditSchedule.add(adSch);
			System.out.println("after the call");
			
		}
		System.out.println("size tmpAuditSchedule .... "+tmpAuditSchedule);*/
		
		
		dataTableResponse.setData(auditSchedule);
		dataTableResponse.setRecordsTotal(totalRecords);
		dataTableResponse.setRecordsFiltered(totalRecords);
		
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return dataTableResponse;
	
	
		
	}
	
	@Override
	public String isAuditObsPendingBfrAuditSubmit(AuditSchedule auditSchedule) {

		Session session=getSession();
		String isAuditObsPendingBfrAuditSubmit ="Y";
		logger.info("LE:: "+ auditSchedule.getLegalEntityCode() + " Audit ID:: "+auditSchedule.getAuditId() + " Bsns Date::" + auditSchedule.getBusinessdateTimestamp() + "Audit Type:: "+ auditSchedule.getAuditTypeCode());
		try {
			StringBuilder queryStr1=new StringBuilder("");
			queryStr1.append(" select count(*) from AuditObservation where legalEntityCode=:legalEntityCode and auditId=:auditId ");
			queryStr1.append(" and auditTypeCode = :auditTypeCode and  ifnull(submissionStatus,'Null') != 'A'  ");
			
			org.hibernate.query.Query query=session.createQuery(queryStr1.toString());
			query.setParameter("legalEntityCode", auditSchedule.getLegalEntityCode());
			query.setParameter("auditId",auditSchedule.getAuditId());
			query.setParameter("auditTypeCode", auditSchedule.getAuditTypeCode());
			logger.info("isAuditObsPendingBfrAuditSubmit QRY is :: "+ query);
	
			isAuditObsPendingBfrAuditSubmit = query.uniqueResult().toString();
			logger.info("isAuditObsPendingBfrAuditSubmit rslt is :: "+ isAuditObsPendingBfrAuditSubmit);
			if(isAuditObsPendingBfrAuditSubmit != null && Integer.parseInt(isAuditObsPendingBfrAuditSubmit) == 0)
				isAuditObsPendingBfrAuditSubmit ="N";
			else isAuditObsPendingBfrAuditSubmit ="Y";
			
			logger.info("isAuditObsPendingBfrAuditSubmit QRY is :: "+ isAuditObsPendingBfrAuditSubmit);
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		return isAuditObsPendingBfrAuditSubmit;
	}
	
	@Override
	public String isAuditObsPending(AuditDto auditDto, String status) {

		Session session=getSession();
		String isAuditObsPendingBfrReadyForReview ="Y";
		logger.info("LE:: "+ auditDto.getLegalEntityCode() + " Audit ID:: "+auditDto.getAuditId() + "Audit Type:: "+ auditDto.getAuditTypeCode()+" status:: "+status);
		try {
			StringBuilder queryStr1=new StringBuilder("");
			queryStr1.append(" select count(*) from AuditObservation where legalEntityCode=:legalEntityCode and auditId=:auditId ");
			if(status.equals("RRR")) {
				queryStr1.append(" and auditTypeCode = :auditTypeCode and  ifnull(submissionStatus,'Null') != 'PA'  ");
			}else if(status.equals("RS")) {
				queryStr1.append(" and auditTypeCode = :auditTypeCode and  ifnull(responseStatus,'Null') != 'PA'  and complianceCategory='N' ");
			}else if(status.equals("WS")) {
				queryStr1.append(" and auditTypeCode = :auditTypeCode and  ifnull(reviewStatus,'Null') != 'PA'  and complianceCategory='N' ");
			}else 
				queryStr1.append(" and auditTypeCode = :auditTypeCode and  ifnull(submissionStatus,'Null') != 'PA'  ");
			
			org.hibernate.query.Query query=session.createQuery(queryStr1.toString());
			query.setParameter("legalEntityCode", auditDto.getLegalEntityCode());
			query.setParameter("auditId",auditDto.getAuditId());
			query.setParameter("auditTypeCode", auditDto.getAuditTypeCode());
			logger.info("isAuditObsPendingBfrAuditSubmit QRY is :: "+ query);
	
			isAuditObsPendingBfrReadyForReview = query.uniqueResult().toString();
			logger.info("isAuditObsPendingBfrAuditSubmit rslt is :: "+ isAuditObsPendingBfrReadyForReview);
			if(isAuditObsPendingBfrReadyForReview != null && Integer.parseInt(isAuditObsPendingBfrReadyForReview) == 0)
				isAuditObsPendingBfrReadyForReview ="N";
			else isAuditObsPendingBfrReadyForReview ="Y";
			
			logger.info("isAuditObsPendingBfrReadyForReview QRY is :: "+ isAuditObsPendingBfrReadyForReview);
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		return isAuditObsPendingBfrReadyForReview;
	}
	
	/** This method is for getting the current and previous Audit details of an Audit, for the Audit Report
	 *******/
	@Override
	public List getAuditDetailsForReport(int legalEntityCode,String userId,String role,String auditId,String planId,String auditTypeCode) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		
		List myAuditDetails= null; 
		StringBuilder queryString=new StringBuilder(" select "
				+" 	(select concat(unit_code , '-' , unit_name) from  maint_entity e where e.unit_code =sch.unit_id and e.legal_entity_code =sch.legal_entity_code ) as unitId ,"
				+"     (Select g.description from  maint_entity e,general_parameter g where e.unit_code =sch.unit_id and e.legal_entity_code =sch.legal_entity_code and e.legal_entity_code =g.legal_entity_code and g.key_1='UNIT_TYPE' and g.key_2='UNIT_TYPE' and g.value=e.unit_type) as unitType,"
				+"     (select concat(unit_code , '-' , unit_name) from  maint_entity e where e.legal_entity_code=sch.legal_entity_code and e.unit_code ="
				+" 		( select e1.parent_unit_code from maint_entity e1 where e1.legal_entity_code=sch.legal_entity_code and e1.unit_code=sch.unit_id)) parentUnitId ,"
				+"     (select concat(u.first_name , ' ' , u.last_name) from  user u where u.user_id =sch.unit_head and u.legal_entity_code =sch.legal_entity_code ) as unitHead ,"
				+"     (select concat(u.first_name , ' ' , u.last_name) from  user u where u.legal_entity_code =sch.legal_entity_code and u.user_id ="
				+" 		(Select t.user_id from  audit_team t where t.audit_id=sch.audit_id and t.legal_entity_code =sch.legal_entity_code and t.legal_entity_code=u.legal_entity_code and t.user_type='L')"
				+"     ) as auditLead ,"
				+"     sch.plan_id,sch.audit_id,sch.schedule_start_date,sch.schedule_end_date,sch.actual_start_date,sch.actual_end_date,"  //,sch.assessed_rating,sch.effective_rating
				+"     (select concat(rskp.risk_category_code,'-',rskp.risk_category_desc) from risk_score_percentage rskp where rskp.legal_entity_code=sch.legal_entity_code "
				+" 		and IFNULL(sch.assessed_risk_prcntg,100) > rskp.minimun_per AND IFNULL(sch.assessed_risk_prcntg,100) <= rskp.maximum_per and sch.audit_type_code=rskp.audit_type_code) as assessed_risk_prcntg,"
				+" 	(select concat(rskp.risk_category_code,'-',rskp.risk_category_desc) from risk_score_percentage rskp where rskp.legal_entity_code=sch.legal_entity_code "
				+" 		and IFNULL(sch.effective_risk_prcntg,100) > rskp.minimun_per AND IFNULL(sch.effective_risk_prcntg,100) <= rskp.maximum_per and sch.audit_type_code=rskp.audit_type_code) as effective_risk_prcntg,"
				+"     "
				+"     (select concat(u.first_name , ' ' , u.last_name) from  user u where u.legal_entity_code =sch.legal_entity_code and u.user_id ="
				+"     	(Select t.user_id from  audit_team t where t.audit_id=sch.prev_audit_id and t.legal_entity_code =sch.legal_entity_code and t.legal_entity_code=u.legal_entity_code and t.user_type='L')"
				+"      ) as prevAuditLead ,"
				+" 	(select sch1.plan_id from audit_schedule sch1 where sch1.legal_entity_code=sch.legal_entity_code and sch1.audit_id=sch.prev_audit_id) as prevPlanId, prev_audit_id,"
				+"     (select sch1.schedule_start_date from audit_schedule sch1 where sch1.legal_entity_code=sch.legal_entity_code and sch1.audit_id=sch.prev_audit_id) as prevSchStartDate,"
				+"     (select sch1.schedule_end_date from audit_schedule sch1 where sch1.legal_entity_code=sch.legal_entity_code and sch1.audit_id=sch.prev_audit_id) as prevSchEndDate,"
				+"     (select sch1.actual_start_date from audit_schedule sch1 where sch1.legal_entity_code=sch.legal_entity_code and sch1.audit_id=sch.prev_audit_id) as prevActStartDate,"
				+"     (select sch1.actual_end_date from audit_schedule sch1 where sch1.legal_entity_code=sch.legal_entity_code and sch1.audit_id=sch.prev_audit_id) as prevActEndDate,"
				+"     (select concat(rskp.risk_category_code,'-',rskp.risk_category_desc) from risk_score_percentage rskp where rskp.legal_entity_code=sch.legal_entity_code "
				+" 		 and IFNULL(sch.prev_assessed_risk_prcntg,100) > rskp.minimun_per AND IFNULL(sch.prev_assessed_risk_prcntg,100) <= rskp.maximum_per and sch.audit_type_code=rskp.audit_type_code) as prev_assessed_risk_prcntg,"
				+" 	   (select concat(rskp.risk_category_code,'-',rskp.risk_category_desc) from risk_score_percentage rskp where rskp.legal_entity_code=sch.legal_entity_code "
				+" 		 and IFNULL(sch.effective_risk_prcntg,100) > rskp.minimun_per AND IFNULL(sch.effective_risk_prcntg,100) <= rskp.maximum_per and sch.audit_type_code=rskp.audit_type_code) as prev_effective_risk_prcntg  "
				+"     ,(Select count(t.user_type) as team_size from audit_team t where t.audit_id=sch.audit_id and t.legal_entity_code =sch.legal_entity_code and  t.user_type='M') as team_size "
				+"     "
				+"  from audit_schedule sch where legal_entity_code=:legalEntityCode and audit_id=:auditId");
			
			logger.info("Before the qry...."+ queryString.toString());
			
			Query query=session.createNativeQuery(queryString.toString())
					.setParameter("legalEntityCode", legalEntityCode).setParameter("auditId", auditId);
			
			Object[] obj = (Object[])query.getSingleResult();
			try{
			if(obj !=null) {
				myAuditDetails = new ArrayList();
				// Setting up the Unit Details
				HashMap map =new HashMap();
				map.put("UNIT_NAME",obj[0].toString());
				map.put("UNIT_TYPE",obj[1].toString());
				map.put("PARANET_UNIT_NAME",obj[2].toString());
				map.put("UNIT_HEAD",obj[3].toString());
				myAuditDetails.add(map);
				
				// Setting up the Current Audit Details
				map =new HashMap();
				map.put("LEAD_AUDITOR",obj[4].toString());
				map.put("AUDIT_TEAM_SIZE",(obj[22] != null)?obj[22].toString():"");
				map.put("PLAN_ID",obj[5].toString());
				map.put("AUDIT_ID",obj[6].toString());
				map.put("SCHEDULE_START_DATE",obj[7].toString());
				map.put("SCHEDULE_END_DATE",obj[8].toString());
				map.put("ACTUAL_START_DATE",(obj[9] != null)?obj[9].toString():"");
				map.put("ACTUAL_END_DATE",(obj[10] != null)?obj[10].toString():"");
				map.put("ASSESSED_RATING",(obj[11] != null)?obj[11].toString():"");
				map.put("EFFECTIVE_RATING",(obj[12] != null)?obj[12].toString():"");
				map.put("AUDIT_PERIOD_FROM",(obj[9] != null)?obj[9].toString():"");
				map.put("AUDIT_PERIOD_TO",(obj[10] != null)?obj[10].toString():"");
				myAuditDetails.add(map);
				
				// Setting up the Previous Audit Details
				map =new HashMap();
				map.put("PREV_LEAD_AUDITOR",(obj[13] != null)?obj[13].toString():"");
				map.put("PREV_PLAN_ID",(obj[14] != null)?obj[14].toString():"");
				map.put("PREV_AUDIT_ID",(obj[15] != null)?obj[15].toString():"");
				map.put("PREV_SCHEDULE_START_DATE",(obj[16] != null)?obj[16].toString():"");
				map.put("PREV_SCHEDULE_END_DATE",(obj[17] != null)?obj[17].toString():"");
				map.put("PREV_ACTUAL_START_DATE",(obj[18] != null)?obj[18].toString():"");
				map.put("PREV_ACTUAL_END_DATE",(obj[19] != null)?obj[19].toString():"");
				map.put("PREV_ASSESSED_RATING",(obj[20] != null)?obj[20].toString():"");
				map.put("PREV_EFFECTIVE_RATING",(obj[21] != null)?obj[21].toString():"");
				map.put("PREV_AUDIT_PERIOD_FROM",(obj[18] != null)?obj[18].toString():"");
				map.put("PREV_AUDIT_PERIOD_TO",(obj[19] != null)?obj[19].toString():"");
				myAuditDetails.add(map);
			}
			
			System.out.println("myAuditDetails .... "+myAuditDetails);
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return myAuditDetails; 
	}
	
	/** This method is for retrieving and grouping the observations based on Audit Group & Audit SubGroup of an Audit, for the Audit Report
	 *******/
	@Override
	public List getAuditObservationDetailsForReport(int legalEntityCode,String userId,String role,String auditId,String planId,String auditTypeCode) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		
		AuditSchedule auditSchedule = null;
		List myAuditObservationDetails= null; 
		StringBuilder queryString=new StringBuilder(" select group_observation_id, "
			+" (select concat(g.audit_group_code,'-',g.audit_group_name) from maint_audit_group g where g.legal_entity_code=m.legal_entity_code and m.audit_group_code=g.audit_group_code and m.audit_type_code=g.audit_type_code) as auditGrp, "
			+"  (select concat(sg.audit_sub_group_code,'-',sg.audit_sub_group_name) from maint_audit_subgroup sg where sg.legal_entity_code=m.legal_entity_code and m.audit_group_code=sg.audit_group_code and m.audit_sub_group_code=sg.audit_sub_group_code and m.audit_type_code=sg.audit_type_code) as auditSubGrp, "
			+"  (select concat(a.activity_code,'-',a.activity_name) from maint_audit_activity a where a.legal_entity_code=m.legal_entity_code and a.activity_id=m.activity_id) as actvityId, "
			+"  (select concat(p.process_code,'-',p.process_name) from maint_audit_process p where p.legal_entity_code=m.legal_entity_code and p.process_id=m.process_id) as processId, "
			+"  (select concat(f.finding_code,'-',f.finding_name) from maint_audit_finding f where f.legal_entity_code=m.legal_entity_code and f.finding_id=m.finding_id) as findingId, "
			+"   o.capture_way,IFNULL(o.remarks,'') as remarks, IFNULL(o.cust_id,'') as cust_id,IFNULL(o.account_no,'') as account_no,IFNULL(o.account_name,''),IFNULL(o.limit_amount,''),IFNULL(o.balance,''),IFNULL(o.finding_remarks,''), "
			+"  (select concat(c.criticality_code,'-',c.criticality_desc) from maint_criticality c,maint_audit_activity a where a.legal_entity_code=c.legal_entity_code and c.criticality_code=a.a_criticality and c.criticality_of_type='Activity' and m.activity_id=a.activity_id and c.legal_entity_code=m.legal_entity_code ) as activityCriticality, "
			+"  (select concat(c.criticality_code,'-',c.criticality_desc) from maint_criticality c,maint_audit_process p where p.legal_entity_code=c.legal_entity_code and c.criticality_code=p.p_criticality and c.criticality_of_type='Process' and m.process_id=p.process_id and c.legal_entity_code=m.legal_entity_code ) as processCriticality, "
			+"  (select concat(c.criticality_code,'-',c.criticality_desc) from maint_criticality c,maint_audit_finding f where f.legal_entity_code=c.legal_entity_code and c.criticality_code=f.f_criticality and c.criticality_of_type='Finding' and m.finding_id=f.finding_id and c.legal_entity_code=m.legal_entity_code ) as findingCriticality "
			+"	,o.observation_id, compliance_category "
			+"  ,(select count(*) from audit_document_details d where d.legal_entity_code=o.legal_entity_code and d.observation_id = o.observation_id ) as docs_yesno "
			+" from audit_observation o, activity_process_finding_mapping m "
			+" where o.legal_entity_code=:legalEntityCode and audit_id=:auditId and o.mapping_id=m.mapping_id and o.legal_entity_code=m.legal_entity_code and o.audit_type_code=m.audit_type_code "
			+"  order by capture_way desc,group_observation_id ");
				
			logger.info("Before the qry...."+ queryString.toString());
			
			Query query=session.createNativeQuery(queryString.toString())
					.setParameter("legalEntityCode", legalEntityCode).setParameter("auditId", auditId);
			
			List qrylst = query.list();
			try{
				int qrySize=qrylst.size();
				String tmpGrpObsId=""; int cnt=1;
				
				AuditObservationDto auditObsDto= null;
				AuditObservation auditObs = null;
				List<AuditObservation> auditObsList=null;
				
				myAuditObservationDetails = new ArrayList();
				auditObsDto = new AuditObservationDto();
				auditObsList = new ArrayList();
				for ( Iterator iter = qrylst.iterator(); iter.hasNext(); ) {
					Object[] obj = (Object[]) iter.next();
					
					String grpObsId=obj[0].toString();
					//logger.info("tmpGrpObsId .."+tmpGrpObsId+" grpObsId.."+grpObsId);
					if(!tmpGrpObsId.equals("") && !tmpGrpObsId.equals(grpObsId)) {
						logger.info("cnt .."+ cnt+" tmpGrpObsId .."+tmpGrpObsId+" size .."+qrySize+ " listSize.."+auditObsList.size()+" auditObsList ...."+auditObsList);
						auditObsDto.setAuditObservations(auditObsList);
						myAuditObservationDetails.add(auditObsDto);
						auditObsList = new ArrayList();
						auditObsDto = new AuditObservationDto();
					}					
					auditObs = new AuditObservation();
					auditObs.setLegalEntityCode(legalEntityCode);
					auditObs.setGroupObservationId(grpObsId);
					auditObs.setAuditGroupCode(obj[1].toString());
					auditObs.setAuditSubGroupCode(obj[2].toString());
					auditObs.setActivityCode(obj[3].toString());
					auditObs.setProcessCode(obj[4].toString());
					auditObs.setFindingCode(obj[5].toString());
					auditObs.setCaptureWay(obj[6].toString());
					if(obj[7] !=null ) auditObs.setRemarks(obj[7].toString());
					if(obj[8] !=null )auditObs.setCustId(obj[8].toString());
					if(obj[9] !=null )auditObs.setAccountNo(obj[9].toString());
					if(obj[10] !=null )auditObs.setAccountName(obj[10].toString());
					if(obj[11] !=null )auditObs.setLimitAmount(obj[11].toString());
					if(obj[12] !=null )auditObs.setBalance(obj[12].toString());
					if(obj[13] !=null )auditObs.setFindingRemarks(obj[13].toString());
					if(obj[14] !=null )auditObs.setaCriticality(obj[14].toString());
					if(obj[15] !=null )auditObs.setpCriticality(obj[15].toString());
					if(obj[16] !=null )auditObs.setfCriticality(obj[16].toString());
					if(obj[17] !=null )auditObs.setObservationId(obj[17].toString());
					if(obj[18] !=null )auditObs.setComplianceCategory(obj[18].toString());
					if(obj[19] !=null )auditObs.setDocUploadYesNo(Integer.parseInt(obj[19].toString()) == 0 ? "No": "Yes" );
					auditObsList.add(auditObs);
					
					
					if(cnt == qrySize ) {
						logger.info("cnt .."+ cnt+" tmpGrpObsId .."+tmpGrpObsId+" size .."+qrySize+ " listSize.."+auditObsList.size()+" auditObsList ...."+auditObsList);
						auditObsDto.setAuditObservations(auditObsList);
						myAuditObservationDetails.add(auditObsDto);
					}
					cnt++;
					tmpGrpObsId =grpObsId;
				}
			
				System.out.println("myAuditObservationDetails .... "+myAuditObservationDetails);
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return myAuditObservationDetails; 
	}
	
	/** This method is for retrieving and grouping the observations based on Audit Group & Audit SubGroup of an Audit, for the Audit Report
	 *******/
	@Override
	public Boolean getFetchObservationsExtrnlAndInsertInternal(int legalEntityCode,String userId,String unitId,String auditId,String planId,String auditTypeCode) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		
		Boolean fetchInsertStatus= true;
		AuditSchedule auditSchedule = null;
		List myAuditObservationDetails= null; 
		List<AuditObservation> auditObservations = null;
		
		try {
			logger.info("Inside getFetchObservationsExtrnlAndInsertInternal legalEntityCode.."+legalEntityCode +" userId.."+userId);
			logger.info("unitId.."+unitId +" auditId.."+auditId+" planId.."+planId+" auditTypeCode.."+auditTypeCode);
			/***************** This block is to retrieve the Observation details, based on Finding way order by MappingId *********************/
			StringBuilder queryString1=new StringBuilder(" "
					+ " SELECT o.* FROM observation_dump o"
					+ "  WHERE  o.legal_entity_code =:legalEntityCode AND o.plan_id=:unitId "
					+ "  	  AND  capture_way='F' "
					+ "  ORDER BY mapping_id, capture_type");
			
			Query query1=session.createNativeQuery(queryString1.toString())
					.setParameter("legalEntityCode", legalEntityCode).setParameter("unitId", unitId);
			
			List<Object[]> lstFindObs = query1.list();
			System.out.println("Find obs total.."+ lstFindObs.size());
			
			/***************** This block is to retrieve the Observation details, based on Account way order by CustId *********************/
			StringBuilder queryString2=new StringBuilder(" "
					+ " SELECT o.* FROM observation_dump o"
					+ "  WHERE  o.legal_entity_code =:legalEntityCode AND o.plan_id=:unitId "
					+ "  	  AND  capture_way='A' "
					+ "  ORDER BY cust_id ");
			
			Query query2=session.createNativeQuery(queryString2.toString())
					.setParameter("legalEntityCode", legalEntityCode).setParameter("unitId", unitId);
			
			List<Object[]> lstAccObs = query2.list();
			System.out.println("Acc obs total.."+ lstAccObs.size());
			
			/********* This section to combine both the records ***********/
			List<Object[]> lst = new ArrayList<Object[]>();
			for ( Object[] rec: lstFindObs ) lst.add(rec);
			for ( Object[] rec: lstAccObs )	lst.add(rec);
			
			System.out.println(" obs total.."+ lst.size());
			
			int i=0;
			String groupObservationId ="", observationId ="", tmpMapId="",tmpCptTyp="", tmpCustId="";
			auditObservations = new ArrayList<AuditObservation>();
			
			for ( Object[] rec: lst ) {
				AuditObservation auditObservation = new AuditObservation();
				
				if(i ==0 || ("F".equalsIgnoreCase(rec[7].toString()) && !tmpMapId.equalsIgnoreCase(rec[6].toString()) && !tmpCptTyp.equalsIgnoreCase(rec[8].toString())) 
						|| ("A".equalsIgnoreCase(rec[7].toString()) && !tmpCustId.equalsIgnoreCase(rec[11].toString()))  ) {
					groupObservationId= sequenceAppenderService.getAutoSequenceId();
				}
				observationId= sequenceAppenderService.getAutoSequenceId();
				
				if(rec[0] != null )auditObservation.setLegalEntityCode(legalEntityCode);
				if(rec[1] != null )auditObservation.setAuditTypeCode(auditTypeCode);
				if(rec[2] != null )auditObservation.setPlanId(planId);
				if(rec[3] != null )auditObservation.setAuditId(auditId);
				
				if(rec[4] != null )auditObservation.setGroupObservationId(groupObservationId);
				if(rec[5] != null )auditObservation.setObservationId(observationId);
				if(rec[6] != null )auditObservation.setMappingId(rec[6].toString());
				if(rec[7] != null )auditObservation.setCaptureWay(rec[7].toString());
				if(rec[8] != null )auditObservation.setCaptureType(rec[8].toString());
				if(rec[9] != null )auditObservation.setAccountNo(rec[9].toString());
				if(rec[10] != null )auditObservation.setAccountName(rec[10].toString());
				if(rec[11] != null )auditObservation.setCustId(rec[11].toString());
				if(rec[12] != null )auditObservation.setAccountCurrency(rec[12].toString());
				if(rec[13] != null )auditObservation.setLimitType(rec[13].toString());
				if(rec[14] != null )auditObservation.setLimitAmount(rec[14].toString());
				if(rec[15] != null )auditObservation.setLimitCurrency(rec[15].toString());
				if(rec[16] != null )auditObservation.setBalance(rec[16].toString());
				if(rec[17] != null ) {
					DateFormat formatter = new SimpleDateFormat("YYYY-MM-DD"); 
					Date limitDate = (Date)formatter.parse(rec[17].toString());
					auditObservation.setDate(limitDate);
				}
				if(rec[18] != null )auditObservation.setFindingId(rec[18].toString());
				if(rec[19] != null )auditObservation.setFindingDescription(rec[19].toString());
				//if(rec[20] != null )auditObservation.setFindingRemarks(rec[20].toString());
				if(rec[21] != null )auditObservation.setSubmissionStatus("U");
				if(rec[22] != null )auditObservation.setFindingOwner(userId);
				//if(rec[23] != null )auditObservation.setFindingDate(rec[23].toString());
				if(rec[24] != null )auditObservation.setFindingCriticality(rec[24].toString());
				if(rec[25] != null )auditObservation.setObservationCriticality(rec[25].toString());
				//if(rec[26] != null )auditObservation.setResponseId(rec[26].toString());
				//if(rec[27] != null )auditObservation.setResponseDescription(rec[27].toString());
				//if(rec[28] != null )auditObservation.setResponseRemarks(rec[28].toString());
				//if(rec[29] != null )auditObservation.setResponseOwner(rec[29].toString());
				//if(rec[30] != null )auditObservation.setResponseDate(rec[30].toString());
				//if(rec[31] != null )auditObservation.setResponseStatus(rec[31].toString());
				//if(rec[32] != null )auditObservation.setReviewId(rec[32].toString());
				//if(rec[33] != null )auditObservation.setReviewDescription(rec[33].toString());
				//if(rec[34] != null )auditObservation.setReviewRemarks(rec[34].toString());
				//if(rec[35] != null )auditObservation.setReviewOwner(rec[35].toString());
				//if(rec[36] != null )auditObservation.setReviewDate(rec[36].toString());
				//if(rec[37] != null )auditObservation.setReviewStatus(rec[37].toString());
				//if(rec[38] != null )auditObservation.setRemarks(rec[38].toString());
				//if(rec[39] != null )auditObservation.setComplianceCategory(rec[39].toString());
				if(rec[40] != null )auditObservation.setStatus("OU");
				if(rec[41] != null )auditObservation.setEntityStatus("A");
				if(rec[42] != null )auditObservation.setMaker(userId);
				//if(rec[43] != null )auditObservation.setMakerTimestamp(rec[43].toString());
				if(rec[44] != null )auditObservation.setChecker(rec[44].toString());
				//if(rec[45] != null )auditObservation.setCheckerTimestamp(rec[45].toString());
				//if(rec[46] != null )auditObservation.setBusinessdateTimestamp(rec[46].toString());
				//if(rec[47] != null )auditObservation.setSysdateTimestamp(rec[47].toString());

				auditObservation.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditObservation.getLegalEntityCode()));
				auditObservation.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				auditObservation.setMakerTimestamp(auditObservation.getBusinessdateTimestamp());
				
				auditObservations.add(auditObservation);
				
				tmpMapId = rec[6].toString();
				tmpCptTyp = (rec[8]!= null ? rec[8].toString() : "XXXX");
				tmpCustId = (rec[11]!= null ? rec[11].toString() : "XXXX");
				i++;
				
			}
			/******************** Observations Fetch logic, Ends here ********************************/
			
			for (AuditObservation auditObservation : auditObservations) {
				/*auditObservation.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditObservation.getLegalEntityCode()));
				auditObservation.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				auditObservation.setMakerTimestamp(auditObservation.getBusinessdateTimestamp());
				if(BankAuditUtil.isEmptyString(auditObservation.getObservationId())){
					auditObservation.setObservationId(sequenceAppenderService.getAutoSequenceId());
				}*/
				System.out.println("*************************************");
				System.out.println(auditObservation.getGroupObservationId());
				System.out.println(auditObservation.getObservationId());
				System.out.println("*************************************");
				
				auditObservationDao.flushSession();
				auditObservationDao.save(auditObservation);
			}
			
			session.createQuery("update AuditSchedule set interfaceAccFetch ='Y' "
					+ " where "
					+ " 	legalEntityCode =:legalEntityCode "
					+ " 	and auditTypeCode =:auditTypeCode "
					+ " 	and auditId =:auditId ")
			.setParameter("legalEntityCode", legalEntityCode)
			.setParameter("auditTypeCode", auditTypeCode)
			.setParameter("auditId", auditId)
			.executeUpdate();
			
		}catch(Exception e) {
			fetchInsertStatus = false;
			e.printStackTrace(System.out);
		}
		System.out.println("fetchInsertStatus .."+fetchInsertStatus);
		return fetchInsertStatus; 
	}
	
	/** This method is for retrieving and grouping the observations based on Audit Group & Audit SubGroup of an Audit, for the Audit Report
	 *******/
	@Override
	public String getAlreadyFetchObsStatus(int legalEntityCode,String userId,String auditId,String planId,String auditTypeCode) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		
		String fetchInsertStatus= "N";
		AuditSchedule auditSchedule = null;
		
		try {
			logger.info(" Inside getFetchObservationsExtrnlAndInsertInternal legalEntityCode.."+legalEntityCode +" userId.."+userId);
			logger.info(" auditId.."+auditId+" planId.."+planId+" auditTypeCode.."+auditTypeCode);
			/***************** This block is to retrieve the Observation details, based on Finding way order by MappingId *********************/
			StringBuilder queryString1=new StringBuilder(" FROM AuditSchedule sch "
					+ "  WHERE  sch.legalEntityCode =:legalEntityCode AND sch.auditId=:auditId ");
			
			auditSchedule=(AuditSchedule)(session.createQuery(queryString1.toString())
					.setParameter("legalEntityCode", legalEntityCode).setParameter("auditId", auditId).uniqueResult());
			
			logger.info(" auditSchedule .."+ auditSchedule.getInterfaceAccFetch());
			if(auditSchedule.getInterfaceAccFetch() != null && "Y".equalsIgnoreCase(auditSchedule.getInterfaceAccFetch()))
				fetchInsertStatus ="Y";
			
		}catch(Exception e) {
			fetchInsertStatus = "Exception";
			e.printStackTrace(System.out);
		}
		System.out.println("fetchInsertStatus .."+fetchInsertStatus);
		return fetchInsertStatus; 
	}
	
	/******* To get the Audits related to Dashboard Top Boxes ********************************/
	@SuppressWarnings("unchecked")
	@Override
	public DataTableResponse getAuditsOnDashboard(int legalEntityCode,String userId, String search, Integer orderColumn,
			String orderDirection, Integer page, Integer size, String auditStatus,String auditTypeCode, String unitsListStr, List unitsList
			,LocalDate fromDate,LocalDate toDate,List auditList) {

		Session session = getSession();
		session.setDefaultReadOnly(true);
		
		logger.info("auditStatus .. "+auditStatus + " unitsList .. "+unitsListStr);
		logger.info("fromDate .. "+fromDate + " toDate .. "+toDate +" auditList .."+ auditList);

		/********************** This block is to retrieve the User details --> UserId and UserName **************************/
		StringBuilder queryString0=new StringBuilder(// " Select concat(u.firstName , ' ' , u.lastName) as firstName, u.userId "
				 " from User u  "
				+ " where "
				+ " u.legalEntityCode =:legalEntityCode "
				);
		
		Query query1=session.createQuery(queryString0.toString())
				.setParameter("legalEntityCode", legalEntityCode);
		
		List lst = query1.list();
		HashMap<String, String> userDtls = new HashMap<String, String>();
		for ( Iterator iter = lst.iterator(); iter.hasNext(); ) {
			User usr = (User) iter.next();
			if(usr.getUserId().equalsIgnoreCase(userId))
				userDtls.put(usr.getUserId(), "Me"); // for the same User we are stamping as "You"
			else userDtls.put(usr.getUserId(), usr.getFirstName()+" "+usr.getMiddleName()+" "+usr.getLastName());	
		}
		logger.info("userId is .... "+ userId+" serach:: "+search +" legal entity code:: "+legalEntityCode);
		logger.info("User details val is .... "+ userDtls);
		/******************** User Retrieval logic, Ends here ********************************/
		
		DataTableResponse dataTableResponse=new DataTableResponse();
		try {
		//StringBuilder queryString=new StringBuilder(" from AuditSchedule where legalEntityCode =:legalEntityCode ");
		StringBuilder queryString=new StringBuilder("select sch as auditSchedule, " 
				+ " legalEntityCode,"
				+ "(select concat(auditTypeCode , '-' , auditTypeDesc) from MaintAuditTypeDesc at where at.auditTypeCode=sch.auditTypeCode and at.legalEntityCode= sch.legalEntityCode ) as auditTypeCode,"
				
				+ "planId,auditId, "
				+ " (Select concat(unitCode , '-' , unitName) from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitId,  "
				
				+ " (Select g.description from  MaintEntity e,GeneralParameter g where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=e.unitType) as unitType, "
				
				+ " (Select c.criticalityDesc from  MaintEntity e,MaintCriticality c where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =c.legalEntityCode and e.uCriticality=c.criticalityCode and c.criticalityOfType='Entity') as uCriticality, "
				
				//+ " (Select concat(u.firstName , ' ' , u.lastName) from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
				+ " (Select t.userId from  AuditTeam t where t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
				
				+" duration," //Code to comment //+ " (Select p.duration from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as duration, "
				+" frequency," //Code to comment //+ " (Select p.frequency from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as frequency, "
				//+ " (select tm.auditTypeCode,GROUP_CONCAT(tm.name) from (Select t.auditTypeCode,t.planId, t.auditId, concat(u.firstName , ' ' , u.lastName) as name from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='T') tm where  GROUP BY tm.auditTypeCode  ) as teamMember "
				+ " (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus) as auditStatus, "
				+ " (Select concat(u.userId , '-' , u.firstName, ' ',u.middleName,' ',u.lastName) from  User u where u.legalEntityCode =sch.legalEntityCode and u.userId=sch.maker) as maker "
				+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='N' and o.reviewStatus='R' ) as responseReject "
				+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='C' and o.submissionStatus='A') as complianceCount "
				+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='NA' and o.submissionStatus='A') as notApplicableCount "
				//+ " , auditStatus "
				+ ", (Select g.value from GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='AUDIT_EARLY_START' and g.key2='EARLY_START_ALLOWED') as earlyStartAllowed "
				+ ", (Select g.value from GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='AUDIT_OFFSET_DAYS' and g.key2='AUDIT_OFFSET_DAYS') as auditOffsetDays " 
				+ ", (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.observationStatus) as auditStatusTemp " // This result to stamp in Audit status in the Observation status is AE i.e Audit Reported
				+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode "
				+ " and sch.unitId IN (:unitsList) "
				+ "	and sch.scheduleStartDate BETWEEN '"+fromDate+"' AND '"+toDate+"'  " );
				
		if(!BankAuditUtil.isEmptyString(auditTypeCode))
			queryString= queryString.append(" AND sch.auditTypeCode = :auditTypeCode ");
		if("P".equalsIgnoreCase(auditStatus)){
			queryString=queryString.append(" and ( auditStatus in ('AP')) "); 
		}else if("I".equalsIgnoreCase(auditStatus)){
			queryString=queryString.append(" and ( auditStatus in ('AI')) "); 
		}else if("C".equalsIgnoreCase(auditStatus)){
			queryString=queryString.append(" and ( auditStatus in ('AS','AR','AW','AC')) "); 
		}else if("W".equalsIgnoreCase(auditStatus)){
			queryString=queryString.append(" and ( auditId in (:auditList)) ");  // cond to get the List of Audits which are in Watchlist
		}
		else queryString=queryString.append(" and ( auditStatus in ('AI','AP' ,'AS','AR','AW','AC','AF')) "); 				
				
		System.out.println("Before the qry....");
		
		if(!BankAuditUtil.isEmptyString(search)){
			queryString=queryString.append(" and ( "
					+ " sch.auditTypeCode IN (SELECT a.auditTypeCode FROM MaintAuditTypeDesc a  WHERE a.legalEntityCode=sch.legalEntityCode AND a.auditTypeDesc LIKE :search) "
					+ " or planId like :search "
					+ " or auditId like :search "
					//+ " or unitId like :search "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m WHERE m.legalEntityCode=sch.legalEntityCode AND (m.unitName LIKE :search or m.unitCode LIKE :search )) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,GeneralParameter g WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=m.unitType and g.description LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintCriticality c WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =c.legalEntityCode and m.uCriticality=c.criticalityCode and c.criticalityOfType='Entity' and  c.criticalityDesc LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintAuditParameter p WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =p.legalEntityCode and m.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and  p.duration LIKE :search) "
					+ " or sch.auditId IN (SELECT t.auditId FROM User u,AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.legalEntityCode =u.legalEntityCode and t.userId=u.userId and (t.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or DATE_FORMAT(sch.scheduleStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.scheduleEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.lastAuditDate, '%d %b %Y') LIKE :search "
					+ " or sch.maker IN (SELECT u.userId FROM User u WHERE u.legalEntityCode =sch.legalEntityCode and (u.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus and g.description LIKE :search) "
					+ " ) "
					// + " )"
					);
		}
		
		/*queryString=queryString.append("  ORDER BY FIELD(auditStatus, 'AI','P','AP','AS','AC','AU') asc ");*/
		String[] columns={
				"auditTypeCode",
				"(auditId *1 ), (planId *1 )", //"CAST(planId AS Integer),CAST(auditId AS Integer) "
				"unitType",
				"(unitId * 1) ",  //"unitId",
				"uCriticality",
				"duration",
				"lastAuditDate",//last audit date actually 
				"sch.scheduleStartDate",
				"sch.scheduleEndDate",
				"sch.actualStartDate",
				"sch.actualEndDate",
				"teamLead", // Team Lead
				// "sch.maker", // Team Member
				"sch.maker",
				"sch.auditStatus"
		};

		/*if(orderColumn!=null
				&& !BankAuditUtil.isEmptyString(orderDirection)){
			queryString=queryString.append(" order by ").append(columns[orderColumn]).append(" ").append(orderDirection);
		}*/
		System.out.println("orderColumn **.... "+ orderColumn +"  orderDirection ...."+ orderDirection );
		if(orderColumn != null && orderColumn == -1 && !BankAuditUtil.isEmptyString(orderDirection)){ // -1 send for the first time from the UI during landing page.
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc  "); // The code modified to get the records in the order of Status on landing page, the sequence is  Initiated, Planned, Submitted, Respond, Reviewed, Closed
		}else if(orderColumn!=null && !BankAuditUtil.isEmptyString(orderDirection)){
			if(orderColumn==0) {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection).append(" , FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc ,(auditId *1 ) asc  ");
			}else {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection);
			}
		}else {
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc  ");
		}
		
		System.out.println("queryString .... "+ queryString.toString());
		
		Query query=(Query) session.createQuery(queryString.toString())				
				.setResultTransformer(new ResultTransformer() {
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						AuditSchedule auditSchedule=null;
						//System.out.println("tuple[0] ...."+tuple[0]);
						if(tuple[0]!=null){
							auditSchedule=(AuditSchedule)tuple[0];
							/* session.evict(maintEntity);*/
							
							if(tuple[1]!=null){
								auditSchedule.setLegalEntityCode(Integer.parseInt(tuple[1].toString()));								
							}
							if(tuple[2]!=null){
								auditSchedule.setAuditTypeCode(tuple[2].toString());
							}
							
							if(tuple[3]!=null){
								auditSchedule.setPlanId(tuple[3].toString());
							}
							
							if(tuple[4]!=null){
								auditSchedule.setAuditId(tuple[4].toString());
							}
							if(tuple[5]!=null){
								auditSchedule.setUnitId(tuple[5].toString());
							}
							if(tuple[6]!=null){
								auditSchedule.setUnitType(tuple[6].toString());
							}
							if(tuple[7]!=null){
								auditSchedule.setuCriticality(tuple[7].toString());
							}
							if(tuple[8]!=null){
								//auditSchedule.setTeamLead(tuple[8].toString()+"-"+userDtls.get(tuple[8].toString()));
								auditSchedule.setTeamLead(userDtls.get(tuple[8].toString()));
							}
							if(tuple[9]!=null){
								auditSchedule.setDuration(tuple[9].toString());
							}
							if(tuple[10]!=null){
								auditSchedule.setFrequency(tuple[10].toString());
							}
							if(tuple[11]!=null){
								if("P".equalsIgnoreCase(tuple[11].toString()))auditSchedule.setAuditStatus("AP"); // temp purpose as in few earlier records the Planned status is reflecting as "P"
								else if("AE".equalsIgnoreCase(auditSchedule.getObservationStatus())) auditSchedule.setAuditStatus(tuple[18] !=null ?tuple[18].toString() :tuple[11].toString() );
								else auditSchedule.setAuditStatus(tuple[11].toString());
							}
							if(tuple[12]!=null){
								auditSchedule.setMaker(tuple[12].toString());
							}
							if(tuple[13]!=null && auditSchedule.getRespondedFindings() != null){
								auditSchedule.setResponseReject(Integer.parseInt(tuple[13].toString()));
								auditSchedule.setRespondedFindings(auditSchedule.getRespondedFindings()- (Integer.parseInt(tuple[13].toString()))); // Included to find out the Responded Observations
							}else auditSchedule.setResponseReject(0);
							
							if(tuple[14]!=null){
								auditSchedule.setComplianceCount(Integer.parseInt(tuple[14].toString()));
							}else auditSchedule.setComplianceCount(0);
							
							if(tuple[15]!=null){
								auditSchedule.setNotApplicableCount(Integer.parseInt(tuple[15].toString()));
							}else auditSchedule.setNotApplicableCount(0);
							
							if(tuple[16]!=null){
								auditSchedule.setEarlyStartAllowed(tuple[16].toString());
							}else auditSchedule.setEarlyStartAllowed("Y");
							
							if(tuple[17]!=null){
								auditSchedule.setAuditOffsetDays(Integer.parseInt(tuple[17].toString()));
							}else auditSchedule.setAuditOffsetDays(0);
							
							int tmSize =auditSchedule.getAuditTeams().size()-1;
							String teamMember="";
							System.out.println("Audit Id .... "+ auditSchedule.getAuditId()+" tmSize .."+tmSize);
							for( AuditTeam adtTm: auditSchedule.getAuditTeams() ) {
								
								adtTm.setUserId(adtTm.getUserId()+"-"+userDtls.get(adtTm.getUserId()));
								
								if(!"L".equalsIgnoreCase(adtTm.getUserType())) teamMember +=adtTm.getUserId() + ",";
								System.out.println("teamMember .... "+ teamMember);
							}if(tmSize >0 ) auditSchedule.setTeamMember(teamMember.substring(0,teamMember.lastIndexOf(",")));
							System.out.println("Team member .... "+auditSchedule.getTeamMember());
							//System.out.println("Team size ...."+auditSchedule.getAuditTeams().size());
							
						}
						return auditSchedule;
					}
			@Override
			public List transformList(List collection) {
				return collection;
			}
		})		
				.setParameter("legalEntityCode",legalEntityCode).setParameter("unitsList", unitsList);
				//.setParameter("fromDate", fromDate)
				//.setParameter("toDate", toDate);
		if(!BankAuditUtil.isEmptyString(auditTypeCode))
				query.setParameter("auditTypeCode", auditTypeCode);

		if("W".equalsIgnoreCase(auditStatus) && auditList != null) {
				query.setParameter("auditList", auditList);
		}
		
		if(!BankAuditUtil.isEmptyString(search)){
			query.setParameter("search", "%"+search+"%");
		}
		
		System.out.println("page :: "+page +"size :: "+ size);
		List<AuditSchedule> tmpAuditSchedule =query.list(); 
		Long totalRecords=null;
		try {
			totalRecords = (long)tmpAuditSchedule.size();
		}catch(Exception e) {
			totalRecords = (long)0;
		}
		List<AuditSchedule> auditSchedule=query.setFirstResult((page*size)).setMaxResults(size).list();
		
		System.out.println("Bfr size tmpAuditSchedule is .... "+tmpAuditSchedule.size()+" totalRecords:: "+ totalRecords);
		
		/*int i=0;
		for(AuditSchedule adSch:auditSchedule){
			System.out.println("Inside adSch ...");
			if("A2".equalsIgnoreCase(adSch.getAuditId()));
			else 	tmpAuditSchedule.add(adSch);
			System.out.println("after the call");
			
		}
		System.out.println("size tmpAuditSchedule .... "+tmpAuditSchedule);*/
		
		
		dataTableResponse.setData(auditSchedule);
		dataTableResponse.setRecordsTotal(totalRecords);
		dataTableResponse.setRecordsFiltered(totalRecords);
		
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return dataTableResponse;
	
	}
	
	/****************** To get the Watchlist Audits ***********************/
	@SuppressWarnings("unchecked")
	@Override
	public List getWatchListForAudits(int legalEntityCode, String auditTypeCode,LocalDate startDate) {
		Session session=getSession();
		List<String> watchList=null;
		String auditTypeCode_cond = "";
		logger.info("getWatchListForAudits .. "+ legalEntityCode +" auditTypeCode.."+auditTypeCode +" startDate.. "+ startDate);
		try {
			watchList = new ArrayList<String>();
			if(!BankAuditUtil.isEmptyString(auditTypeCode))
				auditTypeCode_cond= "AND s.audit_type_code= :auditTypeCode ";
			
			StringBuilder str = new StringBuilder(" "+
					" 		SELECT s.audit_id FROM risk_score_percentage p, audit_schedule s, "+
					" 			      		(SELECT legal_entity_code, audit_type_code,MIN(rating_internal) AS rating_internal  "+
					" 							FROM risk_score_percentage "+
					"							WHERE legal_entity_code=:legalEntityCode "+
					"					    		GROUP BY audit_type_code) AS pd "+
					" 				  WHERE p.legal_entity_code=pd.legal_entity_code AND p.legal_entity_code=s.legal_entity_code "+
					" 					AND  p.audit_type_code=pd.audit_type_code AND p.rating_internal=pd.rating_internal  "+
					" 					AND effective_risk_prcntg <= p.maximum_per AND p.audit_type_code=s.audit_type_code "+
					" 					AND s.actual_start_date >=:startDate "+ auditTypeCode_cond +
					" 		UNION  "+
					" 		SELECT s.audit_id FROM audit_schedule s WHERE s.rating_improvement <= -2 AND s.legal_entity_code=:legalEntityCode  "+ auditTypeCode_cond +
					"  ");
			
			Query qry =session.createNativeQuery(str.toString())
				.setParameter("legalEntityCode", legalEntityCode)
				.setParameter("startDate",startDate);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode))
				qry.setParameter("auditTypeCode", auditTypeCode);
		
			watchList=(qry.list());
		}catch(Exception e) {
			e.printStackTrace();
		}
		return watchList;
	}

	
	@Override
	public List getRiskCntByBusinssAndProdByMapping(int legalEntityCode, String auditTypeCode, String planId,String auditId, String auditStatus) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		List myRiskSummarylst = new ArrayList();
		try {
			
			StringBuilder queryStr1=new StringBuilder(" SELECT e.levelCode from AuditSchedule sch, MaintEntity e  WHERE "
					+" sch.legalEntityCode = e.legalEntityCode AND e.unitCode=sch.unitId AND"
					+" e.legalEntityCode=:legalEntityCode AND sch.auditId=:auditId   ");
			
			String entityLevelCode=(String)session.createQuery(queryStr1.toString())
					.setParameter("legalEntityCode", legalEntityCode).setParameter("auditId", auditId)
					.uniqueResult();
			
			logger.info("getRiskCntByBusinssAndProdByMapping QRY is :: "+ entityLevelCode);
			
			
			//   ifnull(submissionStatus,'Null') != 'A' 
			StringBuilder queryString=new StringBuilder("   "
					+ " SELECT  " 
					+ "     m.audit_group_code, "   	// 0
					+ "		max(g.audit_group_name), "  // 1
					+ "     m.audit_sub_group_code, "	// 2
					+ "		max(s.audit_sub_group_name), " // 3
					+ "     o.submission_status, "		// 4
					+ "     COUNT(*) " 					// 5
					+ " FROM " 
					+ "     maint_audit_group g, maint_audit_subgroup s,activity_process_finding_mapping m " 
					+ "         LEFT JOIN " 
					+ "     audit_observation o ON m.mapping_id = o.mapping_id " 
					+ "         AND m.legal_entity_code = o.legal_entity_code " 
					+ "         AND audit_id =:auditId " 
					+ " WHERE " 
					+ "     m.audit_type_code =:auditTypeCode  and m.audit_type_code =g.audit_type_code and m.audit_type_code=s.audit_type_code " 
					+ "     and g.legal_entity_code= s.legal_entity_code and g.audit_type_code = s.audit_type_code and g.audit_group_code=s.audit_group_code " 
					+ "     and m.legal_entity_code=g.legal_entity_code and m.legal_entity_code=s.legal_entity_code  " 
					+ "     and m.audit_group_code=g.audit_group_code and m.audit_sub_group_code= s.audit_sub_group_code " 
					+ "     AND m.legal_entity_code =:legalEntityCode " 
					+ "		AND ( m.risk_belongs_to= '3' OR m.risk_belongs_to =:entityLevelCode OR ifnull(m.risk_belongs_to,'0') = '0' ) "
					+ " GROUP BY m.audit_group_code , m.audit_sub_group_code , o.submission_status " 
					+ " ORDER BY m.audit_group_code , m.audit_sub_group_code " 
					+ " ");
			System.out.println("Before the qry....");
			
			Query query2lst=session.createSQLQuery(queryString.toString())
					.setParameter("legalEntityCode", legalEntityCode)
					.setParameter("auditId", auditId).setParameter("auditTypeCode", auditTypeCode).setParameter("entityLevelCode", entityLevelCode);
			
			List qrylst = query2lst.list();
			logger.info("after executing obj.... "+ qrylst.size());
			
			RiskSummaryDtls riskSummDtls = new RiskSummaryDtls();
			String bsnsPrdComb = null; String tmpBsnsPrdComb =""; int cnt=0; 	int total=0;
			try{
				
				int rsltSize=qrylst.size();
				logger.info("size is .... "+ rsltSize);
				for ( Iterator iter = qrylst.iterator(); iter.hasNext(); ) {
					
					Object[] obj = (Object[]) iter.next();
					bsnsPrdComb = obj[0].toString()+"_"+obj[2].toString();
					logger.info("bsnsPrdComb .... "+ bsnsPrdComb);
					if(tmpBsnsPrdComb.equalsIgnoreCase(bsnsPrdComb)) {
						if(obj[4]!=null && obj[4].toString().equals("U")) riskSummDtls.setUnauthMapping(obj[5].toString());
						else if(obj[4]!=null && obj[4].toString().equals("A")) riskSummDtls.setAuthMapping(obj[5].toString());
						total += Integer.parseInt(obj[5].toString()); 
					}else {
						if(cnt>0)myRiskSummarylst.add(riskSummDtls);
						
						riskSummDtls = new RiskSummaryDtls();
						riskSummDtls.setAuditGroupCode(obj[0].toString());	
						riskSummDtls.setAuditGroupCodeName(obj[1].toString());
						riskSummDtls.setAuditSubGroupCode(obj[2].toString());	
						riskSummDtls.setAuditSubGroupCodeName(obj[3].toString());
						riskSummDtls.setLegalEntityCode(legalEntityCode);
						riskSummDtls.setAuditId(auditId);
						riskSummDtls.setAuditTypeCode(auditTypeCode);
						riskSummDtls.setChecked("Y");
						
						if(obj[4]!=null && obj[4].toString().equals("U")) riskSummDtls.setUnauthMapping(obj[5].toString());
						else if(obj[4]!=null && obj[4].toString().equals("A")) riskSummDtls.setAuthMapping(obj[5].toString());
						total =Integer.parseInt(obj[5].toString());
						riskSummDtls.setTotalMapping(obj[5].toString());
					}cnt++;
					
					if(cnt==rsltSize) myRiskSummarylst.add(riskSummDtls);
					logger.info(" cnt .. "+ cnt +"riskSummDtls is .... "+ riskSummDtls  );
					}				
				/*for ( Iterator iter = qrylst.iterator(); iter.hasNext(); ) {
										
					Object[] obj = (Object[]) iter.next();
					bsnsPrdComb = obj[0].toString()+"_"+obj[2].toString();
					logger.info("bsnsPrdComb .... "+ bsnsPrdComb);
					if(tmpBsnsPrdComb.equalsIgnoreCase(bsnsPrdComb)) {
						if(obj[4]!=null && obj[4].toString().equals("U")) riskSummDtls.put("UNAUTH", obj[5].toString());
						else if(obj[4]!=null && obj[4].toString().equals("A")) riskSummDtls.put("AUTH", obj[5].toString());
						total += Integer.parseInt(obj[5].toString()); 
					}else {
						if(cnt>0)myRiskSummarylst.add(riskSummDtls);
						
						riskSummDtls = new HashMap();
						riskSummDtls.put("BUSINESS_LINE_CODE", obj[0].toString());	
						riskSummDtls.put("BUSINESS_LINE_NAME", obj[1].toString());
						riskSummDtls.put("PRODUCT_CODE", obj[2].toString());	
						riskSummDtls.put("PRODUCT_NAME", obj[3].toString());
						if(obj[4]!=null && obj[4].toString().equals("U")) riskSummDtls.put("UNAUTH", obj[5].toString());
						else if(obj[4]!=null && obj[4].toString().equals("A")) riskSummDtls.put("AUTH", obj[5].toString());
						total =Integer.parseInt(obj[5].toString());
						riskSummDtls.put("TOTAL", obj[5].toString());
					}cnt++;
					
					if(cnt==rsltSize) myRiskSummarylst.add(riskSummDtls);
					logger.info(" cnt .. "+ cnt +"riskSummDtls is .... "+ riskSummDtls  );
					}*/
				}catch(Exception e) {
					e.printStackTrace(System.out);
				}
			logger.info("myRiskSummarylst .."+myRiskSummarylst);
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return myRiskSummarylst; 
	}
	
	@Override
	public List<RiskSummaryDtls> getRiskCntByBusinssAndProdByRiskId(int legalEntityCode, String auditTypeCode, String planId,String auditId, String auditStatus) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		List<RiskSummaryDtls> myRiskSummarylst = new ArrayList();
		try {
			logger.info("Inside getRiskCntByBusinssAndProdByRiskId ..  .. ..");
			StringBuilder queryString=new StringBuilder("   "
					+ " SELECT  r, "
					+ "  (SELECT auditGroupName  FROM MaintAuditGroup g"
					+ "		WHERE g.legalEntityCode=r.legalEntityCode AND r.auditTypeCode=:auditTypeCode AND r.auditTypeCode=g.auditTypeCode AND  g.auditGroupCode=r.auditGroupCode ) as auditGroupCodeName, "
					+ "  (SELECT auditSubGroupName  from MaintAuditSubgroup s "
					+ "		WHERE s.legalEntityCode=r.legalEntityCode AND s.auditTypeCode=:auditTypeCode AND r.auditTypeCode=s.auditTypeCode"
					+ "			AND  s.auditGroupCode=r.auditGroupCode AND s.auditSubGroupCode=r.auditSubGroupCode) as auditSubGroupCodeName, "
					+ "  (select count(m.auditSubGroupCode) from AuditObservation as o, ActivityProcessFindingMapping as m where "
					+ "        o.legalEntityCode=m.legalEntityCode and o.mappingId=m.mappingId and o.auditTypeCode=m.auditTypeCode and "
					+ "        m.auditGroupCode=r.auditGroupCode and m.auditSubGroupCode=r.auditSubGroupCode and m.legalEntityCode=r.legalEntityCode "
					+ "        and m.auditTypeCode=r.auditTypeCode and "
					+ "        o.legalEntityCode=r.legalEntityCode and o.auditId=r.auditId "
					+ "						and o.submissionStatus = 'A') as authMapping, "
					+ "  (select count(m.auditSubGroupCode) from AuditObservation as o, ActivityProcessFindingMapping as m where "
					+ "        o.legalEntityCode=m.legalEntityCode and o.mappingId=m.mappingId and o.auditTypeCode=m.auditTypeCode and "
					+ "        m.auditGroupCode=r.auditGroupCode and m.auditSubGroupCode=r.auditSubGroupCode and m.legalEntityCode=r.legalEntityCode "
					+ "        and m.auditTypeCode=r.auditTypeCode and "
					+ "        o.legalEntityCode=r.legalEntityCode and o.auditId=r.auditId "
					+ "						and o.submissionStatus <> 'A') as unauthMapping "
					
					+ " FROM RiskSummaryDtls r " 
					+ " WHERE " 
					+ "     r.auditId =:auditId  " 
					+ "     AND r.legalEntityCode=:legalEntityCode" 
					+ " ORDER BY r.auditGroupCode , r.auditSubGroupCode " 
					+ " ");
			System.out.println("Before the qry....");
			
			Query query=session.createQuery(queryString.toString())
					.setResultTransformer(new ResultTransformer() {
						
						@Override
						public Object transformTuple(Object[] tuple, String[] aliases) {
							RiskSummaryDtls riskSummaryDtls=null;
							if(tuple[0]!=null) {
								riskSummaryDtls=(RiskSummaryDtls)tuple[0];							
							}
							if(tuple[1]!=null) riskSummaryDtls.setAuditGroupCodeName(tuple[1].toString());
							if(tuple[2]!=null) riskSummaryDtls.setAuditSubGroupCodeName(tuple[2].toString());
							if(tuple[3]!=null) riskSummaryDtls.setAuthMapping(tuple[3].toString());
							if(tuple[4]!=null) riskSummaryDtls.setUnauthMapping(tuple[4].toString());
							
							return riskSummaryDtls;
						}
						
						@Override
						public List transformList(List collection) {
							return collection;
						}
					})
					.setParameter("legalEntityCode", legalEntityCode)
					.setParameter("auditId", auditId).setParameter("auditTypeCode", auditTypeCode);
			
			myRiskSummarylst = query.list();
			logger.info("after executing obj.... "+ myRiskSummarylst.size());
			logger.info("myRiskSummarylst .."+myRiskSummarylst);
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return myRiskSummarylst; 
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean isPreviousAuditExist(int legalEntityCode,String unitId,String auditTypeCode,String auditId) {
		Session session=getSession();
		boolean isPreviousAuditExist = false;
		Integer isPreviousAuditExistCnt=0;
		try {
			isPreviousAuditExistCnt = Integer.parseInt((session.createQuery("SELECT COUNT(*)  FROM AuditSchedule sch WHERE "
					+ " legalEntityCode =:legalEntityCode "
					+ " AND auditTypeCode =:auditTypeCode "
					+ " AND auditId = :auditId "
					+ " AND prevAuditId in (SELECT sch1.auditId from AuditSchedule sch1 WHERE sch1.legalEntityCode =:legalEntityCode AND sch.unitId =sch1.unitId) ")
					.setParameter("legalEntityCode", legalEntityCode)
					.setParameter("auditTypeCode", auditTypeCode).setParameter("auditId", auditId)
					.uniqueResult()).toString());
			logger.info(" isPreviousAuditExist cnt .. "+ isPreviousAuditExistCnt);
			if(isPreviousAuditExistCnt > 0) isPreviousAuditExist = true;
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return isPreviousAuditExist;
						
	}
	
	
	/*********************************************** BaaSDOS Changes implemented here ************************************************/
	@Override
	public List<RiskSummaryDtls> getObservationCntByAgAsgActByMapping(int legalEntityCode, String auditTypeCode, String planId,String auditId, String auditStatus) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		List myRiskSummarylst = new ArrayList();
		try {
			
			logger.info("Inside getObservationCntByAgAsgActByMapping QRY is :: "+ auditTypeCode+" :: "+auditStatus+" :: "+auditId);
			/*StringBuilder queryStr1=new StringBuilder(" SELECT e.levelCode from AuditSchedule sch, MaintEntity e  WHERE "
					+" sch.legalEntityCode = e.legalEntityCode AND e.unitCode=sch.unitId AND"
					+" e.legalEntityCode=:legalEntityCode AND sch.auditId=:auditId   ");
			
			String entityLevelCode=(String)session.createQuery(queryStr1.toString())
					.setParameter("legalEntityCode", legalEntityCode).setParameter("auditId", auditId)
					.uniqueResult(); 			
			logger.info("getRiskCntByBusinssAndProdByMapping QRY is :: "+ entityLevelCode); */
			
			
			//   ifnull(submissionStatus,'Null') != 'A' 
			StringBuilder queryString=new StringBuilder("   "
					+ " SELECT  " 
					+ "     m.audit_type_code, t.audit_type_desc, "   	// 0,1
					+ "		m.audit_group_code, g.audit_group_name, " 	// 2,3
					+ "     m.audit_sub_group_code, s.audit_sub_group_name, "	// 4,5
					+ "		a.activity_code, a.activity_name , " 		// 6,7
					+ "     COUNT(*) " 									// 8
					+ " FROM " 
					+ "     activity_process_finding_mapping m  " 
					+ "     JOIN maint_audit_type_desc t ON t.legal_entity_code=m.legal_entity_code and t.audit_type_code=m.audit_type_code " 
					+ "     JOIN maint_audit_group g ON g.legal_entity_code=m.legal_entity_code and g.audit_type_code=m.audit_type_code "
					+ "									 and g.audit_group_code=m.audit_group_code " 
					+ "     JOIN maint_audit_subgroup s ON s.legal_entity_code=m.legal_entity_code and s.audit_type_code=m.audit_type_code "
					+ "										and s.audit_group_code=m.audit_group_code and s.audit_sub_group_code=m.audit_sub_group_code " 
					+ "     JOIN maint_audit_activity a ON a.legal_entity_code=m.legal_entity_code and a.activity_code=m.activity_code AND a.entity_status='A' " 
					+ " WHERE " 
					+ "     m.audit_type_code =:auditTypeCode  AND m.legal_entity_code =:legalEntityCode AND m.entity_status='A' " 
					+ " GROUP BY m.audit_type_code, m.audit_group_code, m.audit_sub_group_code, a.activity_code,a.activity_name " 
					+ " ORDER BY m.audit_group_code , m.audit_sub_group_code, m.activity_code " 
					+ " ");
			System.out.println("Before the qry....");
			
			Query query2lst=session.createSQLQuery(queryString.toString())
					.setParameter("legalEntityCode", legalEntityCode)
					.setParameter("auditTypeCode", auditTypeCode);
			
			List qrylst = query2lst.list();
			logger.info("after executing obj.... "+ qrylst.size());
			
			RiskSummaryDtls riskSummDtls = new RiskSummaryDtls();
			String bsnsPrdComb = null; String tmpBsnsPrdComb =""; int cnt=0; 	int total=0;
			try{
				int rsltSize=qrylst.size();
				logger.info("size is .... "+ rsltSize);
				for ( Iterator iter = qrylst.iterator(); iter.hasNext(); ) {
					Object[] obj = (Object[]) iter.next();
					riskSummDtls = new RiskSummaryDtls();
					riskSummDtls.setAuditTypeCode(obj[0].toString());	
					riskSummDtls.setAuditTypeDesc(obj[1].toString());
					riskSummDtls.setAuditGroupCode(obj[2].toString());	
					riskSummDtls.setAuditGroupCodeName(obj[3].toString());
					riskSummDtls.setAuditSubGroupCode(obj[4].toString());	
					riskSummDtls.setAuditSubGroupCodeName(obj[5].toString());
					riskSummDtls.setActivityCode(obj[6].toString());	
					riskSummDtls.setActivityName(obj[7].toString());
					riskSummDtls.setTotalMapping(obj[8].toString());
					riskSummDtls.setUnauthMapping(obj[8].toString());
					riskSummDtls.setLegalEntityCode(legalEntityCode);
					riskSummDtls.setAuditId(auditId);
					riskSummDtls.setChecked("Y");
					
					myRiskSummarylst.add(riskSummDtls);
				}
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}
			logger.info("myRiskSummarylst .."+myRiskSummarylst);
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return myRiskSummarylst; 
	}
	
	@Override
	public List<RiskSummaryDtls> getObservationCntByAgAsgActByAuditId(int legalEntityCode, String auditTypeCode, String planId,String auditId, String auditStatus) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		List<RiskSummaryDtls> myRiskSummarylst = new ArrayList();
		try {
			logger.info("Inside getObservationCntByAgAsgActByAuditId ..  .. .."+ auditTypeCode+" :: "+ auditId +" :: "+ auditStatus);
			StringBuilder queryString=new StringBuilder("   "
					+ " SELECT  r, "
					+ "  (SELECT auditGroupName  FROM MaintAuditGroup g"
					+ "		WHERE g.legalEntityCode=r.legalEntityCode AND r.auditTypeCode=:auditTypeCode AND r.auditTypeCode=g.auditTypeCode AND  g.auditGroupCode=r.auditGroupCode ) as auditGroupCodeName, "
					+ "  (SELECT auditSubGroupName  from MaintAuditSubgroup s "
					+ "		WHERE s.legalEntityCode=r.legalEntityCode AND s.auditTypeCode=:auditTypeCode AND r.auditTypeCode=s.auditTypeCode"
					+ "			AND  s.auditGroupCode=r.auditGroupCode AND s.auditSubGroupCode=r.auditSubGroupCode) as auditSubGroupCodeName, "
					+ "  (SELECT activityName  from MaintAuditActivity a "
					+ "		WHERE a.legalEntityCode=r.legalEntityCode AND a.activityCode=r.activityCode AND a.entityStatus='A') as auditSubGroupCodeName, "
					
					+ "  (select count(m.auditSubGroupCode) from AuditObservation as o, ActivityProcessFindingMapping as m where "
					+ "        o.legalEntityCode=m.legalEntityCode and o.mappingId=m.mappingId and o.auditTypeCode=m.auditTypeCode and "
					+ "        m.auditGroupCode=r.auditGroupCode and m.auditSubGroupCode=r.auditSubGroupCode and m.legalEntityCode=r.legalEntityCode "
					+ "        and m.auditTypeCode=r.auditTypeCode and m.activityCode=r.activityCode and "
					+ "        o.legalEntityCode=r.legalEntityCode and o.auditId=r.auditId "
					+ "						and o.submissionStatus = 'A') as authMapping, "
					+ "  (select count(m.auditSubGroupCode) from AuditObservation as o, ActivityProcessFindingMapping as m where "
					+ "        o.legalEntityCode=m.legalEntityCode and o.mappingId=m.mappingId and o.auditTypeCode=m.auditTypeCode and "
					+ "        m.auditGroupCode=r.auditGroupCode and m.auditSubGroupCode=r.auditSubGroupCode and m.legalEntityCode=r.legalEntityCode "
					+ "        and m.auditTypeCode=r.auditTypeCode and m.activityCode=r.activityCode and "
					+ "        o.legalEntityCode=r.legalEntityCode and o.auditId=r.auditId "
					+ "						and o.submissionStatus in ('U','R') ) as unauthMapping, "
					//+ "						and o.submissionStatus <> 'A') as unauthMapping "
					+ "  (select count(m.auditSubGroupCode) from AuditObservation as o, ActivityProcessFindingMapping as m where "
					+ "        o.legalEntityCode=m.legalEntityCode and o.mappingId=m.mappingId and o.auditTypeCode=m.auditTypeCode and "
					+ "        m.auditGroupCode=r.auditGroupCode and m.auditSubGroupCode=r.auditSubGroupCode and m.legalEntityCode=r.legalEntityCode "
					+ "        and m.auditTypeCode=r.auditTypeCode and m.activityCode=r.activityCode and "
					+ "        o.legalEntityCode=r.legalEntityCode and o.auditId=r.auditId "
					+ "						and o.submissionStatus not in ('A','U','R') ) as pendingAuthMapping "
					
					+ " FROM RiskSummaryDtls r " 
					+ " WHERE " 
					+ "     r.auditId =:auditId  " 
					+ "     AND r.legalEntityCode=:legalEntityCode" 
					+ " ORDER BY r.auditGroupCode , r.auditSubGroupCode, r.activityCode " 
					+ " ");
			System.out.println("Before the qry....");
			
			Query query=session.createQuery(queryString.toString())
					.setResultTransformer(new ResultTransformer() {
						
						@Override
						public Object transformTuple(Object[] tuple, String[] aliases) {
							RiskSummaryDtls riskSummaryDtls=null;
							if(tuple[0]!=null) {
								riskSummaryDtls=(RiskSummaryDtls)tuple[0];							
							}
							if(tuple[1]!=null) riskSummaryDtls.setAuditGroupCodeName(tuple[1].toString());
							if(tuple[2]!=null) riskSummaryDtls.setAuditSubGroupCodeName(tuple[2].toString());
							if(tuple[3]!=null) riskSummaryDtls.setActivityName(tuple[3].toString());
							if(tuple[4]!=null) riskSummaryDtls.setAuthMapping(tuple[4].toString());
							if(tuple[5]!=null) riskSummaryDtls.setUnauthMapping(tuple[5].toString());
							if(tuple[6]!=null) riskSummaryDtls.setPendingAuthMapping(tuple[6].toString());
							int totalMapping = Integer.parseInt(riskSummaryDtls.getAuthMapping()) + Integer.parseInt(riskSummaryDtls.getUnauthMapping()) 
							 				   + Integer.parseInt(riskSummaryDtls.getPendingAuthMapping());
							riskSummaryDtls.setTotalMapping(totalMapping+"");
							
							return riskSummaryDtls;
						}
						
						@Override
						public List transformList(List collection) {
							return collection;
						}
					})
					.setParameter("legalEntityCode", legalEntityCode)
					.setParameter("auditId", auditId).setParameter("auditTypeCode", auditTypeCode);
			
			myRiskSummarylst = query.list();
			logger.info("after executing obj.... "+ myRiskSummarylst.size());
			logger.info("myRiskSummarylst .."+myRiskSummarylst);
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return myRiskSummarylst; 
	}
	
	@Override
	public List<RiskSummaryDtls> getObservationCntByAgAsgActByAuditIdResponse(int legalEntityCode, String auditTypeCode, String planId,String auditId, String auditStatus) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		List<RiskSummaryDtls> myRiskSummarylst = new ArrayList();
		try {
			logger.info("Inside getObservationCntByAgAsgActByAuditIdResponse ..  .. .."+ auditTypeCode+" :: "+ auditId +" :: "+ auditStatus);
			StringBuilder queryString=new StringBuilder("   "
					+ " SELECT  r, "
					+ "  (SELECT auditGroupName  FROM MaintAuditGroup g"
					+ "		WHERE g.legalEntityCode=r.legalEntityCode AND r.auditTypeCode=:auditTypeCode AND r.auditTypeCode=g.auditTypeCode AND  g.auditGroupCode=r.auditGroupCode ) as auditGroupCodeName, "
					+ "  (SELECT auditSubGroupName  from MaintAuditSubgroup s "
					+ "		WHERE s.legalEntityCode=r.legalEntityCode AND s.auditTypeCode=:auditTypeCode AND r.auditTypeCode=s.auditTypeCode"
					+ "			AND  s.auditGroupCode=r.auditGroupCode AND s.auditSubGroupCode=r.auditSubGroupCode) as auditSubGroupCodeName, "
					+ "  (SELECT activityName  from MaintAuditActivity a "
					+ "		WHERE a.legalEntityCode=r.legalEntityCode AND a.activityCode=r.activityCode AND a.entityStatus='A') as auditSubGroupCodeName, "
					
					+ "  (select count(m.auditSubGroupCode) from AuditObservation as o, ActivityProcessFindingMapping as m where "
					+ "        o.legalEntityCode=m.legalEntityCode and o.mappingId=m.mappingId and o.auditTypeCode=m.auditTypeCode and "
					+ "        m.auditGroupCode=r.auditGroupCode and m.auditSubGroupCode=r.auditSubGroupCode and m.legalEntityCode=r.legalEntityCode "
					+ "        and m.auditTypeCode=r.auditTypeCode and m.activityCode=r.activityCode and "
					+ "        o.legalEntityCode=r.legalEntityCode and o.auditId=r.auditId "
					+ "	       and o.responseStatus = 'A' and o.complianceCategory in ('N','C')) as authMapping, "
					+ "  (select count(m.auditSubGroupCode) from AuditObservation as o, ActivityProcessFindingMapping as m where "
					+ "        o.legalEntityCode=m.legalEntityCode and o.mappingId=m.mappingId and o.auditTypeCode=m.auditTypeCode and "
					+ "        m.auditGroupCode=r.auditGroupCode and m.auditSubGroupCode=r.auditSubGroupCode and m.legalEntityCode=r.legalEntityCode "
					+ "        and m.auditTypeCode=r.auditTypeCode and m.activityCode=r.activityCode and "
					+ "        o.legalEntityCode=r.legalEntityCode and o.auditId=r.auditId "
					+ "		   and (o.responseStatus = 'U' or o.responseStatus IS NULL) and o.complianceCategory in ('N','C')) as unauthMapping, "
					//+ "						and o.submissionStatus <> 'A') as unauthMapping "
					+ "  (select count(m.auditSubGroupCode) from AuditObservation as o, ActivityProcessFindingMapping as m where "
					+ "        o.legalEntityCode=m.legalEntityCode and o.mappingId=m.mappingId and o.auditTypeCode=m.auditTypeCode and "
					+ "        m.auditGroupCode=r.auditGroupCode and m.auditSubGroupCode=r.auditSubGroupCode and m.legalEntityCode=r.legalEntityCode "
					+ "        and m.auditTypeCode=r.auditTypeCode and m.activityCode=r.activityCode and "
					+ "        o.legalEntityCode=r.legalEntityCode and o.auditId=r.auditId "
					+ "		   and (o.responseStatus ='PA' OR o.responseStatus='R') and o.complianceCategory in ('N','C')) as pendingAuthMapping "
					
					+ " FROM RiskSummaryDtls r " 
					+ " WHERE " 
					+ "     r.auditId =:auditId  " 
					+ "     AND r.legalEntityCode=:legalEntityCode" 
					+ " ORDER BY r.auditGroupCode , r.auditSubGroupCode, r.activityCode " 
					+ " ");
			System.out.println("Before the qry....");
			
			Query query=session.createQuery(queryString.toString())
					.setResultTransformer(new ResultTransformer() {
						
						@Override
						public Object transformTuple(Object[] tuple, String[] aliases) {
							RiskSummaryDtls riskSummaryDtls=null;
							if(tuple[0]!=null) {
								riskSummaryDtls=(RiskSummaryDtls)tuple[0];							
							}
							if(tuple[1]!=null) riskSummaryDtls.setAuditGroupCodeName(tuple[1].toString());
							if(tuple[2]!=null) riskSummaryDtls.setAuditSubGroupCodeName(tuple[2].toString());
							if(tuple[3]!=null) riskSummaryDtls.setActivityName(tuple[3].toString());
							if(tuple[4]!=null) riskSummaryDtls.setAuthMapping(tuple[4].toString());
							if(tuple[5]!=null) riskSummaryDtls.setUnauthMapping(tuple[5].toString());
							if(tuple[6]!=null) riskSummaryDtls.setPendingAuthMapping(tuple[6].toString());
							
							int totalMapping = Integer.parseInt(riskSummaryDtls.getAuthMapping()) + Integer.parseInt(riskSummaryDtls.getUnauthMapping()) 
			 				   + Integer.parseInt(riskSummaryDtls.getPendingAuthMapping());
							riskSummaryDtls.setTotalMapping(totalMapping+"");
			
							return riskSummaryDtls;
						}
						
						@Override
						public List transformList(List collection) {
							return collection;
						}
					})
					.setParameter("legalEntityCode", legalEntityCode)
					.setParameter("auditId", auditId).setParameter("auditTypeCode", auditTypeCode);
			
			myRiskSummarylst = query.list();
			logger.info("after executing obj.... "+ myRiskSummarylst.size());
			logger.info("myRiskSummarylst .."+myRiskSummarylst);
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return myRiskSummarylst; 
	}
	
	@Override
	public List<RiskSummaryDtls> getObservationCntByAgAsgActByAuditIdReview(int legalEntityCode, String auditTypeCode, String planId,String auditId, String auditStatus) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		List<RiskSummaryDtls> myRiskSummarylst = new ArrayList();
		try {
			logger.info("Inside getObservationCntByAgAsgActByAuditIdReview ..  .. .."+ auditTypeCode+" :: "+ auditId +" :: "+ auditStatus);
			StringBuilder queryString=new StringBuilder("   "
					+ " SELECT  r, "
					+ "  (SELECT auditGroupName  FROM MaintAuditGroup g"
					+ "		WHERE g.legalEntityCode=r.legalEntityCode AND r.auditTypeCode=:auditTypeCode AND r.auditTypeCode=g.auditTypeCode AND  g.auditGroupCode=r.auditGroupCode ) as auditGroupCodeName, "
					+ "  (SELECT auditSubGroupName  from MaintAuditSubgroup s "
					+ "		WHERE s.legalEntityCode=r.legalEntityCode AND s.auditTypeCode=:auditTypeCode AND r.auditTypeCode=s.auditTypeCode"
					+ "			AND  s.auditGroupCode=r.auditGroupCode AND s.auditSubGroupCode=r.auditSubGroupCode) as auditSubGroupCodeName, "
					+ "  (SELECT activityName  from MaintAuditActivity a "
					+ "		WHERE a.legalEntityCode=r.legalEntityCode AND a.activityCode=r.activityCode AND a.entityStatus='A') as auditSubGroupCodeName, "
					
					+ "  (select count(m.auditSubGroupCode) from AuditObservation as o, ActivityProcessFindingMapping as m where "
					+ "        o.legalEntityCode=m.legalEntityCode and o.mappingId=m.mappingId and o.auditTypeCode=m.auditTypeCode and "
					+ "        m.auditGroupCode=r.auditGroupCode and m.auditSubGroupCode=r.auditSubGroupCode and m.legalEntityCode=r.legalEntityCode "
					+ "        and m.auditTypeCode=r.auditTypeCode and m.activityCode=r.activityCode and "
					+ "        o.legalEntityCode=r.legalEntityCode and o.auditId=r.auditId "
					+ "		  and o.reviewStatus = 'A' and o.complianceCategory in ('N','C')) as authMapping, "
					+ "  (select count(m.auditSubGroupCode) from AuditObservation as o, ActivityProcessFindingMapping as m where "
					+ "        o.legalEntityCode=m.legalEntityCode and o.mappingId=m.mappingId and o.auditTypeCode=m.auditTypeCode and "
					+ "        m.auditGroupCode=r.auditGroupCode and m.auditSubGroupCode=r.auditSubGroupCode and m.legalEntityCode=r.legalEntityCode "
					+ "        and m.auditTypeCode=r.auditTypeCode and m.activityCode=r.activityCode and "
					+ "        o.legalEntityCode=r.legalEntityCode and o.auditId=r.auditId "
					+ "		   and o.reviewStatus = 'U' and o.complianceCategory in ('N','C')) as unauthMapping, "
					//+ "						and o.submissionStatus <> 'A') as unauthMapping "
					+ "  (select count(m.auditSubGroupCode) from AuditObservation as o, ActivityProcessFindingMapping as m where "
					+ "        o.legalEntityCode=m.legalEntityCode and o.mappingId=m.mappingId and o.auditTypeCode=m.auditTypeCode and "
					+ "        m.auditGroupCode=r.auditGroupCode and m.auditSubGroupCode=r.auditSubGroupCode and m.legalEntityCode=r.legalEntityCode "
					+ "        and m.auditTypeCode=r.auditTypeCode and m.activityCode=r.activityCode and "
					+ "        o.legalEntityCode=r.legalEntityCode and o.auditId=r.auditId "
					+ "		   and o.reviewStatus ='PA' and o.complianceCategory in ('N','C')) as pendingAuthMapping "
					
					+ " FROM RiskSummaryDtls r " 
					+ " WHERE " 
					+ "     r.auditId =:auditId  " 
					+ "     AND r.legalEntityCode=:legalEntityCode" 
					+ " ORDER BY r.auditGroupCode , r.auditSubGroupCode, r.activityCode " 
					+ " ");
			System.out.println("Before the qry....");
			
			Query query=session.createQuery(queryString.toString())
					.setResultTransformer(new ResultTransformer() {
						
						@Override
						public Object transformTuple(Object[] tuple, String[] aliases) {
							RiskSummaryDtls riskSummaryDtls=null;
							if(tuple[0]!=null) {
								riskSummaryDtls=(RiskSummaryDtls)tuple[0];							
							}
							if(tuple[1]!=null) riskSummaryDtls.setAuditGroupCodeName(tuple[1].toString());
							if(tuple[2]!=null) riskSummaryDtls.setAuditSubGroupCodeName(tuple[2].toString());
							if(tuple[3]!=null) riskSummaryDtls.setActivityName(tuple[3].toString());
							if(tuple[4]!=null) riskSummaryDtls.setAuthMapping(tuple[4].toString());
							if(tuple[5]!=null) riskSummaryDtls.setUnauthMapping(tuple[5].toString());
							if(tuple[6]!=null) riskSummaryDtls.setPendingAuthMapping(tuple[6].toString());
							
							return riskSummaryDtls;
						}
						
						@Override
						public List transformList(List collection) {
							return collection;
						}
					})
					.setParameter("legalEntityCode", legalEntityCode)
					.setParameter("auditId", auditId).setParameter("auditTypeCode", auditTypeCode);
			
			myRiskSummarylst = query.list();
			logger.info("after executing obj.... "+ myRiskSummarylst.size());
			logger.info("myRiskSummarylst .."+myRiskSummarylst);
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return myRiskSummarylst; 
	}
	
	/********* For BAAS implementation ************/
	@Override
	public List<RiskSummaryDtls> getObservationCntByAuditIdReview(int legalEntityCode, String auditTypeCode, String planId,String auditId, String auditStatus) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		List<RiskSummaryDtls> myRiskSummarylst = new ArrayList();
		try {
			logger.info("Inside getObservationCntByAuditIdReview ..  .. .."+ auditTypeCode+" :: "+ auditId +" :: "+ auditStatus);
			StringBuilder queryString=new StringBuilder("   "
					+ " SELECT  sch.auditId, "
					+ " 	(select count(*) from AuditObservation o where o.auditId=sch.auditId and o.complianceCategory='N' and o.legalEntityCode=sch.legalEntityCode) as nonComp, " 
					+ " 	(select count(*) from AuditObservation o where o.auditId=sch.auditId and o.reviewStatusAttribute='R' and o.legalEntityCode=sch.legalEntityCode) as reviewed, "
					+ " 	(select count(*) from AuditObservation o where o.auditId=sch.auditId and o.reviewStatusAttribute='A' and o.legalEntityCode=sch.legalEntityCode) as accepted, "
					+ " 	(select count(*) from AuditObservation o where o.auditId=sch.auditId and o.reviewStatusAttribute='FC' and o.legalEntityCode=sch.legalEntityCode) as furtherComp, "
					+ " 	(select count(*) from AuditObservation o where o.auditId=sch.auditId and o.reviewStatusAttribute='FC' and o.responseStatus in ('U','R','PA')) as bankAction, "
					+ " 	(select count(*) from AuditObservation o where o.auditId=sch.auditId and o.reviewStatusAttribute='FC' and o.responseStatus in ('A')) as reviewerAction "
					+ " from AuditSchedule as sch where sch.auditId =:auditId  "
					+ " 	AND sch.legalEntityCode=:legalEntityCode AND sch.auditTypeCode=:auditTypeCode " 
					+ " ");
			
			logger.info(" Before the qry....");
			
			Query query=session.createQuery(queryString.toString())
					.setResultTransformer(new ResultTransformer() {
						
						@Override
						public Object transformTuple(Object[] tuple, String[] aliases) {
							RiskSummaryDtls riskSummaryDtls=new RiskSummaryDtls();
							//if(tuple[1]!=null) riskSummaryDtls.setAuditGroupCodeName(tuple[1].toString());
							//if(tuple[2]!=null) riskSummaryDtls.setAuditSubGroupCodeName(tuple[2].toString());
							//if(tuple[3]!=null) riskSummaryDtls.setActivityName(tuple[3].toString());
							if(tuple[1]!=null) riskSummaryDtls.setTotalNonCompRecord(tuple[1].toString());
							if(tuple[2]!=null) riskSummaryDtls.setTotalCarryFwd(tuple[2].toString());
							if(tuple[3]!=null) riskSummaryDtls.setTotalAccepted(tuple[3].toString());
							if(tuple[4]!=null) riskSummaryDtls.setTotalFurtherComp(tuple[4].toString());
							if(tuple[5]!=null) riskSummaryDtls.setBankResponsibility(tuple[5].toString());
							if(tuple[6]!=null) riskSummaryDtls.setReviewerResponsibility(tuple[6].toString());
							
							return riskSummaryDtls;
						}
						
						@Override
						public List transformList(List collection) {
							return collection;
						}
					})
					.setParameter("legalEntityCode", legalEntityCode)
					.setParameter("auditId", auditId).setParameter("auditTypeCode", auditTypeCode);
			
			myRiskSummarylst = query.list();
			logger.info("after executing obj.... "+ myRiskSummarylst.size());
			logger.info("myRiskSummarylst .."+myRiskSummarylst);
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return myRiskSummarylst; 
	}
	
	
	@Override
	public List<AuditSchedule> getAuditsForNotification(int legalEntityCode,String auditTypeCode, String userId, String notificatioNtype) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		List<AuditSchedule> auditSchlst = new ArrayList();
		int durationFrom=0, durationTo=0;
		try {
			if("1".equalsIgnoreCase(notificatioNtype)) {
				durationFrom=30; durationTo=60;
			}else {
				durationFrom=1; durationTo=7;			
			}
			logger.info("Inside getAuditsForNotification ..  .. .."+ legalEntityCode+" :: "+ auditTypeCode +" :: "+ notificatioNtype);
			StringBuilder queryString=new StringBuilder("   "
					+ " select sch as auditSchedule , "
					+ " 	DATE_SUB(get_financial_year_endDate_forDate(4,scheduleStartDate),INTERVAL 1 YEAR) AS finYr " 
					+ " from AuditSchedule as sch "
					+ " where sch.legalEntityCode=:legalEntityCode AND  "
					+ " 	sch.scheduleStartDate BETWEEN DATE_ADD(CURDATE(), INTERVAL :durationFrom DAY) AND DATE_ADD(CURDATE(), INTERVAL :durationTo DAY) " 
					+ " ");
			
			logger.info(" Before the qry....");
			
			Query query=session.createQuery(queryString.toString())
					.setResultTransformer(new ResultTransformer() {
						
						@Override
						public Object transformTuple(Object[] tuple, String[] aliases) {
							AuditSchedule aSch=new AuditSchedule();
							if(tuple[0]!=null) aSch= (AuditSchedule)tuple[0];
							if(tuple[1]!=null) aSch.setFinancialYear((Date)tuple[1]);
							return aSch;
						}						
						@Override
						public List transformList(List collection) {
							return collection;
						}
					}).setParameter("legalEntityCode", legalEntityCode)
					.setParameter("durationFrom", durationFrom).setParameter("durationTo", durationTo);
			
			auditSchlst = query.list();
			logger.info("after executing obj.... "+ auditSchlst.size());
			logger.info("auditSchlst .."+auditSchlst);
			}catch(Exception e) {
				e.printStackTrace(System.out);
			}return auditSchlst; 
	}
	
	/********* End Here ***********/
	
	@Override
	public void updateReportStatus(AuditSchedule auditSchedule) {
		Session session = getSession();
		try {
			String reportStatus =auditSchedule.getReportStatus();
			String allocator =auditSchedule.getAllocator();
			String reportReviewer = auditSchedule.getReportReviewer();
			Date reportReviewerStartDate = auditSchedule.getReportReviewerStartDate();
			Date reportReviewEndDate = auditSchedule.getReportReviewEndDate();
			Date reportReviewerTargetDate = auditSchedule.getReportReviewerTargetDate();
			Date reportDispatchDate = auditSchedule.getReportDispatchDate();
			String auditerId =auditSchedule.getAuditerId(); 
			logger.info("updateReportStatus reportStatus:: "+ reportStatus + " allocator ::"+allocator+ " reportReviewer:: "+reportReviewer +" auditerId:: "+auditerId);
			
			AuditSchedule audSch1= (AuditSchedule)session.get(AuditSchedule.class,auditSchedule);
			logger.info("audSch1 from Table auditStatus  :: "+ audSch1.getAuditStatus() +" reportStatus :: "+ audSch1.getReportStatus());
			
			if("RAR".equalsIgnoreCase(reportStatus)){ // Reviewer Allocated
				audSch1.setAllocator(allocator);
				audSch1.setReportReviewer(reportReviewer);
			}else if("RI".equalsIgnoreCase(reportStatus)) {//if("RUR".equalsIgnoreCase(reportStatus)) {  // Report Under Review, Review Initiated
				audSch1.setReportStatus(reportStatus);
				audSch1.setReportReviewerStartDate(reportReviewerStartDate);
			}else if("RF".equalsIgnoreCase(reportStatus) ) { // Review finalized
				audSch1.setReportReviewEndDate(reportReviewEndDate);
			}else if("RD".equalsIgnoreCase(reportStatus) ) { // report dispatched
				audSch1.setReportDispatchDate(reportDispatchDate);
			}			
			audSch1.setReportStatus(reportStatus);
			session.update(audSch1);
			
			/******* Logic to move the Remarks entered by Inspector or Reviewer from audit_observation_report_review_capture_wrk to mst */
			if("RRR".equalsIgnoreCase(reportStatus) || "FS".equalsIgnoreCase(reportStatus) 
					|| "RC".equalsIgnoreCase(reportStatus) || "RR".equalsIgnoreCase(reportStatus) || "RA".equalsIgnoreCase(reportStatus) || "RS".equalsIgnoreCase(reportStatus)){
				// Call the logic to insert data into Mst table from wrk table  
				
			}
			/** Logic end here for, Remarks hostory capture **/
		
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
	}
	
	@Override
	public String updateReportStatus(AuditDto auditDto) {
		Session session = getSession();
		try {
			String reportStatus =auditDto.getReportStatus();
			String allocator =auditDto.getAllocator();
			String reportReviewer = auditDto.getReportReviewer();
			//Date reportSubmissionDate = auditDto.get();
			Date reportReviewerStartDate = auditDto.getReportReviewerStartDate();
			Date reportReviewEndDate = auditDto.getReportReviewEndDate();
			Date reportReviewerTargetDate = auditDto.getReportReviewerTargetDate();
			Date reportDispatchDate = auditDto.getReportDispatchDate();
			String auditId =  auditDto.getAuditId();
			Integer legalEntityCode = auditDto.getLegalEntityCode();
			//String auditerId =auditDto.getAuditerId(); 
			logger.info("updateReportStatus reportStatus:: "+ reportStatus + " allocator ::"+allocator+ " reportReviewer:: "+reportReviewer);
						
			//AuditSchedule audSch1= (AuditSchedule)session.get(AuditSchedule.class,auditSchedule);
			
			Map<String, Object> properties = new HashMap<String, Object>();
			properties.put("legalEntityCode", auditDto.getLegalEntityCode());
			properties.put("auditTypeCode", auditDto.getAuditTypeCode());
			properties.put("planId", auditDto.getPlanId());
			properties.put("auditId", auditDto.getAuditId());			
			AuditSchedule audSch1 = (AuditSchedule)auditScheduleDao.getUniqueEntityByMatchingProperties(AuditSchedule.class, properties);
			logger.info("audSch1 from Table auditStatus  :: "+ audSch1.getAuditStatus() +" reportStatus :: "+ audSch1.getReportStatus());
			
			String assigneeRole = null;
			if("RAR".equalsIgnoreCase(reportStatus)){ // Reviewer Allocated
				audSch1.setAllocator(allocator);
				audSch1.setReportReviewer(reportReviewer); 	
				assigneeRole = "G12";
			}else if("RI".equalsIgnoreCase(reportStatus)) { //if("RUR".equalsIgnoreCase(reportStatus)) { // Report Under Review, Review Initiated
				audSch1.setReportStatus(reportStatus);
				audSch1.setReportReviewerStartDate(businessDateService.getBusinessDateTimestampByLegalEntityCode(audSch1.getLegalEntityCode()));
			}else if("RS".equalsIgnoreCase(reportStatus) ) { // Review finalized
				audSch1.setReportReviewEndDate(reportReviewEndDate);
				audSch1.setIrFinalisationDate(reportReviewEndDate);	
				assigneeRole = "G8"; // for AuditLog
			}else if("RD".equalsIgnoreCase(reportStatus) ) { // Report dispatched
				audSch1.setReportDispatchDate(reportDispatchDate);				 
			}else if("RRR".equalsIgnoreCase(reportStatus) ) { // IR submission date
				audSch1.setIrSubmissionDate(businessDateService.getBusinessDateTimestampByLegalEntityCode(audSch1.getLegalEntityCode()));				 			
			}else if("RA".equalsIgnoreCase(reportStatus) ) { // Review accepted by Reviewer, back to Allocator
				assigneeRole = "G11";				 			
			}else if("RC".equalsIgnoreCase(reportStatus) || "RR".equalsIgnoreCase(reportStatus)) { // Review completed Or Rejected by Reviewer, back to PIO
				assigneeRole = "G8"; // for AuditLog
			}else if("FS".equalsIgnoreCase(reportStatus)) { // Revised by PIO, back to same Reviewer
				assigneeRole = "G12"; // for AuditLog
			}  
			
			audSch1.setReportStatus(reportStatus);
			
			audSch1.setAssigneeId(auditDto.getAssigneeId());
			audSch1.setActionMakerId(auditDto.getActionMakerId());
			audSch1.setActionMakerRole(auditDto.getActionMakerRole());
			
			logger.info("UpdateReportStatus for Audit Log :: "+ auditDto.getAssigneeId()+" :: "+ assigneeRole);
			AuditScheduleStagesStatusHst auditScheduleStagesStatusHst = new AuditScheduleStagesStatusHst();
			auditScheduleStagesStatusHst.setStagesStatus(reportStatus);
			auditScheduleStagesStatusHst.setCode(reportStatus);
			auditScheduleStagesStatusHst.setActionType(BankAuditConstant.ACTION_TYPE_INSPECTION);
			auditScheduleStagesStatusHst.setAssigneeRole(assigneeRole);
			auditScheduleStagesStatusHst.setAssigneeId(auditDto.getAssigneeId());
			auditScheduleStagesStatusHstService.saveAuditStagesStatus(audSch1, auditScheduleStagesStatusHst);	
			
			/******************** For Branch Inspection during Report dispatch, need to Close the Inspection *******************/
			if("RD".equalsIgnoreCase(reportStatus) && BankAuditConstant.INSPECTION_TYPE_BRANCHI.equalsIgnoreCase(audSch1.getAuditTypeCode())){
				audSch1.setAuditStatus("AC"); // Inspection marked as Closed.
				auditScheduleStagesStatusHst.setStagesStatus("AC");
				auditScheduleStagesStatusHst.setCode("AC");
				auditScheduleStagesStatusHstService.saveAuditStagesStatus(audSch1, auditScheduleStagesStatusHst);	
			} 
			session.update(audSch1);
			
			if("RRR".equalsIgnoreCase(reportStatus) || "FS".equalsIgnoreCase(reportStatus) 
					|| "RC".equalsIgnoreCase(reportStatus) || "RR".equalsIgnoreCase(reportStatus) || "RA".equalsIgnoreCase(reportStatus) || "RS".equalsIgnoreCase(reportStatus)){
						 	
				List<AuditObservationReportReviewCaptureWrk> listAuditObservationReportReviewCaptureWrk = auditObservationDao.getAuditObservationReportReviewCaptureWrk(legalEntityCode, auditId);
				if(listAuditObservationReportReviewCaptureWrk.size()>0 && !listAuditObservationReportReviewCaptureWrk.isEmpty()){
					for(AuditObservationReportReviewCaptureWrk auditCaptureWrk : listAuditObservationReportReviewCaptureWrk){
						AuditObservationReportReviewCapture auditObservationReportReviewCaptureMaster = new AuditObservationReportReviewCapture();
						BeanUtils.copyProperties(auditObservationReportReviewCaptureMaster, auditCaptureWrk);
						auditObservationDao.save(auditObservationReportReviewCaptureMaster);
					}			
					auditObservationDao.deleteAllAuditObservationReportReviewCaptureWrk(legalEntityCode, auditId);
				} 	
			
				///Mark the cycle is completed based on report status-> inspection and report-review
				auditObservationDao.markedNotesAsCycleCompleted(legalEntityCode, auditDto.getAuditTypeCode(), auditDto.getPlanId(), auditId);			
								
			}
			session.flush();
			return BankAuditConstant.SUCCESS; 
		}catch(Exception e) {
			e.printStackTrace(System.out);
			return BankAuditConstant.FAILED; 
		}		
	}
	
	@Override
	public AuditSchedule getAuditDetailsByPlanIdAndAuditId(int legalEntityCode, String auditTypeCode, String planId,
			String auditId) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		
		AuditSchedule auditSchedule = null;
		try {
			logger.info("Inside getAuditDetailsByPlanIdAndAuditId .... "+ legalEntityCode +" :: "+ auditTypeCode +" :: "+ planId +" :: "+ auditId);
			StringBuilder queryString=new StringBuilder("select sch as auditSchedule, " 
					+ " legalEntityCode,"
					+ "(select concat(auditTypeCode , '-' , auditTypeDesc) from MaintAuditTypeDesc at where at.auditTypeCode=sch.auditTypeCode and at.legalEntityCode= sch.legalEntityCode ) as auditTypeCode,"
					
					+ "planId,auditId, "
					+ " (Select concat(unitCode , '-' , unitName) from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitId,  "
					
					+ " (Select g.description from  MaintEntity e,GeneralParameter g where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=e.unitType) as unitType, "
					
					+ " (Select c.criticalityDesc from  MaintEntity e,MaintCriticality c where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =c.legalEntityCode and e.uCriticality=c.criticalityCode and c.criticalityOfType='Entity') as uCriticality, "
					
					+ " (Select concat(u.firstName , ' ' , u.lastName) from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
					
					+ "  duration," //+ " (Select p.duration from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as duration, "
					+ "  frequency, "//+ " (Select p.frequency from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as frequency, "
					//+ " (select tm.auditTypeCode,GROUP_CONCAT(tm.name) from (Select t.auditTypeCode,t.planId, t.auditId, concat(u.firstName , ' ' , u.lastName) as name from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='T') tm where  GROUP BY tm.auditTypeCode  ) as teamMember "
					+ " (Select prevAuditId from  AuditSchedule sch1 where sch1.legalEntityCode =sch.legalEntityCode and sch1.auditId=sch.prevAuditId ) as prevPrevAuditId, " // Included to get the Previous to previous Audit Id
					+ " (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus) as auditStatus "
					+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='N' and o.reviewStatus='R') as responseReject "
					+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='C' and o.submissionStatus='A') as complianceCount "
					+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='NA' and o.submissionStatus='A') as notApplicableCount "
					+ ", (Select concat(sch.reportStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='REPORT_STATUS' and g.value=sch.reportStatus) as reportStatus "
					+ ", (Select concat(sch.reportReviewer, '-',u.firstName , ' ' , u.lastName) from  User u where u.userId =sch.reportReviewer and u.legalEntityCode =sch.legalEntityCode ) as reportReviewer "
					+ ", (Select concat(sch.allocator, '-',u.firstName , ' ' , u.lastName) from  User u where u.userId =sch.allocator and u.legalEntityCode =sch.legalEntityCode ) as allocator "
					+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode  and auditId=:auditId "); /* and planId=:planId */
			System.out.println("Before the qry....");
			
			Query query=(Query) session.createQuery(queryString.toString())				
					.setResultTransformer(new ResultTransformer() {
						@Override
						public Object transformTuple(Object[] tuple, String[] aliases) {
							AuditSchedule auditSchedule=null;
							System.out.println("tuple[0] ...."+tuple[0]);
							if(tuple[0]!=null){
								auditSchedule=(AuditSchedule)tuple[0];
								/* session.evict(maintEntity);*/
								
								if(tuple[1]!=null){
									auditSchedule.setLegalEntityCode(Integer.parseInt(tuple[1].toString()));								
								}
								if(tuple[2]!=null){
									auditSchedule.setAuditTypeCode(tuple[2].toString());
								}
								
								if(tuple[3]!=null){
									auditSchedule.setPlanId(tuple[3].toString());
								}
								
								if(tuple[4]!=null){
									auditSchedule.setAuditId(tuple[4].toString());
								}
								if(tuple[5]!=null){
									auditSchedule.setUnitId(tuple[5].toString());
								}
								if(tuple[6]!=null){
									auditSchedule.setUnitType(tuple[6].toString());
								}
								if(tuple[7]!=null){
									auditSchedule.setuCriticality(tuple[7].toString());
								}
								if(tuple[8]!=null){
									auditSchedule.setTeamLead(tuple[8].toString());
								}
								if(tuple[9]!=null){
									auditSchedule.setDuration(tuple[9].toString());
								}
								if(tuple[10]!=null){
									auditSchedule.setFrequency(tuple[10].toString());
								}
								if(tuple[11]!=null)	auditSchedule.setPrevPrevAuditId(tuple[11].toString()); // Included to get the Previous to previous Audit Id
								
								if(tuple[12]!=null)	auditSchedule.setAuditStatus(tuple[12].toString()); 
								
								if(tuple[13]!=null && auditSchedule.getRespondedFindings() != null){
									auditSchedule.setResponseReject(Integer.parseInt(tuple[13].toString()));
									auditSchedule.setRespondedFindings(auditSchedule.getRespondedFindings()- (Integer.parseInt(tuple[13].toString()))); // Included to find out the Responded Observations
								}else auditSchedule.setResponseReject(0);
								
								if(tuple[14]!=null){
									auditSchedule.setComplianceCount(Integer.parseInt(tuple[14].toString()));
								}else auditSchedule.setComplianceCount(0);
								
								if(tuple[15]!=null){
									auditSchedule.setNotApplicableCount(Integer.parseInt(tuple[15].toString()));
								}else auditSchedule.setNotApplicableCount(0);
								
								if(tuple[16]!=null)	auditSchedule.setReportStatus(tuple[16].toString());
								if(tuple[17]!=null)	auditSchedule.setReportReviewer(tuple[17].toString());
								if(tuple[18]!=null)	auditSchedule.setAllocator(tuple[18].toString());
								
							}
							return auditSchedule;
						}
				@Override
				public List transformList(List collection) {
					return collection;
				}
			})      .setParameter("legalEntityCode",legalEntityCode)
					//.setParameter("planId",planId)
					.setParameter("auditId",auditId);
			
			 auditSchedule=(AuditSchedule)query.uniqueResult(); 

		}catch(Exception e) {
			e.printStackTrace();
		}return auditSchedule; 
	}
	
	/** Method to get the Inspections as View, for Operations and Management users **/
	@SuppressWarnings("unchecked")
	@Override
	public DataTableResponse getAuditsForView(int legalEntityCode,String userId, String unitCode, String roleId, String search,Integer orderColumn, String orderDirection, Integer page, Integer size,
			LocalDate financialYear, String auditTypeCode, List<LocalDate>  financialYearStrtEndList) { // Added to filter the records based on Financial Year and AuditType

		Session session = getSession();
		session.setDefaultReadOnly(true);
		
		logger.info("Inside getAuditsForView :: "+ legalEntityCode+" :: "+ userId +" :: "+ unitCode+" :: "+roleId+" :: "+search);
		/********************** This block is to retrieve the User details --> UserId and UserName **************************/
		StringBuilder queryString0=new StringBuilder(" from User u where  u.legalEntityCode =:legalEntityCode ");
		
		Query query1=session.createQuery("from User u where  u.legalEntityCode =:legalEntityCode ").setParameter("legalEntityCode", legalEntityCode);
		
		List lst = query1.list();
		HashMap<String, String> userDtls = new HashMap<String, String>();
		for ( Iterator iter = lst.iterator(); iter.hasNext(); ) {
			User usr = (User) iter.next();
			if(usr.getUserId().equalsIgnoreCase(userId))
				userDtls.put(usr.getUserId(), "Me"); // for the same User we are stamping as "You"
			else userDtls.put(usr.getUserId(), (usr.getFirstName()==null?"":usr.getFirstName()) 
											+ (usr.getMiddleName()==null?"":(" "+usr.getMiddleName())) 
											+ (usr.getLastName()==null?"":(" "+usr.getLastName())) );	
		}
		logger.info("User details val is .... "+ userDtls);
		/******************** User Retrieval logic, Ends here ********************************/
		
		Date businessDate =businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		logger.info("businessDate .... "+ businessDate);
		List<String> maintEntities = null;
		maintEntities=maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode,"user",userId);
			logger.info("maintEntities .... "+maintEntities);
		
		boolean isDeptAsRMD =false;
		//isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, "", userId);
		
		// Logic added to filter the Records based on Financial Year and Audit Type
		logger.info("financial Year :: "+ financialYear +" auditTypeCode :: "+auditTypeCode +" financial Year StartEnd:: "+ financialYearStrtEndList);
		
		
		DataTableResponse dataTableResponse=new DataTableResponse();
		try {
			StringBuilder queryString=new StringBuilder("select sch as auditSchedule, " 
				+ " legalEntityCode,"
				+ "(select concat(auditTypeCode , '-' , auditTypeDesc) from MaintAuditTypeDesc at where at.auditTypeCode=sch.auditTypeCode and at.legalEntityCode= sch.legalEntityCode ) as auditTypeCode,"
				
				+ "planId,auditId, "
				//+ " (Select concat(unitCode , '-' , unitName) from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitId,  "
				+ " (Select unitName from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitName,  "
				+ " (Select g.description from  MaintEntity e,GeneralParameter g where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=e.unitType) as unitType, "
				+ " (Select c.criticalityDesc from  MaintEntity e,MaintCriticality c where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =c.legalEntityCode and e.uCriticality=c.criticalityCode and c.criticalityOfType='Entity') as uCriticality, "
				+ " (Select t.userId from  AuditTeam t where t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
				+" duration," //Code to comment //+ " (Select p.duration from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as duration, "
				+" frequency," //Code to comment //+ " (Select p.frequency from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as frequency, "
				+ " (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus) as auditStatus, "
				+ " (Select concat(u.userId , '-' , ifnull(u.firstName,''), ' ',ifnull(u.middleName,''),' ',ifnull(u.lastName,'') ) "
				+ " from  User u where u.legalEntityCode =sch.legalEntityCode and u.userId=sch.maker) as maker "
				+" ,0,0,0 "  // No need to calculate responseReject, Compliance, NA
				//+ " , auditStatus "
				+ ", (Select g.value from GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='AUDIT_EARLY_START' and g.key2='EARLY_START_ALLOWED') as earlyStartAllowed "
				+ ", (Select g.value from GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='AUDIT_OFFSET_DAYS' and g.key2='AUDIT_OFFSET_DAYS') as auditOffsetDays " 
				+ ", (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.observationStatus) as auditStatusTemp " // This result to stamp in Audit status in the Observation status is AE i.e Audit Reported
				+ ", (select group_concat(t.userId) from AuditTeam t where t.legalEntityCode=sch.legalEntityCode AND t.auditId=sch.auditId AND t.userType='M' ) AS teamMember "
				+" ,   sch.reportStatus " // Report review status added for BaaSDOS implementation 
				+ ",  (Select concat(sch.reportStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='REPORT_STATUS' and g.value=sch.reportStatus) as reportStatusDesc " // Report review status desc added for BaaSDOS implementation 
				+ " , (Select concat(sch.status , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode "
				+ " and g.key1='STATUS' and g.key2='STATUS' and g.value=sch.status) as authStatus "  
				 + " from AuditSchedule sch where legalEntityCode =:legalEntityCode "
				+ " and  IFNULL(auditStatus,'NotNull') not in ('AD','AU','DRP','UP','AN')   "
				);
				
				//if(!isDeptAsRMD) {
				//	queryString.append(" and  sch.auditTypeCode IN (SELECT asgm.auditTypeCode FROM MaintEntityAuditSubgroupMapping as asgm WHERE asgm.legalEntityCode=sch.legalEntityCode and asgm.mappingType='U' and asgm.id =:userId )"); // To show the Assessments to which the Assessor Mapped (Department mapping)
				//}
				//if(visibleAuditList !=null && visibleAuditList.s)
				//+ " and (sch.auditId  IN :visibleAuditList  OR auditStatus in ('AI','AS','AR','AC','AU','UP','AD','AW')) " //commented to remove Visibility cond, Condition included to get the Audits as per the Visibility logic maintained in general parameter.
					
			    if(("G2").equalsIgnoreCase(roleId) || ("G8").equalsIgnoreCase(roleId)) {
			    	queryString.append(" and sch.auditId IN (SELECT t.auditId FROM AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userId=:userId  )");
			    }else if (("G1").equalsIgnoreCase(roleId) || ("G6").equalsIgnoreCase(roleId)) {
			    	queryString.append(" and sch.unitId IN (:maintEntities)  ");
			    }else {
			    	queryString.append(" and sch.unitId IN (:maintEntities)  ");
			    }
			    
		// Financial Year and Audit Type filter added for filtering
				if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
					queryString.append(" and  sch.auditTypeCode =:auditTypeCode "); 
				}if(financialYear !=null) {
					LocalDate fYStartDt = financialYearStrtEndList.get(0);
					LocalDate fYearEndDt = financialYearStrtEndList.get(1);
					logger.info("fYStartDt :: "+fYStartDt+" fYEndDt :: "+fYearEndDt);
					queryString.append(" And (sch.scheduleStartDate between '"+fYStartDt+"' and '"+fYearEndDt+"' )");
					//queryString.append(" And (sch.scheduleStartDate between :fYStartDt and :fYearEndDt )");
				}		
			    
		logger.info("Before the qry....");
		
		if(!BankAuditUtil.isEmptyString(search)){
			queryString=queryString.append(" and ( "
					+ " sch.auditTypeCode IN (SELECT a.auditTypeCode FROM MaintAuditTypeDesc a  WHERE a.legalEntityCode=sch.legalEntityCode AND (a.auditTypeDesc LIKE :search OR a.auditTypeCode LIKE :search)) "
					+ " or planId like :search "
					+ " or auditId like :search "
					//+ " or unitId like :search "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m WHERE m.legalEntityCode=sch.legalEntityCode AND (m.unitName LIKE :search or m.unitCode LIKE :search )) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,GeneralParameter g WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=m.unitType and g.description LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintCriticality c WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =c.legalEntityCode and m.uCriticality=c.criticalityCode and c.criticalityOfType='Entity' and  c.criticalityDesc LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintAuditParameter p WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =p.legalEntityCode and m.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and  p.duration LIKE :search) "
					+ " or sch.auditId IN (SELECT t.auditId FROM User u,AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.legalEntityCode =u.legalEntityCode and t.userId=u.userId and (t.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or DATE_FORMAT(sch.scheduleStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.scheduleEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.lastAuditDate, '%d %b %Y') LIKE :search "
					+ " or sch.maker IN (SELECT u.userId FROM User u WHERE u.legalEntityCode =sch.legalEntityCode and (u.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus and g.description LIKE :search) "
					+ " or sch.reportStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' and g.key2='REPORT_STATUS' and g.value=sch.reportStatus and g.description LIKE :search) "
					// + " or teamMember like :search "
					+ " or sch.auditId IN (select t.auditId from AuditTeam t, User u where t.legalEntityCode=sch.legalEntityCode AND t.auditId=sch.auditId AND t.userType='M' AND t.legalEntityCode=u.legalEntityCode AND t.userId=u.userId "
					+ "						AND sch.unitId=u.unitCode AND (u.firstName like :search OR u.middleName like :search OR u.lastName like :search OR u.userId like :search )) "
					
					//+ " ) "
					
						+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' "
						+ " and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus "
						+ " and (g.description LIKE :search or g.value LIKE :search)"
						+ " and   ( sch.observationStatus !='AE'  ) "
						+ " ) "
						
						+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' "
						+ " and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus "
						+ " and (g.description LIKE :search or g.value LIKE :search)"
						+ " and   ( sch.observationStatus  ='AE' and sch.auditStatus='AW'  ) "
						+ " ) " 
						
						+ "  " );
						
						if((search.length()==2 && search.toUpperCase().startsWith("EX") )
						|| (search.length()==3 && search.toUpperCase().startsWith("EXI"))
						|| (search.length()==4 && search.toUpperCase().startsWith("EXIT"))
						|| ((search.length()==5 || search.length()==6) && search.toUpperCase().startsWith("EXITE")) ){
							queryString.append("Or (sch.auditStatus='AI' and sch.observationStatus='AE' ) )");
						}	
						else{
							queryString.append(" )" );
							if(search.toUpperCase().startsWith("INI")){
								queryString.append("and  ( sch.auditStatus='AI' and (sch.observationStatus is null or sch.observationStatus='' ) )");
							}
						}
					/*queryString.append(" )" );*/
		}
		
		/*queryString=queryString.append("  ORDER BY FIELD(auditStatus, 'AI','P','AP','AS','AC','AU') asc ");*/
		String[] columns={
				"auditTypeCode",
				"(auditId *1 ), (planId *1 )", //"CAST(planId AS Integer),CAST(auditId AS Integer) "
				"unitType",
				"(unitId * 1) ",  //"unitId",
				"uCriticality",
				"duration",
				"lastAuditDate",//last audit date actually 
				"sch.scheduleStartDate",
				"sch.scheduleEndDate",
				"sch.actualStartDate",
				"sch.actualEndDate",
				"teamLead", // Team Lead
				// "sch.maker", // Team Member
				"sch.maker",
				"sch.reportStatus",
				"sch.auditStatus",
				"unitName",  
				"financialYear"
		};

		/*if(orderColumn!=null
				&& !BankAuditUtil.isEmptyString(orderDirection)){
			queryString=queryString.append(" order by ").append(columns[orderColumn]).append(" ").append(orderDirection);
		}*/
		logger.info(" orderColumn **.... "+ orderColumn +"  orderDirection ...."+ orderDirection );
		if(orderColumn != null && orderColumn == -1 && !BankAuditUtil.isEmptyString(orderDirection)){ // -1 send for the first time from the UI during landing page.
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AI','AS','AR','AC') asc  "); // The code modified to get the records in the order of Status on landing page, the sequence is  Initiated, Planned, Submitted, Respond, Reviewed, Closed
		}else if(orderColumn!=null && !BankAuditUtil.isEmptyString(orderDirection)){
			if(orderColumn==0) {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection).append(" , FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc ,(auditId *1 ) asc  ");
			}else {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection);
			}
		}else {
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AI','AS','AR','AC') asc  ");
		}
		
		logger.info("queryString .... "+ queryString.toString());
		
		Query query=(Query) session.createQuery(queryString.toString())				
				.setResultTransformer(new ResultTransformer() {
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						AuditSchedule auditSchedule=null;
						//System.out.println("tuple[0] ...."+tuple[0]);
						if(tuple[0]!=null){
							auditSchedule=(AuditSchedule)tuple[0];
							/* session.evict(maintEntity);*/
							
							if(tuple[1]!=null){
								auditSchedule.setLegalEntityCode(Integer.parseInt(tuple[1].toString()));								
							}
							if(tuple[2]!=null){
								auditSchedule.setAuditTypeCode(tuple[2].toString());
							}
							
							if(tuple[3]!=null){
								auditSchedule.setPlanId(tuple[3].toString());
							}
							
							if(tuple[4]!=null){
								auditSchedule.setAuditId(tuple[4].toString());
							}
							if(tuple[5]!=null){
								//auditSchedule.setUnitId(tuple[5].toString());
								//String unitCodeName=tuple[5].toString();
								//auditSchedule.setUnitId(unitCodeName);
								//auditSchedule.setUnitName(unitCodeName.substring(unitCodeName.indexOf('-')+1));
								auditSchedule.setUnitId(auditSchedule.getUnitId()+"-"+tuple[5].toString());
								auditSchedule.setUnitName(tuple[5].toString());
							}
							if(tuple[6]!=null){
								auditSchedule.setUnitType(tuple[6].toString());
							}
							if(tuple[7]!=null){
								auditSchedule.setuCriticality(tuple[7].toString());
							}
							if(tuple[8]!=null){ 
									String teamLead = userDtls.get(tuple[8].toString());
									auditSchedule.setTeamLead(teamLead.equalsIgnoreCase("Me")?"Me":tuple[8].toString()+"-"+teamLead);
								 
								//auditSchedule.setTeamLead(tuple[8].toString()+"-"+userDtls.get(tuple[8].toString()));
								//auditSchedule.setTeamLead(userDtls.get(tuple[8].toString()));
							}
							if(tuple[9]!=null){
								auditSchedule.setDuration(tuple[9].toString());
							}
							if(tuple[10]!=null){
								auditSchedule.setFrequency(tuple[10].toString());
							}
							if(tuple[11]!=null){
								if("P".equalsIgnoreCase(tuple[11].toString()))auditSchedule.setAuditStatus("AP"); // temp purpose as in few earlier records the Planned status is reflecting as "P"
								else if("AE".equalsIgnoreCase(auditSchedule.getObservationStatus())) auditSchedule.setAuditStatus(tuple[18] !=null ?tuple[18].toString() :tuple[11].toString() );
								else auditSchedule.setAuditStatus(tuple[11].toString());
							}
							if(tuple[12]!=null){
								auditSchedule.setMaker(tuple[12].toString());
							}
							if(tuple[13]!=null && auditSchedule.getRespondedFindings() != null){
								auditSchedule.setResponseReject(Integer.parseInt(tuple[13].toString()));
								auditSchedule.setRespondedFindings(auditSchedule.getRespondedFindings()- (Integer.parseInt(tuple[13].toString()))); // Included to find out the Responded Observations
							}else auditSchedule.setResponseReject(0);
							
							if(tuple[14]!=null){
								auditSchedule.setComplianceCount(Integer.parseInt(tuple[14].toString()));
							}else auditSchedule.setComplianceCount(0);
							
							if(tuple[15]!=null){
								auditSchedule.setNotApplicableCount(Integer.parseInt(tuple[15].toString()));
							}else auditSchedule.setNotApplicableCount(0);
							
							if(tuple[16]!=null){
								auditSchedule.setEarlyStartAllowed(tuple[16].toString());
							}else auditSchedule.setEarlyStartAllowed("Y");
							
							if(tuple[17]!=null){
								auditSchedule.setAuditOffsetDays(Integer.parseInt(tuple[17].toString()));
							}else auditSchedule.setAuditOffsetDays(0);
							
							if(tuple[19]!=null){
								String teamMembers="";
								String[] members = tuple[19].toString().split(",");
								for (String member: members) {
									teamMembers+=member+"-"+userDtls.get(member)+",";
								}
								auditSchedule.setTeamMember(teamMembers.substring(0,teamMembers.length()-1));
							}
							
							if(tuple[20]!=null) auditSchedule.setReportStatus(tuple[20].toString());
							if(tuple[21]!=null) auditSchedule.setReportStatusDesc(tuple[21].toString());
							
							if(tuple[22]!=null) auditSchedule.setStatus(tuple[22].toString());
							
							/*int tmSize =auditSchedule.getAuditTeams().size()-1;
							String teamMember="";
							System.out.println("Audit Id .... "+ auditSchedule.getAuditId()+" tmSize .."+tmSize);
							for( AuditTeam adtTm: auditSchedule.getAuditTeams() ) {
								
								adtTm.setUserId(adtTm.getUserId()+"-"+userDtls.get(adtTm.getUserId()));
								
								if(!"L".equalsIgnoreCase(adtTm.getUserType())) teamMember +=adtTm.getUserId() + ",";
								System.out.println("teamMember .... "+ teamMember);
							}if(tmSize >0 ) auditSchedule.setTeamMember(teamMember.substring(0,teamMember.lastIndexOf(",")));*/
							//System.out.println("Team member .... "+auditSchedule.getTeamMember());
							//System.out.println("Team size ...."+auditSchedule.getAuditTeams().size());
							
						}
						return auditSchedule;
					}
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).setParameter("legalEntityCode",legalEntityCode); //.setParameter("visibleAuditList", visibleAuditList);
		
		if(("G2").equalsIgnoreCase(roleId) || ("G8").equalsIgnoreCase(roleId)) {
	    	query.setParameter("userId",userId  );
	    }else if (("G1").equalsIgnoreCase(roleId) || ("G6").equalsIgnoreCase(roleId)) {
	    	query.setParameter("maintEntities", maintEntities);
	    }else {
	    	query.setParameter("maintEntities", maintEntities);
	    }
		
		if(!BankAuditUtil.isEmptyString(search)){
			query.setParameter("search", "%"+search+"%");
		}
		
		if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
			query.setParameter("auditTypeCode", auditTypeCode);
		}
		
		logger.info("page :: "+page +"size :: "+ size);
		List<AuditSchedule> tmpAuditSchedule =query.list(); 
		Long totalRecords=null;
		try {
			totalRecords = (long)tmpAuditSchedule.size();
		}catch(Exception e) {
			totalRecords = (long)0;
		}
		List<AuditSchedule> auditSchedule=query.setFirstResult((page*size)).setMaxResults(size).list();
		
		logger.info("Bfr size tmpAuditSchedule is .... "+tmpAuditSchedule.size()+" totalRecords:: "+ totalRecords);
		
		/*int i=0;
		for(AuditSchedule adSch:auditSchedule){
			System.out.println("Inside adSch ...");
			if("A2".equalsIgnoreCase(adSch.getAuditId()));
			else 	tmpAuditSchedule.add(adSch);
			System.out.println("after the call");
			
		}
		System.out.println("size tmpAuditSchedule .... "+tmpAuditSchedule);*/
		
		
		dataTableResponse.setData(auditSchedule);
		dataTableResponse.setRecordsTotal(totalRecords);
		dataTableResponse.setRecordsFiltered(totalRecords);
		
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return dataTableResponse;
	
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public DataTableResponse getAuditsForLetter(int legalEntityCode, String userId, String search,Integer orderColumn, String orderDirection, Integer page, Integer size, String role,
			LocalDate financialYear, String auditTypeCode, List<LocalDate>  financialYearStrtEndList) { // Added to filter the records based on Financial Year and AuditType

		Session session = getSession();
		session.setDefaultReadOnly(true);
		
		logger.info("Inside getAuditsForView :: "+ legalEntityCode+" :: "+ userId +" :: "+ search+" :: "+role);
		/********************** This block is to retrieve the User details --> UserId and UserName **************************/
		StringBuilder queryString0=new StringBuilder(" from User u where  u.legalEntityCode =:legalEntityCode ");
		
		Query query1=session.createQuery("from User u where  u.legalEntityCode =:legalEntityCode ").setParameter("legalEntityCode", legalEntityCode);
		
		List lst = query1.list();
		HashMap<String, String> userDtls = new HashMap<String, String>();
		for ( Iterator iter = lst.iterator(); iter.hasNext(); ) {
			User usr = (User) iter.next();
			if(usr.getUserId().equalsIgnoreCase(userId))
				userDtls.put(usr.getUserId(), "Me"); // for the same User we are stamping as "You"
			else userDtls.put(usr.getUserId(), (usr.getFirstName()==null?"":usr.getFirstName()) 
											+ (usr.getMiddleName()==null?"":(" "+usr.getMiddleName())) 
											+ (usr.getLastName()==null?"":(" "+usr.getLastName())) );	
		}
		logger.info("User details val is .... "+ userDtls);
		/******************** User Retrieval logic, Ends here ********************************/
		
		Date businessDate =businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		logger.info("businessDate .... "+ businessDate);
		List<String> maintEntities = null;
		maintEntities=maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode,"user",userId);
			logger.info("maintEntities .... "+maintEntities);
		
		boolean isDeptAsRMD =false;
		//isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, "", userId);
		
		// Logic added to filter the Records based on Financial Year and Audit Type
		logger.info("financial Year :: "+ financialYear +" auditTypeCode :: "+auditTypeCode +" financial Year StartEnd:: "+ financialYearStrtEndList);
		
		DataTableResponse dataTableResponse=new DataTableResponse();
		try {
			StringBuilder queryString=new StringBuilder("select sch as auditSchedule, " 
				+ " legalEntityCode,"   // 1
				+ "(select concat(auditTypeCode , '-' , auditTypeDesc) from MaintAuditTypeDesc at where at.auditTypeCode=sch.auditTypeCode and at.legalEntityCode= sch.legalEntityCode ) as auditTypeCode,"
				
				+ "planId,auditId, " // 4
				+ " (Select unitName from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitName,  "
				// + " (Select concat(unitCode , '-' , unitName) from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitId,  "
				+ " (Select g.description from  MaintEntity e,GeneralParameter g where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=e.unitType) as unitType, "
				+ " (Select c.criticalityDesc from  MaintEntity e,MaintCriticality c where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =c.legalEntityCode and e.uCriticality=c.criticalityCode and c.criticalityOfType='Entity') as uCriticality, "
				+ " (Select t.userId from  AuditTeam t where t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
				+" duration," //Code to comment //+ " (Select p.duration from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as duration, "
				+" frequency," //Code to comment //+ " (Select p.frequency from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as frequency, "
				+ " (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus) as auditStatus, "
				+ " (Select concat(u.userId , '-' , ifnull(u.firstName,''), ' ',ifnull(u.middleName,''),' ',ifnull(u.lastName,'') ) "
				+ " from  User u where u.legalEntityCode =sch.legalEntityCode and u.userId=sch.maker) as maker "
				+" ,0,0,0 "  // No need to calculate responseReject, Compliance, NA
				//+ " , auditStatus "
				+ ", (Select g.value from GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='AUDIT_EARLY_START' and g.key2='EARLY_START_ALLOWED') as earlyStartAllowed "
				+ ", (Select g.value from GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='AUDIT_OFFSET_DAYS' and g.key2='AUDIT_OFFSET_DAYS') as auditOffsetDays " 
				+ ", (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.observationStatus) as auditStatusTemp " // This result to stamp in Audit status in the Observation status is AE i.e Audit Reported
				+ ", (select group_concat(t.userId) from AuditTeam t where t.legalEntityCode=sch.legalEntityCode AND t.auditId=sch.auditId AND t.userType='M' ) AS teamMember "
				+" ,   sch.reportStatus " // Report review status added for BaaSDOS implementation 
				+ ", (Select concat(sch.reportStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='REPORT_STATUS' and g.value=sch.reportStatus) as reportStatusDesc " // Report review status desc added for BaaSDOS implementation 
				+ ", (Select concat(sch.status , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode "
				+ "       and g.key1='STATUS' and g.key2='STATUS' and g.value=sch.status) as authStatus, "     // 22
				
				+ " (Select concat(e1.unitName , '-' , e1.unitCode) from  MaintEntity e, MaintEntity e1  where e.unitCode =sch.unitId "
				+ "  and e.legalEntityCode =sch.legalEntityCode and e1.unitCode = e.parentUnitCode and  e1.legalEntityCode =sch.legalEntityCode) as parentUnitCode    "  // 23
				+ " , sch.unitId "
				
				+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode "
				+ "  	and IFNULL(auditStatus,'NotNull') IN ('AP','AI','AS','AR','AW','AC') " // To show the Inspection from "Ready for Review" state
				);
				
				if("G2".equals(role) || "G8".equals(role) ) {
					queryString.append(" and sch.auditId IN (SELECT t.auditId FROM AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userId=:userId )  "); 
				}else if("G12".equals(role)) {
					queryString.append(" and  sch.unitId IN (:maintEntities) ");
				}						
		
		// Financial Year and Audit Type filter added for filtering
				if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
					queryString.append(" and  sch.auditTypeCode =:auditTypeCode "); 
				}if(financialYear !=null) {
					LocalDate fYStartDt = financialYearStrtEndList.get(0);
					LocalDate fYearEndDt = financialYearStrtEndList.get(1);
					logger.info("fYStartDt :: "+fYStartDt+" fYEndDt :: "+fYearEndDt);
					queryString.append(" And (sch.scheduleStartDate between '"+fYStartDt+"' and '"+fYearEndDt+"' )");
					//queryString.append(" And (sch.scheduleStartDate between :fYStartDt and :fYearEndDt )");
				}
				
		logger.info("Before the qry....");
		
		if(!BankAuditUtil.isEmptyString(search)){
			queryString=queryString.append(" and ( "
					+ " sch.auditTypeCode IN (SELECT a.auditTypeCode FROM MaintAuditTypeDesc a  WHERE a.legalEntityCode=sch.legalEntityCode AND (a.auditTypeDesc LIKE :search OR a.auditTypeCode LIKE :search)) "
					+ " or planId like :search "
					+ " or auditId like :search "
					//+ " or unitId like :search "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m WHERE m.legalEntityCode=sch.legalEntityCode AND (m.unitName LIKE :search or m.unitCode LIKE :search )) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,GeneralParameter g WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=m.unitType and g.description LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintCriticality c WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =c.legalEntityCode and m.uCriticality=c.criticalityCode and c.criticalityOfType='Entity' and  c.criticalityDesc LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintAuditParameter p WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =p.legalEntityCode and m.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and  p.duration LIKE :search) "
					+ " or sch.auditId IN (SELECT t.auditId FROM User u,AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.legalEntityCode =u.legalEntityCode and t.userId=u.userId and (t.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or DATE_FORMAT(sch.scheduleStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.scheduleEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.lastAuditDate, '%d %b %Y') LIKE :search "
					+ " or sch.maker IN (SELECT u.userId FROM User u WHERE u.legalEntityCode =sch.legalEntityCode and (u.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus and g.description LIKE :search) "
					+ " or sch.reportStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' and g.key2='REPORT_STATUS' and g.value=sch.reportStatus and g.description LIKE :search) "
					// + " or teamMember like :search "
					+ " or sch.auditId IN (select t.auditId from AuditTeam t, User u where t.legalEntityCode=sch.legalEntityCode AND t.auditId=sch.auditId AND t.userType='M' AND t.legalEntityCode=u.legalEntityCode AND t.userId=u.userId "
					+ "						AND sch.unitId=u.unitCode AND (u.firstName like :search OR u.middleName like :search OR u.lastName like :search OR u.userId like :search )) "
					
					//+ " ) "
					
						+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' "
						+ " and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus "
						+ " and (g.description LIKE :search or g.value LIKE :search)"
						+ " and   ( sch.observationStatus !='AE'  ) "
						+ " ) "
						
						+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' "
						+ " and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus "
						+ " and (g.description LIKE :search or g.value LIKE :search)"
						+ " and   ( sch.observationStatus  ='AE' and sch.auditStatus='AW'  ) "
						+ " ) " 
						
						+ "  " );
						
						if((search.length()==2 && search.toUpperCase().startsWith("EX") )
						|| (search.length()==3 && search.toUpperCase().startsWith("EXI"))
						|| (search.length()==4 && search.toUpperCase().startsWith("EXIT"))
						|| ((search.length()==5 || search.length()==6) && search.toUpperCase().startsWith("EXITE")) ){
							queryString.append("Or (sch.auditStatus='AI' and sch.observationStatus='AE' ) )");
						}	
						else{
							queryString.append(" )" );
							if(search.toUpperCase().startsWith("INI")){
								queryString.append("and  ( sch.auditStatus='AI' and (sch.observationStatus is null or sch.observationStatus='' ) )");
							}
						}
					/*queryString.append(" )" );*/
		}
		
		/*queryString=queryString.append("  ORDER BY FIELD(auditStatus, 'AI','P','AP','AS','AC','AU') asc ");*/
		String[] columns={
				"auditTypeCode",
				"(auditId *1 ), (planId *1 )", //"CAST(planId AS Integer),CAST(auditId AS Integer) "
				"unitType",
				"(unitId * 1) ",  //"unitId",
				"uCriticality",
				"duration",
				"lastAuditDate",//last audit date actually 
				"sch.scheduleStartDate",
				"sch.scheduleEndDate",
				"sch.actualStartDate",
				"sch.actualEndDate",
				"teamLead", // Team Lead
				// "sch.maker", // Team Member
				"sch.maker",
				"sch.reportStatus",
				"sch.auditStatus",
				"unitName",  
				"financialYear"
		};

		/*if(orderColumn!=null
				&& !BankAuditUtil.isEmptyString(orderDirection)){
			queryString=queryString.append(" order by ").append(columns[orderColumn]).append(" ").append(orderDirection);
		}*/
		logger.info(" orderColumn **.... "+ orderColumn +"  orderDirection ...."+ orderDirection );
		if(orderColumn != null && orderColumn == -1 && !BankAuditUtil.isEmptyString(orderDirection)){ // -1 send for the first time from the UI during landing page.
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AI','AS','AR','AC') asc  "); // The code modified to get the records in the order of Status on landing page, the sequence is  Initiated, Planned, Submitted, Respond, Reviewed, Closed
		}else if(orderColumn!=null && !BankAuditUtil.isEmptyString(orderDirection)){
			if(orderColumn==0) {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection).append(" , FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc ,(auditId *1 ) asc  ");
			}else {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection);
			}
		}else {
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AI','AS','AR','AC') asc  ");
		}
		
		logger.info("queryString .... "+ queryString.toString());
		
		Query query=(Query) session.createQuery(queryString.toString())				
				.setResultTransformer(new ResultTransformer() {
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						AuditSchedule auditSchedule=null;
						//System.out.println("tuple[0] ...."+tuple[0]);
						if(tuple[0]!=null){
							auditSchedule=(AuditSchedule)tuple[0];
							/* session.evict(maintEntity);*/
							
							if(tuple[1]!=null){
								auditSchedule.setLegalEntityCode(Integer.parseInt(tuple[1].toString()));								
							}
							if(tuple[2]!=null){
								auditSchedule.setAuditTypeCode(tuple[2].toString());
							}
							
							if(tuple[3]!=null){
								auditSchedule.setPlanId(tuple[3].toString());
							}
							
							if(tuple[4]!=null){
								auditSchedule.setAuditId(tuple[4].toString());
							}
							if(tuple[24]!=null){
								auditSchedule.setUnitId(tuple[24].toString()+"-"+tuple[5].toString());
								auditSchedule.setUnitName(tuple[5].toString());
								// auditSchedule.setUnitId(tuple[5].toString());
								//auditSchedule.setUnitName(tuple[5].toString().split("-")[1]);
							}
							if(tuple[6]!=null){
								auditSchedule.setUnitType(tuple[6].toString());
							}
							if(tuple[7]!=null){
								auditSchedule.setuCriticality(tuple[7].toString());
							}
							if(tuple[8]!=null){ 
									String teamLead = userDtls.get(tuple[8].toString());
									auditSchedule.setTeamLead(teamLead.equalsIgnoreCase("Me")?"Me":tuple[8].toString()+"-"+teamLead);
								 
								//auditSchedule.setTeamLead(tuple[8].toString()+"-"+userDtls.get(tuple[8].toString()));
								//auditSchedule.setTeamLead(userDtls.get(tuple[8].toString()));
							}
							if(tuple[9]!=null){
								auditSchedule.setDuration(tuple[9].toString());
							}
							if(tuple[10]!=null){
								auditSchedule.setFrequency(tuple[10].toString());
							}
							if(tuple[11]!=null){
								if("P".equalsIgnoreCase(tuple[11].toString()))auditSchedule.setAuditStatus("AP"); // temp purpose as in few earlier records the Planned status is reflecting as "P"
								else if("AE".equalsIgnoreCase(auditSchedule.getObservationStatus())) auditSchedule.setAuditStatus(tuple[18] !=null ?tuple[18].toString() :tuple[11].toString() );
								else auditSchedule.setAuditStatus(tuple[11].toString());
							}
							if(tuple[12]!=null){
								auditSchedule.setMaker(tuple[12].toString());
							}
							if(tuple[13]!=null && auditSchedule.getRespondedFindings() != null){
								auditSchedule.setResponseReject(Integer.parseInt(tuple[13].toString()));
								auditSchedule.setRespondedFindings(auditSchedule.getRespondedFindings()- (Integer.parseInt(tuple[13].toString()))); // Included to find out the Responded Observations
							}else auditSchedule.setResponseReject(0);
							
							if(tuple[14]!=null){
								auditSchedule.setComplianceCount(Integer.parseInt(tuple[14].toString()));
							}else auditSchedule.setComplianceCount(0);
							
							if(tuple[15]!=null){
								auditSchedule.setNotApplicableCount(Integer.parseInt(tuple[15].toString()));
							}else auditSchedule.setNotApplicableCount(0);
							
							if(tuple[16]!=null){
								auditSchedule.setEarlyStartAllowed(tuple[16].toString());
							}else auditSchedule.setEarlyStartAllowed("Y");
							
							if(tuple[17]!=null){
								auditSchedule.setAuditOffsetDays(Integer.parseInt(tuple[17].toString()));
							}else auditSchedule.setAuditOffsetDays(0);
							
							if(tuple[19]!=null){
								String teamMembers="";
								String[] members = tuple[19].toString().split(",");
								for (String member: members) {
									teamMembers+=member+"-"+userDtls.get(member)+",";
								}
								auditSchedule.setTeamMember(teamMembers.substring(0,teamMembers.length()-1));
							}
							
							if(tuple[20]!=null) auditSchedule.setReportStatus(tuple[20].toString());
							if(tuple[21]!=null) auditSchedule.setReportStatusDesc(tuple[21].toString());
							
							if(tuple[22]!=null) auditSchedule.setStatus(tuple[22].toString());
							
							if(tuple[23]!=null) auditSchedule.setParentUnitCodeName(tuple[23].toString());
							
							
							/*int tmSize =auditSchedule.getAuditTeams().size()-1;
							String teamMember="";
							System.out.println("Audit Id .... "+ auditSchedule.getAuditId()+" tmSize .."+tmSize);
							for( AuditTeam adtTm: auditSchedule.getAuditTeams() ) {
								
								adtTm.setUserId(adtTm.getUserId()+"-"+userDtls.get(adtTm.getUserId()));
								
								if(!"L".equalsIgnoreCase(adtTm.getUserType())) teamMember +=adtTm.getUserId() + ",";
								System.out.println("teamMember .... "+ teamMember);
							}if(tmSize >0 ) auditSchedule.setTeamMember(teamMember.substring(0,teamMember.lastIndexOf(",")));*/
							//System.out.println("Team member .... "+auditSchedule.getTeamMember());
							//System.out.println("Team size ...."+auditSchedule.getAuditTeams().size());
							
						}
						return auditSchedule;
					}
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).setParameter("legalEntityCode",legalEntityCode); //.setParameter("visibleAuditList", visibleAuditList);
		
		if("G2".equals(role) || "G8".equals(role) ) {
			query.setParameter("userId",userId);
		}else if("G12".equals(role)) {
			query.setParameter("maintEntities", maintEntities);
		}	
		
		if(!BankAuditUtil.isEmptyString(search)){
			query.setParameter("search", "%"+search+"%");
		}
		
		if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
			query.setParameter("auditTypeCode", auditTypeCode);
		}
		
		logger.info("page :: "+page +"size :: "+ size);
		List<AuditSchedule> tmpAuditSchedule =query.list(); 
		Long totalRecords=null;
		try {
			totalRecords = (long)tmpAuditSchedule.size();
		}catch(Exception e) {
			totalRecords = (long)0;
		}
		List<AuditSchedule> auditSchedule=query.setFirstResult((page*size)).setMaxResults(size).list();
		
		logger.info("Bfr size tmpAuditSchedule is .... "+tmpAuditSchedule.size()+" totalRecords:: "+ totalRecords);
		
		/*int i=0;
		for(AuditSchedule adSch:auditSchedule){
			System.out.println("Inside adSch ...");
			if("A2".equalsIgnoreCase(adSch.getAuditId()));
			else 	tmpAuditSchedule.add(adSch);
			System.out.println("after the call");
			
		}
		System.out.println("size tmpAuditSchedule .... "+tmpAuditSchedule);*/
		
		
		dataTableResponse.setData(auditSchedule);
		dataTableResponse.setRecordsTotal(totalRecords);
		dataTableResponse.setRecordsFiltered(totalRecords);
		
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return dataTableResponse;
	
	}
	
	/* Service to get the Branch inspections for the Bank */
	/************* 
	* Service to get the list of Branch inspections by AIO/PIO and by BANK User 
	* AIO/PIO : auditId-> Mandatory, (Unit id is of the Audit Id)
	* BANK User: UnitId-> Mandatory (Unit id is of the Bank user)
	*************/
	@SuppressWarnings("unchecked")
	@Override
	public DataTableResponse getMyBranchAudits(int legalEntityCode, String auditId, String unitCode, String userId, String role, String search,Integer orderColumn, String orderDirection, Integer page, Integer size,
			LocalDate financialYear, String auditTypeCode, List<LocalDate>  financialYearStrtEndList) { // Added to filter the records based on Financial Year and AuditType

		Session session = getSession();
		session.setDefaultReadOnly(true);
		
		List<String> auditTypeCodeLst=Arrays.asList("BRANCHI", "ITISI");

		logger.info("Inside getMyBranchAudits .."+auditId +" :: "+ unitCode +" :: "+userId +" :: "+role);
		/********************** This block is to retrieve the User details --> UserId and UserName **************************/
		StringBuilder queryString0=new StringBuilder(// " Select concat(u.firstName , ' ' , u.lastName) as firstName, u.userId "
				 " from User u  "
				+ " where "
				+ " u.legalEntityCode =:legalEntityCode "
				);
		
		Query query1=session.createQuery(queryString0.toString())
				.setParameter("legalEntityCode", legalEntityCode);
		
		List lst = query1.list();
		HashMap<String, String> userDtls = new HashMap<String, String>();
		for ( Iterator iter = lst.iterator(); iter.hasNext(); ) {
			User usr = (User) iter.next();
			if(usr.getUserId().equalsIgnoreCase(userId))
				userDtls.put(usr.getUserId(), "Me"); // for the same User we are stamping as "You"
			else userDtls.put(usr.getUserId(), (usr.getFirstName()==null?"":usr.getFirstName()) 
											+ (usr.getMiddleName()==null?"":(" "+usr.getMiddleName())) 
											+ (usr.getLastName()==null?"":(" "+usr.getLastName())) );	
		}
		logger.info("userId is .... "+ userId+" serach:: "+search +" legal entity code:: "+legalEntityCode);
		logger.info("User details val is .... "+ userDtls);
		/******************** User Retrieval logic, Ends here ********************************/
		
		/**************** To get the list of Units under the Bank User ********************/
		List<String> unitList=new ArrayList<String>();
		if("G3".equalsIgnoreCase(role) || "G31".equalsIgnoreCase(role)) {
			unitList=maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode,"unit", unitCode);
			logger.info("List of units .. "+ unitList );
		}
		
		// Logic added to filter the Records based on Financial Year and Audit Type
		logger.info("financial Year :: "+ financialYear +" auditTypeCode :: "+auditTypeCode +" financial Year StartEnd:: "+ financialYearStrtEndList);
		
		DataTableResponse dataTableResponse=new DataTableResponse();
		try {
		//StringBuilder queryString=new StringBuilder(" from AuditSchedule where legalEntityCode =:legalEntityCode ");
		StringBuilder queryString=new StringBuilder("select sch as auditSchedule, " 
				+ " legalEntityCode,"
				+ "(select concat(auditTypeCode , '-' , auditTypeDesc) from MaintAuditTypeDesc at where at.auditTypeCode=sch.auditTypeCode and at.legalEntityCode= sch.legalEntityCode ) as auditTypeCode,"
				
				+ "planId,auditId, "
				//+ " (Select concat(unitCode , '-' , unitName) from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitId,  "
				+ " (Select unitName from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitName,  "
				
				+ " (Select g.description from  MaintEntity e,GeneralParameter g where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=e.unitType) as unitType, "
				
				+ " (Select c.criticalityDesc from  MaintEntity e,MaintCriticality c where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =c.legalEntityCode and e.uCriticality=c.criticalityCode and c.criticalityOfType='Entity') as uCriticality, "
				
				+ " (Select t.userId from  AuditTeam t where t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
				
				+" duration," //Code to comment //+ " (Select p.duration from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as duration, "
				+" frequency," //Code to comment //+ " (Select p.frequency from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as frequency, "
				+ " (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus) as auditStatus, "
				
				+ " (Select concat(u.userId , '-' , ifnull(u.firstName,''), ' ',ifnull(u.middleName,''),' ',ifnull(u.lastName,'') ) "
				+ " from  User u where u.legalEntityCode =sch.legalEntityCode and u.userId=sch.maker) as maker "
								
				+" ,0,0,0 "  // No need to calculate responseReject, Compliance, NA
				//+ " , auditStatus "
				+ ", (Select g.value from GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='AUDIT_EARLY_START' and g.key2='EARLY_START_ALLOWED') as earlyStartAllowed "
				+ ", (Select g.value from GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='AUDIT_OFFSET_DAYS' and g.key2='AUDIT_OFFSET_DAYS') as auditOffsetDays " 
				+ ", (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.observationStatus) as auditStatusTemp " // This result to stamp in Audit status in the Observation status is AE i.e Audit Reported
				+ ", (select group_concat(t.userId) from AuditTeam t where t.legalEntityCode=sch.legalEntityCode AND t.auditId=sch.auditId AND t.userType='M' ) AS teamMember "
				+" ,   sch.reportStatus " // Report review status added for BaaSDOS implementation 
				+ ",  (Select concat(sch.reportStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='REPORT_STATUS' and g.value=sch.reportStatus) as reportStatusDesc " // Report review status desc added for BaaSDOS implementation 
								
			 	+ " , (Select concat(sch.status , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode "
				+ " and g.key1='STATUS' and g.key2='STATUS' and g.value=sch.status) as authStatus "  
				
				+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode "
			//	+ " AND sch.unitId IN (SELECT unitCode FROM MaintEntity e WHERE e.parentUnitCode=:unitCode) " // based on condition 
				+ " AND IFNULL(sch.reportStatus,'NotNull') IN ('RD') " // To get only the records which are in report Dispatched status
			//	+ " AND sch.auditTypeCode = :auditTypeCode ");  // Audit Type as BRANCHI
				+ " AND sch.auditTypeCode in (:auditTypeCodeLst) ");  // Audit Type as BRANCHI or ITISI
		
		if("G3".equalsIgnoreCase(role) || "G31".equalsIgnoreCase(role)) {
			queryString.append(" AND sch.unitId IN :unitList ");
		}else 
			queryString.append(" AND sch.unitId IN (SELECT unitCode FROM MaintEntity e WHERE e.parentUnitCode=:unitCode OR e.unitCode=:unitCode )");  // OR e.unitCode=:unitCode to include ITIS audit type
		
		// queryString.append(" OR ( sch.unitId IN (SELECT unitCode FROM MaintEntity e WHERE e.unitCode=:unitCode) AND sch.auditTypeCode='ITISI' )"); // Added for Inspection type ITISI  // "+BankAuditConstant.INSPECTION_TYPE_ITISI+"
					
		// Financial Year and Audit Type filter added for filtering
				if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
					queryString.append(" and  sch.auditTypeCode =:auditTypeCode "); 
				}if(financialYear !=null) {
					LocalDate fYStartDt = financialYearStrtEndList.get(0);
					LocalDate fYearEndDt = financialYearStrtEndList.get(1);
					logger.info("fYStartDt :: "+fYStartDt+" fYEndDt :: "+fYearEndDt);
					queryString.append(" And (sch.scheduleStartDate between '"+fYStartDt+"' and '"+fYearEndDt+"' )");
					//queryString.append(" And (sch.scheduleStartDate between :fYStartDt and :fYearEndDt )");
				}
		
		logger.info("Before the qry....");
		
		if(!BankAuditUtil.isEmptyString(search)){
			queryString=queryString.append(" and ( "
					+ " sch.auditTypeCode IN (SELECT a.auditTypeCode FROM MaintAuditTypeDesc a  WHERE a.legalEntityCode=sch.legalEntityCode AND (a.auditTypeDesc LIKE :search OR a.auditTypeCode LIKE :search)) "
					+ " or planId like :search "
					+ " or auditId like :search "
					//+ " or unitId like :search "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m WHERE m.legalEntityCode=sch.legalEntityCode AND (m.unitName LIKE :search or m.unitCode LIKE :search )) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,GeneralParameter g WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=m.unitType and g.description LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintCriticality c WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =c.legalEntityCode and m.uCriticality=c.criticalityCode and c.criticalityOfType='Entity' and  c.criticalityDesc LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintAuditParameter p WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =p.legalEntityCode and m.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and  p.duration LIKE :search) "
					+ " or sch.auditId IN (SELECT t.auditId FROM User u,AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.legalEntityCode =u.legalEntityCode and t.userId=u.userId and (t.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or DATE_FORMAT(sch.scheduleStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.scheduleEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.lastAuditDate, '%d %b %Y') LIKE :search "
					+ " or sch.maker IN (SELECT u.userId FROM User u WHERE u.legalEntityCode =sch.legalEntityCode and (u.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus and g.description LIKE :search) "
					+ " or sch.reportStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' and g.key2='REPORT_STATUS' and g.value=sch.reportStatus and g.description LIKE :search) "
					// + " or teamMember like :search "
					+ " or sch.auditId IN (select t.auditId from AuditTeam t, User u where t.legalEntityCode=sch.legalEntityCode AND t.auditId=sch.auditId AND t.userType='M' AND t.legalEntityCode=u.legalEntityCode AND t.userId=u.userId "
					+ "						AND sch.unitId=u.unitCode AND (u.firstName like :search OR u.middleName like :search OR u.lastName like :search OR u.userId like :search )) "
					
					//+ " ) "
					
						+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' "
						+ " and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus "
						+ " and (g.description LIKE :search or g.value LIKE :search)"
						+ " and   ( sch.observationStatus !='AE'  ) "
						+ " ) "
						
						+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' "
						+ " and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus "
						+ " and (g.description LIKE :search or g.value LIKE :search)"
						+ " and   ( sch.observationStatus  ='AE' and sch.auditStatus='AW'  ) "
						+ " ) " 
						
						+ "  " );
						
						if((search.length()==2 && search.toUpperCase().startsWith("EX") )
						|| (search.length()==3 && search.toUpperCase().startsWith("EXI"))
						|| (search.length()==4 && search.toUpperCase().startsWith("EXIT"))
						|| ((search.length()==5 || search.length()==6) && search.toUpperCase().startsWith("EXITE")) ){
							queryString.append("Or (sch.auditStatus='AI' and sch.observationStatus='AE' ) )");
						}	
						else{
							queryString.append(" )" );
							if(search.toUpperCase().startsWith("INI")){
								queryString.append("and  ( sch.auditStatus='AI' and (sch.observationStatus is null or sch.observationStatus='' ) )");
							}
						}
					/*queryString.append(" )" );*/
		}
		
		/*queryString=queryString.append("  ORDER BY FIELD(auditStatus, 'AI','P','AP','AS','AC','AU') asc ");*/
		String[] columns={
				"auditTypeCode",
				"(auditId *1 ), (planId *1 )", //"CAST(planId AS Integer),CAST(auditId AS Integer) "
				"unitType",
				"(unitId * 1) ",  //"unitId",
				"uCriticality",
				"duration",
				"lastAuditDate",//last audit date actually 
				"sch.scheduleStartDate",
				"sch.scheduleEndDate",
				"sch.actualStartDate",
				"sch.actualEndDate",
				"teamLead", // Team Lead
				// "sch.maker", // Team Member
				"sch.maker",
				"sch.reportStatus",  // 13
				"sch.auditStatus",    // 14
				"unitName",  
				"financialYear"
		};

		/*if(orderColumn!=null
				&& !BankAuditUtil.isEmptyString(orderDirection)){
			queryString=queryString.append(" order by ").append(columns[orderColumn]).append(" ").append(orderDirection);
		}*/
		logger.info(" orderColumn **.... "+ orderColumn +"  orderDirection ...."+ orderDirection );
		if(orderColumn != null && orderColumn == -1 && !BankAuditUtil.isEmptyString(orderDirection)){ // -1 send for the first time from the UI during landing page.
			queryString=queryString.append(" ORDER BY scheduleStartDate desc  "); // The code modified to get the records in the order of Status on landing page, the sequence is  Initiated, Planned, Submitted, Respond, Reviewed, Closed
		}else if(orderColumn!=null && !BankAuditUtil.isEmptyString(orderDirection)){
			if(orderColumn==0) {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection).append(" , FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc ,(auditId *1 ) asc  ");
			}else {
				queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection);
			}
		}else {
			queryString=queryString.append(" ORDER BY scheduleStartDate desc ");  // FIELD(auditStatus, 'AI','AP','AS','AR','AC') asc
		}
		
		logger.info("queryString .... "+ queryString.toString());
		
		Query query=(Query) session.createQuery(queryString.toString())				
				.setResultTransformer(new ResultTransformer() {
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						AuditSchedule auditSchedule=null;
						//System.out.println("tuple[0] ...."+tuple[0]);
						if(tuple[0]!=null){
							auditSchedule=(AuditSchedule)tuple[0];
							/* session.evict(maintEntity);*/
							
							if(tuple[1]!=null){
								auditSchedule.setLegalEntityCode(Integer.parseInt(tuple[1].toString()));								
							}
							if(tuple[2]!=null){
								auditSchedule.setAuditTypeCode(tuple[2].toString());
							}
							
							if(tuple[3]!=null){
								auditSchedule.setPlanId(tuple[3].toString());
							}
							
							if(tuple[4]!=null){
								auditSchedule.setAuditId(tuple[4].toString());
							}
							if(tuple[5]!=null){
								//String unitCodeName=tuple[5].toString();
								//auditSchedule.setUnitId(unitCodeName);
								//auditSchedule.setUnitName(unitCodeName.substring(unitCodeName.indexOf('-')+1));
								auditSchedule.setUnitId(auditSchedule.getUnitId()+"-"+tuple[5].toString());
								auditSchedule.setUnitName(tuple[5].toString());
							}
							if(tuple[6]!=null){
								auditSchedule.setUnitType(tuple[6].toString());
							}
							if(tuple[7]!=null){
								auditSchedule.setuCriticality(tuple[7].toString());
							}
							if(tuple[8]!=null){ 
									String teamLead = userDtls.get(tuple[8].toString());
									auditSchedule.setTeamLead(teamLead.equalsIgnoreCase("Me")?"Me":tuple[8].toString()+"-"+teamLead);
								 
								//auditSchedule.setTeamLead(tuple[8].toString()+"-"+userDtls.get(tuple[8].toString()));
								//auditSchedule.setTeamLead(userDtls.get(tuple[8].toString()));
							}
							if(tuple[9]!=null){
								auditSchedule.setDuration(tuple[9].toString());
							}
							if(tuple[10]!=null){
								auditSchedule.setFrequency(tuple[10].toString());
							}
							if(tuple[11]!=null){
								if("P".equalsIgnoreCase(tuple[11].toString()))auditSchedule.setAuditStatus("AP"); // temp purpose as in few earlier records the Planned status is reflecting as "P"
								else if("AE".equalsIgnoreCase(auditSchedule.getObservationStatus())) auditSchedule.setAuditStatus(tuple[18] !=null ?tuple[18].toString() :tuple[11].toString() );
								else auditSchedule.setAuditStatus(tuple[11].toString());
							}
							if(tuple[12]!=null){
								auditSchedule.setMaker(tuple[12].toString());
							}
							if(tuple[13]!=null && auditSchedule.getRespondedFindings() != null){
								auditSchedule.setResponseReject(Integer.parseInt(tuple[13].toString()));
								auditSchedule.setRespondedFindings(auditSchedule.getRespondedFindings()- (Integer.parseInt(tuple[13].toString()))); // Included to find out the Responded Observations
							}else auditSchedule.setResponseReject(0);
							
							if(tuple[14]!=null){
								auditSchedule.setComplianceCount(Integer.parseInt(tuple[14].toString()));
							}else auditSchedule.setComplianceCount(0);
							
							if(tuple[15]!=null){
								auditSchedule.setNotApplicableCount(Integer.parseInt(tuple[15].toString()));
							}else auditSchedule.setNotApplicableCount(0);
							
							if(tuple[16]!=null){
								auditSchedule.setEarlyStartAllowed(tuple[16].toString());
							}else auditSchedule.setEarlyStartAllowed("Y");
							
							if(tuple[17]!=null){
								auditSchedule.setAuditOffsetDays(Integer.parseInt(tuple[17].toString()));
							}else auditSchedule.setAuditOffsetDays(0);
							
							if(tuple[19]!=null){
								String teamMembers="";
								String[] members = tuple[19].toString().split(",");
								for (String member: members) {
									teamMembers+=member+"-"+userDtls.get(member)+",";
								}
								auditSchedule.setTeamMember(teamMembers.substring(0,teamMembers.length()-1));
							}
							
							if(tuple[20]!=null) auditSchedule.setReportStatus(tuple[20].toString());
							if(tuple[21]!=null) auditSchedule.setReportStatusDesc(tuple[21].toString());
							
							if(tuple[22]!=null) auditSchedule.setStatus(tuple[22].toString());
							
							/*int tmSize =auditSchedule.getAuditTeams().size()-1;
							String teamMember="";
							System.out.println("Audit Id .... "+ auditSchedule.getAuditId()+" tmSize .."+tmSize);
							for( AuditTeam adtTm: auditSchedule.getAuditTeams() ) {
								
								adtTm.setUserId(adtTm.getUserId()+"-"+userDtls.get(adtTm.getUserId()));
								
								if(!"L".equalsIgnoreCase(adtTm.getUserType())) teamMember +=adtTm.getUserId() + ",";
								System.out.println("teamMember .... "+ teamMember);
							}if(tmSize >0 ) auditSchedule.setTeamMember(teamMember.substring(0,teamMember.lastIndexOf(",")));*/
							//System.out.println("Team member .... "+auditSchedule.getTeamMember());
							//System.out.println("Team size ...."+auditSchedule.getAuditTeams().size());
							
						}
						return auditSchedule;
					}
			@Override
			public List transformList(List collection) {
				return collection;
			}
		})		
		.setParameter("legalEntityCode",legalEntityCode).setParameter("auditTypeCodeLst", auditTypeCodeLst); //.setParameter("visibleAuditList", visibleAuditList);
		
		if("G3".equalsIgnoreCase(role) || "G31".equalsIgnoreCase(role)) query.setParameter("unitList", unitList);
		else query.setParameter("unitCode",unitCode);
		
		if(!BankAuditUtil.isEmptyString(search)){
			query.setParameter("search", "%"+search+"%");
		}
		
		if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
			query.setParameter("auditTypeCode", auditTypeCode);
		}
		
		logger.info("page :: "+page +"size :: "+ size);
		List<AuditSchedule> tmpAuditSchedule =query.list(); 
		Long totalRecords=null;
		try {
			totalRecords = (long)tmpAuditSchedule.size();
		}catch(Exception e) {
			totalRecords = (long)0;
		}
		List<AuditSchedule> auditSchedule=query.setFirstResult((page*size)).setMaxResults(size).list();
		
		logger.info("Bfr size tmpAuditSchedule is .... "+tmpAuditSchedule.size()+" totalRecords:: "+ totalRecords);
		
		/*int i=0;
		for(AuditSchedule adSch:auditSchedule){
			System.out.println("Inside adSch ...");
			if("A2".equalsIgnoreCase(adSch.getAuditId()));
			else 	tmpAuditSchedule.add(adSch);
			System.out.println("after the call");
			
		}
		System.out.println("size tmpAuditSchedule .... "+tmpAuditSchedule);*/
		
		
		dataTableResponse.setData(auditSchedule);
		dataTableResponse.setRecordsTotal(totalRecords);
		dataTableResponse.setRecordsFiltered(totalRecords);
		
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return dataTableResponse;
	
	}
	
	
	@Override
	public AuditSchedule getFYAndAuditSerialNoBfrInitiate(int legalEntityCode, String auditId,String letterCode, String unitCode, String auditTypeCode, Date schStartDate, String auditStatus) {
		Session session = getSession();
		AuditSchedule sch= null;
		try {
			sch= new AuditSchedule();
			logger.info("Inside getFYAndAuditSerialNoBfrInitiate .. "+ legalEntityCode +" :: "+auditId+" :: "+letterCode+" :: "+unitCode+" :: "+auditTypeCode+ " :: "+auditStatus);
			//For BaaSDOS implementation, Logic to get the PreviousAuditId and Serial no
				String prevAuditId=null, auditStatusMax=null; int auditSerialNo=1;
				StringBuilder prvAuditDtls=new StringBuilder(" select audit_id, audit_serial_no, audit_status from audit_schedule  "
						+ " where /* audit_type_code=:auditTypeCode and */ legal_entity_code=:legalEntityCode and unit_id=:unitId "
						+ " 	and  audit_serial_no in (select ifnull(max(audit_serial_no),0) as max_sl_no from audit_schedule "
						+ "									 where legal_entity_code=:legalEntityCode and /* audit_type_code=:auditTypeCode and */ unit_id=:unitId) "
						+ " order by schedule_end_date limit 1 ");
					
				Query prvAuditDtlsQry=session.createNativeQuery(prvAuditDtls.toString())
						.setParameter("legalEntityCode", legalEntityCode)
						.setParameter("unitId", unitCode)
						/*.setParameter("auditTypeCode", auditTypeCode)*/;  // Need to uncomment 
				 
				Object prvObj = prvAuditDtlsQry.uniqueResult();
				logger.info("prvObj ::"+prvObj +" prvAuditDtls::"+prvAuditDtls );
				try{
					if(prvObj != null  && ((Object[])prvObj).length > 0)
					{
						prevAuditId  = (((Object[])prvObj)[0]!=null?((Object[])prvObj)[0].toString():null);
						auditSerialNo  = (((Object[])prvObj)[1]!=null?(Integer.parseInt(((Object[])prvObj)[1].toString())):0);
						auditStatusMax  = (((Object[])prvObj)[2]!=null?((Object[])prvObj)[2].toString():null);
						logger.info("prevAuditId.... "+ prevAuditId +" serialNo.... "+auditSerialNo+" auditStatusMax...."+auditStatusMax);
						if("AP".equalsIgnoreCase(auditStatus))
							auditSerialNo += 1;						
					}logger.info(" serialNo final :: "+auditSerialNo);
					sch.setAuditSerialNo(auditSerialNo);
				}catch(Exception e) {
					e.printStackTrace(System.out);
				}// end here
				
				//For BaaSDOS implementation, Logic to get the Financial year end date
				Date fn_year=null;
				Object fyObj=session.createNativeQuery("select DATE_SUB(get_financial_year_endDate_forDate(:legalEntityCode, :schStartDate),INTERVAL 1 Year)")
						.setParameter("legalEntityCode", legalEntityCode)
						.setParameter("schStartDate", schStartDate).getSingleResult();
				
				logger.info("FyObj .."+fyObj);
				try{
					if(fyObj != null )
						sch.setFinancialYear((Date)fyObj);
						logger.info("FY year.... "+sch.getFinancialYear());
				}catch(Exception e) {
					e.printStackTrace(System.out);
				}// end here
			
				logger.info("FY ::"+sch.getFinancialYear() +"Audit Sl No:: "+sch.getAuditSerialNo());
				
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return sch;
	}
	
	@Override
	public String getAuditSerialNoBfrInitiate(int legalEntityCode, String auditId,String letterCode, String unitCode, String auditTypeCode) {
		Session session = getSession();
		String auditSlNo= null;
		try {
			
			logger.info("Inside getFYAndAuditSerialNoBfrInitiate .. "+ legalEntityCode +" :: "+auditId+" :: "+letterCode+" :: "+unitCode+" :: "+auditTypeCode);
			//For BaaSDOS implementation, Logic to get the Serial no
				String prevAuditId=null; int auditSerialNo=1;
				StringBuilder prvAuditDtls=new StringBuilder(" select audit_id, audit_serial_no from audit_schedule  "
						+ " where audit_type_code=:auditTypeCode and legal_entity_code=:legalEntityCode and unit_id=:unitId "
						+ " 	and  audit_serial_no in (select ifnull(max(audit_serial_no),0) as max_sl_no from audit_schedule "
						+ "									 where legal_entity_code=:legalEntityCode and audit_type_code=:auditTypeCode and unit_id=:unitId) "
						+ " order by schedule_end_date limit 1 ");
					
				Query prvAuditDtlsQry=session.createNativeQuery(prvAuditDtls.toString())
						.setParameter("legalEntityCode", legalEntityCode)
						.setParameter("unitId", unitCode)
						.setParameter("auditTypeCode", auditTypeCode);
				
				Object prvObj = prvAuditDtlsQry.uniqueResult();
				logger.info("prvObj ::"+prvObj +" prvAuditDtls::"+prvAuditDtls );
				try{
					if(prvObj != null  && ((Object[])prvObj).length > 0)
					{
						prevAuditId  = (((Object[])prvObj)[0]!=null?((Object[])prvObj)[0].toString():null);
						auditSerialNo  = (((Object[])prvObj)[1]!=null?(Integer.parseInt(((Object[])prvObj)[1].toString())):0);
						logger.info("prevAuditId.... "+ prevAuditId +" serialNo.... "+auditSerialNo);
						auditSerialNo += 1;						
					}logger.info(" serialNo final :: "+auditSerialNo);
				}catch(Exception e) {
					e.printStackTrace(System.out);
				}// end here				
				auditSlNo=auditSerialNo+"";
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return auditSlNo;
	}
	
	@Override
	//public void updateMyAuditRatingParameterStatus(int legalEntityCode, String auditId, String ratingParamMaker, String ratingParamReviewer, String ratingParameterStatus) {
	public void updateMyAuditRatingParameterStatus(AuditSchedule auditSchedule) {
		Session session = getSession();
		String auditSlNo= null;
		logger.info("Inside updateMyAuditRatingParameterStatus .. "+ auditSchedule.getAuditId());
		try {
			/*AuditSchedule audSch= (AuditSchedule)session.createQuery("FROM AuditSchedule WHERE legalEntityCode=:legalEntityCode AND auditId=:auditId ")
					.setParameter("legalEntityCode", legalEntityCode).setParameter("auditId", auditId).uniqueResult();
			if(!"A".equalsIgnoreCase(ratingParameterStatus)) {
				audSch.setRatingParameterMaker(ratingParamMaker);
				audSch.setRatingParameterReviewer(ratingParamReviewer);
			}
			audSch.setRatingParameterStatus(ratingParameterStatus);*/
			
			String ratingParamStatus =auditSchedule.getRatingParameterStatus();
			String ratingParameterMaker =auditSchedule.getRatingParameterMaker();
			String ratingParameterReviewer =auditSchedule.getRatingParameterReviewer();
			String ratingParameterReviewerAssigned =auditSchedule.getRatingParameterReviewerAssigned();
			String ratingParameterHoReviewer =auditSchedule.getRatingParameterHoReviewer();
			String ratingEffectiveRiskPrc = auditSchedule.getNormalisedAfterOverlayScore();
			String ratingEffectiveRating = auditSchedule.getFinalRating();
			
			logger.info("updateMyAuditRatingParameterStatus ratingParamStatus:: "+ ratingParamStatus + " Mkr::"+ratingParameterMaker+ " Rvwr:: "+ratingParameterReviewer+" HoRvwr:: "+ratingParameterHoReviewer );
			AuditSchedule audSch= (AuditSchedule)session.get(AuditSchedule.class,auditSchedule);
					
			audSch.setRatingParameterStatus(ratingParamStatus);
			audSch.setRatingParameterMaker(ratingParameterMaker);
			audSch.setRatingParameterReviewer(ratingParameterReviewer);
			audSch.setRatingParameterReviewerAssigned(ratingParameterReviewerAssigned);
			audSch.setRatingParameterHoReviewer(ratingParameterHoReviewer);
			//if("RPP".equalsIgnoreCase(ratingParamStatus) || "RPR".equalsIgnoreCase(ratingParamStatus) ){
			if("RPP".equalsIgnoreCase(ratingParamStatus) || "RPR".equalsIgnoreCase(ratingParamStatus) || "RPRU".equalsIgnoreCase(ratingParamStatus) ){  // RPRU also included, as during Interim review/Save by Reviewer the Rating score to update
				audSch.setEffectiveRiskPrcntg(ratingParameterReviewerAssigned);
				audSch.setEffectiveRating(ratingEffectiveRating);
			}			
			session.update(audSch);
			session.flush();
		
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}		
	}
	
	@Override
	public void updateMyAuditRatingComplianceObsScoreStatus(AuditSchedule auditSchedule) {
		Session session = getSession();
		String auditSlNo= null;
		logger.info("Inside updateMyAuditRatingComplianceObsScoreStatus .. "+ auditSchedule.getAuditId() +" :: "+ auditSchedule.getRatingComplianceStatus());
		try {
			/*AuditSchedule audSch= (AuditSchedule)session.createQuery("FROM AuditSchedule WHERE legalEntityCode=:legalEntityCode AND auditId=:auditId ")
					.setParameter("legalEntityCode", legalEntityCode).setParameter("auditId", auditId).uniqueResult();
			if(!"A".equalsIgnoreCase(ratingParameterStatus)) {
				audSch.setRatingParameterMaker(ratingParamMaker);
				audSch.setRatingParameterReviewer(ratingParamReviewer);
			}
			audSch.setRatingParameterStatus(ratingParameterStatus);*/
			
			String ratingCompStatus =auditSchedule.getRatingComplianceStatus();
			String ratingCompReviewer =auditSchedule.getRatingComplianceReviewer();
			String ratingCompReviewerAssigned =auditSchedule.getRatingComplianceReviewerAssigned();
			String ratingCompAuditor =auditSchedule.getRatingComplianceAuditor();
			String ratingCompAuditorAssigned =auditSchedule.getRatingComplianceAuditorAssigned();
			
			String deskScore =auditSchedule.getDeskComplianceScore();
			String deskRating =auditSchedule.getDeskComplianceRating();
			String fieldScore =auditSchedule.getOnsiteComplianceScore();
			String fieldRating =auditSchedule.getOnsiteComplianceRating();
			
			logger.info("updateMyAuditRatingParameterStatus ratingCompStatus:: "+ ratingCompStatus + " Rvwr::"+ratingCompReviewer+ " RvwrAssgn:: "+ratingCompReviewerAssigned+" Adtr:: "+ratingCompAuditor+" AdtrAssgn:: "+ratingCompAuditorAssigned );
			logger.info(" DeskScore:: "+ deskScore + " DeskRat::"+deskRating+ " FieldScore:: "+fieldScore+" FieldRat:: "+fieldRating);
			AuditSchedule audSch= (AuditSchedule)session.get(AuditSchedule.class,auditSchedule);
			audSch.setRatingComplianceStatus(ratingCompStatus);
			
			StringBuilder strComplRatingQry = new StringBuilder();
			// RCDDF => Rating Desk Compliance Draft	RCDU=>UnAuth	RCDM=>Modified by Reviewer	  RCDS=> Rating Desk Compliance Submitted
			if("RCDDF".equalsIgnoreCase(ratingCompStatus) || "RCDU".equalsIgnoreCase(ratingCompStatus) || "RCDM".equalsIgnoreCase(ratingCompStatus) || "RCDS".equalsIgnoreCase(ratingCompStatus) ){
				audSch.setRatingComplianceReviewer(ratingCompReviewer);
				audSch.setRatingComplianceReviewerAssigned(ratingCompReviewerAssigned);
				audSch.setRatingComplianceReviewed((new Timestamp(System.currentTimeMillis())));
				//if("RCDS".equalsIgnoreCase(ratingCompStatus)) { // commented to update the score during PIO submit, Review team Save and Submit time
				if("RCDS".equalsIgnoreCase(ratingCompStatus) || "RCDU".equalsIgnoreCase(ratingCompStatus) || "RCDM".equalsIgnoreCase(ratingCompStatus)) {
					audSch.setDeskComplianceScore(deskScore);
					audSch.setDeskComplianceRating(deskRating);
					
					if("RCDS".equalsIgnoreCase(ratingCompStatus) ){
						AuditRatingComplianceScoreDto auditRatingComplianceScoreDto = auditRatingComplianceScoreService
								.getAuditRatingComplianceScores(audSch.getLegalEntityCode(), audSch.getAuditId(), "D", null);					
						strComplRatingQry.append( " UPDATE AuditRating rating SET "
								+ " rating.deskComplianceMaximumMarks = '"+auditRatingComplianceScoreDto.getDeskMaxMarks()+"', "
								+ " rating.deskComplianceMarksObtained = '"+auditRatingComplianceScoreDto.getDeskTotalMarks()+"' ");					
					}
				}
			}else { //RCFDF => Rating Field Compliance Draft	 RCFU=>UnAuth	RCFM=>Modified by Reviewer 	 RCFS=> Rating Field Compliance Submitted
				audSch.setRatingComplianceAuditor(ratingCompAuditor);
				audSch.setRatingComplianceAuditorAssigned(ratingCompAuditorAssigned);
				audSch.setRatingComplianceAudited((new Timestamp(System.currentTimeMillis())));
				//if("RCFS".equalsIgnoreCase(ratingCompStatus) ) { // commented to update the score during PIO submit, Review team Save and Submit time
				if("RCFS".equalsIgnoreCase(ratingCompStatus) || "RCFU".equalsIgnoreCase(ratingCompStatus) || "RCFM".equalsIgnoreCase(ratingCompStatus)) {
					audSch.setOnsiteComplianceScore(fieldScore);
					audSch.setOnsiteComplianceRating(fieldRating);
					
					if("RCFS".equalsIgnoreCase(ratingCompStatus)){
						AuditRatingComplianceScoreDto auditRatingComplianceScoreDto = auditRatingComplianceScoreService
								.getAuditRatingComplianceScores(audSch.getLegalEntityCode(), audSch.getAuditId(), "F", null);					
						strComplRatingQry.append( " UPDATE AuditRating rating SET "
								+ " rating.onsiteComplianceMaximumMarks = '"+auditRatingComplianceScoreDto.getFieldMaxMarks()+"', "
								+ " rating.onsiteComplianceMarksObtained = '"+auditRatingComplianceScoreDto.getFieldTotalMarks()+"' "); 					 
					}
				}
			}
			session.update(audSch);
			strComplRatingQry.append(" WHERE rating.legalEntityCode = :legalEntityCode"
					+ " AND rating.auditTypeCode = :auditTypeCode "
					+ " AND rating.auditId = :auditId ");
			session.createQuery(strComplRatingQry.toString())
					.setParameter("legalEntityCode", audSch.getLegalEntityCode())
					.setParameter("auditTypeCode", audSch.getAuditTypeCode())
					.setParameter("auditId", audSch.getAuditId())
					.executeUpdate();
			session.flush();
		
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}		
	}

	
	/* Method to add few additional */
	@Override
	public AuditSchedule getAuditByAuditId(int legalEntityCode, String auditTypeCode, String planId, String auditId) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		
		AuditSchedule auditSchedule = null;
		try {
			StringBuilder queryString=new StringBuilder("select sch as auditSchedule, "   //0
					+ "(select concat(auditTypeCode , '-' , auditTypeDesc) from MaintAuditTypeDesc at where at.auditTypeCode=sch.auditTypeCode and at.legalEntityCode= sch.legalEntityCode ) as auditTypeCode,"
					+ " (Select concat(unitCode , '-' , unitName) from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitId,  "
					+ " (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus) as auditStatus, "
					+ " (Select rmCode from  MaintRatingAuditTypeMapping m where m.auditTypeCode =sch.auditTypeCode and m.legalEntityCode =sch.legalEntityCode) as rmCode  "
					+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode  and auditId=:auditId "); /* and planId=:planId */
			System.out.println("Before the qry....");
			
			Query query=(Query) session.createQuery(queryString.toString())				
					.setResultTransformer(new ResultTransformer() {
						@Override
						public Object transformTuple(Object[] tuple, String[] aliases) {
							AuditSchedule auditSchedule=null;
							if(tuple[0]!=null){
								auditSchedule=(AuditSchedule)tuple[0];
								if(tuple[1]!=null) auditSchedule.setAuditTypeCode(tuple[1].toString());
								if(tuple[2]!=null) auditSchedule.setUnitId(tuple[2].toString());
								if(tuple[3]!=null)	auditSchedule.setAuditStatus(tuple[3].toString());
								if(tuple[4]!=null)	auditSchedule.setRmCode(tuple[4].toString());
							}
							return auditSchedule;
						}
				@Override
				public List transformList(List collection) {
					return collection;
				}
			}).setParameter("legalEntityCode",legalEntityCode)
		      .setParameter("auditId",auditId);
			
			 auditSchedule=(AuditSchedule)query.uniqueResult(); 
		}catch(Exception e) {
			e.printStackTrace();
		}return auditSchedule; 
	}	
	
	@Override
	public AuditSchedule getAuditByAuditId(int legalEntityCode, String auditTypeCode, String auditId) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		logger.info("Inside getAuditByAuditId .."+ auditId + " :: "+ auditTypeCode);
		
		return (AuditSchedule)session.createQuery("FROM AuditSchedule sch WHERE sch.legalEntityCode =:legalEntityCode  AND sch.auditId=:auditId "
				+ " AND sch.auditTypeCode=:auditTypeCode").setParameter("legalEntityCode",legalEntityCode)
				.setParameter("auditId",auditId).setParameter("auditTypeCode",auditTypeCode).uniqueResult();		 
	}	
	
	@Override
	public AuditRating getAuditRatingByAuditId(int legalEntityCode, String auditTypeCode, String auditId) {
		Session session = getSession();
		session.setDefaultReadOnly(true);
		logger.info("Inside getAuditRatingByAuditId .."+ auditId);
		
		return (AuditRating)session.createQuery("FROM AuditRating ar WHERE ar.legalEntityCode =:legalEntityCode  and ar.auditId=:auditId")
				.setParameter("legalEntityCode",legalEntityCode)
			      .setParameter("auditId",auditId).uniqueResult();		 
	}	
	
	@Override
	public void updateAuditRatingStatus(AuditSchedule auditSchedule, String ratingParameterStatus) {
		Session session = getSession();
		logger.info("Inside updateAuditRatingStatus .. "+ auditSchedule.getAuditId() + " :: "+auditSchedule.getRatingParameterStatus());
		try {
			// AuditRating auditRating=getAuditRatingByAuditId(auditSchedule.getLegalEntityCode(), auditSchedule.getAuditTypeCode(), auditSchedule.getAuditId());
			Map<String, Object> properties = new HashMap<String, Object>();
			properties.put("legalEntityCode", auditSchedule.getLegalEntityCode());
			properties.put("auditTypeCode", auditSchedule.getAuditTypeCode());
			properties.put("unitId", auditSchedule.getUnitId());
			properties.put("auditId", auditSchedule.getAuditId());			
			AuditRating auditRating = (AuditRating)auditScheduleDao.getUniqueEntityByMatchingProperties(AuditRating.class, properties);
			
			logger.info("auditRating .. "+auditRating);
			boolean auditRatingNew=false;
			if(auditRating==null) {
				auditRating = new AuditRating();
				auditRating.setLegalEntityCode(auditSchedule.getLegalEntityCode());
				auditRating.setAuditId(auditSchedule.getAuditId());
				auditRating.setAuditTypeCode(auditSchedule.getAuditTypeCode());
				auditRating.setUnitId(auditSchedule.getUnitId());	
				auditRating.setEntityStatus("A");
				auditRating.setStatus("A");
				auditRating.setMaker(auditSchedule.getRatingParameterMaker());
				auditRating.setMakerTimestamp(new Timestamp(System.currentTimeMillis()));
				auditRatingNew=true;
			}
			if("RPP".equalsIgnoreCase(ratingParameterStatus)){ // PIO Ratings
				auditRating.setSupervisoryIoRiskPrcntg(auditSchedule.getSupervisoryIoRiskPrcntg());
				auditRating.setSupervisoryIoRating(auditSchedule.getSupervisoryIoRating());
				auditRating.setAuditerId(auditSchedule.getRatingParameterMaker());				
				auditRating.setSupervisoryRiskPrcntg(auditSchedule.getNormalisedAfterOverlayScore());
				auditRating.setSupervisoryRating(auditSchedule.getFinalRating());
				auditRating.setFinalRating(auditSchedule.getFinalRating());
			}else if("RPR".equalsIgnoreCase(ratingParameterStatus) || "RPRU".equalsIgnoreCase(ratingParameterStatus)){ // Reviewer Rating // RPRU also included for interim update
				auditRating.setSupervisoryRoRiskPrcntg(auditSchedule.getSupervisoryRoRiskPrcntg());
				auditRating.setSupervisoryRoRating(auditSchedule.getSupervisoryRoRating());
				auditRating.setReviewerId(auditSchedule.getRatingParameterReviewer());
				auditRating.setReviewedDate(new Timestamp(System.currentTimeMillis()));
				auditRating.setSupervisoryRiskPrcntg(auditSchedule.getNormalisedAfterOverlayScore());
				auditRating.setSupervisoryRating(auditSchedule.getFinalRating());
				auditRating.setFinalRating(auditSchedule.getFinalRating());
			}
			else if("RPS".equalsIgnoreCase(ratingParameterStatus)){ // Reviewer Rating
				auditRating.setHoReviewerId(auditSchedule.getRatingParameterHoReviewer());
				auditRating.setHoReviewedDate(new Timestamp(System.currentTimeMillis()));
				auditRating.setSupervisoryHoRiskPrcntg(auditSchedule.getNormalisedAfterOverlayScore());
				auditRating.setSupervisoryHoRating(auditSchedule.getFinalRating());
			}
			//auditRating.setSupervisoryRiskPrcntg(auditSchedule.getNormalizedScoreFinal());			
			
			auditRating.setManagementScore(auditSchedule.getManagementScore());
			auditRating.setIntegratedScore(auditSchedule.getIntegratedScore());
			auditRating.setIntegratedScoreAftrPOverlay(auditSchedule.getIntegratedScoreAftrPOverlay());
			auditRating.setIntegratedScoreAftrPOverlay(auditSchedule.getNormalizedScoreFinal());
			auditRating.setRatingAftrPOverlay(auditSchedule.getRatingAftrPOverlay());
			auditRating.setRatingAftrMOverlay(auditSchedule.getRatingAftrMOverlay());
			
			auditRating.setRatingParameterStatus(ratingParameterStatus);
			
			/*if(auditRatingNew)
				session.save(auditRating);
			else { 
				session.flush();	
				session.update(auditRating);				
			}*/			
			session.saveOrUpdate(auditRating);
			session.flush();				
			//session.clear();
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}		
	}
	
	@Override
	public EntityAuditDataDto getEntityAuditData(int legalEntityCode, String auditTypeCode, String auditId, String unitId) {
		Session session = getSession();
		String auditSlNo= null;
		EntityAuditDataDto eDto=new EntityAuditDataDto();
		try {
			
			logger.info("Inside getEntityAuditData .. "+ legalEntityCode +" :: "+auditTypeCode+" :: "+auditId+" :: "+unitId);
			StringBuilder auditEntDtls=new StringBuilder(" SELECT sch.audit_id, sch.financial_year, e.unit_code, e.unit_name,    "  // 3
						+ "  (SELECT a.state_name FROM maint_address a WHERE a.state_code=e.state LIMIT 1 ) AS state_name , "  // 4
						+ "  (SELECT e1.unit_name FROM maint_entity e1 WHERE e1.unit_code=e.parent_unit_code ) AS parent_unit_name " // 5
						+ "	FROM audit_schedule sch, maint_entity e "
						+ " WHERE sch.legal_entity_code=e.legal_entity_code and sch.unit_id=e.unit_code and "
						+ "   sch.audit_id=:auditId and sch.legal_entity_code=:legalEntityCode ");
					
				Query auditEntDtlsQry=session.createNativeQuery(auditEntDtls.toString())
						.setParameter("legalEntityCode", legalEntityCode)
						.setParameter("auditId", auditId);
				
			logger.info("Query before .. "+ auditEntDtlsQry );
			Object[] obj = (Object[])auditEntDtlsQry.getSingleResult();
			eDto.setAuditId(auditId);				
			if(obj !=null) {
				if(obj[1] !=null) eDto.setFinancialYear(obj[1].toString());
				if(obj[2] !=null) eDto.setUnitCode(obj[2].toString());
				if(obj[3] !=null) eDto.setUnitName(obj[3].toString());					
				if(obj[4] !=null) eDto.setStateName(obj[4].toString());
				if(obj[5] !=null) eDto.setParentUnitName(obj[5].toString());
			}
							
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return eDto;
	}
	
	@Override
	public List<AuditSchedule> getAuditSchedules(Integer legalEntityCode, String auditTypeCode){
		Session session = getSession();
		logger.info("Inside getAuditSchedules .. "+ legalEntityCode +" :: "+auditTypeCode);
		
		List<AuditSchedule> lstSchedules=new ArrayList<AuditSchedule>();
			
		StringBuilder str=new StringBuilder(" From AuditSchedule sch WHERE sch.legalEntityCode=:legalEntityCode");
		if(auditTypeCode!=null) {
			str.append("  AND sch.auditTypeCode=:auditTypeCode");
		}
		Query qry=(Query) session.createQuery(str.toString());
		qry.setParameter("legalEntityCode", legalEntityCode);
		
		if(auditTypeCode!=null) 
			qry.setParameter("auditTypeCode", auditTypeCode);
		
		lstSchedules=qry.list();
		return lstSchedules;
	}
	
	@Override
	public List<AuditActionItem> getAuditActionItem(Integer legalEntityCode, String auditTypeCode, String auditId){
		Session session = getSession();
		logger.info("Inside getAuditActionItem .. "+ auditTypeCode +" :: "+auditId);
			
		return session.createQuery(" From AuditActionItem at WHERE at.legalEntityCode=:legalEntityCode AND at.auditTypeCode=:auditTypeCode AND at.auditId=:auditId ")
		.setParameter("legalEntityCode", legalEntityCode).setParameter("auditTypeCode", auditTypeCode).setParameter("auditId", auditId).list();
	}
	
	@Override
	public void saveAuditActionItem(Integer legalEntityCode, String auditTypeCode, String auditId){
		Session session = getSession(); 
		
		String qryStr = " insert into audit_action_item"
				+ " (legal_entity_code, audit_type_code, audit_id, action_item, action_item_type)"
				+ " Select "
				+ " legal_entity_code, audit_type_code, '"+auditId+"', action_item, action_item_type "
				+ " from maint_action_item "
				+ " Where legal_entity_code = '"+legalEntityCode+"' "
				+ " and  audit_type_code = '"+auditTypeCode+"'  " ;
		session.createNativeQuery(qryStr).executeUpdate();
	}
		
	@Override
	public AuditSchedule checkLatestITISAuditDetailsForUnit(Integer legalEntityCode, String unitId){
		Session session = getSession(); 
		session.setDefaultReadOnly(true);
		
		Map<String, LocalDate> financialYearMap = BankAuditUtil.getFinancialYearDates(new Date());
		LocalDate financialYearStartDtPrevThree  = financialYearMap.get("FIN_YR_START_DATE").minusYears(3);
		LocalDate financialYearEndDtCurrent = financialYearMap.get("FIN_YR_END_DATE");
 	 	 
		String qryStr = "  FROM AuditSchedule sch "
				+ " WHERE sch.legalEntityCode= :legalEntityCode"
				+ " AND sch.unitId = :unitId  "
				+ " AND sch.auditTypeCode = :auditTypeITIS "
				+ " AND (sch.actualStartDate BETWEEN '"+financialYearStartDtPrevThree+"' AND '"+financialYearEndDtCurrent+"') "
				+ " ORDER BY sch.actualStartDate ASC ";
     
		AuditSchedule auditSchedule = (AuditSchedule) session.createQuery(qryStr)
				.setParameter("legalEntityCode", legalEntityCode)
				.setParameter("unitId", unitId)
				.setParameter("auditTypeITIS", BankAuditConstant.INSPECTION_TYPE_ITISI)
				.setMaxResults(1)
				.uniqueResult();
		return auditSchedule;
		
	}
	
	@Override
	public String getFinancialYearByAuditId(Integer legalEntityCode, String auditTypeCode, String auditId){
		Session session = getSession(); 
		session.setDefaultReadOnly(true);
		String finYearStr=null;
		logger.info("Inside getFinancialYearByAuditId .. "+ auditId+" :: "+ auditTypeCode);
		String qryStr = "SELECT financialYear  FROM AuditSchedule sch "
				+ " WHERE sch.legalEntityCode= :legalEntityCode"
				+ " AND sch.auditId = :auditId AND sch.auditTypeCode = :auditTypeCode ";
     
		Date finYear= (Date)session.createQuery(qryStr).setParameter("legalEntityCode", legalEntityCode)
				.setParameter("auditId", auditId).setParameter("auditTypeCode", auditTypeCode).getSingleResult();
		
		finYearStr=(finYear !=null?finYear.toString().substring(0, 10):"");
		logger.info("finYearStr .."+finYearStr);
		
		return finYearStr;
		
	}
	
	@Override
	public String isAuditReviewPending(AuditDto auditDto, String status) {

		Session session=getSession();
		String isReviewObsPendingBfrAuditClosure ="N";
		logger.info("LE:: "+ auditDto.getLegalEntityCode() + " Audit ID:: "+auditDto.getAuditId() + "Audit Type:: "+ auditDto.getAuditTypeCode()+" status:: "+status);
		try {
			StringBuilder queryStr1=new StringBuilder("");
			queryStr1.append(" SELECT COUNT(*) FROM AuditObservation "
					+ " WHERE legalEntityCode=:legalEntityCode and auditId=:auditId and auditTypeCode = :auditTypeCode ");
			if(status.equals("AC")) {
				queryStr1.append(" AND (reviewStatusAttribute='FC' OR ( reviewStatusAttribute IN ('R','A') AND reviewStatus='PA') ) ");
			}else {
				//queryStr1.append(" AND (reviewStatusAttribute='FC' OR (reviewStatus='PA' AND reviewStatusAttribute IN ('R','A')))  ");
			}
			
			org.hibernate.query.Query query=session.createQuery(queryStr1.toString());
			query.setParameter("legalEntityCode", auditDto.getLegalEntityCode());
			query.setParameter("auditId",auditDto.getAuditId());
			query.setParameter("auditTypeCode", auditDto.getAuditTypeCode());
			logger.info("isAuditObsPendingBfrAuditSubmit QRY is :: "+ query);
	
			isReviewObsPendingBfrAuditClosure = query.uniqueResult().toString();
			logger.info("isReviewObsPendingBfrAuditClosure rslt is :: "+ isReviewObsPendingBfrAuditClosure);
			if(isReviewObsPendingBfrAuditClosure != null && Integer.parseInt(isReviewObsPendingBfrAuditClosure) == 0)
				isReviewObsPendingBfrAuditClosure ="N";
			else isReviewObsPendingBfrAuditClosure ="Y";
			
			logger.info("isReviewObsPendingBfrAuditClosure QRY is :: "+ isReviewObsPendingBfrAuditClosure);
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		return isReviewObsPendingBfrAuditClosure;
	}

	
}
