package com.bankaudit.rest.process.dao;
import java.math.BigInteger;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.stream.Collectors;

import javax.persistence.TemporalType;

import org.hibernate.Session;
import org.hibernate.query.Query;
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.DashboardDto;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.dto.process.AuditStatusGraphResponseDto;
import com.bankaudit.dto.process.BranchPerformanceBUResponse;
import com.bankaudit.dto.process.BranchPerformanceResponseDto;
import com.bankaudit.dto.process.PlanCalendarResponseDto;
import com.bankaudit.dto.process.RatingTrendDto;
import com.bankaudit.dto.process.RatingVarianceGraphResponseDto;
import com.bankaudit.dto.process.RealTimeRectificationResponseDto;
import com.bankaudit.dto.process.ScheduleVarianceGraphResponseDto;
import com.bankaudit.dto.process.UnitBreakUpResponseDto;
import com.bankaudit.model.MaintUsergroupRoles;
import com.bankaudit.model.User;
import com.bankaudit.process.model.AuditReportDynamicTable;
import com.bankaudit.process.model.AuditSchedule;
import com.bankaudit.process.model.AuditTeam;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.MaintEntityService;
import com.bankaudit.util.BankAuditUtil;

@Repository
public class DashboardDaoImpl extends AbstractDao implements DashboardDao {
	
	/*actual_start_date*/
	
	@Autowired
	BusinessDateService businessDateService;
	
	@Lazy
	@Autowired
	DashboardDao dashboardDao;
	
	@Autowired
	MaintEntityService maintEntityService;
	
	static final Logger logger = Logger.getLogger(DashboardDaoImpl.class);

	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<AuditStatusGraphResponseDto> getAuditStatusQuarterly(Integer legalEntityCode, String auditType,
			String unitType, String criticality, String userId, Date businessDate,String role,List<String> unitList) {
		
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDate);
		Integer year=null;
		
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		Integer currentYear=year;
		Integer previousYear=currentYear-1;
		
	/*	LocalDate previousFinancialYearStartDate=LocalDate.of(previousYear, 04, 1);*/
	    /*	LocalDate currentFinancialYearEndDate=LocalDate.of(currentYear, 03, 31);*/
		
		/*PREVIOUS YEAR quarters */
		//LocalDate previousFinancialYearQ1StartDate = LocalDate.of(previousYear, 04, 1);
		
		LocalDate FinancialYearStartDate  = dashboardDao.getFinancialYearStartDate(legalEntityCode);
		logger.info("FinancialYearStartDate :: "+FinancialYearStartDate);
		
		LocalDate previousFinancialYearQ1StartDate = FinancialYearStartDate.minusMonths(12);
		LocalDate previousFinancialYearQ1EndDate = previousFinancialYearQ1StartDate.plusMonths(3).minusDays(1);

		LocalDate  previousFinancialYearQ2StartDate =previousFinancialYearQ1EndDate.plusDays(1);
		LocalDate  previousFinancialYearQ2EndDate = previousFinancialYearQ2StartDate.plusMonths(3).minusDays(1);


		LocalDate  previousFinancialYearQ3StartDate =previousFinancialYearQ2EndDate.plusDays(1);
		LocalDate  previousFinancialYearQ3EndDate = previousFinancialYearQ3StartDate.plusMonths(3).minusDays(1);

		
		LocalDate  previousFinancialYearQ4StartDate =previousFinancialYearQ3EndDate.plusDays(1);
		LocalDate  previousFinancialYearQ4EndDate = previousFinancialYearQ4StartDate.plusMonths(3).minusDays(1);

       /*CURRENT YEAR quarters*/
		
		LocalDate nextFinancialYearQ1StartDate = previousFinancialYearQ4EndDate.plusDays(1);
		LocalDate nextFinancialYearQ1EndDate = nextFinancialYearQ1StartDate.plusMonths(3).minusDays(1);

		LocalDate  nextFinancialYearQ2StartDate =nextFinancialYearQ1EndDate.plusDays(1);
		LocalDate  nextFinancialYearQ2EndDate = nextFinancialYearQ2StartDate.plusMonths(3).minusDays(1);


		LocalDate  nextFinancialYearQ3StartDate =nextFinancialYearQ2EndDate.plusDays(1);
		LocalDate  nextFinancialYearQ3EndDate = nextFinancialYearQ3StartDate.plusMonths(3).minusDays(1);

		
		LocalDate  nextFinancialYearQ4StartDate =nextFinancialYearQ3EndDate.plusDays(1);
		LocalDate  nextFinancialYearQ4EndDate = nextFinancialYearQ4StartDate.plusMonths(3).minusDays(1);
		
		
		
		
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		System.out.println("Inside getAuditStatusQuarterly.... userId "+userId );
		System.out.println(" PQ1Strt:: "+ previousFinancialYearQ1StartDate +" PQ1End:: "+previousFinancialYearQ1EndDate);
		System.out.println(" PQ2Strt:: "+ previousFinancialYearQ2StartDate +" PQ2End:: "+previousFinancialYearQ2EndDate);
		System.out.println(" PQ3Strt:: "+ previousFinancialYearQ3StartDate +" PQ3End:: "+previousFinancialYearQ3EndDate);
		System.out.println(" PQ4Strt:: "+ previousFinancialYearQ4StartDate +" PQ4End:: "+previousFinancialYearQ4EndDate);
		System.out.println(" CQ3Strt:: "+ nextFinancialYearQ1StartDate +" CQ1End:: "+nextFinancialYearQ1EndDate);
		System.out.println(" CQ2Strt:: "+ nextFinancialYearQ2StartDate +" CQ2End:: "+nextFinancialYearQ2EndDate);
		System.out.println(" CQ3Strt:: "+ nextFinancialYearQ3StartDate +" CQ3End:: "+nextFinancialYearQ3EndDate);
		System.out.println(" CQ3Strt:: "+ nextFinancialYearQ4StartDate +" CQ3End:: "+nextFinancialYearQ4EndDate);
		
		StringBuilder query= new StringBuilder(
				" SELECT COUNT(aus.audit_status) AS audit_count , " 
						 + "   (CASE WHEN aus.audit_status = 'AP' THEN 'planned' " 
						 + "         WHEN aus.audit_status = 'AI' THEN 'initiated' " 
						 + "		 WHEN aus.audit_status = 'AS' THEN 'submitted' " 
						 + "         WHEN aus.audit_status = 'AR' THEN 'responded' " 
						 + "            ELSE 'closed' " 
						 + "    END)  AS audit_status, "
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearQ1StartDate AND DATE(aus.schedule_start_date) <=:previousFinancialYearQ1EndDate  THEN 'PREV_Q1' ELSE  " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearQ2StartDate AND DATE(aus.schedule_start_date) <=:previousFinancialYearQ2EndDate THEN 'PREV_Q2' ELSE  " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearQ3StartDate  AND DATE(aus.schedule_start_date) <=:previousFinancialYearQ3EndDate THEN 'PREV_Q3' ELSE  " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearQ4StartDate  AND DATE(aus.schedule_start_date) <=:previousFinancialYearQ4EndDate THEN 'PREV_Q4' ELSE  " 
						 + "    " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearQ1StartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearQ1EndDate  THEN 'CUR_Q1' ELSE  " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearQ2StartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearQ2EndDate THEN 'CUR_Q2' ELSE  " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearQ3StartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearQ3EndDate THEN 'CUR_Q3' ELSE  " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearQ4StartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearQ4EndDate THEN 'CUR_Q4' " 
						 + "    END) " 
						 + "    END)   " 
						 + "    END)   " 
						 + "    END) " 
						 + "    END) " 
						 + "    END)   " 
						 + "    END)   " 
						 + "    END) AS ytd " 
						 + "   FROM audit_schedule AS aus ,maint_entity AS me " 
						 + "   WHERE  " 
						 + "   aus.legal_entity_code=me.legal_entity_code " 
						 + "   AND aus.unit_id=me.unit_code   " 
						 
						 + "   AND aus.legal_entity_code =:legalEntityCode " 
						 + "   AND aus.audit_status IN ('AI','AP' ,'AS','AR','AW','AC','AF')  " 
						 + "   AND DATE(aus.schedule_start_date) BETWEEN :previousFinancialYearQ1StartDate AND :nextFinancialYearQ4EndDate "
				)  ;
		// based on role 
		if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){   // MGMNT modified to SM & Operations also included
			query.append(" AND aus.unit_id in (:unitList) ");
		}else{
			query.append( "    AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					  +"    aus.legal_entity_code=aut.legal_entity_code "
					  +"    AND aus.audit_type_code=aut.audit_type_code "
					  +"    AND aus.plan_id=aut.plan_id "
					  +"    AND aus.audit_id=aut.audit_id "
					  +"    AND aut.user_id =:userId    "
					  +"    ) ");
			          
		}
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
        query.append(
				   "   GROUP BY   "
				 + "   (CASE WHEN aus.audit_status = 'AP' THEN 'planned' " 
				 + "         WHEN aus.audit_status = 'AI' THEN 'initiated' " 
				 + "		 WHEN aus.audit_status = 'AS' THEN 'submitted' " 
				 + "         WHEN aus.audit_status = 'AR' THEN 'responded' " 
				 + "            ELSE 'closed' " 
				 + "    END), "  
				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearQ1StartDate AND DATE(aus.schedule_start_date) <=:previousFinancialYearQ1EndDate  THEN 'PREV_Q1' ELSE  " 
				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearQ2StartDate AND DATE(aus.schedule_start_date) <=:previousFinancialYearQ2EndDate THEN 'PREV_Q2' ELSE  " 
				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearQ3StartDate  AND DATE(aus.schedule_start_date) <=:previousFinancialYearQ3EndDate THEN 'PREV_Q3' ELSE  " 
				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearQ4StartDate  AND DATE(aus.schedule_start_date) <=:previousFinancialYearQ4EndDate THEN 'PREV_Q4' ELSE  " 
				 + "    " 
				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearQ1StartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearQ1EndDate  THEN 'CUR_Q1' ELSE  " 
				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearQ2StartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearQ2EndDate THEN 'CUR_Q2' ELSE  " 
				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearQ3StartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearQ3EndDate THEN 'CUR_Q3' ELSE  " 
				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearQ4StartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearQ4EndDate THEN 'CUR_Q4' " 
				 + "    END) " 
				 + "    END)   " 
				 + "    END)   " 
				 + "    END) " 
				 + "    END) " 
				 + "    END)   " 
				 + "    END)   " 
				 + "    END)  " 
        		);
        
		
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("previousFinancialYearQ1StartDate", previousFinancialYearQ1StartDate)
		.setParameter("previousFinancialYearQ2StartDate", previousFinancialYearQ2StartDate)
		.setParameter("previousFinancialYearQ3StartDate", previousFinancialYearQ3StartDate)
		.setParameter("previousFinancialYearQ4StartDate", previousFinancialYearQ4StartDate)
		.setParameter("previousFinancialYearQ1EndDate", previousFinancialYearQ1EndDate)
		.setParameter("previousFinancialYearQ2EndDate", previousFinancialYearQ2EndDate)
		.setParameter("previousFinancialYearQ3EndDate", previousFinancialYearQ3EndDate)
		.setParameter("previousFinancialYearQ4EndDate", previousFinancialYearQ4EndDate)
		
		.setParameter("nextFinancialYearQ1StartDate",nextFinancialYearQ1StartDate)
		.setParameter("nextFinancialYearQ2StartDate",nextFinancialYearQ2StartDate)
		.setParameter("nextFinancialYearQ3StartDate",nextFinancialYearQ3StartDate)
		.setParameter("nextFinancialYearQ4StartDate",nextFinancialYearQ4StartDate)
		.setParameter("nextFinancialYearQ1EndDate", nextFinancialYearQ1EndDate)
		.setParameter("nextFinancialYearQ2EndDate", nextFinancialYearQ2EndDate)
		.setParameter("nextFinancialYearQ3EndDate", nextFinancialYearQ3EndDate)
		.setParameter("nextFinancialYearQ4EndDate", nextFinancialYearQ4EndDate)

		.setParameter("legalEntityCode", legalEntityCode);
	
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}
	 
        if(role.equalsIgnoreCase("RVWR") ||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){ // Operation role also included
        	if(unitList.isEmpty()){
				unitList.add("");
			}
        	hqlQuery.setParameterList("unitList",unitList);
		}else{
			hqlQuery.setParameter("userId",userId);
			          
		}
        
        Map<String,String> map = new HashMap<>();
		List lst= hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=null; 
				if(tuple!=null){
					auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
					if(tuple[0]!=null){
						auditStatusGraphResponseDto.setCount(Long.parseLong(tuple[0].toString()));
					}
					if(tuple[1]!=null){
						auditStatusGraphResponseDto.setAuditStatus(tuple[1].toString());						
		            }
					if(tuple[2]!=null){
						auditStatusGraphResponseDto.setYtd(tuple[2].toString());
						map.put(tuple[2].toString(), tuple[1].toString()); // To collect all Quarters having values
					}
					
				}
				
				return auditStatusGraphResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
		System.out.println("retreieved QRTRLY map .... "+ map);
		//System.out.println("lst bfr .... "+ lst.size());
		
		//Logic to Check and append the missing Quarters
		String[] qtrArry= {"PREV_Q1","PREV_Q2","PREV_Q3","PREV_Q4","CUR_Q1","CUR_Q2","CUR_Q3","CUR_Q4"};
		try {
		for(String qtr:qtrArry)
			if(!map.containsKey(qtr)) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
				auditStatusGraphResponseDto.setYtd(qtr);
				auditStatusGraphResponseDto.setAuditStatus("total");
				auditStatusGraphResponseDto.setCount(0l);
				lst.add(auditStatusGraphResponseDto);
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		//ends here
		
		//System.out.println("lst aftr .... "+ lst.size());
		return lst;
	}

	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<AuditStatusGraphResponseDto> getAuditStatusHalfYearly(Integer legalEntityCode, String auditType,
			String unitType, String criticality, String userId, Date businessDate,String role,List<String> unitList) {
		
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDate);
		
		Integer year=null;
		
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		Integer currentYear=year;
		Integer previousYear=currentYear-1;
		
		/*PREVIOUS YEAR half year dates */
        //LocalDate previousFinancialYearFirstHalfStartDate = LocalDate.of(previousYear, 04, 1);
		
		LocalDate FinancialYearStartDate  = dashboardDao.getFinancialYearStartDate(legalEntityCode);
		logger.info("FinancialYearStartDate :: "+FinancialYearStartDate);
		
		LocalDate previousFinancialYearFirstHalfStartDate = FinancialYearStartDate.minusMonths(12);
		LocalDate previousFinancialYearFirstHalfEndDate = previousFinancialYearFirstHalfStartDate.plusMonths(6).minusDays(1);

		LocalDate  previousFinancialYearSecondtHalfStartDate =previousFinancialYearFirstHalfEndDate.plusDays(1);
		LocalDate  previousFinancialYearSecondtHalfEndDate = previousFinancialYearSecondtHalfStartDate.plusMonths(6).minusDays(1);


		/*CURRENT YEAR quarters*/
		LocalDate nextFinancialYearFirstHalfStartDate = previousFinancialYearSecondtHalfEndDate.plusDays(1);
		LocalDate nextFinancialYearFirstHalfEndDate = nextFinancialYearFirstHalfStartDate.plusMonths(6).minusDays(1);

		LocalDate  nextFinancialYearSecondtHalfStartDate =nextFinancialYearFirstHalfEndDate.plusDays(1);
		LocalDate  nextFinancialYearSecondtHalfEndDate = nextFinancialYearSecondtHalfStartDate.plusMonths(6).minusDays(1);
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);			
		StringBuilder query= new StringBuilder(
				" SELECT COUNT(aus.audit_status) AS audit_count , " 
						 + "   (CASE WHEN aus.audit_status = 'AP' THEN 'planned' " 
						 + "         WHEN aus.audit_status = 'AI' THEN 'initiated' " 
						 + "		 WHEN aus.audit_status = 'AS' THEN 'submitted' " 
						 + "         WHEN aus.audit_status = 'AR' THEN 'responded' " 
						 + "            ELSE 'closed' " 
						 + "    END)  AS audit_status, "
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearFirstHalfStartDate AND DATE(aus.schedule_start_date) <=:previousFinancialYearFirstHalfEndDate  THEN 'PREV_FIRST_HF' ELSE  " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearSecondtHalfStartDate AND DATE(aus.schedule_start_date) <=:previousFinancialYearSecondtHalfEndDate THEN 'PREV_SECOND_HF' ELSE  " 
						
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearFirstHalfStartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearFirstHalfEndDate  THEN 'CUR_FIRST_HF' ELSE  " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearSecondtHalfStartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearSecondtHalfEndDate THEN 'CUR_SECOND_HF'  "  
						 + "    END) " 
						 + "    END)   " 
						 + "    END)   " 
						 + "    END) AS ytd " 
						 + "   FROM audit_schedule AS aus ,maint_entity AS me " 
						 + "   WHERE  " 
						 + "   aus.legal_entity_code=me.legal_entity_code " 
						 + "   AND aus.unit_id=me.unit_code   " 
						 
						
						 
						 + "   AND aus.legal_entity_code =:legalEntityCode " 
						 + "   AND aus.audit_status IN ('AI','AP' ,'AS','AR','AW','AC','AF')  " 
						 + "   AND DATE(aus.schedule_start_date) BETWEEN :previousFinancialYearFirstHalfStartDate AND :nextFinancialYearSecondtHalfEndDate "
				)  ;
		
		// based on role 
		if(role.equalsIgnoreCase("RVWR") ||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS") ){ // Operation role also included.
			query.append(" AND aus.unit_id in (:unitList) ");
		}else{
			query.append( "    AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					  +"    aus.legal_entity_code=aut.legal_entity_code "
					  +"    AND aus.audit_type_code=aut.audit_type_code "
					  +"    AND aus.plan_id=aut.plan_id "
					  +"    AND aus.audit_id=aut.audit_id "
					  +"    AND aut.user_id =:userId    "
					  +"    ) ");
			          
		}
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
        query.append(
				   "   GROUP BY " 
						   + "   (CASE WHEN aus.audit_status = 'AP' THEN 'planned' " 
							 + "         WHEN aus.audit_status = 'AI' THEN 'initiated' " 
							 + "		 WHEN aus.audit_status = 'AS' THEN 'submitted' " 
							 + "         WHEN aus.audit_status = 'AR' THEN 'responded' " 
							 + "            ELSE 'closed' " 
							 + "    END)  , "
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearFirstHalfStartDate AND DATE(aus.schedule_start_date) <=:previousFinancialYearFirstHalfEndDate  THEN 'PREV_FIRST_HF' ELSE  " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearSecondtHalfStartDate AND DATE(aus.schedule_start_date) <=:previousFinancialYearSecondtHalfEndDate THEN 'PREV_SECOND_HF' ELSE  " 
						
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearFirstHalfStartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearFirstHalfEndDate  THEN 'CUR_FIRST_HF' ELSE  " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearSecondtHalfStartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearSecondtHalfEndDate THEN 'CUR_SECOND_HF'  "  
						 + "    END) " 
						 + "    END)   " 
						 + "    END)   " 
						 + "    END)  "  
        		);
        
		
		 Query hqlQuery=session.createNativeQuery(query.toString())
		.setParameter("previousFinancialYearFirstHalfStartDate", previousFinancialYearFirstHalfStartDate)
		.setParameter("previousFinancialYearSecondtHalfStartDate", previousFinancialYearSecondtHalfStartDate)
		
		.setParameter("previousFinancialYearFirstHalfEndDate", previousFinancialYearFirstHalfEndDate)
		.setParameter("previousFinancialYearSecondtHalfEndDate", previousFinancialYearSecondtHalfEndDate)
		
		.setParameter("nextFinancialYearFirstHalfStartDate",nextFinancialYearFirstHalfStartDate)
		.setParameter("nextFinancialYearSecondtHalfStartDate",nextFinancialYearSecondtHalfStartDate)
		
		.setParameter("nextFinancialYearFirstHalfEndDate",nextFinancialYearFirstHalfEndDate)
		.setParameter("nextFinancialYearSecondtHalfEndDate",nextFinancialYearSecondtHalfEndDate)
		
		.setParameter("legalEntityCode", legalEntityCode);
		 
			if(!BankAuditUtil.isEmptyString(auditType)){
				hqlQuery.setParameter("auditType", auditType);
			}
			
			if(!BankAuditUtil.isEmptyString(unitType)){
				hqlQuery.setParameter("unitType", unitType);
			}
			
	        if(!BankAuditUtil.isEmptyString(criticality)){
	        	hqlQuery.setParameter("criticality", criticality);
			}
	        if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){ 
	        	if(unitList.isEmpty()){
					unitList.add("");
				}
	        	hqlQuery.setParameterList("unitList",unitList);
			}else{
				hqlQuery.setParameter("userId",userId);
				          
			}
	        
		 
	        Map<String,String> map = new HashMap<>();
			List lst= hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=null; 
				if(tuple!=null){
					auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
					if(tuple[0]!=null){
						auditStatusGraphResponseDto.setCount(Long.parseLong(tuple[0].toString()));
					}
					if(tuple[1]!=null){
						auditStatusGraphResponseDto.setAuditStatus(tuple[1].toString());						
		            }
					if(tuple[2]!=null){
						auditStatusGraphResponseDto.setYtd(tuple[2].toString());
						map.put(tuple[2].toString(), tuple[1].toString()); // To collect all HalfYearly having values
					}
					
				}
				
				return auditStatusGraphResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
		//Logic to Check and append the missing HalfYears
				String[] hlfYrArry= {"PREV_FIRST_HF","PREV_SECOND_HF","CUR_FIRST_HF","CUR_SECOND_HF"};
				try {
				for(String hlfYr:hlfYrArry)
					if(!map.containsKey(hlfYr)) {
						AuditStatusGraphResponseDto auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
						auditStatusGraphResponseDto.setYtd(hlfYr);
						auditStatusGraphResponseDto.setAuditStatus("total");
						auditStatusGraphResponseDto.setCount(0l);
						lst.add(auditStatusGraphResponseDto);
					}
				}catch(Exception e) {
					e.printStackTrace(System.out);
				}
				//ends here
				
		return lst;
		
	}
	
	
	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<AuditStatusGraphResponseDto> getAuditStatusYearly(Integer legalEntityCode, String auditType,
			String unitType, String criticality, String userId, Date businessDate,String role,List<String> unitList) {
		
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDate);
		Integer year=null;
		
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		Integer currentYear=year;
		Integer previousYear=currentYear-1;
		
		/*PREVIOUS YEAR  dates */
        //LocalDate previousFinancialYearStartDate = LocalDate.of(previousYear, 04, 1);
		
		LocalDate FinancialYearStartDate  = dashboardDao.getFinancialYearStartDate(legalEntityCode);
		logger.info("FinancialYearStartDate :: "+FinancialYearStartDate);
		
		LocalDate previousFinancialYearStartDate = FinancialYearStartDate.minusMonths(12);
		LocalDate previousFinancialYearEndDate = previousFinancialYearStartDate.plusMonths(12).minusDays(1);

       /*CURRENT YEAR dates*/
		
		LocalDate nextFinancialYearStartDate = previousFinancialYearEndDate.plusDays(1);
		LocalDate nextFinancialYearEndDate = nextFinancialYearStartDate.plusMonths(12).minusDays(1);
		
		logger.info("previousFinancialYearStartDate ...."+previousFinancialYearStartDate+" previousFinancialYearEndDate ...."+previousFinancialYearEndDate);
		logger.info("nextFinancialYearStartDate ...."+nextFinancialYearStartDate+" nextFinancialYearEndDate ...."+nextFinancialYearEndDate);
		logger.info("unitList .... "+ unitList);
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);			
		StringBuilder query= new StringBuilder(
				" SELECT COUNT(aus.audit_status) AS audit_count , " 
						 + "   (CASE WHEN aus.audit_status = 'AP' THEN 'planned' " 
						 + "         WHEN aus.audit_status = 'AI' THEN 'initiated' " 
						 + "		 WHEN aus.audit_status = 'AS' THEN 'submitted' " 
						 + "         WHEN aus.audit_status = 'AR' THEN 'responded' " 
						 + "            ELSE 'closed' " 
						 + "    END)  AS audit_status, "					
        				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearStartDate AND DATE(aus.schedule_start_date) <=:previousFinancialYearEndDate  THEN 'PREV_YEAR' ELSE  " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearStartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearEndDate  THEN 'CUR_YEAR'  " 
						 + "    END)   " 
						 + "    END) AS ytd " 
						 + "   FROM audit_schedule AS aus ,maint_entity AS me " 
						 + "   WHERE  " 
						 + "   aus.legal_entity_code=me.legal_entity_code " 
						 + "   AND aus.unit_id=me.unit_code   " 
						 
						
						 
						 + "   AND aus.legal_entity_code =:legalEntityCode " 
						 + "   AND aus.audit_status IN ('AI','AP' ,'AS','AR','AW','AC','AF')  " 
						 + "   AND DATE(aus.schedule_start_date) BETWEEN :previousFinancialYearStartDate AND :nextFinancialYearEndDate "
				)  ;
		
		// based on role 
		if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			query.append(" AND aus.unit_id in (:unitList) ");
		}else{
			query.append( "    AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					  +"    aus.legal_entity_code=aut.legal_entity_code "
					  +"    AND aus.audit_type_code=aut.audit_type_code "
					  +"    AND aus.plan_id=aut.plan_id "
					  +"    AND aus.audit_id=aut.audit_id "
					  +"    AND aut.user_id =:userId    "
					  +"    ) ");
			          
		}
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
        query.append(
				   "   GROUP BY   "
						   + "   (CASE WHEN aus.audit_status = 'AP' THEN 'planned' " 
							 + "         WHEN aus.audit_status = 'AI' THEN 'initiated' " 
							 + "		 WHEN aus.audit_status = 'AS' THEN 'submitted' " 
							 + "         WHEN aus.audit_status = 'AR' THEN 'responded' " 
							 + "            ELSE 'closed' " 
							 + "    END)  , "
				         + "   (CASE WHEN DATE(aus.schedule_start_date) >=:previousFinancialYearStartDate AND DATE(aus.schedule_start_date) <=:previousFinancialYearEndDate  THEN 'PREV_YEAR' ELSE  " 
						 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:nextFinancialYearStartDate AND DATE(aus.schedule_start_date) <=:nextFinancialYearEndDate  THEN 'CUR_YEAR'  " 
						 + "    END)   " 
						 + "    END) "  
        		);
        
		
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("previousFinancialYearStartDate", previousFinancialYearStartDate)
		.setParameter("previousFinancialYearEndDate", previousFinancialYearEndDate)
		
		.setParameter("nextFinancialYearStartDate", nextFinancialYearStartDate)
		.setParameter("nextFinancialYearEndDate", nextFinancialYearEndDate)
		
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}
        if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
        	if(unitList.isEmpty()){
				unitList.add("");
			}
        	hqlQuery.setParameterList("unitList",unitList);
		}else{
			hqlQuery.setParameter("userId",userId);
			          
		}
        
	 
        Map<String,String> map = new HashMap<>();
		List lst=hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=null; 
				if(tuple!=null){
					auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
					if(tuple[0]!=null){
						auditStatusGraphResponseDto.setCount(Long.parseLong(tuple[0].toString()));
					}
					if(tuple[1]!=null){
						auditStatusGraphResponseDto.setAuditStatus(tuple[1].toString());						
		            }
					if(tuple[2]!=null){
						auditStatusGraphResponseDto.setYtd(tuple[2].toString());
						map.put(tuple[2].toString(), tuple[1].toString()); // To collect all Yearly having values
					}
					
				}
				
				return auditStatusGraphResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
	  //Logic to Check and append the missing Years
		String[] yearlyArr= {"PREV_YEAR","CUR_YEAR"};
		try {
		for(String yearly:yearlyArr)
			if(!map.containsKey(yearly)) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
				auditStatusGraphResponseDto.setYtd(yearly);
				auditStatusGraphResponseDto.setAuditStatus("total");
				auditStatusGraphResponseDto.setCount(0l);
				lst.add(auditStatusGraphResponseDto);
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		//ends here
		
		return lst;
		
	}

	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<AuditStatusGraphResponseDto> getAuditStatusByRange(Integer legalEntityCode, String auditType,
			String unitType, String criticality, String userId, LocalDate fromDate, LocalDate toDate,String role,List<String> unitList) {
		
		
		
		/*PREVIOUS YEAR  dates 
        LocalDate previousFinancialYearStartDate = LocalDate.of(2014, 04, 1);
		LocalDate previousFinancialYearEndDate = previousFinancialYearStartDate.plusMonths(12).minusDays(1);

       CURRENT YEAR dates
		
		LocalDate nextFinancialYearStartDate = previousFinancialYearEndDate.plusDays(1);
		LocalDate nextFinancialYearEndDate = nextFinancialYearStartDate.plusMonths(12).minusDays(1);*/
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);			
		StringBuilder query= new StringBuilder(
				" SELECT COUNT(aus.audit_status) AS audit_count , " 
						 + "   (CASE WHEN aus.audit_status = 'AP' THEN 'planned' " 
						 + "         WHEN aus.audit_status = 'AI' THEN 'initiated' " 
						 + "		 WHEN aus.audit_status = 'AS' THEN 'submitted' " 
						 + "         WHEN aus.audit_status = 'AR' THEN 'responded' " 
						 + "            ELSE 'closed' " 
						 + "    END)  AS audit_status, "					
        				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:fromDate AND DATE(aus.schedule_start_date) <=:toDate  THEN 'range'   " 
						 + "    END) AS ytd " 
						 + "   FROM audit_schedule AS aus ,maint_entity AS me " 
						 + "   WHERE  " 
						 + "   aus.legal_entity_code=me.legal_entity_code " 
						 + "   AND aus.unit_id=me.unit_code   " 
						 
					
						 
						 + "   AND aus.legal_entity_code =:legalEntityCode " 
						 + "   AND aus.audit_status IN ('AI','AP' ,'AS','AR','AW','AC','AF')  " 
						 + "   AND DATE(aus.schedule_start_date) BETWEEN :fromDate AND :toDate "
				)  ;
		// based on role 
		if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			query.append(" AND aus.unit_id in (:unitList) ");
		}else{
			query.append( "    AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					  +"    aus.legal_entity_code=aut.legal_entity_code "
					  +"    AND aus.audit_type_code=aut.audit_type_code "
					  +"    AND aus.plan_id=aut.plan_id "
					  +"    AND aus.audit_id=aut.audit_id "
					  +"    AND aut.user_id =:userId    "
					  +"    ) ");
			          
		}
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
        query.append(
				   "   GROUP BY  " 
						   + "   (CASE WHEN aus.audit_status = 'AP' THEN 'planned' " 
							 + "         WHEN aus.audit_status = 'AI' THEN 'initiated' " 
							 + "		 WHEN aus.audit_status = 'AS' THEN 'submitted' " 
							 + "         WHEN aus.audit_status = 'AR' THEN 'responded' " 
							 + "            ELSE 'closed' " 
							 + "    END) , "
				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:fromDate AND DATE(aus.schedule_start_date) <=:toDate  THEN 'range'   " 
				 + "    END)  " 
        		);
        
		
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("fromDate", fromDate)
		.setParameter("toDate", toDate)
	
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}
        if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
        	if(unitList.isEmpty()){
				unitList.add("");
			}
        	hqlQuery.setParameterList("unitList",unitList);
		}else{
			hqlQuery.setParameter("userId",userId);
			          
		}
        
	return hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=null; 
				if(tuple!=null){
					auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
					if(tuple[0]!=null){
						auditStatusGraphResponseDto.setCount(Long.parseLong(tuple[0].toString()));
					}
					if(tuple[1]!=null){
						auditStatusGraphResponseDto.setAuditStatus(tuple[1].toString());						
		            }
					if(tuple[2]!=null){
						auditStatusGraphResponseDto.setYtd(tuple[2].toString());
					}
					
				}
				
				return auditStatusGraphResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
		
	}

	@Override
	public DataTableResponse getAuditSchedules(int legalEntityCode, String userId, String search, Integer orderColumn,
			String orderDirection, Integer page, Integer size,  String role,List<String> unitList) {

		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());
				logger.info("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 ********************************/
			
		DataTableResponse dataTableResponse=new DataTableResponse();
		try {
		//StringBuilder queryString=new StringBuilder(" from AuditSchedule where legalEntityCode =:legalEntityCode ");
			
			StringBuilder queryString=new StringBuilder();
		if(role.equalsIgnoreCase("ADTR")){
			 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, "
					
					+ " (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, "
					+ " (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 "
					// + ",  concat(sch.assessedRating, (Select concat('-' , r.riskCategoryDesc) from  RiskScorePercentage r where r.legalEntityCode =sch.legalEntityCode and sch.auditTypeCode=r.auditTypeCode and sch.assessedRating=r.riskCategoryCode)) as assessedRating "
					+ " , (Select  r.riskCategoryDesc from  RiskScorePercentage r where r.legalEntityCode =sch.legalEntityCode and sch.auditTypeCode=r.auditTypeCode and sch.assessedRating=r.riskCategoryCode) as assessedRating " // Code with out description
					+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode "
					//+ " and sch.legalEntityCode=t.legalEntityCode and t.auditId=sch.auditId and t.userId=:userId"
					+ " and   IFNULL(auditStatus,'NotNull') in ('AP','AI','AS','AR','AW','AC') "
					+ " 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(role.equalsIgnoreCase("BU")||role.equalsIgnoreCase("BL")){
			 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, "
					
					+ " (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, "
					+ " (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 "
					//+ ",  concat(sch.assessedRating, (Select concat('-' , r.riskCategoryDesc) from  RiskScorePercentage r where r.legalEntityCode =sch.legalEntityCode and sch.auditTypeCode=r.auditTypeCode and sch.assessedRating=r.riskCategoryCode)) as assessedRating "
					+ " , (Select  r.riskCategoryDesc from  RiskScorePercentage r where r.legalEntityCode =sch.legalEntityCode and sch.auditTypeCode=r.auditTypeCode and sch.assessedRating=r.riskCategoryCode) as assessedRating " // Code with out description
					+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode "
					//+ " and sch.legalEntityCode=t.legalEntityCode and t.auditId=sch.auditId and t.userId=:userId"
					+ " and   IFNULL(auditStatus,'NotNull') in ('AI','AS','AR','AW','AC') "  // 'AP','AI'
					+ " and  sch.unitId IN (SELECT t.unitCode FROM User t WHERE  t.legalEntityCode =sch.legalEntityCode and t.userId=:userId  ) "
					);
		}else if(role.equalsIgnoreCase("RVWR")){
			 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, "
						
						+ " (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, "
						+ " (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 "
						//+ ",  concat(sch.assessedRating, (Select concat('-' , r.riskCategoryDesc) from  RiskScorePercentage r where r.legalEntityCode =sch.legalEntityCode and sch.auditTypeCode=r.auditTypeCode and sch.assessedRating=r.riskCategoryCode)) as assessedRating "
						+ " , (Select  r.riskCategoryDesc from  RiskScorePercentage r where r.legalEntityCode =sch.legalEntityCode and sch.auditTypeCode=r.auditTypeCode and sch.assessedRating=r.riskCategoryCode) as assessedRating " // Code with out description
						+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode "
						//+ " and sch.legalEntityCode=t.legalEntityCode and t.auditId=sch.auditId and t.userId=:userId"
						+ " and   IFNULL(auditStatus,'NotNull') in ('AP','AI','AS','AR','AW','AC') "
						+ " and  sch.unitId IN (:unitList) "
						);
			}
		System.out.println("Before the qry....");
		
		/***** Removed the Filter criteria, as in Dashboard there is no search ***********/
		/*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",
				"unitType",
				"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"
		};

		
		queryString=queryString.append(" ORDER BY FIELD(sch.auditStatus, 'AI','AP','AS','AR','AW','AC') asc, sch.actualStartDate asc ");
		
		System.out.println("orderColumn .... "+ orderColumn +"  orderDirection ...."+ orderDirection );
		/*if(orderColumn!=null && !BankAuditUtil.isEmptyString(orderDirection)){
			queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection);
		}else {
			queryString=queryString.append(" ORDER BY FIELD(auditStatus, 'AP','AI') asc  ");
		}*/
		
		System.out.println("queryString .... "+ queryString.toString());
		
		@SuppressWarnings("deprecation")
		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");
								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.setAssessedRating(tuple[17].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());
							
							if(auditSchedule.getUnitHead() != null) {
								auditSchedule.setUnitHead(auditSchedule.getUnitHead()+"-"+userDtls.get(auditSchedule.getUnitHead()));
							}
							
							System.out.println("Unit Head ...."+auditSchedule.getUnitHead());
						}
						return auditSchedule;
					}
			@Override
			public List transformList(List collection) {
				return collection;
			}
		})		
				.setParameter("legalEntityCode",legalEntityCode)
				;

		/*if(!BankAuditUtil.isEmptyString(search)){
			query.setParameter("search", "%"+search+"%");
		}*/
		
		if(role.equalsIgnoreCase("RVWR")){
			if(unitList.isEmpty()){
				unitList.add("");
			}
			query.setParameterList("unitList",unitList);
		}else{
			query.setParameter("userId",userId);
		}
		
		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;
	
	}

	@SuppressWarnings({ "deprecation", "unchecked" })
	@Override
	public List<ScheduleVarianceGraphResponseDto> getScheduleVariance(int legalEntityCode, String auditType,
			String period, LocalDate fromDate, LocalDate toDate, String userId,String role,List<String> unitList,String unitType,String criticality) {
		
		Session session=getSession();
		
	    session.setDefaultReadOnly(true);
	    StringBuilder query= new StringBuilder(
			" SELECT   COUNT(unit_id) AS unitCount ,                                                                        "
			+" ( DATEDIFF(schedule_end_date,schedule_start_date )-DATEDIFF(actual_end_date, actual_start_date)) AS delay     "
			+"  FROM audit_schedule as aus  ,maint_entity AS me  WHERE                                                                                    "
			+"  audit_status in('AC','AS','AR','AW')                                                                         "
			+"  AND aus.legal_entity_code =:legalEntityCode   "                                                                   
			 + " And  aus.legal_entity_code=me.legal_entity_code " 
			 + "   AND aus.unit_id=me.unit_code   " 				                                                                                                             
				)  ;
		
		if(role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS") ){
			query.append(" AND aus.unit_id in (:unitList) ");
		}else{
			query.append( "    AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					  +"    aus.legal_entity_code=aut.legal_entity_code "
					  +"    AND aus.audit_type_code=aut.audit_type_code "
					  +"    AND aus.plan_id=aut.plan_id "
					  +"    AND aus.audit_id=aut.audit_id "
					  +"    AND aut.user_id =:userId    "
					  +"    ) ");
			          
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
        query.append(
        		"  AND actual_start_date BETWEEN :fromDate AND :toDate                                                     "
        				+"  GROUP BY                                                                                                     "
        				+"  DATEDIFF(schedule_end_date,schedule_start_date )-DATEDIFF( actual_end_date,actual_start_date)               "
 
        		);
        Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("fromDate", fromDate)
		.setParameter("toDate", toDate)
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			if(unitList.isEmpty()){
				unitList.add("");
			}
			hqlQuery.setParameterList("unitList",unitList);
		}else{
			hqlQuery.setParameter("userId",userId);
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}
	
	return hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				ScheduleVarianceGraphResponseDto scheduleVarianceGraphResponseDto=null;
				if(tuple!=null){
					scheduleVarianceGraphResponseDto=new  ScheduleVarianceGraphResponseDto();
					if(tuple[0]!=null){
						scheduleVarianceGraphResponseDto.setUnitCount(Integer.parseInt(tuple[0].toString()));
					}
					if(tuple[1]!=null){
						scheduleVarianceGraphResponseDto.setDelay(Integer.parseInt(tuple[1].toString()));			
		            }
					
					
				}
				
				return scheduleVarianceGraphResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
		
	}

	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<ScheduleVarianceGraphResponseDto> getScheduleDelay(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId,String role,List<String> unitList,String unitType,String criticality) {
		
		
		
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
				
		StringBuilder query= new StringBuilder(
				
				
			" SELECT   COUNT(unit_id) AS unitCount ,                                                                        "
			+" ( DATEDIFF(schedule_start_date,actual_start_date)) AS delay     "
			+"  FROM audit_schedule as aus  ,maint_entity AS me  WHERE                                                                                    "
			+"  audit_status in('AI','AC','AS','AR','AW')                                                                         "
			+"  AND aus.legal_entity_code =:legalEntityCode   "                                                                   
			 + " And   aus.legal_entity_code=me.legal_entity_code " 
			 + "   AND aus.unit_id=me.unit_code   " 
			
                                                           
							                                                                                                             
				)  ;
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
		if(role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			query.append(" AND aus.unit_id in (:unitList) ");
		}else{
			query.append( "   AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					  +"    aus.legal_entity_code=aut.legal_entity_code "
					  +"    AND aus.audit_type_code=aut.audit_type_code "
					  +"    AND aus.plan_id=aut.plan_id "
					  +"    AND aus.audit_id=aut.audit_id "
					  +"    AND aut.user_id =:userId    "
					  +"    ) ");
			          
		}
		
        query.append(
        		"  AND actual_start_date BETWEEN :fromDate AND :toDate    "
        				+"  GROUP BY "
        				+"  DATEDIFF(schedule_start_date,actual_start_date) "
 
        		);
        
		
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("fromDate", fromDate)
		.setParameter("toDate", toDate)
		
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			if(unitList.isEmpty()){
				unitList.add("");
			}
			hqlQuery.setParameterList("unitList",unitList);
		}else{
			hqlQuery.setParameter("userId",userId);
		}
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}
		
	
	return hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				ScheduleVarianceGraphResponseDto scheduleVarianceGraphResponseDto=null;
				if(tuple!=null){
					scheduleVarianceGraphResponseDto=new  ScheduleVarianceGraphResponseDto();
					if(tuple[0]!=null){
						scheduleVarianceGraphResponseDto.setUnitCount(Integer.parseInt(tuple[0].toString()));
					}
					if(tuple[1]!=null){
						scheduleVarianceGraphResponseDto.setDelay(Integer.parseInt(tuple[1].toString()));			
		            }
					
					
				}
				
				return scheduleVarianceGraphResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
		
	}

	//New method getRealTimeRectification implemented for the same
	@SuppressWarnings({ "deprecation", "serial", "unchecked" })
	// @Override 
	public List<RealTimeRectificationResponseDto> getRealTimeRectificationOld(int legalEntityCode, String auditType,
			String period, LocalDate fromDate, LocalDate toDate, String userId,String role,List<String> unitList,String unitType,String criticality) {
		
		
		//Code by Debasish to handle default AuditType code // need to comment
		if(auditType != null && !auditType.trim().equals("") );
		else auditType="AT001";
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
				
		StringBuilder query= new StringBuilder(
				
				
			" SELECT   COUNT(unit_id) AS unitCount ,                                                                        "
					 +"   (CASE WHEN (100*`rectified_findings`)/`total_findings`>=0  AND (100*`rectified_findings`)/`total_findings`<20  THEN '0-20' ELSE  "  
					 +"   (CASE WHEN (100*`rectified_findings`)/`total_findings`>=20 AND (100*`rectified_findings`)/`total_findings`<40 THEN '20-40' ELSE  "  
					 +"   (CASE WHEN (100*`rectified_findings`)/`total_findings`>=40 AND (100*`rectified_findings`)/`total_findings`<60 THEN '40-60' ELSE  "  
					 +"   (CASE WHEN (100*`rectified_findings`)/`total_findings`>=60 AND (100*`rectified_findings`)/`total_findings`<80 THEN '60-80' ELSE  "  
					 +"   (CASE WHEN (100*`rectified_findings`)/`total_findings`>=80 AND (100*`rectified_findings`)/`total_findings`<=100 THEN '80-100'   "  
					 +"     "  
					 +"     END)      "  
					 +"     END)  "  
					 +"     END)  "  
					 +"     END)     "  
					 +"     END) AS audit_range,  "  
					 + " (select concat(rsp.risk_category_code , '-' , rsp.risk_category_desc) from risk_score_percentage rsp where "
					 + "  rsp.risk_category_code=aus.assessed_rating "
					 + " and rsp.audit_type_code=aus.audit_type_code "
					 + " and rsp.legal_entity_code=aus.legal_entity_code ) as assessed_rating  " 
				
					 +"       "  
					
				
				
			+"  FROM audit_schedule as aus  ,maint_entity AS me  WHERE                                                                                    "
			+"  audit_status in('AC','AS','AR','AW')                                                                         "
			+"  AND aus.legal_entity_code =:legalEntityCode "
			+ " AND aus.rectified_findings IS NOT NULL  "    
			+ " AND aus.total_findings IS NOT NULL  "    
			 + " and  aus.legal_entity_code=me.legal_entity_code " 
			 + "   AND aus.unit_id=me.unit_code   " 
			                                  
							                                                                                                             
				)  ;
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
		if(role.equalsIgnoreCase("ADTR")){
			query.append(" AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					 +"    aus.legal_entity_code=aut.legal_entity_code "
					 +"    AND aus.audit_type_code=aut.audit_type_code "
					 +"    AND aus.plan_id=aut.plan_id "
					 +"    AND aus.audit_id=aut.audit_id "
					 +"    AND aut.user_id =:userId    "
					 +"    ) ");
		}else if(role.equalsIgnoreCase("BU")||role.equalsIgnoreCase("BL")){
			query.append(" and  aus.unit_id IN (SELECT t.unit_code FROM user t WHERE "
					+ " t.legal_entity_code =aus.legal_entity_code "
					+ " and t.user_id=:userId  ) ");
		}else if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM")){
			query.append(" and  aus.unit_id IN (:unitList) ");
		}
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
        query.append(
        		"  AND actual_start_date BETWEEN :fromDate AND :toDate                                                     "
        				+"  GROUP BY                                                                                                     "
        				 +"   (CASE WHEN (100*`rectified_findings`)/`total_findings`>=0  AND (100*`rectified_findings`)/`total_findings`<20  THEN '0-20' ELSE  "  
    					 +"   (CASE WHEN (100*`rectified_findings`)/`total_findings`>=20 AND (100*`rectified_findings`)/`total_findings`<40 THEN '20-40' ELSE  "  
    					 +"   (CASE WHEN (100*`rectified_findings`)/`total_findings`>=40 AND (100*`rectified_findings`)/`total_findings`<60 THEN '40-60' ELSE  "  
    					 +"   (CASE WHEN (100*`rectified_findings`)/`total_findings`>=60 AND (100*`rectified_findings`)/`total_findings`<80 THEN '60-80' ELSE  "  
    					 +"   (CASE WHEN (100*`rectified_findings`)/`total_findings`>=80 AND (100*`rectified_findings`)/`total_findings`<=100 THEN '80-100'  "  
    					 +"     "  
    					 +"     END)      "  
    					 +"     END)  "  
    					 +"     END)  "  
    					 +"     END)     "  
    					 +"     END), "
    					 + " assessed_rating order by audit_range,assessed_rating "  
 
        		);
        
		
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("fromDate", fromDate)
		.setParameter("toDate", toDate)
		
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(role.equalsIgnoreCase("ADTR")){
			hqlQuery.setParameter("userId",userId);
		}else if(role.equalsIgnoreCase("BU")||role.equalsIgnoreCase("BL")){
			hqlQuery.setParameter("userId",userId);
		}else if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM")){
			if(unitList.isEmpty()){
				unitList.add("");
			}
			hqlQuery.setParameterList("unitList", unitList);
		}
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}		
	return hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				RealTimeRectificationResponseDto realTimeRectificationResponseDto=null;
				if(tuple!=null){
					realTimeRectificationResponseDto=new  RealTimeRectificationResponseDto();
					if(tuple[0]!=null){
						realTimeRectificationResponseDto.setUnitCount(Integer.parseInt(tuple[0].toString()));
					}
					if(tuple[1]!=null){
						realTimeRectificationResponseDto.setAuditRange(tuple[1].toString());			
		            }
					
					if(tuple[2]!=null){
						realTimeRectificationResponseDto.setRating(tuple[2].toString());
					}
					
				}
				
				return realTimeRectificationResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
		
	}

	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<RatingVarianceGraphResponseDto> getRatingStatus(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId,String role,List<String> unitList,List<String> auditsList, String unitType,String criticality) {
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		StringBuilder query= new StringBuilder(
				          " SELECT  COUNT(aus.unit_id) ,"
				         +"  CONCAT(rsp.risk_category_code,'-',rsp.risk_category_desc) AS assessed_rating "  
						 +" FROM "
						 +"   risk_score_percentage AS rsp  "
						 +"   LEFT JOIN audit_schedule AS aus  "
						 +"     ON aus.legal_entity_code = rsp.legal_entity_code  "
						 +"     AND aus.audit_status IN ('AC', 'AS', 'AR', 'WS')  "
						 +"     AND aus.audit_type_code = rsp.audit_type_code "
						 +"     AND IFNULL(aus.assessed_risk_prcntg,100) > rsp.minimun_per AND IFNULL(aus.assessed_risk_prcntg,100) <= rsp.maximum_per " 
				);
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND aus.unit_id in (select unit_code from MaintEntity where legal_entity_code=aus.legal_entity_code "
					+ " and unit_type =:unitType  )  ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND aus.unit_id in (select unit_code from MaintEntity where legal_entity_code=aus.legal_entity_code "
					+ " and u_criticality =:criticality  )  ");
        	
		}
		
		if(role.equalsIgnoreCase("ADTR")){
			query.append(" AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					 +"    aus.legal_entity_code=aut.legal_entity_code "
					 +"    AND aus.audit_type_code=aut.audit_type_code "
					 +"    AND aus.plan_id=aut.plan_id "
					 +"    AND aus.audit_id=aut.audit_id "
					 +"    AND aut.user_id =:userId    "
					 +"    ) ");
		}else if(role.equalsIgnoreCase("BU")||role.equalsIgnoreCase("BL")){
			query.append(" and  aus.unit_id IN (SELECT t.unit_code FROM user t WHERE "
					+ " t.legal_entity_code =aus.legal_entity_code "
					+ " and t.user_id=:userId  ) ");
		}else if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			query.append(" and  aus.unit_id IN (:unitList) ");
		}
		
		//query.append( "     AND aus.actual_start_date BETWEEN :fromDate  AND :toDate "
		query.append(" AND aus.audit_id IN (:auditsList)      "
				 +"     WHERE rsp.legal_entity_code =:legalEntityCode ");
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND rsp.audit_type_code =:auditType ");
		}
		
		
		
		query.append(
				" GROUP BY rsp.risk_category_code "
				+" ORDER BY rating_internal desc " // to show the ratings in the Descending order
		);
	
		Query hqlQuery= session.createNativeQuery(query.toString())
		//.setParameter("fromDate", fromDate)
		//.setParameter("toDate", toDate)
		.setParameter("auditsList", auditsList)
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(role.equalsIgnoreCase("ADTR")){
			hqlQuery.setParameter("userId",userId);
		}else if(role.equalsIgnoreCase("BU")||role.equalsIgnoreCase("BL")){
			hqlQuery.setParameter("userId",userId);
		}else if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			if(unitList.isEmpty()){
				unitList.add("");
			}
			hqlQuery.setParameterList("unitList", unitList);
		}
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}	
        
        Map map = new HashMap<String, Integer>();
        List lst= hqlQuery.setResultTransformer(new ResultTransformer() {
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				RatingVarianceGraphResponseDto ratingVarianceGraphResponseDto=null;
				if(tuple!=null){
					ratingVarianceGraphResponseDto=new  RatingVarianceGraphResponseDto();
					if(tuple[0]!=null){
						ratingVarianceGraphResponseDto.setUnitCount(Integer.parseInt(tuple[0].toString()));
						int cnt=0;
						if(map.containsKey("UNIT_COUNT")) cnt=Integer.parseInt(map.get("UNIT_COUNT").toString());
						map.put("UNIT_COUNT", Integer.parseInt(tuple[0].toString())+cnt);
					}
					if(tuple[1]!=null){
						ratingVarianceGraphResponseDto.setRating(tuple[1].toString());			
		            }
					
				}
				
				return ratingVarianceGraphResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
        
        logger.info("map .."+map);
        logger.info("lst .."+lst);
        int unitsCount = unitList.size();
        int unitsRatedCount = Integer.parseInt(map.get("UNIT_COUNT").toString());
        if(unitsCount != unitsRatedCount){
        	RatingVarianceGraphResponseDto rtDto = new RatingVarianceGraphResponseDto();
        	rtDto.setUnitCount(unitsCount - unitsRatedCount);
        	rtDto.setRating("UnRated");
        	lst.add(rtDto);
        }
        return lst;
				
	}
	
	
	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<Map<String, HashMap<String,Long>>> getRatingVariance(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId,String role,List<String> unitList,List<String> auditsList,String unitType,String criticality) {
		
		System.out.println("fromDate .... "+ fromDate + " toDate.... "+toDate);
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		StringBuilder query= new StringBuilder(" SELECT  "
				+"     CONCAT(risk_category_code,'-',risk_category_desc) AS risk_score, "
				+"     COUNT(rating_internal) AS no_of_audits,  rating_internal, "
				+"     CASE "
				+" 		   WHEN rating_imprv = 1000 THEN 'M' "    // Introducing the Maiden, the Units rated for the first time.(There is no comparison)
				+"         WHEN rating_imprv > 0 THEN 'B' "
				+"         WHEN rating_imprv < 0 THEN 'W' "
				+"         WHEN rating_imprv = 0 THEN 'S' "
				+"         ELSE 'N' "
				+"     END AS rating_imp "
				+" FROM "
				+"     (SELECT  r.risk_category_code, r.risk_category_desc, "
				+"             a.audit_id,a.assessed_risk_prcntg,a.prev_assessed_risk_prcntg, "
				+"             r.rating_internal, "
				+"			   CASE WHEN  prev_assessed_risk_prcntg IS NULL THEN 1000 " // 1000 to Check for the maiden entry
				+"				    ELSE "
				+"             		   (r.rating_internal - (SELECT r1.rating_internal "
				+"  	                 FROM  risk_score_percentage r1 "
				+"           		      WHERE "
				+"                    		 r1.audit_type_code = a.audit_type_code "
				+"                           AND r1.legal_entity_code = a.legal_entity_code "
				+"                           AND IFNULL(a.prev_assessed_risk_prcntg, 100) > r1.minimun_per "
				+"                           AND IFNULL(a.prev_assessed_risk_prcntg, 100) <= r1.maximum_per))  "
				+"				END AS rating_imprv "
				+"      FROM "
				+"         risk_score_percentage r "
				+"     LEFT OUTER JOIN audit_schedule a ON r.audit_type_code = a.audit_type_code "
				+"         AND r.legal_entity_code = a.legal_entity_code "
				+"         AND IFNULL(a.assessed_risk_prcntg, 100) > r.minimun_per "
				+"         AND IFNULL(a.assessed_risk_prcntg, 100) <= r.maximum_per "
				//+"		   AND a.actual_start_date BETWEEN :fromDate AND :toDate "
				+"		   AND a.audit_id IN (:auditsList) "
				+"		   And a.audit_status in ('AS','AR','AW','AC') "
				)  ;
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND a.unit_id in (select e.unit_code from maint_entity e where legal_entity_code=a.legal_entity_code "
					+ " and e.unit_type =:unitType  )  ");
		}
		if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND a.unit_id in (select e.unit_code from maint_entity e where legal_entity_code=a.legal_entity_code "
					+ " and e.u_criticality =:criticality  )  ");
        }
		/*if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			query.append(" and  a.unit_id IN (:unitList) ");
		}*/
        
        query.append("    WHERE "
					+"      r.legal_entity_code =:legalEntityCode  "
					+"      AND r.audit_type_code =:auditType ) AS rating_variance ");
		
		/*if(!BankAuditUtil.isEmptyString(auditType)){   // Audit Type code is mandatory
			query.append(" AND r.audit_type_code =:auditType ");
		}*/  
		query.append(" GROUP BY risk_category_code , rating_imp ORDER BY rating_internal desc ");  // to show the ratings in the Descending order
	
		Query hqlQuery= session.createNativeQuery(query.toString())
		//.setParameter("fromDate", fromDate).setParameter("toDate", toDate)
		.setParameter("auditsList", auditsList)
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		/*if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			if(unitList.isEmpty()){
				unitList.add("");
			}
			hqlQuery.setParameterList("unitList", unitList);
		}*/
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}	
        
        List<Map<String, HashMap<String,Long>>> resultLst = new ArrayList();
        Map<String, HashMap<String,Long>> outerMap = new HashMap(); 
        
        List ls = hqlQuery.list();
        
        String rating=""; int iterateCnt=0;
 		HashMap<String,Long> ratImp = new HashMap();
 		for(Object obj: ls) {
 			Object[] obji=(Object[])obj;iterateCnt++;
 			if(obji[2]!=null && rating.equalsIgnoreCase(obji[2].toString())) {
 				ratImp.put(obji[3].toString(), Long.parseLong(obji[1].toString()));
 				
 			}else {
 				if(!rating.equals("")) resultLst.add(outerMap);
 				outerMap = new HashMap();
 				ratImp = new HashMap();
 				if(obji[3]!=null && obji[1]!=null && !"N".equalsIgnoreCase(obji[3].toString())) ratImp.put(obji[3].toString(), Long.parseLong(obji[1].toString()));
 				outerMap.put(obji[0].toString(), ratImp);
 			}
 			rating = (obji[2]!=null)?obji[2].toString():rating;
 			if(iterateCnt == ls.size()) { // length to be modified
 				if(obji[3]!=null && obji[1]!=null && !"N".equalsIgnoreCase(obji[3].toString())) ratImp.put(obji[3].toString(), Long.parseLong(obji[1].toString()));
 				outerMap.put(obji[0].toString(), ratImp);
 				resultLst.add(outerMap);
 			}
 		}System.out.println("resultLst .."+resultLst); 
        
        
        /*Map<String, HashMap<String,Long>> map = new HashMap();List<Map<String, HashMap<String,Long>>> ls1 = new ArrayList(); 
      
       List ls = hqlQuery.list();
       
       String rating=""; int cnt=0;
		HashMap<String,Long> ratImp = new HashMap();
		for(Object obj: ls) {
			Object[] obji=(Object[])obj;cnt++;
			System.out.println("=================================================="+ ls1);
			if(rating.equalsIgnoreCase(obji[2].toString())) {
				ratImp.put(obji[3].toString(), Long.parseLong(obji[1].toString()));
				
			}else {
				if(!rating.equals("")) ls1.add(map);
				System.out.println("===.."+ ls1);
				map = new HashMap();
				System.out.println("===##"+ ls1);
				ratImp = new HashMap();
				if(!"N".equalsIgnoreCase(obji[3].toString()))ratImp.put(obji[3].toString(), Long.parseLong(obji[1].toString()));
				map.put(obji[0].toString(), ratImp);
			}
			rating =obji[2].toString();
			if(cnt == ls.size()) { // length to be modified
				ratImp.put(obji[3].toString(), Long.parseLong(obji[1].toString()));
				map.put(obji[0].toString(), ratImp);
				ls1.add(map);
			}System.out.println("ratImp .."+ratImp);
		}System.out.println("ls1 .."+ls1);*/
        
        return resultLst;
		
	}
	
	
	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<AuditStatusGraphResponseDto> getMyAuditStatistics(Integer legalEntityCode, String auditType,
			String unitType, String criticality, String userId, Date businessDate) {
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		/*Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDate);
		Integer currentYear=calendar.get(Calendar.YEAR);
		Integer previousYear=currentYear-1;
		//LocalDate FinancialYearStartDate = LocalDate.of(currentYear, 04, 1);
		*/
		
		LocalDate FinancialYearEndDate = dashboardDao.getFinancialYearEndDate(legalEntityCode);
		LocalDate FinancialYearStartDate = FinancialYearEndDate.minusMonths(12).plusDays(1);
		
		logger.info("getMyAuditStatistics legalEntityCode::"+legalEntityCode+" userId::"+userId +" auditType::"+auditType+" unitType::"+unitType+" criticality::"+criticality +" businessDate::"+businessDate);
		logger.info("FinancialYearStartDate ::"+ FinancialYearStartDate +" FinancialYearEndDate :: "+FinancialYearEndDate);		
		
		StringBuilder query= new StringBuilder(
				" SELECT COUNT(aus.audit_status) AS audit_count , " 
						 + "   (CASE WHEN aus.audit_status in ('AP','AI') THEN 'planned' ELSE 'submitted' END) AS audit_status, " 
						 + "   if(tm.user_type='L','Lead','Member') as user_type, "
        				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:fromDate AND DATE(aus.schedule_start_date) <=:toDate  THEN 'range'   " 
						 + "    END) AS ytd " 
						 + "   FROM audit_schedule AS aus ,maint_entity AS me, audit_team AS tm" 
						 + "   WHERE  " 
						 + "   aus.legal_entity_code=me.legal_entity_code " 
						 + "   AND aus.unit_id=me.unit_code   " 
						 
						 /*+"    AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
						 +"    aus.legal_entity_code=aut.legal_entity_code "
						 +"    AND aus.audit_type_code=aut.audit_type_code "
						 +"    AND aus.plan_id=aut.plan_id "
						 +"    AND aus.audit_id=aut.audit_id "
						 +"    AND aut.user_id =:userId    "
						 +"    ) "*/  // Not required as Audit Team Table used for join
						 
						 + "   AND aus.legal_entity_code =:legalEntityCode " 
						 + "   AND aus.audit_status IN ('AP','AI' ,'AS','AR','AW','AC','AF')  " 
						 + "   AND DATE(aus.schedule_start_date) BETWEEN :fromDate AND :toDate "
						 + "   AND aus.legal_entity_code=tm.legal_entity_code AND aus.audit_id = tm.audit_id and tm.user_id= :userId "
						 + "   AND tm.legal_entity_code =me.legal_entity_code AND tm.unit_id=me.unit_code "
				)  ;
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
        query.append(
				   "   GROUP BY  (CASE WHEN aus.audit_status in ('AP','AI') THEN 'planned' ELSE 'submitted' END), " 
				 + "    tm.user_type, " 
				 + "   (CASE WHEN DATE(aus.schedule_start_date) >=:fromDate AND DATE(aus.schedule_start_date) <=:toDate  THEN 'range'   " 
				 + "    END)  "
				 + "   order by user_type "
        		);
        
		
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("fromDate", FinancialYearStartDate)
		.setParameter("toDate", FinancialYearEndDate)
		.setParameter("userId",userId)
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}
	 
	return hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=null; 
				if(tuple!=null){
					auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
					if(tuple[0]!=null){
						auditStatusGraphResponseDto.setCount(Long.parseLong(tuple[0].toString()));
					}
					if(tuple[1]!=null){
						auditStatusGraphResponseDto.setAuditStatus(tuple[1].toString());						
		            }
					if(tuple[2]!=null){
						auditStatusGraphResponseDto.setYtd(tuple[2].toString());
					}
					
				}
				
				return auditStatusGraphResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
		
	}

	@SuppressWarnings({ "deprecation", "rawtypes" })
	@Override
	public BranchPerformanceResponseDto getBranchPerformance(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, List<String> unitList,String unitType,String criticality) {
		
		
		
		if(unitList.isEmpty()){
			unitList.add("");
		}
		Session session=getSession();
		
	    session.setDefaultReadOnly(true);	
	    
	    logger.info("getBranchPerformance ...."+ legalEntityCode +" auditType.."+auditType +" unitList.."+unitList );
		StringBuilder query= new StringBuilder(
				
				
			" SELECT   sum(aus.total_findings) AS totalFindings ,                                                                        "
					
		 +" sum(aus.rectified_findings) as rectifiedFindings   "  
		 +"       "  
				
			+"  FROM audit_schedule as aus  ,maint_entity AS me WHERE                                                                                    "
			+"  aus.legal_entity_code =:legalEntityCode "
			+ "  and  aus.unit_id IN (:unitList) "
			 + " and  aus.legal_entity_code=me.legal_entity_code " 
			 + "   AND aus.unit_id=me.unit_code   " 
			 
				)  ;
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
        query.append(
        		"  AND actual_start_date BETWEEN :fromDate AND :toDate "
        		);
        
		
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("fromDate", fromDate)
		.setParameter("toDate", toDate)
		.setParameterList("unitList", unitList)
		
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}
		
	return(BranchPerformanceResponseDto) hqlQuery
			.setResultTransformer(new ResultTransformer() {
				
				@Override
				public Object transformTuple(Object[] tuple, String[] aliases) {
					BranchPerformanceResponseDto auditStatusGraphResponseDto=null; 
					if(tuple!=null){
						auditStatusGraphResponseDto=new BranchPerformanceResponseDto();
						if(tuple[0]!=null){
							auditStatusGraphResponseDto.setTotalFindings(Integer.parseInt(tuple[0].toString()));
						}
						if(tuple[1]!=null){
							auditStatusGraphResponseDto.setRectifiedFindings(Integer.parseInt(tuple[1].toString()));						
			            }
						
						
					}
					
					return auditStatusGraphResponseDto;
				}
				
				@Override
				public List transformList(List collection) {
					return collection;
				}
			}).uniqueResult();
		
		
	}


	

	@Override
	public AuditSchedule getLatestAuditId(int legalEntityCode, String auditTypeCode, String unitCode) {
		
		Session session=getSession();		
		return (AuditSchedule) session.createQuery(" from AuditSchedule where "
				+ " auditStatus in ('AS','AR','AW','AC') "
				+ " and  legalEntityCode =:legalEntityCode "
				+ " and auditTypeCode =:auditTypeCode "
				+ " and unitId =:unitId order by actualEndDate desc  ")
				.setParameter("legalEntityCode", legalEntityCode)
				.setParameter("auditTypeCode", auditTypeCode)
				.setParameter("unitId", unitCode)
				.setMaxResults(1)
				.uniqueResult();
	}

	@SuppressWarnings({ "deprecation", "serial", "unchecked" })
	@Override
	public List<BranchPerformanceBUResponse> getBranchPerformanceForBU(int legalEntityCode, List<String> auditTypes,
			String userId, String role, List<String> planIds, List<String> auditIds) {
	    
		Session session=getSession();
		

		/*return session.createNativeQuery(
				  "  SELECT  f.f_criticality as criticality ,COUNT(ao.observation_id) as observationCount   FROM maint_audit_finding AS f  " 
						 + "    " 
						 + "   LEFT JOIN activity_process_finding_mapping AS apfm  " 
						 + "   ON apfm.finding_id=f.finding_id   " 
						 + "   AND apfm.legal_entity_code=f.legal_entity_code   " 
						 + "     " 
						 + "   LEFT JOIN audit_observation AS ao   " 
						 + "   ON ao.legal_entity_code=apfm.legal_entity_code  " 
						 + "   AND ao.mapping_id=apfm.mapping_id  " 
						 + "   AND ao.audit_type_code in (:auditType)  " 
						 + "   AND ao.plan_id in (:planId)  " 
						 + "   AND ao.audit_id in (:auditId)  " 
						 + "     " 
						 + "   WHERE f.legal_entity_code =:legalEntityCode  " 
						 + "    GROUP BY f.f_criticality   " 
				)*/ // Query commented to make changes to retrieve the results based on Response time from Audit Schedule table
		/*return session.createNativeQuery(
				  "  SELECT  f.f_criticality as criticality ,COUNT(aos.observation_id) as observationCount   FROM maint_audit_finding AS f  " 
						 + "    " 
						 + "   LEFT JOIN activity_process_finding_mapping AS apfm  " 
						 + "   ON apfm.finding_id=f.finding_id   " 
						 + "   AND apfm.legal_entity_code=f.legal_entity_code   " 
						 + "     " 
						 + "   LEFT JOIN  " 
						 + "	(select ao.legal_entity_code, ao.mapping_id,ao.audit_id,ao.observation_id,ao.plan_id,ao.audit_type_code "   
						 + " 				from audit_observation AS ao , audit_schedule AS ash "  
						 + "           where ao.legal_entity_code=ash.legal_entity_code AND ao.audit_id=ash.audit_id " 
						 + "			AND ao.response_date < date_add(ash.actual_end_date,INTERVAL ash.response_time DAY) "
						 + "            AND ao.audit_id in (:auditId)  ) as aos "
						 + "   ON aos.legal_entity_code=apfm.legal_entity_code  " 
						 + "   AND aos.mapping_id=apfm.mapping_id  " 
						 + "   AND aos.audit_type_code in (:auditType)  " 
						 + "   AND aos.plan_id in (:planId)  " 
						 + "   AND aos.audit_id in (:auditId)  " 
						 + "     " 
						 + "   WHERE f.legal_entity_code =:legalEntityCode  " 
						 + "    GROUP BY f.f_criticality   " 
				)*/
		return session.createNativeQuery(
						" SELECT f.f_criticality as criticality ,aos.response_type, f.score,"
						+ " 		COUNT(aos.observation_id) as observationCount    "
						+ "     FROM "
						+ "         (select c.criticality_code as f_criticality,c.score as score,c.legal_entity_code,af.finding_id  "
						+ " 			from maint_criticality c "
						+ " 			LEFT JOIN "
						+ " 				maint_audit_finding AS af   "
						+ " 				on c.legal_entity_code=af.legal_entity_code and  c.criticality_code=af.f_criticality  "
						+ " 				where c.criticality_of_type='Finding' and c.legal_entity_code=:legalEntityCode "
						+ " 		) as f          "
						+ "     LEFT JOIN "
						+ "         activity_process_finding_mapping AS apfm      "
						+ "             ON apfm.finding_id=f.finding_id AND apfm.legal_entity_code=f.legal_entity_code            "
						+ "     LEFT JOIN "
						+ " 		(select ao.legal_entity_code, ao.mapping_id,ao.audit_id,ao.observation_id,ao.audit_type_code, "
						+ "                 case when ao.response_date < date_add(ash.actual_end_date,INTERVAL ash.response_time DAY) then 'RESPOND_ONTIME' "
						+ " 				     else 'DELAY' end as response_type "
						+ "          from audit_observation AS ao , audit_schedule AS ash       "
						+ "             where ao.legal_entity_code=ash.legal_entity_code AND ao.audit_id=ash.audit_id      "
						+ "              AND ao.audit_id in (:auditId)  ) as aos "
						+ "           		"
						+ "   			ON aos.legal_entity_code=apfm.legal_entity_code  " 
						+ "   				AND aos.mapping_id=apfm.mapping_id  " 
						+ "   				AND aos.audit_type_code in (:auditType)  " 
						//+ "   				AND aos.plan_id in (:planId)  " 
						+ "   				AND aos.audit_id in (:auditId)  " 
						+ " 		  WHERE "
						+ "             f.legal_entity_code =:legalEntityCode       "
						+ "         GROUP BY "
						+ "             f.f_criticality,aos.response_type order by score desc, aos.response_type desc   "
				)
		.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				BranchPerformanceBUResponse branchPerformanceBUResponse=null;
				
				if(tuple!=null){
					branchPerformanceBUResponse=new BranchPerformanceBUResponse();
					if(tuple[0]!=null)	branchPerformanceBUResponse.setCriticality(tuple[0].toString());
					if(tuple[1]!=null)	branchPerformanceBUResponse.setRespType(tuple[1].toString());
					if(tuple[2]!=null)	branchPerformanceBUResponse.setCriticalityScore(tuple[2].toString());
					if(tuple[3]!=null) 	branchPerformanceBUResponse.setObservationCount(Long.parseLong(tuple[3].toString()));
				}
				
				return branchPerformanceBUResponse;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		})
		.setParameter("legalEntityCode", legalEntityCode)
		.setParameterList("auditType", auditTypes)
		.setParameterList("auditId", auditIds)
		//.setParameterList("planId", planIds)
		.list();
		
	
	}

	@SuppressWarnings("deprecation")
	@Override
	public List<UnitBreakUpResponseDto> getUnitBreakUp(int legalEntityCode, String auditType, String unitType, String period,
			LocalDate fromDate, LocalDate toDate, String role, String userId) {
		
		Session session =getSession();
		
		StringBuilder query=new StringBuilder(
				 "   SELECT mc.criticality_code , COUNT(me.unit_code)  FROM maint_criticality AS mc   " 
						 + "   LEFT JOIN maint_entity AS me ON me.legal_entity_code=mc.legal_entity_code " 
						 + "   AND me.u_criticality=mc.criticality_code " );
		
                 if(!BankAuditUtil.isEmptyString(unitType)){
                	 query.append("  AND me.unit_type =:unitType ");
                 }
                 if(!BankAuditUtil.isEmptyString(period)){
                	 query.append("   AND me.unit_open_date BETWEEN :fromDate AND :toDate ");
                 }
		         query.append( "   WHERE mc.legal_entity_code =:legalEntityCode " 
		        		 	 + "   and mc.criticality_of_type='Entity' "   // Condition added to retrieve only Entity type criticality
							 + "   GROUP BY mc.criticality_code "
							 + "   ORDER BY mc.score desc"); // To show the Criticality in descending order
		
				Query q=session.createNativeQuery(query.toString())
				.setParameter("legalEntityCode", legalEntityCode);
				
				  if(!BankAuditUtil.isEmptyString(unitType)){
	                	q.setParameter("unitType", unitType);
	                 }
	                 if(!BankAuditUtil.isEmptyString(period)){
	                	 q.setParameter("fromDate", fromDate);
	                	 q.setParameter("toDate", toDate);
	                 }
				q.setResultTransformer(new ResultTransformer() {
					
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						UnitBreakUpResponseDto unitBreakUpResponseDto=null;
						if(tuple!=null){
							unitBreakUpResponseDto=new UnitBreakUpResponseDto();
							if(tuple[0]!=null){
								//unitBreakUpResponseDto.setCriticality(tuple[0].toString());
								unitBreakUpResponseDto.setCriteriaCode(tuple[0].toString());
							}
							if(tuple[1]!=null){
								unitBreakUpResponseDto.setCount(Long.parseLong(tuple[1].toString()));
							}
						}
						return unitBreakUpResponseDto;
					}
					
					@Override
					public List transformList(List collection) {
						return collection;
					}
				});
		
		return q.list();
	}
	
	
	@SuppressWarnings("deprecation")
	@Override
	public List<UnitBreakUpResponseDto> getUnitBreakUpCriticalityWise(int legalEntityCode, String auditType, String unitType, String period,
			LocalDate fromDate, LocalDate toDate, String role, String userId, String criteria) {
		
		Session session =getSession();
		
		StringBuilder query=new StringBuilder(
				 "   SELECT mc.criticality_code ,mc.criticality_desc, COUNT(me.unit_code)  FROM maint_criticality AS mc   " 
						 + "     LEFT JOIN  " 
						 + "       (select distinct me.legal_entity_code,me.u_criticality,me.unit_code from maint_entity AS me "
						 + "		JOIN audit_subgroup_mapping_v as mp " 
						 + "          ON me.legal_entity_code=mp.legal_entity_code AND me.unit_code= mp.id  " 
						 + "             AND me.status='A' AND me.entity_status='A'");
					if(!BankAuditUtil.isEmptyString(auditType)){
						query.append( " AND mp.audit_type_code=:auditType ");
			        }		
					query.append("   ) as me "
						 + "     ON me.legal_entity_code=mc.legal_entity_code AND me.u_criticality=mc.criticality_code "
						 + "   WHERE mc.legal_entity_code =:legalEntityCode " 
		        		 + "     AND mc.criticality_of_type='Entity' "   // Condition added to retrieve only Entity type criticality
						 + "   GROUP BY mc.criticality_code,mc.criticality_desc "
						 + "   ORDER BY mc.score desc"); // To show the Criticality in descending order
		
				Query q=session.createNativeQuery(query.toString())
				.setParameter("legalEntityCode", legalEntityCode);
				
				if(!BankAuditUtil.isEmptyString(auditType)){
	                	q.setParameter("auditType", auditType);
	            }
	                 
				q.setResultTransformer(new ResultTransformer() {
					
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						UnitBreakUpResponseDto unitBreakUpResponseDto=null;
						if(tuple!=null){
							unitBreakUpResponseDto=new UnitBreakUpResponseDto();
							if(tuple[0]!=null){
								unitBreakUpResponseDto.setCriteriaCode(tuple[0].toString());
							}
							if(tuple[1]!=null){
								unitBreakUpResponseDto.setCriteriaDesc(tuple[1].toString());
							}
							if(tuple[2]!=null){
								unitBreakUpResponseDto.setCount(Long.parseLong(tuple[2].toString()));
							}
							unitBreakUpResponseDto.setCriteriaType("Criticality");
						}
						return unitBreakUpResponseDto;
					}
					
					@Override
					public List transformList(List collection) {
						return collection;
					}
				});
		
		return q.list();
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public List<UnitBreakUpResponseDto> getUnitBreakUpUnitTypeClassificatioWise(int legalEntityCode, String auditType, String unitType, String period,
			LocalDate fromDate, LocalDate toDate, String role, String userId, String criteria) {
		
		Session session =getSession();
		String key1=null;
		String key2=null;String criteriaType=null;String criteriaClause=null;
		if("U".equalsIgnoreCase(criteria)) {
			key1="UNIT_TYPE";
			key2="UNIT_TYPE";
			criteriaType ="UnitType";
			criteriaClause="me.unit_type";
		}else {
			key1="CLASSIFICATION";
			key2="GEOGRAPHY";
			criteriaType ="Classification";
			criteriaClause="me.classification";
		}
		
		logger.info("criteria.."+criteria+" key1.."+key1+" key2.."+key2+" criteriaType.."+criteriaType+" criteriaClause.."+criteriaClause+" auditType.."+auditType);
		StringBuilder query=new StringBuilder(
				 "   SELECT gp.value,gp.description, COUNT(me.unit_code), :criteriaType as criteriaType  FROM general_parameter AS gp   " 
						 + "    LEFT JOIN  " 
						 + "       (select distinct me.legal_entity_code,me.unit_type,me.classification,me.unit_code from maint_entity AS me "
						 + "		JOIN audit_subgroup_mapping_v as mp " 
						 + "          ON me.legal_entity_code=mp.legal_entity_code AND me.unit_code= mp.id  " 
						 + "             AND me.status='A' AND me.entity_status='A'");
					if(!BankAuditUtil.isEmptyString(auditType)){
						query.append( " AND mp.audit_type_code=:auditType ");
			        }		
					query.append("   ) as me "
						 + "    ON me.legal_entity_code=gp.legal_entity_code AND "+criteriaClause+" = gp.value" 
						 + "      AND gp.key_1=:key1 AND gp.key_2=:key2"
		       			 +"   WHERE gp.legal_entity_code =:legalEntityCode "
		        		 + "   AND gp.key_1=:key1 AND gp.key_2=:key2"  
						 + "   GROUP BY gp.value,gp.description "
						 + "   ORDER BY gp.description ASC"); // To show in ascending order
		
				Query q=session.createNativeQuery(query.toString())
				.setParameter("legalEntityCode", legalEntityCode)
				.setParameter("key1", key1)
				.setParameter("key2", key2)
				.setParameter("criteriaType", criteriaType);
				if(!BankAuditUtil.isEmptyString(auditType)){
					q.setParameter("auditType", auditType);
		        }	
				
				q.setResultTransformer(new ResultTransformer() {
					
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						UnitBreakUpResponseDto unitBreakUpResponseDto=null;
						if(tuple!=null){
							unitBreakUpResponseDto=new UnitBreakUpResponseDto();
							if(tuple[0]!=null){
								unitBreakUpResponseDto.setCriteriaCode(tuple[0].toString());
							}
							if(tuple[1]!=null){
								unitBreakUpResponseDto.setCriteriaDesc(tuple[1].toString());
							}
							if(tuple[2]!=null){
								unitBreakUpResponseDto.setCount(Long.parseLong(tuple[2].toString()));
							}
							if(tuple[3]!=null){
								unitBreakUpResponseDto.setCriteriaType(tuple[3].toString());
							}
						}
						return unitBreakUpResponseDto;
					}
					
					@Override
					public List transformList(List collection) {
						return collection;
					}
				});
		
		return q.list();
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public List<UnitBreakUpResponseDto> getUnitBreakUpRevenueWsie(int legalEntityCode, String auditType, String unitType, String period,
			LocalDate fromDate, LocalDate toDate, String role, String userId, String criteria, List<String> auditsList) {
		
		Session session =getSession();
				
		logger.info("criteria.."+criteria+" auditsList.."+auditsList+" auditType.."+auditType+" legalEntityCode.."+legalEntityCode);
		StringBuilder query=new StringBuilder( " SELECT  "
						+ "     gp.value, "
						+ "     gp.description, "
						+ "     COUNT(aus.audit_id), "
						+ "     'Revenue Leak' AS criteriaType "
						+ " FROM "
						+ "     general_parameter AS gp "
						+ "         LEFT JOIN "
						+ "     audit_schedule AS aus ON gp.legal_entity_code = aus.legal_entity_code "
						+ "         AND aus.audit_id IN (:auditsList) "
						+ "         AND IF(IFNULL(aus.revenue_leakage, - 1) < 1000000, "
						+ " 				IF(IFNULL(aus.revenue_leakage, - 1) < 100000, 0, "
						+ "             100000), "
						+ "         1000000) = gp.value "
						+ " WHERE "
						+ "     gp.legal_entity_code =:legalEntityCode "
						+ "         AND gp.key_1 = 'REVENUE_LEAK' "
						+ "         AND gp.key_2 = 'REVENUE_LEAK' "
						+ " GROUP BY gp.value , gp.description "
						+ " ORDER BY gp.description ASC; "); // To show in ascending order
		
				Query q=session.createNativeQuery(query.toString())
				.setParameter("legalEntityCode", legalEntityCode)
				.setParameter("auditsList", auditsList);
				
				q.setResultTransformer(new ResultTransformer() {
					
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						UnitBreakUpResponseDto unitBreakUpResponseDto=null;
						if(tuple!=null){
							unitBreakUpResponseDto=new UnitBreakUpResponseDto();
							if(tuple[0]!=null){
								unitBreakUpResponseDto.setCriteriaCode(tuple[0].toString());
							}
							if(tuple[1]!=null){
								unitBreakUpResponseDto.setCriteriaDesc(tuple[1].toString());
							}
							if(tuple[2]!=null){
								unitBreakUpResponseDto.setCount(Long.parseLong(tuple[2].toString()));
							}
							if(tuple[3]!=null){
								unitBreakUpResponseDto.setCriteriaType(tuple[3].toString());
							}
						}
						return unitBreakUpResponseDto;
					}
					
					@Override
					public List transformList(List collection) {
						return collection;
					}
				});
		
		return q.list();
	}

	@SuppressWarnings({ "deprecation", "unchecked" })
	@Override
	public List<PlanCalendarResponseDto> getPlanCalendar(int legalEntityCode, LocalDate financialYearStartDate) {
		Session session =getSession();
		
		logger.info("legalEntityCode.. "+legalEntityCode +" financialYearStartDate.. "+financialYearStartDate);
		
		return session.createNativeQuery("  "
				+" SELECT (SELECT CONCAT(atd.audit_type_code,'-',atd.audit_type_desc) FROM maint_audit_type_desc AS atd "
				+" WHERE matd.audit_type_code=atd.audit_type_code AND matd.legal_entity_code=atd.legal_entity_code "
				+"  ) AS auditType, "
				+"  COUNT(ap.plan_id) AS planCount, "
				+"  DATE_ADD(MAX(plan_end_date),INTERVAL 1 DAY ) AS nextPlanStartDate, "
				+"  DATEDIFF(DATE_ADD(MAX(plan_end_date),INTERVAL 1 DAY ), "
				+"  (SELECT bd.business_date FROM business_date AS bd WHERE bd.legal_entity_code=ap.legal_entity_code ) ) "
				+"  AS remainingDays "				
				+"  "
				+"    FROM maint_audit_type_desc AS matd  "
				+"    LEFT OUTER JOIN  "
				+"      audit_plan AS ap "
				+" ON "
				+"  matd.legal_entity_code=ap.legal_entity_code  "
				+" AND ap.plan_start_date >=:financialYearStartDate "
				+" AND matd.audit_type_code=ap.audit_type_code        "
				+" WHERE matd.legal_entity_code =:legalEntityCode "
				+" GROUP BY matd.audit_type_code "
				+" ORDER BY  remainingDays  asc ")  // to show the Audits which are earliest to be planned. 
		.setParameter("legalEntityCode",legalEntityCode)
		.setParameter("financialYearStartDate", financialYearStartDate)
		.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				PlanCalendarResponseDto planCalendarResponseDto=null;
				if(tuple!=null){
					planCalendarResponseDto=new PlanCalendarResponseDto();
					
					if(tuple[0]!=null){
						planCalendarResponseDto.setAuditType(tuple[0].toString());
					}if(tuple[1]!=null){
						planCalendarResponseDto.setPlanCount(Long.parseLong(tuple[1].toString()));
					}if(tuple[2]!=null){
						planCalendarResponseDto.setNextPlanStartDate((Date)tuple[2]);
					}if(tuple[3]!=null){
						planCalendarResponseDto.setRemainingDays(Integer.parseInt(tuple[3].toString()));
					}
					
				}
				
				return planCalendarResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		})
		.list();
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public List<String> getAuditTypes(int legalEntityCode) {
		Session session=getSession();
		
		return  session.createQuery("select auditTypeCode from MaintAuditTypeDesc where "
				+ " legalEntityCode =:legalEntityCode "
				+ " and status = 'A' ")
				.setParameter("legalEntityCode", legalEntityCode)
				.list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public String getNextPlanStartdate(int legalEntityCode, String auditType) {
		Session session=getSession();
		String planStartdate=null;
		logger.info("==================================================================");
		try {
			logger.info("legalEntityCode ::"+legalEntityCode +" auditType::"+auditType);
			Query qry =session.createNativeQuery(" select DATE_ADD(max(plan_end_date),interval 1 Day)  from audit_plan where"
					+ " legal_entity_code =:legalEntityCode "
					+ " and  audit_type_code =:auditType ")
					.setParameter("legalEntityCode", legalEntityCode)
					.setParameter("auditType", auditType);
			logger.info("size is .."+ qry.list().size() + " .. "+ qry.list());
			if(qry.list().size() > 0 && qry.list().get(0) != null) 	planStartdate=qry.list().get(0).toString();
			else planStartdate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode)+"";
		}catch(Exception e) {
			e.printStackTrace();
		}
		return planStartdate;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public String getFinYrEndDate(int legalEntityCode) {
		Session session=getSession();
		String yrEndDate=null;
		
		try {
			Query qry =session.createNativeQuery("select  get_financial_year_endDate(:legalEntityCode) as finYrEndDt from dual ")
				.setParameter("legalEntityCode", legalEntityCode);
		
			yrEndDate=qry.list().get(0).toString();
		}catch(Exception e) {
			e.printStackTrace();
		}
		return yrEndDate;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> getListofAuditors(int legalEntityCode, String auditType) {
		Session session=getSession();
		
		return  session.createQuery(" SELECT distinct u FROM User u,UserRoleMapping m where " 
				 +"  u.legalEntityCode=m.legalEntityCode "
				 +"  AND u.status='A' AND m.status='A' " 
				 +"  AND m.userRoleId LIKE '%ADTR%' "
				 +"  AND u.userId=m.userId "
				 +"  AND u.legalEntityCode =:legalEntityCode")
				.setParameter("legalEntityCode", legalEntityCode)
				.list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public int getUnitWorkingDays(int legalEntityCode, String unitCode, String startDate, String endDate) {
		Session session=getSession();
		int unitWorkingDays=0;
		
		try {
			Query qry =session.createNativeQuery("select GET_DURATION_DATES(:legalEntityCode,:unitCode,:startDate,:endDate) from dual; ")
				.setParameter("legalEntityCode", legalEntityCode)
				.setParameter("unitCode",unitCode)
				.setParameter("startDate",startDate)
				.setParameter("endDate",endDate);
		
			unitWorkingDays=Integer.parseInt(qry.list().get(0).toString());
		}catch(Exception e) {
			e.printStackTrace();
		}
		return unitWorkingDays;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public int getEffortUtilized(int legalEntityCode , String startDate, Map<String, String> nextPlanStartDateMap, String finYrEndDate) {
		Session session=getSession();
		int effortUtilized=0; int mapItrtor=0;
		
		logger.info(" Inside getEffortUtilized legalEntityCode::"+legalEntityCode +" startDate::"+startDate+" nxtPStDt::"+nextPlanStartDateMap + " finYrEndDate::"+finYrEndDate);
		
		try {
			StringBuilder query=new StringBuilder("select ifnull(sum(s.duration * s.man_days),0) as total from audit_schedule s, audit_plan p "
					+ " where p.legal_entity_code=:legalEntityCode and s.plan_id=p.plan_id and s.legal_entity_code=p.legal_entity_code ");
			
			query.append(" and (");
			for (Map.Entry<String,String> entry : nextPlanStartDateMap.entrySet()) {
				if(mapItrtor != 0) query.append(" OR "); mapItrtor++;
				query.append(" (p.audit_type_code ='"+entry.getKey() +"' AND plan_start_date BETWEEN :startDate AND '"+entry.getValue() +"' )");
			}query.append(" )");
			
			logger.info(" getEffortUtilized Qry is :: "+query.toString());
			Double effortDbl = Double.parseDouble(session.createNativeQuery(query.toString())
					.setParameter("legalEntityCode", legalEntityCode)
					.setParameter("startDate",startDate).uniqueResult().toString());
			logger.info("effortDbl .... "+ effortDbl);
			effortUtilized=effortDbl.intValue();
		}catch(Exception e) {
			e.printStackTrace();
		}
		return effortUtilized;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public String getHeadOfficeUnitCode(int legalEntityCode) {
		Session session=getSession();
		String unitcode=null;
		
		try {
			unitcode =session.createQuery("select unitCode from MaintEntity where legalEntityCode=:legalEntityCode "
					+ " AND levelCode='1' ").setParameter("legalEntityCode", legalEntityCode).uniqueResult().toString();
		
			//yrEndDate=qry.list().get(0).toString();
			System.out.println("unitcode ...."+ unitcode);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return unitcode;
	}
	
	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<AuditSchedule> getAuditSummary(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId,String role,List<String> unitList,String unitType,String criticality) {
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
	    StringBuilder query=new StringBuilder("select sch.legal_entity_code,sch.plan_id,sch.audit_id, sch.effective_rating, " // effective_rating -4
	    		+ " ifnull(sch.total_findings,0),ifnull(sch.open_findings,0),ifnull(sch.rectified_findings,0),ifnull(sch.responded_findings,0),ifnull(closed_findings,0), " // closed_findings -9
	    		+ " (select concat(audit_type_code , '-' , audit_type_desc) from maint_audit_type_desc at where at.audit_type_code=sch.audit_type_code and at.legal_entity_code= sch.legal_entity_code ) as auditTypeCode," // - 10
	    		+ " (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,  "  // - 11
	    		+ " (Select concat(sch.audit_status , '-' , g.description) from  general_parameter g where g.legal_entity_code =sch.legal_entity_code and g.key_1='STATUS' and g.key_2='AUDIT_STATUS' and g.value=sch.audit_status) as auditStatus, " // - 12
	    		+ " (Select count(*) from  audit_observation o where o.legal_entity_code =sch.legal_entity_code and o.audit_id=sch.audit_id and o.compliance_category='N' and o.review_status='R' ) as responseReject, " // -13
	    		+ " (Select count(*) from  audit_observation o where o.legal_entity_code =sch.legal_entity_code and o.audit_id=sch.audit_id and o.compliance_category='C' and o.submission_status='A') as complianceCount, " // -14
	    		+ " (Select count(*) from  audit_observation o where o.legal_entity_code =sch.legal_entity_code and o.audit_id=sch.audit_id and o.compliance_category='NA' and o.submission_status='A') as notApplicableCount " // -15
	    		+ " from audit_schedule sch where legal_entity_code =:legalEntityCode "
	    		+ " and   IFNULL(audit_status,'NotNull') in ('AI','AS','AR','AW','AC') "
	    		);
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND sch.unit_id in (select unit_code from maint_entity where legal_entity_code=aus.legal_entity_code "
					+ " and unit_type =:unitType  )  ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND sch.unit_id in (select unit_code from maint_entity where legal_entity_code=aus.legal_entity_code "
					+ " and u_criticality =:criticality  )  ");
        	
		}
		
		if(role.equalsIgnoreCase("ADTR")){
			query.append(" AND sch.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					 +"    sch.legal_entity_code=aut.legal_entity_code "
					 +"    AND sch.audit_type_code=aut.audit_type_code "
					 +"    AND sch.plan_id=aut.plan_id "
					 +"    AND sch.audit_id=aut.audit_id "
					 +"    AND aut.user_id =:userId    "
					 +"    ) ");
		}else if(role.equalsIgnoreCase("BU")||role.equalsIgnoreCase("BL")){
			query.append(" and  sch.unit_id IN (SELECT t.unit_code FROM user t WHERE t.legal_entity_code =sch.legal_entity_code"
					+ " and t.user_id=:userId  ) ");
		}else if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			query.append(" and  sch.unit_id IN (:unitList) ");
		}
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND sch.audit_type_code =:auditType ");
		}
		query.append(" order by actual_start_date desc limit 5 "); // to get only 5 records
	
		
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(role.equalsIgnoreCase("ADTR")){
			hqlQuery.setParameter("userId",userId);
		}else if(role.equalsIgnoreCase("BU")||role.equalsIgnoreCase("BL")){
			hqlQuery.setParameter("userId",userId);
		}else if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			if(unitList.isEmpty()){
				unitList.add("");
			}
			hqlQuery.setParameterList("unitList", unitList);
		}
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}	
	return hqlQuery.setResultTransformer(new ResultTransformer() {
			//sch.legal_entity_code,sch.plan_id,sch.audit_id,sch.effective_rating
		//sch.total_findings,sch.open_findings,sch.sch.responded_findings,closed_findings,
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				AuditSchedule auditSchedule=null;
				if(tuple!=null){
					auditSchedule=new  AuditSchedule();
					if(tuple[1]!=null)	auditSchedule.setPlanId(tuple[1].toString());
					if(tuple[2]!=null)	auditSchedule.setAuditId(tuple[2].toString());
					if(tuple[3]!=null)	auditSchedule.setEffectiveRating(tuple[3].toString());
					if(tuple[4]!=null)	auditSchedule.setTotalFindings(Integer.parseInt(tuple[4].toString()));
					if(tuple[5]!=null)	auditSchedule.setOpenFindings(Integer.parseInt(tuple[5].toString()));
					if(tuple[6]!=null)	auditSchedule.setRectifiedFindings(Integer.parseInt(tuple[6].toString()));
					if(tuple[7]!=null)	auditSchedule.setRespondedFindings(Integer.parseInt(tuple[7].toString()));
					if(tuple[8]!=null)	auditSchedule.setClosedFindings(Integer.parseInt(tuple[8].toString()));
					if(tuple[9]!=null)	auditSchedule.setAuditTypeCode(tuple[9].toString());
					if(tuple[10]!=null)	auditSchedule.setUnitId(tuple[10].toString());
					if(tuple[11]!=null)	auditSchedule.setAuditStatus(tuple[11].toString());
					if(tuple[12]!=null)	auditSchedule.setResponseReject(Integer.parseInt(tuple[12].toString()));
					if(tuple[13]!=null)	auditSchedule.setComplianceCount(Integer.parseInt(tuple[13].toString()));
					if(tuple[14]!=null)	auditSchedule.setNotApplicableCount(Integer.parseInt(tuple[14].toString()));
				}
				
				return auditSchedule;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
		
	}
	
	
	@SuppressWarnings("deprecation")
	@Override
	public List<BranchPerformanceBUResponse> getBranchPerformanceRectification(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, String criticality) {
		
		Session session =getSession();
		List<BranchPerformanceBUResponse> rectList = null;
		logger.info("legalEntityCode::"+legalEntityCode+" auditType::"+auditType+" period::"+period+" fromDate::"+fromDate+" toDate::"+toDate+" userId::"+userId+" role::"+role+" criticality::"+criticality);
		try {
			StringBuilder query=new StringBuilder(
					"  SELECT f.f_criticality as criticality ,aos.response_type,f.score, "
					+ " 		COUNT(aos.observation_id) as observationCount    "
					+ "     FROM "
					+ " 		(select c.criticality_code as f_criticality,c.score as score,c.legal_entity_code,af.finding_id  "
					+ " 			from maint_criticality c "
					+ " 			LEFT JOIN "
					+ " 				maint_audit_finding AS af   "
					+ " 				on c.legal_entity_code=af.legal_entity_code and  c.criticality_code=af.f_criticality  "
					+ " 				where c.criticality_of_type='Finding' and c.legal_entity_code=:legalEntityCode "
					+ " 		) as f "
					+ "     LEFT JOIN "
					+ "         activity_process_finding_mapping AS apfm  "
					+ "             ON apfm.finding_id=f.finding_id AND apfm.legal_entity_code=f.legal_entity_code  "
					+ "     LEFT JOIN "
					+ " 		(select ao.legal_entity_code, ao.mapping_id,ao.audit_id,ao.observation_id,ao.audit_type_code, "
					+ "           case when ao.response_date <= ash.actual_end_date then 'RECTIFIED' "
					+ " 				else 'DELAY' end as response_type "
					+ "         from audit_observation AS ao , audit_schedule AS ash  "
					+ "             where ao.legal_entity_code=ash.legal_entity_code AND ao.audit_id=ash.audit_id  ");
							
			if(!BankAuditUtil.isEmptyString(period)){
	       	 	query.append("   AND ash.actual_start_date BETWEEN :fromDate AND :toDate  ");
	        }
			if(!BankAuditUtil.isEmptyString(auditType)){
	       	 	query.append("   AND ao.audit_type_code in (:auditType) ");
	        }
			query.append(     "           ) as aos"
						+ "          ON aos.legal_entity_code=apfm.legal_entity_code AND aos.mapping_id=apfm.mapping_id "
						+ "          AND aos.audit_type_code = apfm.audit_type_code  "
						+ "             WHERE "
						+ "             f.legal_entity_code =:legalEntityCode  "
						+ "         GROUP BY "
						+ "             f.f_criticality,aos.response_type  order by score desc, aos.response_type desc " );
		         	
			Query q=session.createNativeQuery(query.toString())
				.setParameter("legalEntityCode", legalEntityCode);
				
			if(!BankAuditUtil.isEmptyString(period)){
	           	 q.setParameter("fromDate", fromDate);
	           	 q.setParameter("toDate", toDate);
	        }
			if(!BankAuditUtil.isEmptyString(auditType)){
               	 q.setParameter("auditType", auditType);
            }
			    q.setResultTransformer(new ResultTransformer() {
					
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						BranchPerformanceBUResponse branchPerformanceBUResponse=null;
						//f.f_criticality as criticality ,aos.response_type,f.score, COUNT(aos.observation_id) as observationCount
						
						if(tuple!=null){
							branchPerformanceBUResponse=new BranchPerformanceBUResponse();
							if(tuple[0]!=null)	branchPerformanceBUResponse.setCriticality(tuple[0].toString());
							if(tuple[1]!=null)	branchPerformanceBUResponse.setRespType(tuple[1].toString());
							if(tuple[2]!=null)	branchPerformanceBUResponse.setCriticalityScore(tuple[2].toString());
							if(tuple[3]!=null) 	branchPerformanceBUResponse.setObservationCount(Long.parseLong(tuple[3].toString()));
						}
						return branchPerformanceBUResponse;
					}
					
					@Override
					public List transformList(List collection) {
						return collection;
					}
				});
		
				rectList= q.list();
		
		}catch(Exception e) {
			e.printStackTrace();
		}return rectList;
	}
	
	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<Map<String, Map<String,Long>>> getRatingTrendQuarterly(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId,String role,List<String> unitList,String unitType,String criticality, Date businessDate) {
		
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDate);
		Integer year=null;
		
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		Integer currentYear=year;
		Integer previousYear=currentYear-1;
		
		LocalDate bsnsDateLcl= LocalDate.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH)+1,calendar.get(Calendar.DAY_OF_MONTH) ); // to get the Business date in the Local date format, for comparing the Dates
		
		/*PREVIOUS YEAR quarters */
		//LocalDate previousFinancialYearQ1StartDate = LocalDate.of(previousYear, 04, 1);
		
		LocalDate FinancialYearStartDate  = dashboardDao.getFinancialYearStartDate(legalEntityCode);
		logger.info("FinancialYearStartDate :: "+FinancialYearStartDate);
		
		LocalDate previousFinancialYearQ1StartDate = FinancialYearStartDate.minusMonths(12);
		LocalDate previousFinancialYearQ1EndDate = previousFinancialYearQ1StartDate.plusMonths(3).minusDays(1);

		LocalDate  previousFinancialYearQ2StartDate =previousFinancialYearQ1EndDate.plusDays(1);
		LocalDate  previousFinancialYearQ2EndDate = previousFinancialYearQ2StartDate.plusMonths(3).minusDays(1);

		LocalDate  previousFinancialYearQ3StartDate =previousFinancialYearQ2EndDate.plusDays(1);
		LocalDate  previousFinancialYearQ3EndDate = previousFinancialYearQ3StartDate.plusMonths(3).minusDays(1);
		
		LocalDate  previousFinancialYearQ4StartDate =previousFinancialYearQ3EndDate.plusDays(1);
		LocalDate  previousFinancialYearQ4EndDate = previousFinancialYearQ4StartDate.plusMonths(3).minusDays(1);

       /*CURRENT YEAR quarters*/
		LocalDate nextFinancialYearQ1StartDate = previousFinancialYearQ4EndDate.plusDays(1);
		LocalDate nextFinancialYearQ1EndDate = nextFinancialYearQ1StartDate.plusMonths(3).minusDays(1);

		LocalDate  nextFinancialYearQ2StartDate =nextFinancialYearQ1EndDate.plusDays(1);
		LocalDate  nextFinancialYearQ2EndDate = nextFinancialYearQ2StartDate.plusMonths(3).minusDays(1);

		LocalDate  nextFinancialYearQ3StartDate =nextFinancialYearQ2EndDate.plusDays(1);
		LocalDate  nextFinancialYearQ3EndDate = nextFinancialYearQ3StartDate.plusMonths(3).minusDays(1);

		LocalDate  nextFinancialYearQ4StartDate =nextFinancialYearQ3EndDate.plusDays(1);
		LocalDate  nextFinancialYearQ4EndDate = nextFinancialYearQ4StartDate.plusMonths(3).minusDays(1);
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		logger.info("Inside getAuditStatusQuarterly.... userId.. "+userId + " auditType.. "+auditType+" businessDate.. "+ businessDate+" bsnsDateLcl.. "+bsnsDateLcl);
		logger.info(" unitList .... "+unitList );
		logger.info(" PQ1Strt:: "+ previousFinancialYearQ1StartDate +" PQ1End:: "+previousFinancialYearQ1EndDate);
		logger.info(" PQ2Strt:: "+ previousFinancialYearQ2StartDate +" PQ2End:: "+previousFinancialYearQ2EndDate);
		logger.info(" PQ3Strt:: "+ previousFinancialYearQ3StartDate +" PQ3End:: "+previousFinancialYearQ3EndDate);
		logger.info(" PQ4Strt:: "+ previousFinancialYearQ4StartDate +" PQ4End:: "+previousFinancialYearQ4EndDate);
		logger.info(" CQ3Strt:: "+ nextFinancialYearQ1StartDate +" CQ1End:: "+nextFinancialYearQ1EndDate);
		logger.info(" CQ2Strt:: "+ nextFinancialYearQ2StartDate +" CQ2End:: "+nextFinancialYearQ2EndDate);
		logger.info(" CQ3Strt:: "+ nextFinancialYearQ3StartDate +" CQ3End:: "+nextFinancialYearQ3EndDate);
		logger.info(" CQ3Strt:: "+ nextFinancialYearQ4StartDate +" CQ3End:: "+nextFinancialYearQ4EndDate);
				
		StringBuilder query= new StringBuilder(" SELECT  "
				+" prc.risk_category_desc,rskQtr.period,rskQtr.audit_count from risk_score_percentage prc left join "

				+" (SELECT  "
				+"     COUNT(aus.audit_status) AS audit_count, "
				+"    rsk.risk_category_code,rsk.legal_entity_code,rsk.audit_type_code, "
				+"     (CASE "
				+"         WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearQ1StartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearQ1EndDate THEN 'PREV_Q1' "
				+"         WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearQ2StartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearQ2EndDate THEN 'PREV_Q2' "
				+" 		   WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearQ3StartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearQ3EndDate THEN 'PREV_Q3' "
				+"         WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearQ4StartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearQ4EndDate THEN 'PREV_Q4' "
				+"         WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearQ1StartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearQ1EndDate THEN 'CUR_Q1' "
				+"         WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearQ2StartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearQ2EndDate THEN 'CUR_Q2' "
				+" 		   WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearQ3StartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearQ3EndDate THEN 'CUR_Q3' "
				+"         WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearQ4StartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearQ4EndDate THEN 'CUR_Q4' "
				+"         ELSE 'CUR_Q' "
				+"     END) AS period "
				+" FROM "
				+"     audit_schedule AS aus, "
				+"     maint_entity AS me, risk_score_percentage rsk "
				+" WHERE "
				+"     aus.legal_entity_code = me.legal_entity_code "
				+"         AND aus.unit_id = me.unit_code "
				+"         AND aus.legal_entity_code = :legalEntityCode "
				+"         AND aus.audit_status IN ('AS', 'AR', 'AW', 'AC', 'AF') "
				+"         AND DATE(aus.schedule_start_date) BETWEEN :previousFinancialYearQ1StartDate AND :nextFinancialYearQ4EndDate "
				+"         And aus.legal_entity_code=rsk.legal_entity_code AND aus.audit_type_code=rsk.audit_type_code "
				+"         AND me.legal_entity_code=rsk.legal_entity_code "
				+"         AND (aus.assessed_risk_prcntg >= rsk.minimun_per AND aus.assessed_risk_prcntg < rsk.maximum_per) ");
				
				if(!BankAuditUtil.isEmptyString(auditType)){
					query.append(" AND aus.audit_type_code =:auditType ");
				}
				if(!BankAuditUtil.isEmptyString(unitType)){
					query.append(" AND me.unit_type =:unitType ");
				}
				if(!BankAuditUtil.isEmptyString(criticality)){
					query.append(" AND me.u_criticality =:criticality  ");
				}
				if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
					query.append(" AND me.unit_code IN (:unitList) ");
				}
			
				query.append(" GROUP BY  rsk.risk_category_code,rsk.legal_entity_code,rsk.audit_type_code, "
				+"     (CASE "
				+"         WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearQ1StartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearQ1EndDate THEN 'PREV_Q1' "
				+"         WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearQ2StartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearQ2EndDate THEN 'PREV_Q2' "
				+" 		   WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearQ3StartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearQ3EndDate THEN 'PREV_Q3' "
				+"         WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearQ4StartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearQ4EndDate THEN 'PREV_Q4' "
				+"         WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearQ1StartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearQ1EndDate THEN 'CUR_Q1' "
				+"         WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearQ2StartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearQ2EndDate THEN 'CUR_Q2' "
				+" 		   WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearQ3StartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearQ3EndDate THEN 'CUR_Q3' "
				+"         WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearQ4StartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearQ4EndDate THEN 'CUR_Q4' "
				+"         ELSE 'CUR_Q' "
				+"     END)) as rskQtr  "
				+"     ON prc.legal_entity_code = rskQtr.legal_entity_code and prc.audit_type_code= rskQtr.audit_type_code and prc.risk_category_code = rskQtr.risk_category_code "
				+"     WHERE "
				+"   prc.legal_entity_code=:legalEntityCode and prc.audit_type_code=:auditType "
				+"   ORDER BY rating_internal  ");

				
				Query hqlQuery= session.createNativeQuery(query.toString())
						.setParameter("previousFinancialYearQ1StartDate", previousFinancialYearQ1StartDate)
						.setParameter("previousFinancialYearQ2StartDate", previousFinancialYearQ2StartDate)
						.setParameter("previousFinancialYearQ3StartDate", previousFinancialYearQ3StartDate)
						.setParameter("previousFinancialYearQ4StartDate", previousFinancialYearQ4StartDate)
						.setParameter("previousFinancialYearQ1EndDate", previousFinancialYearQ1EndDate)
						.setParameter("previousFinancialYearQ2EndDate", previousFinancialYearQ2EndDate)
						.setParameter("previousFinancialYearQ3EndDate", previousFinancialYearQ3EndDate)
						.setParameter("previousFinancialYearQ4EndDate", previousFinancialYearQ4EndDate)
						
						.setParameter("nextFinancialYearQ1StartDate",nextFinancialYearQ1StartDate)
						.setParameter("nextFinancialYearQ2StartDate",nextFinancialYearQ2StartDate)
						.setParameter("nextFinancialYearQ3StartDate",nextFinancialYearQ3StartDate)
						.setParameter("nextFinancialYearQ4StartDate",nextFinancialYearQ4StartDate)
						.setParameter("nextFinancialYearQ1EndDate", nextFinancialYearQ1EndDate)
						.setParameter("nextFinancialYearQ2EndDate", nextFinancialYearQ2EndDate)
						.setParameter("nextFinancialYearQ3EndDate", nextFinancialYearQ3EndDate)
						.setParameter("nextFinancialYearQ4EndDate", nextFinancialYearQ4EndDate)

						.setParameter("legalEntityCode", legalEntityCode);
					
						if(!BankAuditUtil.isEmptyString(auditType)){
							hqlQuery.setParameter("auditType", auditType);
						}
						
						if(!BankAuditUtil.isEmptyString(unitType)){
							hqlQuery.setParameter("unitType", unitType);
						}
						
				        if(!BankAuditUtil.isEmptyString(criticality)){
				        	hqlQuery.setParameter("criticality", criticality);
						}
					 
				        if(role.equalsIgnoreCase("RVWR") ||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){ // Operation role also included
				        	if(unitList.isEmpty()){
								unitList.add("");
							}
				        	hqlQuery.setParameterList("unitList",unitList);
						}else{
							hqlQuery.setParameter("userId",userId);
							          
						}
 		Map<String,String> ratingsMap = new HashMap<>();
 		Map<String,Long> periodMap = new HashMap<>();
 		List lst= hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				RatingTrendDto ratingTrendDto=null; 
				if(tuple!=null){
					ratingTrendDto=new RatingTrendDto();
					if(tuple[0]!=null){
						ratingTrendDto.setRating(tuple[0].toString());
						ratingsMap.put(tuple[0].toString(), tuple[0].toString()); // To collect all Quarters having values
					}
					if(tuple[1]!=null){
						ratingTrendDto.setPeriod(tuple[1].toString());		
						periodMap.put(tuple[0].toString()+"-"+tuple[1].toString(), Long.parseLong(tuple[2].toString()));
		            }
					if(tuple[2]!=null){
						ratingTrendDto.setUnitCount(Long.parseLong(tuple[2].toString()));
					}
				}
				return ratingTrendDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
 		
 		List<Map<String, Map<String,Long>>> resultLst = new ArrayList();
 		
 	//Logic to Check and append the missing HalfYears
 		Map<String,Long> periodFnMap = new HashMap();
 		Map<String,Map<String, Long>> periodRatMap = new HashMap();
 		//String[] qtrArry= {"PREV_Q1","PREV_Q2","PREV_Q3","PREV_Q4","CUR_Q1","CUR_Q2","CUR_Q3","CUR_Q4"}; //commented to implement logic
 		
 		/**** Logic modified to retrieve the data till the current Quarter ****/
 		List<String> qtrArry = new ArrayList<String>(Arrays.asList("PREV_Q1","PREV_Q2","PREV_Q3","PREV_Q4","CUR_Q1"));
 		logger.info("bsnsDateLcl.."+bsnsDateLcl +" nextFinancialYearQ4StartDate.."+nextFinancialYearQ4StartDate);
 		if(bsnsDateLcl.compareTo(nextFinancialYearQ4StartDate) >= 0) {
 			qtrArry.add("CUR_Q2");
 			qtrArry.add("CUR_Q3");
 			qtrArry.add("CUR_Q4");
 		}else if(bsnsDateLcl.compareTo(nextFinancialYearQ3StartDate) >= 0) {
 			qtrArry.add("CUR_Q2");
 			qtrArry.add("CUR_Q3");
 		}else if(bsnsDateLcl.compareTo(nextFinancialYearQ2StartDate) >= 0) {
 			qtrArry.add("CUR_Q2");
 		}
 		/** End here*/
 		
		try {
			System.out.println("ratingsMap .... "+ratingsMap); System.out.println("periodMap .... "+periodMap);System.out.println("qtrArry .... "+qtrArry);
			for (Map.Entry<String, String> entry : ratingsMap.entrySet()) {
				periodRatMap = new HashMap();
				periodFnMap = new HashMap();
				for(String qtr: qtrArry) {
					if(!periodMap.containsKey(entry.getKey()+"-"+qtr))
						periodFnMap.put(qtr, 0l);
					else periodFnMap.put(qtr, periodMap.get(entry.getKey()+"-"+qtr));
				}
				Map<String,Long> sorted2=new TreeMap<>(new PeriodComparator());  // Logic to arrange the periods like 
				sorted2.putAll(periodFnMap);
				
				periodRatMap.put(entry.getKey(), sorted2);
				resultLst.add(periodRatMap);
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		//ends here
       
		System.out.println("resultLst .."+ resultLst);
        return resultLst;
	}
	
	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<Map<String, Map<String,Long>>> getRatingTrendHalfYearly(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId,String role,List<String> unitList,String unitType,String criticality, Date businessDate) {
		
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDate);
		
		Integer year=null;
		
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		Integer currentYear=year;
		Integer previousYear=currentYear-1;
		
		LocalDate bsnsDateLcl= LocalDate.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH)+1,calendar.get(Calendar.DAY_OF_MONTH) ); // to get the Business date in the Local date format, for comparing the Dates
		
		/*PREVIOUS YEAR half year dates */
        //LocalDate previousFinancialYearFirstHalfStartDate = LocalDate.of(previousYear, 04, 1);
		
		LocalDate FinancialYearStartDate  = dashboardDao.getFinancialYearStartDate(legalEntityCode);
		logger.info("FinancialYearStartDate :: "+FinancialYearStartDate);
		
		LocalDate previousFinancialYearFirstHalfStartDate = FinancialYearStartDate.minusMonths(12);
		LocalDate previousFinancialYearFirstHalfEndDate = previousFinancialYearFirstHalfStartDate.plusMonths(6).minusDays(1);

		LocalDate  previousFinancialYearSecondtHalfStartDate =previousFinancialYearFirstHalfEndDate.plusDays(1);
		LocalDate  previousFinancialYearSecondtHalfEndDate = previousFinancialYearSecondtHalfStartDate.plusMonths(6).minusDays(1);

		/*CURRENT YEAR quarters*/
		LocalDate nextFinancialYearFirstHalfStartDate = previousFinancialYearSecondtHalfEndDate.plusDays(1);
		LocalDate nextFinancialYearFirstHalfEndDate = nextFinancialYearFirstHalfStartDate.plusMonths(6).minusDays(1);

		LocalDate  nextFinancialYearSecondtHalfStartDate =nextFinancialYearFirstHalfEndDate.plusDays(1);
		LocalDate  nextFinancialYearSecondtHalfEndDate = nextFinancialYearSecondtHalfStartDate.plusMonths(6).minusDays(1);
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		logger.info("Inside getAuditStatusQuarterly.... userId "+userId );
			StringBuilder query= new StringBuilder(" SELECT  "
				+" prc.risk_category_desc,rskQtr.period,rskQtr.audit_count from risk_score_percentage prc left join "

				+" (SELECT  "
				+"     COUNT(aus.audit_status) AS audit_count, "
				+"    rsk.risk_category_code,rsk.legal_entity_code,rsk.audit_type_code, "
				+"     (CASE "
				+"         WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearFirstHalfStartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearFirstHalfEndDate THEN 'PREV_FIRST_HF' "
				+"         WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearSecondtHalfStartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearSecondtHalfEndDate THEN 'PREV_SECOND_HF' "
				+" 		   WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearFirstHalfStartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearFirstHalfEndDate THEN 'CUR_FIRST_HF' "
				+"         WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearSecondtHalfStartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearSecondtHalfEndDate THEN 'CUR_SECOND_HF' "
				+"         ELSE 'CUR_HF' "
				+"     END) AS period "
				+" FROM "
				+"     audit_schedule AS aus, "
				+"     maint_entity AS me, risk_score_percentage rsk "
				+" WHERE "
				+"     aus.legal_entity_code = me.legal_entity_code "
				+"         AND aus.unit_id = me.unit_code "
				+"         AND aus.legal_entity_code = :legalEntityCode "
				+"         AND aus.audit_status IN ('AS', 'AR', 'AW', 'AC', 'AF') "
				+"         AND DATE(aus.schedule_start_date) BETWEEN :previousFinancialYearFirstHalfStartDate AND :nextFinancialYearSecondtHalfEndDate "
				+"         And aus.legal_entity_code=rsk.legal_entity_code AND aus.audit_type_code=rsk.audit_type_code "
				+"         AND me.legal_entity_code=rsk.legal_entity_code "
				+"         AND (aus.assessed_risk_prcntg >= rsk.minimun_per AND aus.assessed_risk_prcntg < rsk.maximum_per) ");
				
				if(!BankAuditUtil.isEmptyString(auditType)){
					query.append(" AND aus.audit_type_code =:auditType ");
				}
				if(!BankAuditUtil.isEmptyString(unitType)){
					query.append(" AND me.unit_type =:unitType ");
				}
				if(!BankAuditUtil.isEmptyString(criticality)){
					query.append(" AND me.u_criticality =:criticality  ");
				}
				if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
					query.append(" AND me.unit_code IN (:unitList) ");
				}
			
				query.append(" GROUP BY  rsk.risk_category_code,rsk.legal_entity_code,rsk.audit_type_code, "
				+"     (CASE "
				+"         WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearFirstHalfStartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearFirstHalfEndDate THEN 'PREV_FIRST_HF' "
				+"         WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearSecondtHalfStartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearSecondtHalfEndDate THEN 'PREV_SECOND_HF' "
				+" 		   WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearFirstHalfStartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearFirstHalfEndDate THEN 'CUR_FIRST_HF' "
				+"         WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearSecondtHalfStartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearSecondtHalfEndDate THEN 'CUR_SECOND_HF' "
				+"         ELSE 'CUR_HF' "
				+"     END)) as rskQtr  "
				+"     ON prc.legal_entity_code = rskQtr.legal_entity_code and prc.audit_type_code= rskQtr.audit_type_code and prc.risk_category_code = rskQtr.risk_category_code "
				+"     WHERE "
				+"   prc.legal_entity_code=:legalEntityCode and prc.audit_type_code=:auditType "
				+"   ORDER BY rating_internal  ");

				
				Query hqlQuery= session.createNativeQuery(query.toString())
						.setParameter("previousFinancialYearFirstHalfStartDate", previousFinancialYearFirstHalfStartDate)
						.setParameter("previousFinancialYearFirstHalfEndDate", previousFinancialYearFirstHalfEndDate)
						.setParameter("previousFinancialYearSecondtHalfStartDate", previousFinancialYearSecondtHalfStartDate)
						.setParameter("previousFinancialYearSecondtHalfEndDate", previousFinancialYearSecondtHalfEndDate)
						.setParameter("nextFinancialYearFirstHalfStartDate", nextFinancialYearFirstHalfStartDate)
						.setParameter("nextFinancialYearFirstHalfEndDate", nextFinancialYearFirstHalfEndDate)
						.setParameter("nextFinancialYearSecondtHalfStartDate", nextFinancialYearSecondtHalfStartDate)
						.setParameter("nextFinancialYearSecondtHalfEndDate", nextFinancialYearSecondtHalfEndDate)
						
						.setParameter("legalEntityCode", legalEntityCode);
					
						if(!BankAuditUtil.isEmptyString(auditType)){
							hqlQuery.setParameter("auditType", auditType);
						}
						
						if(!BankAuditUtil.isEmptyString(unitType)){
							hqlQuery.setParameter("unitType", unitType);
						}
						
				        if(!BankAuditUtil.isEmptyString(criticality)){
				        	hqlQuery.setParameter("criticality", criticality);
						}
					 
				        if(role.equalsIgnoreCase("RVWR") ||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){ // Operation role also included
				        	if(unitList.isEmpty()){
								unitList.add("");
							}
				        	hqlQuery.setParameterList("unitList",unitList);
						}else{
							hqlQuery.setParameter("userId",userId);
							          
						}
 		Map<String,String> ratingsMap = new HashMap<>();
 		Map<String,Long> periodMap = new HashMap<>();
 		List lst= hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				RatingTrendDto ratingTrendDto=null; 
				if(tuple!=null){
					ratingTrendDto=new RatingTrendDto();
					if(tuple[0]!=null){
						ratingTrendDto.setRating(tuple[0].toString());
						ratingsMap.put(tuple[0].toString(), tuple[0].toString()); // To collect all Quarters having values
					}
					if(tuple[1]!=null){
						ratingTrendDto.setPeriod(tuple[1].toString());		
						periodMap.put(tuple[0].toString()+"-"+tuple[1].toString(), Long.parseLong(tuple[2].toString()));
		            }
					if(tuple[2]!=null){
						ratingTrendDto.setUnitCount(Long.parseLong(tuple[2].toString()));
					}
				}
				return ratingTrendDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
 		
 		List<Map<String, Map<String,Long>>> resultLst = new ArrayList();
 		
 		//Logic to Check and append the missing HalfYears
 		Map<String,Long> periodFnMap = new HashMap();
 		Map<String,Map<String, Long>> periodRatMap = new HashMap();
 		
 		/**** Logic modified to retrieve the data till the current Quarter ****/
 		//String[] hlfYrArry= {"PREV_FIRST_HF","PREV_SECOND_HF","CUR_FIRST_HF","CUR_SECOND_HF"};
 		List<String> hlfYrArry = new ArrayList<String>(Arrays.asList("PREV_FIRST_HF","PREV_SECOND_HF","CUR_FIRST_HF"));
 		logger.info("bsnsDateLcl.."+bsnsDateLcl +" nextFinancialYearSecondtHalfStartDate.."+nextFinancialYearSecondtHalfStartDate);
 		if(bsnsDateLcl.compareTo(nextFinancialYearSecondtHalfStartDate) >= 0) {
 			hlfYrArry.add("CUR_SECOND_HF");
 		}
 		/** End here*/
 		
		try {
			System.out.println("ratingsMap .... "+ratingsMap); System.out.println("periodMap .... "+periodMap);
			for (Map.Entry<String, String> entry : ratingsMap.entrySet()) {
				periodRatMap = new HashMap();
				periodFnMap = new HashMap();
				for(String hlfYr: hlfYrArry) {
					if(!periodMap.containsKey(entry.getKey()+"-"+hlfYr))
						periodFnMap.put(hlfYr, 0l);
					else periodFnMap.put(hlfYr, periodMap.get(entry.getKey()+"-"+hlfYr));
				}
				Map<String,Long> sorted2=new TreeMap<>(new PeriodComparator());  // Logic to arrange the periods like 
				sorted2.putAll(periodFnMap);
				
				periodRatMap.put(entry.getKey(), sorted2);
				resultLst.add(periodRatMap);
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		//ends here
       
		System.out.println("resultLst .."+ resultLst);
        return resultLst;
	}
	
	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<Map<String, Map<String,Long>>> getRatingTrendYearly(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId,String role,List<String> unitList,String unitType,String criticality, Date businessDate) {
		
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDate);
		Integer year=null;
		
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		Integer currentYear=year;
		Integer previousYear=currentYear-1;
		
		/*PREVIOUS YEAR  dates */
        //LocalDate previousFinancialYearStartDate = LocalDate.of(previousYear, 04, 1);
		
		LocalDate FinancialYearStartDate  = dashboardDao.getFinancialYearStartDate(legalEntityCode);
		logger.info("FinancialYearStartDate :: "+FinancialYearStartDate);
		
		LocalDate previousFinancialYearStartDate = FinancialYearStartDate.minusMonths(12);
		LocalDate previousFinancialYearEndDate = previousFinancialYearStartDate.plusMonths(12).minusDays(1);

       /*CURRENT YEAR dates*/
		LocalDate nextFinancialYearStartDate = previousFinancialYearEndDate.plusDays(1);
		LocalDate nextFinancialYearEndDate = nextFinancialYearStartDate.plusMonths(12).minusDays(1);
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		logger.info("Inside getAuditStatusQuarterly.... userId "+userId );
			StringBuilder query= new StringBuilder(" SELECT  "
				+" prc.risk_category_desc,rskQtr.period,rskQtr.audit_count from risk_score_percentage prc left join "

				+" (SELECT  "
				+"     COUNT(aus.audit_status) AS audit_count, "
				+"    rsk.risk_category_code,rsk.legal_entity_code,rsk.audit_type_code, "
				+"     (CASE "
				+"         WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearStartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearEndDate THEN 'PREV_YEAR' "
				+"         WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearStartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearEndDate THEN 'CUR_YEAR' "
				+"         ELSE 'CUR_YR' "
				+"     END) AS period "
				+" FROM "
				+"     audit_schedule AS aus, "
				+"     maint_entity AS me, risk_score_percentage rsk "
				+" WHERE "
				+"     aus.legal_entity_code = me.legal_entity_code "
				+"         AND aus.unit_id = me.unit_code "
				+"         AND aus.legal_entity_code = :legalEntityCode "
				+"         AND aus.audit_status IN ('AS', 'AR', 'AW', 'AC', 'AF') "
				+"         AND DATE(aus.schedule_start_date) BETWEEN :previousFinancialYearStartDate AND :nextFinancialYearEndDate "
				+"         And aus.legal_entity_code=rsk.legal_entity_code AND aus.audit_type_code=rsk.audit_type_code "
				+"         AND me.legal_entity_code=rsk.legal_entity_code "
				+"         AND (aus.assessed_risk_prcntg >= rsk.minimun_per AND aus.assessed_risk_prcntg < rsk.maximum_per) ");
				
				if(!BankAuditUtil.isEmptyString(auditType)){
					query.append(" AND aus.audit_type_code =:auditType ");
				}
				if(!BankAuditUtil.isEmptyString(unitType)){
					query.append(" AND me.unit_type =:unitType ");
				}
				if(!BankAuditUtil.isEmptyString(criticality)){
					query.append(" AND me.u_criticality =:criticality  ");
				}
				if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
					query.append(" AND me.unit_code IN (:unitList) ");
				}
			
				query.append(" GROUP BY  rsk.risk_category_code,rsk.legal_entity_code,rsk.audit_type_code, "
				+"     (CASE "
				+"         WHEN DATE(aus.schedule_start_date) >= :previousFinancialYearStartDate AND DATE(aus.schedule_start_date) <= :previousFinancialYearEndDate THEN 'PREV_YEAR' "
				+"         WHEN DATE(aus.schedule_start_date) >= :nextFinancialYearStartDate AND DATE(aus.schedule_start_date) <= :nextFinancialYearEndDate THEN 'CUR_YEAR' "
				+"         ELSE 'CUR_YR' "
				+"     END)) as rskQtr  "
				+"     ON prc.legal_entity_code = rskQtr.legal_entity_code and prc.audit_type_code= rskQtr.audit_type_code and prc.risk_category_code = rskQtr.risk_category_code "
				+"     WHERE "
				+"   prc.legal_entity_code=:legalEntityCode and prc.audit_type_code=:auditType "
				+"   ORDER BY rating_internal  ");

				
				Query hqlQuery= session.createNativeQuery(query.toString())
						.setParameter("previousFinancialYearStartDate", previousFinancialYearStartDate)
						.setParameter("previousFinancialYearEndDate", previousFinancialYearEndDate)
						.setParameter("nextFinancialYearStartDate", nextFinancialYearStartDate)
						.setParameter("nextFinancialYearEndDate", nextFinancialYearEndDate)
						
						.setParameter("legalEntityCode", legalEntityCode);
					
						if(!BankAuditUtil.isEmptyString(auditType)){
							hqlQuery.setParameter("auditType", auditType);
						}
						
						if(!BankAuditUtil.isEmptyString(unitType)){
							hqlQuery.setParameter("unitType", unitType);
						}
						
				        if(!BankAuditUtil.isEmptyString(criticality)){
				        	hqlQuery.setParameter("criticality", criticality);
						}
					 
				        if(role.equalsIgnoreCase("RVWR") ||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){ // Operation role also included
				        	if(unitList.isEmpty()){
								unitList.add("");
							}
				        	hqlQuery.setParameterList("unitList",unitList);
						}else{
							hqlQuery.setParameter("userId",userId);
							          
						}
 		Map<String,String> ratingsMap = new HashMap<>();
 		Map<String,Long> periodMap = new HashMap<>();
 		List lst= hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				RatingTrendDto ratingTrendDto=null; 
				if(tuple!=null){
					ratingTrendDto=new RatingTrendDto();
					if(tuple[0]!=null){
						ratingTrendDto.setRating(tuple[0].toString());
						ratingsMap.put(tuple[0].toString(), tuple[0].toString()); // To collect all Quarters having values
					}
					if(tuple[1]!=null){
						ratingTrendDto.setPeriod(tuple[1].toString());		
						periodMap.put(tuple[0].toString()+"-"+tuple[1].toString(), Long.parseLong(tuple[2].toString()));
		            }
					if(tuple[2]!=null){
						ratingTrendDto.setUnitCount(Long.parseLong(tuple[2].toString()));
					}
				}
				return ratingTrendDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
 		
 		List<Map<String, Map<String,Long>>> resultLst = new ArrayList();
 		
 		//Logic to Check and append the missing HalfYears
 		Map<String,Long> periodFnMap = new HashMap();
 		Map<String,Map<String, Long>> periodRatMap = new HashMap();
 		String[] hlfYrArry= {"PREV_YEAR","CUR_YEAR"};
		try {
			System.out.println("ratingsMap .... "+ratingsMap); System.out.println("periodMap .... "+periodMap);
			for (Map.Entry<String, String> entry : ratingsMap.entrySet()) {
				periodRatMap = new HashMap();
				periodFnMap = new HashMap();
				for(String hlfYr: hlfYrArry) {
					if(!periodMap.containsKey(entry.getKey()+"-"+hlfYr))
						periodFnMap.put(hlfYr, 0l);
					else periodFnMap.put(hlfYr, periodMap.get(entry.getKey()+"-"+hlfYr));
				}
				Map<String,Long> sorted2=new TreeMap<>(new PeriodComparator());  // Logic to arrange the periods like 
				sorted2.putAll(periodFnMap);
				
				periodRatMap.put(entry.getKey(), sorted2);
				resultLst.add(periodRatMap);
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		//ends here
       
		System.out.println("resultLst .."+ resultLst);
        return resultLst;
	}
	
	
	
	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<Map<String,Long>> getRatingCountByDateForTrend(int legalEntityCode, String auditType,String role,List<String> unitList,List<String> auditsList, String unitType,String criticality) {
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
	    List<Map<String, Long>> ratingsLst =null;
	    try {
		StringBuilder query= new StringBuilder(
				          " SELECT  COUNT(aus.unit_id) ,"
				         +"  CONCAT(rsp.risk_category_code,'-',rsp.risk_category_desc) AS assessed_rating "  
						 +" FROM "
						 +"   risk_score_percentage AS rsp  "
						 +"   LEFT JOIN audit_schedule AS aus  "
						 +"     ON aus.legal_entity_code = rsp.legal_entity_code  "
						 +"     AND aus.audit_status IN ('AC', 'AS', 'AR', 'WS')  "
						 +"     AND aus.audit_type_code = rsp.audit_type_code "
						 +"     AND IFNULL(aus.assessed_risk_prcntg,100) > rsp.minimun_per AND IFNULL(aus.assessed_risk_prcntg,100) <= rsp.maximum_per " 
				);
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND aus.unit_id in (select unit_code from MaintEntity where legal_entity_code=aus.legal_entity_code "
					+ " and unit_type =:unitType  )  ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND aus.unit_id in (select unit_code from MaintEntity where legal_entity_code=aus.legal_entity_code "
					+ " and u_criticality =:criticality  )  ");
     	}
		
		query.append(" AND aus.audit_id IN (:auditsList)      "
				 +"     WHERE rsp.legal_entity_code =:legalEntityCode ");
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND rsp.audit_type_code =:auditType ");
		}
		
		query.append(
				" GROUP BY rsp.risk_category_code "
				+" ORDER BY rating_internal desc " // to show the ratings in the Descending order
		);
	
		Query hqlQuery= session.createNativeQuery(query.toString())
		//.setParameter("fromDate", fromDate)
		//.setParameter("toDate", toDate)
		.setParameter("auditsList", auditsList)
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}	
        
        Map ratingMap = new HashMap<String, Long>();
        long ratedUnits=0;
        
        List lst = hqlQuery.list();
        ratingsLst = new ArrayList();
 		for(Object obj: lst) {
 			Object[] obji=(Object[])obj;
 			ratingMap.put(obji[1].toString(), Long.parseLong(obji[0].toString()));
 			ratingsLst.add(ratingMap);
 			ratedUnits +=Long.parseLong(obji[0].toString());
 			ratingMap = new HashMap();
 		}
        
        logger.info("ratingsLst .."+ratingsLst);
        logger.info("ratedUnits .."+ratedUnits);
        long unitsCount = unitList.size();
        long unitsUnRatedCount = unitsCount - ratedUnits;
        if(unitsUnRatedCount > 0){
        	ratingMap.put("U-UnRated", unitsUnRatedCount);
        	ratingsLst.add(ratingMap);
        }
        logger.info("ratingsLst .."+ratingsLst);
	    }catch(Exception e) {
	    	e.printStackTrace(System.out);
	    }
	    return ratingsLst;
				
	}
	
	
	
	
	
	
	
	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<RealTimeRectificationResponseDto> getRealTimeRectification(int legalEntityCode, String auditType,
			String period, LocalDate fromDate, LocalDate toDate, String userId,String role,List<String> unitList,String unitType,String criticality) {
		
		//Code by Debasish to handle default AuditType code // need to comment
		if(auditType != null && !auditType.trim().equals("") );
		else auditType="AT001";
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		logger.info("Inside getAuditStatusQuarterly.... userId "+userId );
			StringBuilder query= new StringBuilder(" SELECT  "
				+" prc.risk_category_desc,rskPrc.audit_range,rskPrc.audit_count from risk_score_percentage prc left join "

				+" (SELECT  "
				+"     COUNT(aus.audit_status) AS audit_count, "
				+"    rsk.risk_category_code,rsk.legal_entity_code,rsk.audit_type_code, "
				+"     (CASE "  
				+"           WHEN (100*`rectified_findings`)/`total_findings`>=0 AND (100*`rectified_findings`)/`total_findings`<20  THEN '0-20' "  
				+"           WHEN (100*`rectified_findings`)/`total_findings`<40 THEN '20-40' "
				+"		   WHEN (100*`rectified_findings`)/`total_findings`<60 THEN '40-60' " 
				+"	       WHEN (100*`rectified_findings`)/`total_findings`<80 THEN '60-80' " 
				+"		   ELSE '80-100'  END) AS audit_range "
				+" FROM "
				+"     audit_schedule AS aus, "
				+"     maint_entity AS me, risk_score_percentage rsk "
				+" WHERE "
				+"     aus.legal_entity_code = me.legal_entity_code "
				+"         AND aus.unit_id = me.unit_code "
				+"         AND aus.legal_entity_code = :legalEntityCode "
				+"         AND aus.audit_status IN ('AS', 'AR', 'AW', 'AC', 'AF') "
				+"         AND actual_start_date BETWEEN :fromDate AND :toDate  "
				+"         And aus.legal_entity_code=rsk.legal_entity_code AND aus.audit_type_code=rsk.audit_type_code "
				+"         AND me.legal_entity_code=rsk.legal_entity_code "
				+"         AND (aus.assessed_risk_prcntg >= rsk.minimun_per AND aus.assessed_risk_prcntg < rsk.maximum_per) ");
				
				if(!BankAuditUtil.isEmptyString(auditType)){
					query.append(" AND aus.audit_type_code =:auditType ");
				}
				if(!BankAuditUtil.isEmptyString(unitType)){
					query.append(" AND me.unit_type =:unitType ");
				}
				if(!BankAuditUtil.isEmptyString(criticality)){
					query.append(" AND me.u_criticality =:criticality  ");
				}
				if(role.equalsIgnoreCase("ADTR")){
					query.append(" AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
							 +"    aus.legal_entity_code=aut.legal_entity_code "
							 +"    AND aus.audit_type_code=aut.audit_type_code "
							 +"    AND aus.plan_id=aut.plan_id "
							 +"    AND aus.audit_id=aut.audit_id "
							 +"    AND aut.user_id =:userId    "
							 +"    ) ");
				}else if(role.equalsIgnoreCase("BU")||role.equalsIgnoreCase("BL")){
					query.append(" AND  aus.unit_id IN (SELECT t.unit_code FROM user t WHERE "
							+ " t.legal_entity_code =aus.legal_entity_code "
							+ " and t.user_id=:userId  ) ");
				}else if(role.equalsIgnoreCase("RVWR") || role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
					query.append(" AND  aus.unit_id IN (:unitList) ");
				}
							
				query.append(" GROUP BY  rsk.risk_category_code,rsk.legal_entity_code,rsk.audit_type_code, "
				+"     (CASE "  
				+"           WHEN (100*`rectified_findings`)/`total_findings`>=0 AND (100*`rectified_findings`)/`total_findings`<20  THEN '0-20' "  
				+"           WHEN (100*`rectified_findings`)/`total_findings`<40 THEN '20-40' "
				+"		   WHEN (100*`rectified_findings`)/`total_findings`<60 THEN '40-60' " 
				+"	       WHEN (100*`rectified_findings`)/`total_findings`<80 THEN '60-80' " 
				+"		   ELSE '80-100' END)"
				+"   )AS rskPrc "
				+"     ON prc.legal_entity_code = rskPrc.legal_entity_code and prc.audit_type_code= rskPrc.audit_type_code and prc.risk_category_code = rskPrc.risk_category_code "
				+"     WHERE "
				+"   prc.legal_entity_code=:legalEntityCode and prc.audit_type_code=:auditType "
				+"   ORDER BY rating_internal desc,audit_range asc  ");

				
				Query hqlQuery= session.createNativeQuery(query.toString())
						.setParameter("fromDate", fromDate)
						.setParameter("toDate", toDate)
						.setParameter("legalEntityCode", legalEntityCode);
					
						if(!BankAuditUtil.isEmptyString(auditType)){
							hqlQuery.setParameter("auditType", auditType);
						}
						
						if(!BankAuditUtil.isEmptyString(unitType)){
							hqlQuery.setParameter("unitType", unitType);
						}
						
				        if(!BankAuditUtil.isEmptyString(criticality)){
				        	hqlQuery.setParameter("criticality", criticality);
						}
					 
				        if(role.equalsIgnoreCase("RVWR") ||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){ // Operation role also included
				        	if(unitList.isEmpty()){
								unitList.add("");
							}
				        	hqlQuery.setParameterList("unitList",unitList);
						}else{
							hqlQuery.setParameter("userId",userId);
							          
						}
 		Map<String,String> ratingsMap = new HashMap<>();
 		Map<String,Integer> rangeMap = new HashMap<>();
 		/*List lst= hqlQuery.setResultTransformer(new ResultTransformer() {
 		  @Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				RealTimeRectificationResponseDto realTimeRectificationResponseDto=null;
				if(tuple!=null){
					realTimeRectificationResponseDto=new RealTimeRectificationResponseDto();
					if(tuple[0]!=null){
						realTimeRectificationResponseDto.setRating(tuple[0].toString())
						ratingsMap.put(tuple[0].toString(), tuple[0].toString()); // To collect all Quarters having values
					}
					if(tuple[1]!=null){
						realTimeRectificationResponseDto.setAuditRange(tuple[1].toString());		
						rangeMap.put(tuple[0].toString()+"_"+tuple[1].toString(), Integer.parseInt(tuple[2].toString()));
		            }
					if(tuple[2]!=null){
						realTimeRectificationResponseDto.setUnitCount(Integer.parseInt(tuple[2].toString()));
					}
				}
				return realTimeRectificationResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();*/
 		List lst = hqlQuery.list();
 		List<String> ratingsLst = new ArrayList();
 		for(Object obj: lst) {
 			Object[] obji=(Object[])obj;
 			if(!ratingsLst.contains(obji[0].toString())) ratingsLst.add(obji[0].toString());
 			if(obji[1]!=null ) {
 				rangeMap.put(obji[0].toString()+"_"+obji[1].toString(), Integer.parseInt(obji[2].toString()));
 			}
 		}
 		List<RealTimeRectificationResponseDto> resultLst = new ArrayList();
 		
 		//Logic to Check and append the missing rectificaion Range
 		String[] rectPrcRangeArr= {"0-20","20-40","40-60","60-80","80-100"};
		try {
			System.out.println("ratingsMap .... "+ratingsMap); System.out.println("ratingsLst .... "+ratingsLst); System.out.println("rangeMap .... "+rangeMap);
			//for (Map.Entry<String, String> entry : ratingsMap.entrySet()) {
			for (String ratings: ratingsLst) {
				for(String rectPrcRange: rectPrcRangeArr) {
					RealTimeRectificationResponseDto realTimeRectificationResponseDto = new RealTimeRectificationResponseDto();
					realTimeRectificationResponseDto.setRating(ratings);
					realTimeRectificationResponseDto.setAuditRange(rectPrcRange);
					if(rangeMap.containsKey(ratings+"_"+rectPrcRange)) 
						realTimeRectificationResponseDto.setUnitCount(rangeMap.get(ratings+"_"+rectPrcRange));
					else realTimeRectificationResponseDto.setUnitCount(0);
					resultLst.add(realTimeRectificationResponseDto);
					realTimeRectificationResponseDto = null;
				}
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		//ends here
       
		System.out.println("resultLst .."+ resultLst);
        return resultLst;
	}
	
	
	/**
	 * this method is to fetch the Units subjected to the given Audit Type 
	 */
	public List<String> getUnitsSpecificToAudit(int legalEntityCode,String auditType,List<String> unitList,String jurisdictionYorN)  {
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);
	    List<String > unitsList =null;
		try {
			logger.info("getUnitsSpecificToAudit .. legalEntityCode:: "+ legalEntityCode+" auditType::"+auditType +" unitList::"+unitList+" jurisdictionYorN::"+jurisdictionYorN);
			StringBuilder str = new StringBuilder(" SELECT distinct id  from audit_subgroup_mapping_v  " +  
					 " WHERE mapping_type='E' and legal_entity_code = :legalEntityCode ") ;
		
				if(!BankAuditUtil.isEmptyString(auditType)) {
					str.append(" AND audit_type_code= :auditType ") ;
				}
		
				if(unitList !=null && "Y".equalsIgnoreCase(jurisdictionYorN)) {
					str.append(" AND id in (:unitList) ") ;
				}
		
				Query hqlQuery = session.createNativeQuery(str.toString())
						.setParameter("legalEntityCode", legalEntityCode);
				
				if(!BankAuditUtil.isEmptyString(auditType)) {
					hqlQuery.setParameter("auditType", auditType);
				}		
						
				if(unitList !=null && "Y".equalsIgnoreCase(jurisdictionYorN))
					hqlQuery.setParameter("unitList", unitList);
				
				unitsList=hqlQuery.list();
				
				logger.info("unitsSpecificToAuditList .. "+ unitsList);

		}catch (Exception e) {
			e.getStackTrace();
			throw e;
		}
		return  unitsList;
	}
	
	/**
	 * this method is to fetch the Latest Audit Ids of the Units 
	 */
	public List<String> getLatestAuditsToUnits(int legalEntityCode,String auditType,List<String> unitsSpecificToAuditList, String role, String jurisdictionYorN)  {
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);
	    List<String > auditsList =null;
		try {
			logger.info("getLatestAuditsToUnits .. legalEntityCode:: "+ legalEntityCode+" auditType::"+auditType +" unitsSpecificToAuditList::"+unitsSpecificToAuditList+" role::"+role+" jurisdictionYorN::"+jurisdictionYorN);
			StringBuilder str = new StringBuilder(" SELECT sc.audit_id FROM audit_schedule sc "
					+"    JOIN "
					+"     (SELECT MAX(actual_start_date) AS actual_start_date, "
					+"             unit_id, legal_entity_code,audit_type_code "
					+"     FROM  audit_schedule "
					+"     WHERE "
					+"         legal_entity_code = :legalEntityCode  ");
			if(!BankAuditUtil.isEmptyString(auditType)) {
				str.append(" AND audit_type_code= :auditType " );
			}
			if(unitsSpecificToAuditList !=null && "Y".equalsIgnoreCase(jurisdictionYorN)) {
				str.append(" AND unit_id in (:unitsSpecificToAuditList) ");
			}
			
			str.append("    GROUP BY unit_id,audit_type_code) AS scg  "
					+"     ON sc.legal_entity_code = scg.legal_entity_code "
					+"         AND sc.audit_type_code = scg.audit_type_code "
					+"         AND scg.unit_id = sc.unit_id "
					+"         AND sc.actual_start_date = scg.actual_start_date ");
				
		
				Query hqlQuery = session.createNativeQuery(str.toString())
						.setParameter("legalEntityCode", legalEntityCode);
				if(!BankAuditUtil.isEmptyString(auditType)) {
					hqlQuery.setParameter("auditType", auditType);
				}
				if(unitsSpecificToAuditList !=null && "Y".equalsIgnoreCase(jurisdictionYorN))
					hqlQuery.setParameter("unitsSpecificToAuditList", unitsSpecificToAuditList);
				
				auditsList=hqlQuery.list();
				
				logger.info("Latest Audits list of the Units .. "+ auditsList);

		}catch (Exception e) {
			e.getStackTrace();
			throw e;
		}
		return  auditsList;
	}
	
	
	/**
	 * this method is to fetch the Latest Audit Ids of the Units before a particular given Date
	 */
	public List<String> getLatestByDateAuditsToUnits(int legalEntityCode,String auditType,List<String> unitsSpecificToAuditList, String role, String jurisdictionYorN, LocalDate byDate)  {
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);
	    List<String > auditsList =null;
		try {
			logger.info("getLatestByDateAuditsToUnits .. legalEntityCode:: "+ legalEntityCode+" auditType::"+auditType +" byDate::"+byDate +" unitsSpecificToAuditList::"+unitsSpecificToAuditList+" role::"+role+" jurisdictionYorN::"+jurisdictionYorN);
			StringBuilder str = new StringBuilder(" SELECT sc.audit_id FROM audit_schedule sc "
					+"    JOIN "
					+"     (SELECT MAX(actual_end_date) AS actual_end_date, "
					+"             unit_id, legal_entity_code,audit_type_code "
					+"     FROM  audit_schedule "
					+"     WHERE "
					+"         legal_entity_code = :legalEntityCode   "
					+" 		   AND actual_end_date <= :byDate ");
			if(!BankAuditUtil.isEmptyString(auditType)) {
				str.append(" AND audit_type_code= :auditType " );
			}
			if(unitsSpecificToAuditList !=null && "Y".equalsIgnoreCase(jurisdictionYorN)) {
				str.append(" AND unit_id in (:unitsSpecificToAuditList) ");
			}
			
			str.append("    GROUP BY unit_id) AS scg  "
					+"     ON sc.legal_entity_code = scg.legal_entity_code "
					+"         AND sc.audit_type_code = scg.audit_type_code "
					+"         AND scg.unit_id = sc.unit_id "
					+"         AND sc.actual_end_date = scg.actual_end_date ");
				
		
				Query hqlQuery = session.createNativeQuery(str.toString())
						.setParameter("legalEntityCode", legalEntityCode)
						.setParameter("byDate", byDate);
				if(unitsSpecificToAuditList !=null && "Y".equalsIgnoreCase(jurisdictionYorN)) {
					hqlQuery.setParameter("auditType", auditType);
				}
				if(unitsSpecificToAuditList !=null && "Y".equalsIgnoreCase(jurisdictionYorN))
					hqlQuery.setParameter("unitsSpecificToAuditList", unitsSpecificToAuditList);
				
				auditsList=hqlQuery.list();
				
				logger.info("Latest Audits list of the Units .. "+ auditsList);

		}catch (Exception e) {
			e.getStackTrace();
			throw e;
		}
		return  auditsList;
	}
	
	/**
	 * this method is to fetch the Units subjected to the given Audit Type 
	 */
	public List<String> getUnitsOpenByDateList(int legalEntityCode,String auditType,List<String> unitsSpecificToAuditList,LocalDate byDate)  {
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);
	    List<String > unitsList =null;
		try {
			logger.info("getUnitsSpecificToAudit .. legalEntityCode:: "+ legalEntityCode+" auditType::"+auditType +" unitList::"+unitsSpecificToAuditList+" byDate::"+byDate);
			StringBuilder str = new StringBuilder(" SELECT distinct unit_code  from maint_entity  " +  
					 " WHERE legal_entity_code = :legalEntityCode AND unit_open_date <= :byDate ") ;
		
				if(unitsSpecificToAuditList !=null ) {
					str.append(" AND unit_code in (:unitList) ") ;
				}
		
				Query hqlQuery = session.createNativeQuery(str.toString())
						.setParameter("legalEntityCode", legalEntityCode)
						.setParameter("byDate", byDate);
						//.setParameter("auditType", auditType);
				if(unitsSpecificToAuditList !=null )
					hqlQuery.setParameter("unitList", unitsSpecificToAuditList);
				
				unitsList=hqlQuery.list();
				
				logger.info("unitsSpecificToAuditList .. "+ unitsList);

		}catch (Exception e) {
			e.getStackTrace();
			throw e;
		}
		return  unitsList;
	}
	
	
	/**
	 * this method is to fetch the User Summary for Admin Dashboard  
	 */
	public Map<String, Integer> getUserDtlsforAdminDB(int legalEntityCode,String userId,String role, Date businessDate)  {
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);
	    Map<String, Integer> userSummaryMap = null;
		try {
			logger.info("getUserDtlsforAdminDB .. legalEntityCode:: "+ legalEntityCode+" userId::"+userId +" role::"+role+" businessDate::"+businessDate);
			StringBuilder str = new StringBuilder(" SELECT " 
					+"	(SELECT count(*) FROM user WHERE legal_entity_code = :legalEntityCode AND status='A' AND entity_status='A') as user_cnt, " 
					+"	(SELECT count(*) FROM user WHERE legal_entity_code = :legalEntityCode AND status='A' AND entity_status='A' AND " 
					+"								DATE(current_login)=b.business_date) as user_actve_cnt "  
					+" FROM business_date b WHERE legal_entity_code=:legalEntityCode ");
					
				Query hqlQuery = session.createNativeQuery(str.toString())
						.setParameter("legalEntityCode", legalEntityCode);
							
				List lst=hqlQuery.list();
				userSummaryMap = new HashMap();
				Object[] usrObj= (Object[]) lst.get(0);
				
				userSummaryMap.put("TOTAL_USERS", Integer.parseInt(usrObj[0].toString()));
				userSummaryMap.put("ACTIVE_USERS", Integer.parseInt(usrObj[1].toString()));
				logger.info("User Summary .. "+ userSummaryMap);

		}catch (Exception e) {
			e.getStackTrace();
			throw e;
		}
		return  userSummaryMap;
	}
	
	@Override
	public LocalDate getFinancialYearStartDate(Integer legalEntityCode) {
		Session session=getSession();
	    session.setDefaultReadOnly(true);
		LocalDate FinancialYearStartDate=null;
		try {
			logger.info("getFinancialYearStartDate .. legalEntityCode:: "+ legalEntityCode);
			StringBuilder str = new StringBuilder(" select get_financial_year_endDate(:legalEntityCode) from dual  ");
					
			Query hqlQuery = session.createNativeQuery(str.toString())
						.setParameter("legalEntityCode", legalEntityCode);
							
			Date date=(Date)hqlQuery.uniqueResult();
			logger.info("date is .. "+ date);
			
			Calendar calendar=Calendar.getInstance();
			calendar.setTime(date);
			Integer currentYear=calendar.get(Calendar.YEAR);
			Integer currentMonth=calendar.get(Calendar.MONTH);
			Integer currentDay=calendar.get(Calendar.DAY_OF_MONTH);

			logger.info("currentYear::"+currentYear+" currentMonth::"+currentMonth +" currentDay::"+currentDay);
			
			LocalDate FinancialYearEndDate = LocalDate.of(currentYear, currentMonth+1, currentDay);
			FinancialYearStartDate = FinancialYearEndDate.minusMonths(12).plusDays(1);
			logger.info("FinancialYearEndDate::"+FinancialYearEndDate+" FinancialYearStartDate::"+FinancialYearStartDate );
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		return FinancialYearStartDate;
	}
	
	@Override
	public LocalDate getFinancialYearEndDate(Integer legalEntityCode) {
		Session session=getSession();
	    session.setDefaultReadOnly(true);
		LocalDate FinancialYearEndDate=null;
		try {
			logger.info("getFinancialYearStartDate .. legalEntityCode:: "+ legalEntityCode);
			StringBuilder str = new StringBuilder(" select get_financial_year_endDate(:legalEntityCode) from dual  ");
					
			Query hqlQuery = session.createNativeQuery(str.toString())
						.setParameter("legalEntityCode", legalEntityCode);
							
			Date date=(Date)hqlQuery.uniqueResult();
			logger.info("date is .. "+ date);
			
			Calendar calendar=Calendar.getInstance();
			calendar.setTime(date);
			Integer currentYear=calendar.get(Calendar.YEAR);
			Integer currentMonth=calendar.get(Calendar.MONTH);
			Integer currentDay=calendar.get(Calendar.DAY_OF_MONTH);
			logger.info("currentYear::"+currentYear+" currentMonth::"+currentMonth +" currentDay::"+currentDay);
			
			FinancialYearEndDate = LocalDate.of(currentYear, currentMonth+1, currentDay);
			logger.info("FinancialYearEndDate::"+FinancialYearEndDate );
			logger.info("FinancialYear ::"+FinancialYearEndDate.getYear() +" :: "+FinancialYearEndDate.getMonthValue() +" :: "+FinancialYearEndDate.getDayOfMonth() );
			
		}catch(Exception e) {
			e.printStackTrace();
		}
	return FinancialYearEndDate;
		
	}
	
	
	/**
	 * this method is to fetch the User Roles count for Admin Dashboard  
	 */
	public List<MaintUsergroupRoles> getRolewiseUsersCount(int legalEntityCode,String userId,String role)  {
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);
	    List<MaintUsergroupRoles> listUserRoles = null;
		try {
			logger.info("getRolewiseUsersCount .. legalEntityCode:: "+ legalEntityCode+" userId::"+userId +" role::"+role);
			StringBuilder str = new StringBuilder(" SELECT r.ug_role_code, r.ug_role_desc,r.ug_role_name, r.legal_entity_code , IFNULL(m.role_cnt, 0) as role_cnt, r.entity_status" + 
					"	FROM maint_usergroup_roles r  " + 
					"        LEFT OUTER JOIN " + 
					"    (SELECT COUNT(user_role_id) AS role_cnt,user_role_id,legal_entity_code " + 
					"		FROM user_role_mapping WHERE legal_entity_code =:legalEntityCode " + 
					"		GROUP BY user_role_id) AS m " + 
					"    ON r.ug_role_code = m.user_role_id AND r.legal_entity_code = m.legal_entity_code " + 
					"    WHERE r.entity_status='A' AND r.legal_entity_code =:legalEntityCode  " +
					" 		AND r.ug_role_code != 'SADM' "); //not to consider Super Admin Role for the Client, It is used only for internal BAAS purpose
					
					
				Query hqlQuery = session.createNativeQuery(str.toString())
						.setParameter("legalEntityCode", legalEntityCode);
							
				hqlQuery.setResultTransformer(new ResultTransformer() {
					
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						MaintUsergroupRoles maintUsergroupRoles=null;
						if(tuple!=null){
							maintUsergroupRoles=new MaintUsergroupRoles();
							if(tuple[0]!=null){
								maintUsergroupRoles.setUgRoleCode(tuple[0].toString());
							}
							if(tuple[1]!=null){
								maintUsergroupRoles.setUgRoleDesc(tuple[1].toString());
							}
							if(tuple[2]!=null){
								maintUsergroupRoles.setUgRoleName(tuple[2].toString());
							}
							if(tuple[3]!=null){
								maintUsergroupRoles.setLegalEntityCode(Integer.parseInt(tuple[3].toString()));
							}
							if(tuple[4]!=null){
								maintUsergroupRoles.setRolesCount(Integer.parseInt(tuple[4].toString()));
							}
							if(tuple[5]!=null){
								maintUsergroupRoles.setEntityStatus(tuple[5].toString());
							}
						}
						return maintUsergroupRoles;
					}
					
					@Override
					public List transformList(List collection) {
						return collection;
					}
				});
				listUserRoles=hqlQuery.list();
		}catch(Exception e) {
			e.printStackTrace();
		}
		return listUserRoles;
	}
	
	/**
	 * this method is to fetch the Target Audits and Units eligible for Audit count Operations/Management Dashboard  
	 */
	public Map<String, Integer> getTargetUnitAuditsUnitCount(int legalEntityCode, String unitsLst, String auditTypeCode,String currFinStDate,String currFinEnDate)  {
		 
		Session session=getSession();
	    session.setDefaultReadOnly(true);
	    Map<String, Integer> auditUnitstrgtAuditMap = null;
		try {
			logger.info(" DaoImpl=> getTargetUnitAuditsUnitCount .. legalEntityCode:: "+ legalEntityCode+" auditTypeCode::"+auditTypeCode+" currFinStDate::"+currFinStDate+" currFinEnDate::"+currFinEnDate);
			logger.info(" unitsLst::"+unitsLst);
			StringBuilder str = new StringBuilder("SELECT   COUNT(distinct id) as auditUnits, COUNT(id) as allAuditUnits, SUM(no_of_audits) as targetUnitCount "+ 
					"  FROM "+
					"      (SELECT f.legal_entity_code, f.audit_type_code,  f.frequency,  f.id, "+
					"              CASE "+
					"                  WHEN ISNULL(f.last_audit_date) OR DATE_ADD(f.last_audit_date, INTERVAL f.frequency MONTH) < :currFinStDate "+		// If the no Audits before LAST_FY_END OR The (lastAuditDate+ Frequency) < LAST_FY_END , then 
					"  						THEN FLOOR(DATEDIFF(:currFinEnDate, DATE_ADD(:currFinStDate, INTERVAL f.frequency MONTH)) / (f.frequency * 30.5)) + 1 "+   // Then Calculate the number of Audits possible between [CUR_FY_ST] to [CUR_FY_END] using Frequency
					"                  ELSE FLOOR(DATEDIFF(:currFinEnDate, DATE_ADD(f.last_audit_date, INTERVAL f.frequency MONTH)) / (f.frequency * 30.5)) + 1 "+ // ELSE Calculate the number of Audits possible between [LAST_AUDIT_DATE (of LAST_FY_END) + Frequency] to [CUR_FY_END] using Frequency
					"              END AS no_of_audits, "+
					"              CASE "+
					"                  WHEN ISNULL(f.last_audit_date) THEN :currFinStDate "+
					"                  WHEN DATE_ADD(f.last_audit_date, INTERVAL f.frequency MONTH) < :currFinStDate THEN :currFinStDate "+
					"                  ELSE DATE_ADD(f.last_audit_date, INTERVAL f.frequency MONTH) "+  // code changed from (frequency * 30.5 DAY) to (frequency * 30.5 DAY)
					//"                  ELSE DATE_ADD(f.last_audit_date, INTERVAL f.frequency * 30.5 DAY) "+  
					"              END AS nxt_dt "+
					"      FROM "+
					"          (SELECT p.legal_entity_code, p.audit_type_code, p.frequency, u.id, "+
					"              (SELECT GREATEST(MAX(schedule_start_date), IFNULL(MAX(actual_start_date), '')) "+
					"               FROM audit_schedule sch "+
					"               WHERE sch.legal_entity_code = p.legal_entity_code "+
					"                     AND p.audit_type_code = sch.audit_type_code AND u.id = sch.unit_id "+
					"                     AND schedule_start_date < :currFinStDate) AS last_audit_date "+		// To compare with Schedule_start_date
					//"                     AND schedule_end_date < :currFinStDate) AS last_audit_date "+		// This inner Query to get the Latest Audit date of Previous Financial Year
					"  	 FROM maint_audit_parameter_derived p, risk_score_percentage s,  "+
					"  		(SELECT DISTINCT m.id, a.audit_type_code, "+
					"  			e.u_criticality,  e.classification, "+
					"  			e.unit_type, e.legal_entity_code "+
					"  		FROM maint_entity_audit_subgroup_mapping m, maint_audit_group a, maint_entity e "+
					"  		WHERE a.legal_entity_code = m.legal_entity_code "+
					"  			AND a.legal_entity_code = e.legal_entity_code "+
					"  			AND m.audit_group_code = a.audit_group_code "+
					"  			AND m.mapping_type = 'E' "+
					"  			AND m.id = e.unit_code "+
					"  			AND a.legal_entity_code =:legalEntityCode "+
					"  			AND e.unit_code in ("+unitsLst+") ");
				if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						str.append("	AND a.audit_type_code =:auditTypeCode ");
					}
					str.append(") AS u  "+	// This inner Table to get the Unit Id's eligible for Audit and also to get the Criticality, Classification, UnitType to get the Frequency from AuditParameterDerived table
					"  	 WHERE "+
					"  		p.legal_entity_code = u.legal_entity_code "+
					"              AND p.audit_type_code = u.audit_type_code "+
					"              AND p.legal_entity_code = s.legal_entity_code "+
					"              AND p.u_criticality = u.u_criticality "+
					"              AND p.classification = u.classification "+
					"              AND p.unit_type = u.unit_type "+
					"              AND p.revenue_leakage = 0 "+
					"              AND s.maximum_per = 100 "+
					"              AND s.risk_category_code = p.rating "+
					"              AND s.audit_type_code = p.audit_type_code "+
					"          ) AS f "+
					"      ) AS ast "+
					"  GROUP BY legal_entity_code ");
			
			logger.info("Query is :: "+ str);	
		
			Query hqlQuery = session.createNativeQuery(str.toString())
					.setParameter("legalEntityCode", legalEntityCode)
					.setParameter("currFinStDate",  currFinStDate).setParameter("currFinEnDate", currFinEnDate);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)) hqlQuery.setParameter("auditTypeCode", auditTypeCode);
						
			Object obj = hqlQuery.uniqueResult();
			logger.info("obj .."+obj);
			auditUnitstrgtAuditMap = new HashMap();
			if(obj != null  && ((Object[])obj).length > 0)	{
				logger.info(" 1st ...."+((Object[])obj)[0].toString() +" 2nd ...."+((Object[])obj)[1].toString()+" 3rd...."+((Object[])obj)[2].toString());
				auditUnitstrgtAuditMap.put("AUDIT_UNITS", Integer.parseInt(((Object[])obj)[0].toString()));
				auditUnitstrgtAuditMap.put("TOTAL_AUDIT_UNITS", Integer.parseInt(((Object[])obj)[1].toString()));
				String trgtAudits = ((Object[])obj)[2].toString();
				auditUnitstrgtAuditMap.put("TARGET_AUDITS", Integer.parseInt(trgtAudits.substring(0,trgtAudits.indexOf("."))));
				logger.info("auditUnitstrgtAuditMap  .. "+ auditUnitstrgtAuditMap);
			}else {
				auditUnitstrgtAuditMap.put("TARGET_AUDITS", 0);
			}
		}catch (Exception e) {
			e.getStackTrace();
			throw e;
		}
		return  auditUnitstrgtAuditMap;
	}

	@SuppressWarnings("unchecked")
	@Override
	public int getWatchListForAudits(int legalEntityCode, String auditTypeCode,String startDate) {
		Session session=getSession();
		int watchList=0;
		String auditTypeCode_cond = "";
		try {
			if(!BankAuditUtil.isEmptyString(auditTypeCode))
				auditTypeCode_cond= "AND s.audit_type_code= :auditTypeCode ";
			
			StringBuilder str = new StringBuilder(" "+
					" SELECT COUNT(*) FROM (	"+
					" 		SELECT s.* 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.* FROM audit_schedule s WHERE s.rating_improvement <= -2 AND s.legal_entity_code=:legalEntityCode  "+ auditTypeCode_cond +
					" ) as watchList ");
			
			Query qry =session.createNativeQuery(str.toString())
				.setParameter("legalEntityCode", legalEntityCode)
				.setParameter("startDate",startDate);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode))
				qry.setParameter("auditTypeCode", auditTypeCode);
		
			watchList=Integer.parseInt(qry.list().get(0).toString());
		}catch(Exception e) {
			e.printStackTrace();
		}
		return watchList;
	}
	
	
	
	//************************* Audit Closure Widget included to get in How many days the Audits get closed *************************************//
	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<AuditStatusGraphResponseDto> getAuditClosureStatusQuarterly(Integer legalEntityCode, String auditType,
			String unitType, String criticality, String userId, Date businessDate,String role,List<String> unitList) {
		
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDate);
		Integer year=null;
		
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		Integer currentYear=year;
		Integer previousYear=currentYear-1;
		
	/*	LocalDate previousFinancialYearStartDate=LocalDate.of(previousYear, 04, 1);*/
	    /*	LocalDate currentFinancialYearEndDate=LocalDate.of(currentYear, 03, 31);*/
		
		/*PREVIOUS YEAR quarters */
		//LocalDate previousFinancialYearQ1StartDate = LocalDate.of(previousYear, 04, 1);
		
		LocalDate FinancialYearStartDate  = dashboardDao.getFinancialYearStartDate(legalEntityCode);
		logger.info("FinancialYearStartDate :: "+FinancialYearStartDate);
		
		LocalDate previousFinancialYearQ1StartDate = FinancialYearStartDate.minusMonths(12);
		LocalDate previousFinancialYearQ1EndDate = previousFinancialYearQ1StartDate.plusMonths(3).minusDays(1);

		LocalDate  previousFinancialYearQ2StartDate =previousFinancialYearQ1EndDate.plusDays(1);
		LocalDate  previousFinancialYearQ2EndDate = previousFinancialYearQ2StartDate.plusMonths(3).minusDays(1);


		LocalDate  previousFinancialYearQ3StartDate =previousFinancialYearQ2EndDate.plusDays(1);
		LocalDate  previousFinancialYearQ3EndDate = previousFinancialYearQ3StartDate.plusMonths(3).minusDays(1);

		
		LocalDate  previousFinancialYearQ4StartDate =previousFinancialYearQ3EndDate.plusDays(1);
		LocalDate  previousFinancialYearQ4EndDate = previousFinancialYearQ4StartDate.plusMonths(3).minusDays(1);

       /*CURRENT YEAR quarters*/
		
		LocalDate nextFinancialYearQ1StartDate = previousFinancialYearQ4EndDate.plusDays(1);
		LocalDate nextFinancialYearQ1EndDate = nextFinancialYearQ1StartDate.plusMonths(3).minusDays(1);

		LocalDate  nextFinancialYearQ2StartDate =nextFinancialYearQ1EndDate.plusDays(1);
		LocalDate  nextFinancialYearQ2EndDate = nextFinancialYearQ2StartDate.plusMonths(3).minusDays(1);


		LocalDate  nextFinancialYearQ3StartDate =nextFinancialYearQ2EndDate.plusDays(1);
		LocalDate  nextFinancialYearQ3EndDate = nextFinancialYearQ3StartDate.plusMonths(3).minusDays(1);

		
		LocalDate  nextFinancialYearQ4StartDate =nextFinancialYearQ3EndDate.plusDays(1);
		LocalDate  nextFinancialYearQ4EndDate = nextFinancialYearQ4StartDate.plusMonths(3).minusDays(1);
		
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		logger.info("Inside getAuditStatusQuarterly.... userId "+userId );
		logger.info(" PQ1Strt:: "+ previousFinancialYearQ1StartDate +" PQ1End:: "+previousFinancialYearQ1EndDate);
		logger.info(" PQ2Strt:: "+ previousFinancialYearQ2StartDate +" PQ2End:: "+previousFinancialYearQ2EndDate);
		logger.info(" PQ3Strt:: "+ previousFinancialYearQ3StartDate +" PQ3End:: "+previousFinancialYearQ3EndDate);
		logger.info(" PQ4Strt:: "+ previousFinancialYearQ4StartDate +" PQ4End:: "+previousFinancialYearQ4EndDate);
		logger.info(" CQ3Strt:: "+ nextFinancialYearQ1StartDate +" CQ1End:: "+nextFinancialYearQ1EndDate);
		logger.info(" CQ2Strt:: "+ nextFinancialYearQ2StartDate +" CQ2End:: "+nextFinancialYearQ2EndDate);
		logger.info(" CQ3Strt:: "+ nextFinancialYearQ3StartDate +" CQ3End:: "+nextFinancialYearQ3EndDate);
		logger.info(" CQ4Strt:: "+ nextFinancialYearQ4StartDate +" CQ4End:: "+nextFinancialYearQ4EndDate);
		
		StringBuilder query= new StringBuilder(
				" SELECT COUNT(aus.audit_status) AS audit_count , " 
						 + "   (CASE WHEN datediff(aus.reviewed_date,aus.actual_end_date) BETWEEN 0 AND 30 THEN '30' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 31 AND 60 THEN '60' " 
						 + "		 WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 61 AND 90 THEN '90' "  
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 91 AND 120 THEN '120' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 121 AND 150 THEN '150' "
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 151 AND 180 THEN '180' "
						 + "       ELSE '180 and above' " 
						 + "    END)  AS audit_closure, "					
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearQ1StartDate AND DATE(aus.reviewed_date) <=:previousFinancialYearQ1EndDate  THEN 'PREV_Q1' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearQ2StartDate AND DATE(aus.reviewed_date) <=:previousFinancialYearQ2EndDate THEN 'PREV_Q2' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearQ3StartDate  AND DATE(aus.reviewed_date) <=:previousFinancialYearQ3EndDate THEN 'PREV_Q3' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearQ4StartDate  AND DATE(aus.reviewed_date) <=:previousFinancialYearQ4EndDate THEN 'PREV_Q4' ELSE  " 
						 + "    		" 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearQ1StartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearQ1EndDate  THEN 'CUR_Q1' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearQ2StartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearQ2EndDate THEN 'CUR_Q2' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearQ3StartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearQ3EndDate THEN 'CUR_Q3' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearQ4StartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearQ4EndDate THEN 'CUR_Q4' " 
						 + "    END) 	" 
						 + "    END)   	" 
						 + "    END)   	" 
						 + "    END) 	" 
						 + "    END) 	" 
						 + "    END)   	" 
						 + "    END)   	" 
						 + "    END) AS ytd " 
						 + "   FROM audit_schedule AS aus ,maint_entity AS me " 
						 + "   WHERE  " 
						 + "   aus.legal_entity_code=me.legal_entity_code " 
						 + "   AND aus.unit_id=me.unit_code   " 
						 + "   AND aus.legal_entity_code =:legalEntityCode " 
						 + "   AND aus.audit_status IN ('AW','AC','AF')  " 
						 + "   AND DATE(aus.reviewed_date) BETWEEN :previousFinancialYearQ1StartDate AND :nextFinancialYearQ4EndDate "
				)  ;
		
		// based on role 
		if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			query.append(" AND aus.unit_id in (:unitList) ");
		}else{
			query.append( "    AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					  +"    aus.legal_entity_code=aut.legal_entity_code "
					  +"    AND aus.audit_type_code=aut.audit_type_code "
					  +"    AND aus.plan_id=aut.plan_id "
					  +"    AND aus.audit_id=aut.audit_id "
					  +"    AND aut.user_id =:userId    "
					  +"	AND reviewed_date is not null "
					  +"    ) ");
			          
		}
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
        query.append(
				   "   GROUP BY   "
						 + "   (CASE WHEN datediff(aus.reviewed_date,aus.actual_end_date) BETWEEN 0 AND 30 THEN '30' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 31 AND 60 THEN '60' " 
						 + "		 WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 61 AND 90 THEN '90' "  
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 91 AND 120 THEN '120' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 121 AND 150 THEN '150' "
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 151 AND 180 THEN '180' "
						 + "       ELSE '180 and above' " 
						 + "    END)  , "
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearQ1StartDate AND DATE(aus.reviewed_date) <=:previousFinancialYearQ1EndDate  THEN 'PREV_Q1' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearQ2StartDate AND DATE(aus.reviewed_date) <=:previousFinancialYearQ2EndDate THEN 'PREV_Q2' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearQ3StartDate  AND DATE(aus.reviewed_date) <=:previousFinancialYearQ3EndDate THEN 'PREV_Q3' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearQ4StartDate  AND DATE(aus.reviewed_date) <=:previousFinancialYearQ4EndDate THEN 'PREV_Q4' ELSE  " 
						 + "    " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearQ1StartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearQ1EndDate  THEN 'CUR_Q1' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearQ2StartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearQ2EndDate THEN 'CUR_Q2' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearQ3StartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearQ3EndDate THEN 'CUR_Q3' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearQ4StartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearQ4EndDate THEN 'CUR_Q4' " 
						 + "    END) " 
						 + "    END)   " 
						 + "    END)   " 
						 + "    END) " 
						 + "    END) " 
						 + "    END)   " 
						 + "    END)   " 
						 + "    END) "  
        		);
        
		
		Query hqlQuery= session.createNativeQuery(query.toString())
				.setParameter("previousFinancialYearQ1StartDate", previousFinancialYearQ1StartDate)
				.setParameter("previousFinancialYearQ2StartDate", previousFinancialYearQ2StartDate)
				.setParameter("previousFinancialYearQ3StartDate", previousFinancialYearQ3StartDate)
				.setParameter("previousFinancialYearQ4StartDate", previousFinancialYearQ4StartDate)
				.setParameter("previousFinancialYearQ1EndDate", previousFinancialYearQ1EndDate)
				.setParameter("previousFinancialYearQ2EndDate", previousFinancialYearQ2EndDate)
				.setParameter("previousFinancialYearQ3EndDate", previousFinancialYearQ3EndDate)
				.setParameter("previousFinancialYearQ4EndDate", previousFinancialYearQ4EndDate)
				
				.setParameter("nextFinancialYearQ1StartDate",nextFinancialYearQ1StartDate)
				.setParameter("nextFinancialYearQ2StartDate",nextFinancialYearQ2StartDate)
				.setParameter("nextFinancialYearQ3StartDate",nextFinancialYearQ3StartDate)
				.setParameter("nextFinancialYearQ4StartDate",nextFinancialYearQ4StartDate)
				.setParameter("nextFinancialYearQ1EndDate", nextFinancialYearQ1EndDate)
				.setParameter("nextFinancialYearQ2EndDate", nextFinancialYearQ2EndDate)
				.setParameter("nextFinancialYearQ3EndDate", nextFinancialYearQ3EndDate)
				.setParameter("nextFinancialYearQ4EndDate", nextFinancialYearQ4EndDate)
		
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}
        if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
        	if(unitList.isEmpty()){
				unitList.add("");
			}
        	hqlQuery.setParameterList("unitList",unitList);
		}else{
			hqlQuery.setParameter("userId",userId);
			          
		}
        
	 
        Map<String,String> map = new HashMap<>();
		List lst=hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=null; 
				if(tuple!=null){
					auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
					if(tuple[0]!=null){
						auditStatusGraphResponseDto.setCount(Long.parseLong(tuple[0].toString()));
					}
					if(tuple[1]!=null){
						auditStatusGraphResponseDto.setAuditStatus(tuple[1].toString());						
		            }
					if(tuple[2]!=null){
						auditStatusGraphResponseDto.setYtd(tuple[2].toString());
						map.put(tuple[2].toString(), tuple[1].toString()); // To collect all Yearly having values
					}
					
				}
				
				return auditStatusGraphResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
		//Logic to Check and append the missing Quarters
		String[] qtrArry= {"PREV_Q1","PREV_Q2","PREV_Q3","PREV_Q4","CUR_Q1","CUR_Q2","CUR_Q3","CUR_Q4"};
		try {
			for(String qtr:qtrArry)
				if(!map.containsKey(qtr)) {
					AuditStatusGraphResponseDto auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
					auditStatusGraphResponseDto.setYtd(qtr);
					auditStatusGraphResponseDto.setAuditStatus("total");
					auditStatusGraphResponseDto.setCount(0l);
					lst.add(auditStatusGraphResponseDto);
				}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		//ends here
		
		return lst;
		
	}
	

	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<AuditStatusGraphResponseDto> getAuditClosureStatusHalfYearly(Integer legalEntityCode, String auditType,
			String unitType, String criticality, String userId, Date businessDate,String role,List<String> unitList) {
		
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDate);
		
		Integer year=null;
		
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		Integer currentYear=year;
		Integer previousYear=currentYear-1;
		
		/*PREVIOUS YEAR half year dates */
        //LocalDate previousFinancialYearFirstHalfStartDate = LocalDate.of(previousYear, 04, 1);
		
		LocalDate FinancialYearStartDate  = dashboardDao.getFinancialYearStartDate(legalEntityCode);
		logger.info("FinancialYearStartDate :: "+FinancialYearStartDate);
		
		LocalDate previousFinancialYearFirstHalfStartDate = FinancialYearStartDate.minusMonths(12);
		LocalDate previousFinancialYearFirstHalfEndDate = previousFinancialYearFirstHalfStartDate.plusMonths(6).minusDays(1);

		LocalDate  previousFinancialYearSecondtHalfStartDate =previousFinancialYearFirstHalfEndDate.plusDays(1);
		LocalDate  previousFinancialYearSecondtHalfEndDate = previousFinancialYearSecondtHalfStartDate.plusMonths(6).minusDays(1);


		/*CURRENT YEAR quarters*/
		LocalDate nextFinancialYearFirstHalfStartDate = previousFinancialYearSecondtHalfEndDate.plusDays(1);
		LocalDate nextFinancialYearFirstHalfEndDate = nextFinancialYearFirstHalfStartDate.plusMonths(6).minusDays(1);

		LocalDate  nextFinancialYearSecondtHalfStartDate =nextFinancialYearFirstHalfEndDate.plusDays(1);
		LocalDate  nextFinancialYearSecondtHalfEndDate = nextFinancialYearSecondtHalfStartDate.plusMonths(6).minusDays(1);
		
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		logger.info("Inside getAuditStatusQuarterly.... userId "+userId );
		logger.info(" PHLF1Strt:: "+ previousFinancialYearFirstHalfStartDate +" PHLF1Strt:: "+previousFinancialYearFirstHalfEndDate);
		logger.info(" PHLF2Strt:: "+ previousFinancialYearSecondtHalfStartDate +" PHLF2End:: "+previousFinancialYearSecondtHalfEndDate);
		logger.info(" CHLF1Strt:: "+ nextFinancialYearFirstHalfStartDate +" CHLF1End:: "+nextFinancialYearFirstHalfEndDate);
		logger.info(" CHLF2Strt:: "+ nextFinancialYearSecondtHalfStartDate +" CHLF2End:: "+nextFinancialYearSecondtHalfEndDate);
		
		StringBuilder query= new StringBuilder(
				" SELECT COUNT(aus.audit_status) AS audit_count , " 
						 + "   (CASE WHEN datediff(aus.reviewed_date,aus.actual_end_date) BETWEEN 0 AND 30 THEN '30' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 31 AND 60 THEN '60' " 
						 + "		 WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 61 AND 90 THEN '90' "  
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 91 AND 120 THEN '120' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 121 AND 150 THEN '150' "
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 151 AND 180 THEN '180' "
						 + "       ELSE '180 and above' " 
						 + "    END)  AS audit_closure, "					
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearFirstHalfStartDate AND DATE(aus.reviewed_date) <=:previousFinancialYearFirstHalfEndDate  THEN 'PREV_FIRST_HF' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearSecondtHalfStartDate AND DATE(aus.reviewed_date) <=:previousFinancialYearSecondtHalfEndDate THEN 'PREV_SECOND_HF' ELSE  " 
						
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearFirstHalfStartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearFirstHalfEndDate  THEN 'CUR_FIRST_HF' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearSecondtHalfStartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearSecondtHalfEndDate THEN 'CUR_SECOND_HF'  "  
						 + "    END) " 
						 + "    END)   " 
						 + "    END)   " 
						 + "    END) AS ytd " 
						 + "   FROM audit_schedule AS aus ,maint_entity AS me " 
						 + "   WHERE  " 
						 + "   aus.legal_entity_code=me.legal_entity_code " 
						 + "   AND aus.unit_id=me.unit_code   " 
						 + "   AND aus.legal_entity_code =:legalEntityCode " 
						 + "   AND aus.audit_status IN ('AW','AC','AF')  " 
						 + "   AND DATE(aus.reviewed_date) BETWEEN :previousFinancialYearFirstHalfStartDate AND :nextFinancialYearSecondtHalfEndDate "
				)  ;
		
		// based on role 
		if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			query.append(" AND aus.unit_id in (:unitList) ");
		}else{
			query.append( "    AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					  +"    aus.legal_entity_code=aut.legal_entity_code "
					  +"    AND aus.audit_type_code=aut.audit_type_code "
					  +"    AND aus.plan_id=aut.plan_id "
					  +"    AND aus.audit_id=aut.audit_id "
					  +"    AND aut.user_id =:userId    "
					  +"	AND reviewed_date is not null "
					  +"    ) ");
			          
		}
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
        query.append(
				   "   GROUP BY   "
						 + "   (CASE WHEN datediff(aus.reviewed_date,aus.actual_end_date) BETWEEN 0 AND 30 THEN '30' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 31 AND 60 THEN '60' " 
						 + "		 WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 61 AND 90 THEN '90' "  
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 91 AND 120 THEN '120' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 121 AND 150 THEN '150' "
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 151 AND 180 THEN '180' "
						 + "       ELSE '180 and above' " 
						 + "    END)  , "
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearFirstHalfStartDate AND DATE(aus.reviewed_date) <=:previousFinancialYearFirstHalfEndDate  THEN 'PREV_FIRST_HF' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearSecondtHalfStartDate AND DATE(aus.reviewed_date) <=:previousFinancialYearSecondtHalfEndDate THEN 'PREV_SECOND_HF' ELSE  " 
						
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearFirstHalfStartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearFirstHalfEndDate  THEN 'CUR_FIRST_HF' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearSecondtHalfStartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearSecondtHalfEndDate THEN 'CUR_SECOND_HF'  "  
						 + "    END) 	" 
						 + "    END)   	" 
						 + "    END)   	" 
						 + "    END) 	" 
        		);
        
		
		Query hqlQuery= session.createNativeQuery(query.toString())
				.setParameter("previousFinancialYearFirstHalfStartDate", previousFinancialYearFirstHalfStartDate)
				.setParameter("previousFinancialYearSecondtHalfStartDate", previousFinancialYearSecondtHalfStartDate)
				
				.setParameter("previousFinancialYearFirstHalfEndDate", previousFinancialYearFirstHalfEndDate)
				.setParameter("previousFinancialYearSecondtHalfEndDate", previousFinancialYearSecondtHalfEndDate)
				
				.setParameter("nextFinancialYearFirstHalfStartDate",nextFinancialYearFirstHalfStartDate)
				.setParameter("nextFinancialYearSecondtHalfStartDate",nextFinancialYearSecondtHalfStartDate)
				
				.setParameter("nextFinancialYearFirstHalfEndDate",nextFinancialYearFirstHalfEndDate)
				.setParameter("nextFinancialYearSecondtHalfEndDate",nextFinancialYearSecondtHalfEndDate)
		
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}
        if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
        	if(unitList.isEmpty()){
				unitList.add("");
			}
        	hqlQuery.setParameterList("unitList",unitList);
		}else{
			hqlQuery.setParameter("userId",userId);
			          
		}
        
	 
        Map<String,String> map = new HashMap<>();
		List lst=hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=null; 
				if(tuple!=null){
					auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
					if(tuple[0]!=null){
						auditStatusGraphResponseDto.setCount(Long.parseLong(tuple[0].toString()));
					}
					if(tuple[1]!=null){
						auditStatusGraphResponseDto.setAuditStatus(tuple[1].toString());						
		            }
					if(tuple[2]!=null){
						auditStatusGraphResponseDto.setYtd(tuple[2].toString());
						map.put(tuple[2].toString(), tuple[1].toString()); // To collect all Yearly having values
					}
					
				}
				
				return auditStatusGraphResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
	  //Logic to Check and append the missing Years
		String[] hlfYrArry= {"PREV_FIRST_HF","PREV_SECOND_HF","CUR_FIRST_HF","CUR_SECOND_HF"};
		try {
		for(String hlfYrly:hlfYrArry)
			if(!map.containsKey(hlfYrly)) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
				auditStatusGraphResponseDto.setYtd(hlfYrly);
				auditStatusGraphResponseDto.setAuditStatus("total");
				auditStatusGraphResponseDto.setCount(0l);
				lst.add(auditStatusGraphResponseDto);
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		//ends here
		
		return lst;
		
	}
	
	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<AuditStatusGraphResponseDto> getAuditClosureStatusYearly(Integer legalEntityCode, String auditType,
			String unitType, String criticality, String userId, Date businessDate,String role,List<String> unitList) {
		
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDate);
		Integer year=null;
		
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		Integer currentYear=year;
		Integer previousYear=currentYear-1;
		
		/*PREVIOUS YEAR  dates */
        //LocalDate previousFinancialYearStartDate = LocalDate.of(previousYear, 04, 1);
		
		LocalDate FinancialYearStartDate  = dashboardDao.getFinancialYearStartDate(legalEntityCode);
		logger.info("FinancialYearStartDate :: "+FinancialYearStartDate);
		
		LocalDate previousFinancialYearStartDate = FinancialYearStartDate.minusMonths(12);
		LocalDate previousFinancialYearEndDate = previousFinancialYearStartDate.plusMonths(12).minusDays(1);

       /*CURRENT YEAR dates*/
		
		LocalDate nextFinancialYearStartDate = previousFinancialYearEndDate.plusDays(1);
		LocalDate nextFinancialYearEndDate = nextFinancialYearStartDate.plusMonths(12).minusDays(1);
		
		logger.info("previousFinancialYearStartDate ...."+previousFinancialYearStartDate+" previousFinancialYearEndDate ...."+previousFinancialYearEndDate);
		logger.info("nextFinancialYearStartDate ...."+nextFinancialYearStartDate+" nextFinancialYearEndDate ...."+nextFinancialYearEndDate);
		logger.info("unitList .... "+ unitList);
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);			
		StringBuilder query= new StringBuilder(
				" SELECT COUNT(aus.audit_status) AS audit_count , " 
						 + "   (CASE WHEN datediff(aus.reviewed_date,aus.actual_end_date) BETWEEN 0 AND 30 THEN '30' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 31 AND 60 THEN '60' " 
						 + "		 WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 61 AND 90 THEN '90' "  
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 91 AND 120 THEN '120' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 121 AND 150 THEN '150' "
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 151 AND 180 THEN '180' "
						 + "       ELSE '180 and above' " 
						 + "    END)  AS audit_closure, "					
        				 + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearStartDate AND DATE(aus.reviewed_date) <=:previousFinancialYearEndDate  THEN 'PREV_YEAR' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearStartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearEndDate  THEN 'CUR_YEAR'  " 
						 + "    END)   " 
						 + "    END) AS ytd " 
						 + "   FROM audit_schedule AS aus ,maint_entity AS me " 
						 + "   WHERE  " 
						 + "   aus.legal_entity_code=me.legal_entity_code " 
						 + "   AND aus.unit_id=me.unit_code   " 
						 + "   AND aus.legal_entity_code =:legalEntityCode " 
						 + "   AND aus.audit_status IN ('AW','AC','AF')  " 
						 + "   AND DATE(aus.reviewed_date) BETWEEN :previousFinancialYearStartDate AND :nextFinancialYearEndDate "
				)  ;
		
		// based on role 
		if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			query.append(" AND aus.unit_id in (:unitList) ");
		}else{
			query.append( "    AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					  +"    aus.legal_entity_code=aut.legal_entity_code "
					  +"    AND aus.audit_type_code=aut.audit_type_code "
					  +"    AND aus.plan_id=aut.plan_id "
					  +"    AND aus.audit_id=aut.audit_id "
					  +"    AND aut.user_id =:userId    "
					  +"	AND reviewed_date is not null "
					  +"    ) ");
			          
		}
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
        query.append(
				   "   GROUP BY   "
						 + "   (CASE WHEN datediff(aus.reviewed_date,aus.actual_end_date) BETWEEN 0 AND 30 THEN '30' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 31 AND 60 THEN '60' " 
						 + "		 WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 61 AND 90 THEN '90' "  
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 91 AND 120 THEN '120' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 121 AND 150 THEN '150' "
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 151 AND 180 THEN '180' "
						 + "       ELSE '180 and above' " 
						 + "    END)  , "
				         + "   (CASE WHEN DATE(aus.reviewed_date) >=:previousFinancialYearStartDate AND DATE(aus.reviewed_date) <=:previousFinancialYearEndDate  THEN 'PREV_YEAR' ELSE  " 
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:nextFinancialYearStartDate AND DATE(aus.reviewed_date) <=:nextFinancialYearEndDate  THEN 'CUR_YEAR'  " 
						 + "    END)   " 
						 + "    END) "  
        		);
        
		
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("previousFinancialYearStartDate", previousFinancialYearStartDate)
		.setParameter("previousFinancialYearEndDate", previousFinancialYearEndDate)
		
		.setParameter("nextFinancialYearStartDate", nextFinancialYearStartDate)
		.setParameter("nextFinancialYearEndDate", nextFinancialYearEndDate)
		
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}
        if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
        	if(unitList.isEmpty()){
				unitList.add("");
			}
        	hqlQuery.setParameterList("unitList",unitList);
		}else{
			hqlQuery.setParameter("userId",userId);
			          
		}
        
	 
        Map<String,String> map = new HashMap<>();
		List lst=hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=null; 
				if(tuple!=null){
					auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
					if(tuple[0]!=null){
						auditStatusGraphResponseDto.setCount(Long.parseLong(tuple[0].toString()));
					}
					if(tuple[1]!=null){
						auditStatusGraphResponseDto.setAuditStatus(tuple[1].toString());						
		            }
					if(tuple[2]!=null){
						auditStatusGraphResponseDto.setYtd(tuple[2].toString());
						map.put(tuple[2].toString(), tuple[1].toString()); // To collect all Yearly having values
					}
					
				}
				
				return auditStatusGraphResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
	  //Logic to Check and append the missing Years
		String[] yearlyArr= {"PREV_YEAR","CUR_YEAR"};
		try {
		for(String yearly:yearlyArr)
			if(!map.containsKey(yearly)) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
				auditStatusGraphResponseDto.setYtd(yearly);
				auditStatusGraphResponseDto.setAuditStatus("total");
				auditStatusGraphResponseDto.setCount(0l);
				lst.add(auditStatusGraphResponseDto);
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		//ends here
		
		return lst;
		
	}
	
	
	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<AuditStatusGraphResponseDto> getAuditClosureStatusByRange(Integer legalEntityCode, String auditType, String unitType,
			String criticality, String userId, LocalDate fromDate, LocalDate toDate, String role, List<String> unitList) {
		
		logger.info(" legalEntityCode.."+legalEntityCode +" auditType.. "+auditType+" unitType.."+unitType +" criticality.."+criticality + " userId.."+userId+ " role.."+role );
		logger.info("fromDate ...."+fromDate+" toDate ...."+toDate);
		logger.info("unitList .... "+ unitList);
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);			
		StringBuilder query= new StringBuilder(
				" SELECT COUNT(aus.audit_status) AS audit_count , " 
						 + "   (CASE WHEN datediff(aus.reviewed_date,aus.actual_end_date) BETWEEN 0 AND 30 THEN '30' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 31 AND 60 THEN '60' " 
						 + "		 WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 61 AND 90 THEN '90' "  
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 91 AND 120 THEN '120' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 121 AND 150 THEN '150' "
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 151 AND 180 THEN '180' "
						 + "       ELSE '180 and above' " 
						 + "    END)  AS audit_closure, "					
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:fromDate AND DATE(aus.reviewed_date) <=:toDate  THEN 'range'   " 
						 + "    END) AS ytd " 
						 + "   FROM audit_schedule AS aus ,maint_entity AS me " 
						 + "   WHERE  " 
						 + "   aus.legal_entity_code=me.legal_entity_code " 
						 + "   AND aus.unit_id=me.unit_code   " 
						 + "   AND aus.legal_entity_code =:legalEntityCode " 
						 + "   AND aus.audit_status IN ('AW','AC','AF')  " 
						 + "   AND DATE(aus.reviewed_date) BETWEEN :fromDate AND :toDate "
				)  ;
		
		// based on role 
		if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
			query.append(" AND aus.unit_id in (:unitList) ");
		}else{
			query.append( "    AND aus.audit_id IN (SELECT aut.audit_id FROM audit_team AS aut WHERE  "
					  +"    aus.legal_entity_code=aut.legal_entity_code "
					  +"    AND aus.audit_type_code=aut.audit_type_code "
					  +"    AND aus.plan_id=aut.plan_id "
					  +"    AND aus.audit_id=aut.audit_id "
					  +"    AND aut.user_id =:userId    "
					  +"	AND reviewed_date is not null "
					  +"    ) ");
			          
		}
		
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND aus.audit_type_code =:auditType ");
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			query.append(" AND me.unit_type =:unitType ");
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	query.append(" AND me.u_criticality =:criticality ");
		}
		
        query.append(
				   "   GROUP BY   "
						 + "   (CASE WHEN datediff(aus.reviewed_date,aus.actual_end_date) BETWEEN 0 AND 30 THEN '30' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 31 AND 60 THEN '60' " 
						 + "		 WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 61 AND 90 THEN '90' "  
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 91 AND 120 THEN '120' " 
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 121 AND 150 THEN '150' "
						 + "         WHEN datediff(aus.reviewed_date,aus.actual_end_date) between 151 AND 180 THEN '180' "
						 + "       ELSE '180 and above' " 
						 + "    END)  , "
						 + "   (CASE WHEN DATE(aus.reviewed_date) >=:fromDate AND DATE(aus.reviewed_date) <=:toDate  THEN 'range'   " 
						 + "    END) "   
        		);
        
		
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("fromDate", fromDate)
		.setParameter("toDate", toDate)
		
		.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		if(!BankAuditUtil.isEmptyString(unitType)){
			hqlQuery.setParameter("unitType", unitType);
		}
		
        if(!BankAuditUtil.isEmptyString(criticality)){
        	hqlQuery.setParameter("criticality", criticality);
		}
        if(role.equalsIgnoreCase("RVWR")||role.equalsIgnoreCase("SM") || role.equalsIgnoreCase("OPS")){
        	if(unitList.isEmpty()){
				unitList.add("");
			}
        	hqlQuery.setParameterList("unitList",unitList);
		}else{
			hqlQuery.setParameter("userId",userId);
			          
		}
        
	 
        Map<String,String> map = new HashMap<>();
        return hqlQuery.setResultTransformer(new ResultTransformer() {
			
			@Override
			public Object transformTuple(Object[] tuple, String[] aliases) {
				AuditStatusGraphResponseDto auditStatusGraphResponseDto=null; 
				if(tuple!=null){
					auditStatusGraphResponseDto=new AuditStatusGraphResponseDto();
					if(tuple[0]!=null){
						auditStatusGraphResponseDto.setCount(Long.parseLong(tuple[0].toString()));
					}
					if(tuple[1]!=null){
						auditStatusGraphResponseDto.setAuditStatus(tuple[1].toString());						
		            }
					if(tuple[2]!=null){
						auditStatusGraphResponseDto.setYtd(tuple[2].toString());
						map.put(tuple[2].toString(), tuple[1].toString()); // To collect all Yearly having values
					}
					
				}
				
				return auditStatusGraphResponseDto;
			}
			
			@Override
			public List transformList(List collection) {
				return collection;
			}
		}).list();
		
	}
	
	
	// Audit Closure status 
	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<List> getAuditClosureStatusYearlyTmp(Integer legalEntityCode, String auditType,
			String unitType, String criticality, String userId, Date businessDate,String role,List<String> unitList) {
		
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDate);
		Integer year=null;
		List<List> adtClsrLst=null;
		
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		Integer currentYear=year;
		Integer previousYear=currentYear-1;
		
		/*PREVIOUS YEAR  dates */
        //LocalDate previousFinancialYearStartDate = LocalDate.of(previousYear, 04, 1);
		
		LocalDate FinancialYearStartDate  = dashboardDao.getFinancialYearStartDate(legalEntityCode);
		logger.info("FinancialYearStartDate :: "+FinancialYearStartDate);
		
		LocalDate previousFinancialYearStartDate = FinancialYearStartDate.minusMonths(12);
		LocalDate previousFinancialYearEndDate = previousFinancialYearStartDate.plusMonths(12).minusDays(1);

       /*CURRENT YEAR dates*/
		
		LocalDate nextFinancialYearStartDate = previousFinancialYearEndDate.plusDays(1);
		LocalDate nextFinancialYearEndDate = nextFinancialYearStartDate.plusMonths(12).minusDays(1);
		
		logger.info("previousFinancialYearStartDate ...."+previousFinancialYearStartDate+" previousFinancialYearEndDate ...."+previousFinancialYearEndDate);
		logger.info("nextFinancialYearStartDate ...."+nextFinancialYearStartDate+" nextFinancialYearEndDate ...."+nextFinancialYearEndDate);
		logger.info("unitList .... "+ unitList);
		
		try {
		Session session=getSession();
	    session.setDefaultReadOnly(true);			
		StringBuilder query= new StringBuilder(
				" select count(*), audit_closure from ( " + 
				"	select " + 
				"	case 	when datediff(s.reviewed_date,s.actual_end_date) between 0 AND 30 THEN 30 " + 
				"		when  datediff(s.reviewed_date,s.actual_end_date) between 31 AND 60 THEN 60 " + 
				"        when  datediff(s.reviewed_date,s.actual_end_date) between 61 AND 90 THEN 90 " + 
				"        when  datediff(s.reviewed_date,s.actual_end_date) between 91 AND 120 THEN 120 " + 
				"        when  datediff(s.reviewed_date,s.actual_end_date) between 121 AND 150 THEN 150 " + 
				"        when  datediff(s.reviewed_date,s.actual_end_date) between 151 AND 180 THEN 180 " + 
				"        ELSE 200 END as audit_closure " + 
				"    from audit_schedule s where legal_entity_code=:legalEntityCode and reviewed_date is not null" + 
				"		and actual_start_date > '2019-04-01'");
		if(!BankAuditUtil.isEmptyString(auditType)){
			query.append(" AND audit_type_code =:auditType ");
		}
		 query.append(" ) as ac group by audit_closure " )  ;
		
		
				
		Query hqlQuery= session.createNativeQuery(query.toString())
			.setParameter("legalEntityCode", legalEntityCode);
		if(!BankAuditUtil.isEmptyString(auditType)){
			hqlQuery.setParameter("auditType", auditType);
		}
		
		List lst=hqlQuery.list();
		Iterator iterator = lst.iterator();
		adtClsrLst = new ArrayList();
		while (iterator.hasNext()) {
			Object[] obj = (Object[])iterator.next();
			// System.out.println(obj[0]+" :: "+obj[1]);
			List clsSts = new ArrayList();
			
			if(obj != null){
				clsSts.add(obj[1]);
				clsSts.add(obj[0]);
			}
			adtClsrLst.add(clsSts);
		}	
		}catch(Exception e) {
			e.printStackTrace();
		}
		List clsSts = new ArrayList();
		clsSts.add("180 and above");
		clsSts.add(0);
		
		adtClsrLst.add(clsSts);
			
		return adtClsrLst;
		
	}
	
	/****************************************************************************************************************************
	 **************************************         DASHBOARDS FOR RCSA NABARD           ****************************************
	 ****************************************************************************************************************************/
	
	public Map getAssessmentSummaryDtls(int legalEntityCode,String units, String auditTypeCode,String plnStDate,String plnEnDate, Boolean isDeptAsRMD, List<String> deptList) {
		Session session=getSession();
		Map map = null;
		try {
			logger.info("getAssessmentSummaryDtls legalEntityCode.. "+legalEntityCode + " units.. "+ units + "auditTypeCode.."+auditTypeCode+" plnStDate.."+plnStDate+" plnEnDate.."+plnEnDate);
			logger.info("isDeptAsRMD .."+ isDeptAsRMD +" deptList .."+ deptList);
			StringBuilder query= new StringBuilder(
					" SELECT  " 
							 + "   (CASE WHEN aus.audit_status = 'AP' THEN 'NOT_INITIATED' " 
							 + "         WHEN aus.audit_status IN ('AI','AS','AR') THEN 'IN_PROGESS' "
							 + "       WHEN aus.audit_status IN ('AW','AC') THEN 'CLOSED' " 
							 + "            ELSE 'NA' " 
							 + "    END)  AS audit_status "		
							 + " 	,COUNT(aus.audit_status) AS audit_count "
	        				 + "   FROM audit_schedule AS aus ,maint_entity AS me " 
							 + "   WHERE  " 
							 + "   aus.legal_entity_code=me.legal_entity_code " 
							 + "   AND aus.unit_id=me.unit_code   " 
							 + "   AND aus.legal_entity_code =:legalEntityCode " 
							 + "   AND aus.audit_status IN ('AI','AP' ,'AS','AR','AW','AC','AF')  " 
							 + "   AND DATE(aus.schedule_start_date) BETWEEN :plnStDate AND :plnEnDate "
					)  ;
			
			query.append(" AND aus.unit_id in ("+units+") ");  //unit_ids in ("+units+")  aus.unit_id in (:units)
						
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				query.append(" AND aus.audit_type_code =:auditTypeCode ");
			}else if(!isDeptAsRMD) {
				query.append(" AND aus.audit_type_code in (:deptList) ");
			}				
				
			query.append(
					   "   GROUP BY   "
							     + "   (CASE WHEN aus.audit_status = 'AP' THEN 'NOT_INITIATED' " 
								 + "         WHEN aus.audit_status IN ('AI','AS','AR') THEN 'IN_PROGESS' "
								 + "       WHEN aus.audit_status IN ('AW','AC') THEN 'CLOSED' " 
								 + "            ELSE 'NA' " 
								 + "    END)   ");
	        
			
			Query hqlQuery= session.createNativeQuery(query.toString())
			.setParameter("plnStDate", plnStDate)
			.setParameter("plnEnDate", plnEnDate)
			.setParameter("legalEntityCode", legalEntityCode)
			//.setParameter("units",units)
			;
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				hqlQuery.setParameter("auditTypeCode", auditTypeCode);
			}else if(!isDeptAsRMD) {
				hqlQuery.setParameter("deptList", deptList);
			}
						
			List ls = hqlQuery.list();
			logger.info("Size lst .."+ls.size());
			Iterator iterator = ls.iterator();
			map= new HashMap<>();
			while(iterator.hasNext()){  
	            Object[] objects = (Object[]) iterator.next();  
	            map.put(objects[0].toString(),objects[1].toString());
	            logger.info(objects[0]+ "= "+objects[1]);
	          }  
			if(!map.containsKey("NOT_INITIATED")) map.put("NOT_INITIATED","0");
			if(!map.containsKey("IN_PROGESS")) map.put("IN_PROGESS","0");
			if(!map.containsKey("CLOSED")) map.put("CLOSED","0");
			int total= Integer.parseInt(map.get("NOT_INITIATED").toString()) + Integer.parseInt(map.get("IN_PROGESS").toString()) +Integer.parseInt(map.get("CLOSED").toString());
			map.put("PLANNED",total+"");			
			logger.info("map ...."+map);
		}catch (Exception e) {
			e.getStackTrace();
			throw e;
		}
		return  map;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<String> getDeptList(Integer legalEntityCode ,String role,String userIdOrUnitId ) {
		Session session=getSession();
		
		return  session.createQuery("SELECT auditTypeCode FROM MaintEntityAuditSubgroupMapping WHERE "
				+ " legalEntityCode =:legalEntityCode "
				+ " AND mappingType ='U' AND id =:userId "
				+ " AND status = 'A' ")
				.setParameter("legalEntityCode", legalEntityCode)
				.setParameter("userId", userIdOrUnitId)
				.list();
	}
	
	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<HashMap<String,String>> getRiskProfileDeptwise(int legalEntityCode,  String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, Boolean isDeptAsRMD, List<String> unitList, List<String> deptList) {
		
		logger.info("getRiskProfileDeptwise .... "+ legalEntityCode + " :: "+auditType+" :: "+period +" :: "+fromDate+" :: "+toDate);
		logger.info("userId.... "+ userId + " :: "+role+" :: "+isDeptAsRMD +" :: "+unitList +" :: "+deptList);
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		StringBuilder query= new StringBuilder(" SELECT  "
				+" o.audit_type_code, o.residul_risk_code, o.residul_risk_desc, COUNT(o.residul_risk_code) as risk_count " 
				+" FROM " 
				+"     audit_observation o " 
				+" WHERE " 
				+"	   o.legal_entity_code =:legalEntityCode AND "
				+"     o.audit_id IN (SELECT  " 
				+"             s.audit_id " 
				+"         FROM " 
				+"             audit_schedule s " 
				+"         WHERE " 
				+"             s.legal_entity_code = o.legal_entity_code " 
				+"                 AND s.audit_id = o.audit_id " 
				+"                 AND s.audit_status IN ('AC','AW') "
				+"				   AND s.unit_id in (:unitList)	"
				+ "				   AND s.schedule_start_date BETWEEN (:fromDate) AND  (:toDate)	"  // Need to uncomment 
				+ "									) " 
				+"         AND o.residul_risk_code IS NOT NULL "); 
		if(!isDeptAsRMD )	
			query.append(" AND audit_type_code IN (:deptList) ");
		query.append(" GROUP BY o.residul_risk_code , o.audit_type_code , o.residul_risk_desc " 
				+" ORDER BY audit_type_code , residul_risk_code " );
			
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("fromDate", fromDate).setParameter("toDate", toDate)
		.setParameter("unitList", unitList)
		.setParameter("legalEntityCode", legalEntityCode);
		
		if(!isDeptAsRMD ) hqlQuery.setParameter("deptList", deptList);
		
        List ls = hqlQuery.list();
        
        String rating=""; int iterateCnt=0; String tmpAuditTypeCode ="";
 		List<HashMap<String,String>> riskMpLst = new ArrayList();
        HashMap<String,String> riskMp = new HashMap();
        HashMap<String,String> riskMpTot = new HashMap();
 		for(Object obj: ls) {
 			Object[] obji=(Object[])obj;
 			if(iterateCnt == 0) {
 				riskMp.put("DEPT_CODE", obji[0]+"");
 				riskMp.put(obji[2]+"", obji[3]+"");
 			}else{
	 			if((obji[0]+"").equalsIgnoreCase(tmpAuditTypeCode)) {
	 				riskMp.put(obji[2]+"", obji[3]+"");
	 			}else {
	 				riskMpLst.add(riskMp);
	 				riskMp = new HashMap();
	 				riskMp.put("DEPT_CODE", obji[0]+"");
	 				riskMp.put(obji[2]+"", obji[3]+"");
	 			}
 			}
 			iterateCnt++; 
 			
 			// Logic to give Total numbers for each Key irrespective of Dept Code
 			if(riskMpTot.containsKey(obji[2]+"")) {
 				int temp = Integer.parseInt((riskMpTot.get(obji[2]+"")!=null)?riskMpTot.get(obji[2]+""):"0") +  ( (obji[3]!=null)? Integer.parseInt(obji[3].toString()) :0) ;
 				riskMpTot.put(obji[2]+"", temp+"");
 			}else {
 				int temp = (obji[3]!=null)? Integer.parseInt(obji[3].toString()) :0 ;
 				riskMpTot.put(obji[2]+"", temp+"");
 			}
 			// End here
 			if(iterateCnt == ls.size()) { 
 				riskMpLst.add(riskMp);
 				riskMpTot.put("DEPT_CODE","TOTAL");
 				riskMpLst.add(riskMpTot);
 			}tmpAuditTypeCode = obji[0]+"";
 		}System.out.println("riskMpLst .."+riskMpLst); 
        return riskMpLst;
		
	}
	
	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<HashMap<String,String>> getRiskProfileProductwise(int legalEntityCode,  String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, Boolean isDeptAsRMD, List<String> unitList, List<String> deptList) {
		
		logger.info("getRiskProfileProductwise .... "+ legalEntityCode + " :: "+auditType+" :: "+period +" :: "+fromDate+" :: "+toDate);
		logger.info("userId.... "+ userId + " :: "+role+" :: "+isDeptAsRMD +" :: "+unitList +" :: "+deptList);
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		StringBuilder query= new StringBuilder(" SELECT  "
				+" o.audit_type_code, o.residul_risk_code, o.residul_risk_desc, COUNT(o.residul_risk_code) as risk_count"
				+ "		,o.audit_grp_name, o.audit_subgrp_name " 
				+" FROM " 
				+"     audit_observation_v o " 
				+" WHERE " 
				+"	   o.legal_entity_code =:legalEntityCode AND "
				+"     o.audit_id IN (SELECT  " 
				+"             s.audit_id " 
				+"         FROM " 
				+"             audit_schedule s " 
				+"         WHERE " 
				+"             s.legal_entity_code = o.legal_entity_code " 
				+"                 AND s.audit_id = o.audit_id " 
				+"                 AND s.audit_status IN ('AC','AW') "
				+"				   AND s.unit_id in (:unitList)	"
				+ "				   AND s.schedule_start_date BETWEEN (:fromDate) AND  (:toDate)	"  // Need to uncomment 
				+ "									) " 
				+"         AND o.residul_risk_code IS NOT NULL "); 
		if(!isDeptAsRMD )	
			query.append(" AND audit_type_code IN (:deptList) ");
		query.append(" GROUP BY o.residul_risk_code , o.audit_type_code , o.residul_risk_desc, o.audit_grp_name, o.audit_subgrp_name " 
				+" ORDER BY audit_type_code ,o.audit_grp_name, o.audit_subgrp_name, residul_risk_code " );
			
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("fromDate", fromDate).setParameter("toDate", toDate)
		.setParameter("unitList", unitList)
		.setParameter("legalEntityCode", legalEntityCode);
		
		if(!isDeptAsRMD ) hqlQuery.setParameter("deptList", deptList);
		
        List ls = hqlQuery.list();
        
        String rating=""; int iterateCnt=0; String tmpAuditTypeCode ="";
 		List<HashMap<String,String>> riskMpLst = new ArrayList();
        HashMap<String,String> riskMp = new HashMap();
        HashMap<String,String> riskMpTot = new HashMap();
 		for(Object obj: ls) {
 			Object[] obji=(Object[])obj;
 			if(iterateCnt == 0) {
 				riskMp.put("DEPT_CODE", obji[0]+"=>"+obji[4]+"=>"+obji[5]);
 				riskMp.put(obji[2]+"", obji[3]+"");
 			}else{
	 			if((obji[0]+"=>"+obji[4]+"=>"+obji[5]).equalsIgnoreCase(tmpAuditTypeCode)) {
	 				riskMp.put(obji[2]+"", obji[3]+"");
	 			}else {
	 				riskMpLst.add(riskMp);
	 				riskMp = new HashMap();
	 				riskMp.put("DEPT_CODE", obji[0]+"=>"+obji[4]+"=>"+obji[5]);
	 				riskMp.put(obji[2]+"", obji[3]+"");
	 			}
 			}
 			iterateCnt++; 
 			
 			// Logic to give Total numbers for each Key irrespective of Dept Code
 			if(riskMpTot.containsKey(obji[2]+"")) {
 				int temp = Integer.parseInt((riskMpTot.get(obji[2]+"")!=null)?riskMpTot.get(obji[2]+""):"0") +  ( (obji[3]!=null)? Integer.parseInt(obji[3].toString()) :0) ;
 				riskMpTot.put(obji[2]+"", temp+"");
 			}else {
 				int temp = (obji[3]!=null)? Integer.parseInt(obji[3].toString()) :0 ;
 				riskMpTot.put(obji[2]+"", temp+"");
 			}
 			// End here
 			if(iterateCnt == ls.size()) { 
 				riskMpLst.add(riskMp);
 				riskMpTot.put("DEPT_CODE","TOTAL");
 				riskMpLst.add(riskMpTot);
 			}tmpAuditTypeCode = obji[0]+"=>"+obji[4]+"=>"+obji[5];
 		}System.out.println("riskMpLst .."+riskMpLst); 
        return riskMpLst;
		
	}
	
	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<HashMap<String,String>> getControlProfileDeptwise(int legalEntityCode,  String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role,Boolean isDeptAsRMD, List<String> unitList, List<String> deptList) {
		
		logger.info("getControlProfileDeptwise .... "+ legalEntityCode + " :: "+auditType+" :: "+period +" :: "+fromDate+" :: "+toDate);
		logger.info("userId.... "+ userId + " :: "+role+" :: "+isDeptAsRMD +" :: "+unitList +" :: "+deptList);
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		StringBuilder query= new StringBuilder(" SELECT  "
				+" o.audit_type_code, o.cntrl_cls_bucket_code, o.cntrl_cls_bucket_desc, COUNT(o.cntrl_cls_bucket_code) as cntrl_profile_cnt " 
				+" FROM " 
				+"     audit_observation o " 
				+" WHERE " 
				+"	   o.legal_entity_code =:legalEntityCode AND "
				+"     o.audit_id IN (SELECT  " 
				+"             s.audit_id " 
				+"         FROM " 
				+"             audit_schedule s " 
				+"         WHERE " 
				+"             s.legal_entity_code = o.legal_entity_code " 
				+"                 AND s.audit_id = o.audit_id " 
				+"                 AND s.audit_status IN ('AC','AW') "
				+"				   AND s.unit_id in (:unitList)	"
				+ "				   AND s.schedule_start_date BETWEEN (:fromDate) AND  (:toDate)	"
				+ "									) " 
				+"         AND o.cntrl_cls_bucket_code IS NOT NULL " );
		if(!isDeptAsRMD )	
			query.append(" AND audit_type_code IN (:deptList) ");
		
		query.append("	GROUP BY o.cntrl_cls_bucket_code , o.audit_type_code , o.cntrl_cls_bucket_desc " 
				+" 		ORDER BY o.audit_type_code , o.cntrl_cls_bucket_code " );
			
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("fromDate", fromDate).setParameter("toDate", toDate)
		.setParameter("unitList", unitList)
		.setParameter("legalEntityCode", legalEntityCode);
		if(!isDeptAsRMD ) hqlQuery.setParameter("deptList", deptList);
		
        List ls = hqlQuery.list();
        
        String rating=""; int iterateCnt=0; String tmpAuditTypeCode ="";
 		List<HashMap<String,String>> cntrlPfMpLst = new ArrayList();
        HashMap<String,String> cntrlPfMp = new HashMap();
        HashMap<String,String> cntrlPfMpTot = new HashMap();
 		for(Object obj: ls) {
 			Object[] obji=(Object[])obj;
 			if(iterateCnt == 0) {
 				cntrlPfMp.put("DEPT_CODE", obji[0]+"");
 				cntrlPfMp.put(obji[1]+"", obji[3]+"");  //  Code changed to Keep the Ops Code as Key
 			}else{
	 			if((obji[0]+"").equalsIgnoreCase(tmpAuditTypeCode)) {
	 				cntrlPfMp.put(obji[1]+"", obji[3]+"");
	 			}else {
	 				cntrlPfMpLst.add(cntrlPfMp);
	 				cntrlPfMp = new HashMap();
	 				cntrlPfMp.put("DEPT_CODE", obji[0]+"");
	 				cntrlPfMp.put(obji[1]+"", obji[3]+"");
	 			}
 			}
 			iterateCnt++; 
 			
 		// Logic to give Total numbers for each Key irrespective of Dept Code
 			if(cntrlPfMpTot.containsKey(obji[1]+"")) {
 				int temp = Integer.parseInt((cntrlPfMpTot.get(obji[1]+"")!=null)?cntrlPfMpTot.get(obji[1]+""):"0") +  ( (obji[3]!=null)? Integer.parseInt(obji[3].toString()) :0) ;
 				cntrlPfMpTot.put(obji[1]+"", temp+"");
 			}else {
 				int temp = (obji[3]!=null)? Integer.parseInt(obji[3].toString()) :0 ;
 				cntrlPfMpTot.put(obji[1]+"", temp+"");
 			}
 			// End here
 			if(iterateCnt == ls.size()) { 
 				cntrlPfMpLst.add(cntrlPfMp);
 				cntrlPfMpTot.put("DEPT_CODE","TOTAL");
 				cntrlPfMpLst.add(cntrlPfMpTot);
 			}tmpAuditTypeCode = obji[0]+"";
 		} 
        return cntrlPfMpLst;
		
	}
	
		
	@SuppressWarnings({ "deprecation", "unchecked", "serial" })
	@Override
	public List<HashMap<String,String>> getControlProfileProductwise(int legalEntityCode,  String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role,Boolean isDeptAsRMD, List<String> unitList, List<String> deptList) {
		
		logger.info("getControlProfileDeptwise .... "+ legalEntityCode + " :: "+auditType+" :: "+period +" :: "+fromDate+" :: "+toDate);
		logger.info("userId.... "+ userId + " :: "+role+" :: "+isDeptAsRMD +" :: "+unitList +" :: "+deptList);
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);	
		StringBuilder query= new StringBuilder(" SELECT  "
				+" o.audit_type_code, o.cntrl_cls_bucket_code, o.cntrl_cls_bucket_desc, COUNT(o.cntrl_cls_bucket_code) as cntrl_profile_cnt " 
				+"  ,o.audit_grp_name, o.audit_subgrp_name "
				+" FROM " 
				+"     audit_observation_v o " 
				+" WHERE " 
				+"	   o.legal_entity_code =:legalEntityCode AND "
				+"     o.audit_id IN (SELECT  " 
				+"             s.audit_id " 
				+"         FROM " 
				+"             audit_schedule s " 
				+"         WHERE " 
				+"             s.legal_entity_code = o.legal_entity_code " 
				+"                 AND s.audit_id = o.audit_id " 
				+"                 AND s.audit_status IN ('AC','AW') "
				+"				   AND s.unit_id in (:unitList)	"
				+ "				   AND s.schedule_start_date BETWEEN (:fromDate) AND  (:toDate)	"
				+ "									) " 
				+"         AND o.cntrl_cls_bucket_code IS NOT NULL " );
		if(!isDeptAsRMD )	
			query.append(" AND audit_type_code IN (:deptList) ");
		
		query.append("	GROUP BY o.cntrl_cls_bucket_code , o.audit_type_code , o.cntrl_cls_bucket_desc ,o.audit_grp_name, o.audit_subgrp_name " 
				+" 		ORDER BY o.audit_type_code , o.cntrl_cls_bucket_code " );
			
		Query hqlQuery= session.createNativeQuery(query.toString())
		.setParameter("fromDate", fromDate).setParameter("toDate", toDate)
		.setParameter("unitList", unitList)
		.setParameter("legalEntityCode", legalEntityCode);
		if(!isDeptAsRMD ) hqlQuery.setParameter("deptList", deptList);
		
        List ls = hqlQuery.list();
        
        String rating=""; int iterateCnt=0; String tmpAuditTypeCode ="";
 		List<HashMap<String,String>> cntrlPfMpLst = new ArrayList();
        HashMap<String,String> cntrlPfMp = new HashMap();
        HashMap<String,String> cntrlPfMpTot = new HashMap();
 		for(Object obj: ls) {
 			Object[] obji=(Object[])obj;
 			if(iterateCnt == 0) {
 				cntrlPfMp.put("DEPT_CODE", obji[0]+"=>"+obji[4]+"=>"+obji[5]);
 				cntrlPfMp.put(obji[1]+"", obji[3]+"");  //  Code changed to Keep the Ops Code as Key
 			}else{
	 			if((obji[0]+"=>"+obji[4]+"=>"+obji[5]).equalsIgnoreCase(tmpAuditTypeCode)) {
	 				cntrlPfMp.put(obji[1]+"", obji[3]+"");
	 			}else {
	 				cntrlPfMpLst.add(cntrlPfMp);
	 				cntrlPfMp = new HashMap();
	 				cntrlPfMp.put("DEPT_CODE", obji[0]+"=>"+obji[4]+"=>"+obji[5]);
	 				cntrlPfMp.put(obji[1]+"", obji[3]+"");
	 			}
 			}
 			iterateCnt++; 
 			
 		// Logic to give Total numbers for each Key irrespective of Dept Code
 			if(cntrlPfMpTot.containsKey(obji[1]+"")) {
 				int temp = Integer.parseInt((cntrlPfMpTot.get(obji[1]+"")!=null)?cntrlPfMpTot.get(obji[1]+""):"0") +  ( (obji[3]!=null)? Integer.parseInt(obji[3].toString()) :0) ;
 				cntrlPfMpTot.put(obji[1]+"", temp+"");
 			}else {
 				int temp = (obji[3]!=null)? Integer.parseInt(obji[3].toString()) :0 ;
 				cntrlPfMpTot.put(obji[1]+"", temp+"");
 			}
 			// End here
 			if(iterateCnt == ls.size()) { 
 				cntrlPfMpLst.add(cntrlPfMp);
 				cntrlPfMpTot.put("DEPT_CODE","TOTAL");
 				cntrlPfMpLst.add(cntrlPfMpTot);
 			}tmpAuditTypeCode = obji[0]+"=>"+obji[4]+"=>"+obji[5];
 		} 
        return cntrlPfMpLst;
		
	}
	
	public Map<String, Integer> getTaskStatistics(int legalEntityCode,String userId,String role, String auditType, String unitId, Boolean isDeptAsRMD, List<String> deptList ,List<String> unitList)  {
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);
	    Map<String, Integer> taskSummaryMap = null;
		try {
			logger.info("getUserDtlsforAdminDB .. legalEntityCode:: "+ legalEntityCode+" userId::"+userId +" role::"+role+" auditType::"+auditType +" unitId:: "+unitId+"isDeptAsRMD .. "+isDeptAsRMD);
			logger.info(" deptList .. "+deptList );
			logger.info(" unitList .. "+unitList );
			StringBuilder str = new StringBuilder(" "
				+ " SELECT g.description, IFNULL(tsk.cntSts, 0)  "
				+ "   FROM general_parameter g  "
				+ " 	     LEFT JOIN "
				+ " 	  (SELECT task_status, COUNT(task_status) AS cntSts, legal_entity_code FROM task_details "
				+ "					WHERE legal_entity_code= :legalEntityCode ");
			if(!isDeptAsRMD )	
				str.append(" AND audit_type_code IN (:deptList) ");
			
			str.append(" AND audit_id in (select s.audit_id from audit_schedule s where legal_entity_code=:legalEntityCode and s.unit_id IN (:unitList)) "
				+ "  GROUP BY task_status) tsk  "	
				+ " 	     ON g.legal_entity_code = tsk.legal_entity_code AND tsk.task_status = g.value "
				+ " WHERE g.key_1 = 'TASK_STATUS' AND g.key_2 = 'TASK_STATUS' AND g.legal_entity_code=:legalEntityCode ");
					
				Query hqlQuery = session.createNativeQuery(str.toString())
						.setParameter("legalEntityCode", legalEntityCode)
						.setParameter("unitList", unitList);
				if(!isDeptAsRMD ) hqlQuery.setParameter("deptList", deptList);
							
				List lst=hqlQuery.list();
				taskSummaryMap = new HashMap();
				int totalTask =0;
				for ( Iterator iter = lst.iterator(); iter.hasNext(); ) {
					Object[] obji=(Object[])iter.next();
					taskSummaryMap.put(obji[0].toString(), Integer.parseInt(obji[1].toString()));
					totalTask += Integer.parseInt(obji[1].toString());
				}
				taskSummaryMap.put("TOTAL", totalTask);
				logger.info("taskSummaryMap Summary .. "+ taskSummaryMap);

		}catch (Exception e) {
			e.getStackTrace();
			throw e;
		}
		return  taskSummaryMap;
	}
	
	public Map<String, Integer> getOverDueTaskStatistics(int legalEntityCode,String userId,String role, String auditType, String unitId, Boolean isDeptAsRMD, List<String> deptList ,List<String> unitList)  {
		
		Session session=getSession();
	    session.setDefaultReadOnly(true);
	    Map<String, Integer> overDueTaskMap = null;
		try {
			Date businessDate =businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
			logger.info("getOverDueTaskStatistics .. legalEntityCode:: "+ legalEntityCode+" userId::"+userId +" role::"+role+" auditType::"+auditType +" unitId:: "+unitId+"isDeptAsRMD .. "+isDeptAsRMD);
			logger.info(" deptList .. "+deptList );
			logger.info(" unitList .. "+unitList );
			StringBuilder query= new StringBuilder(
						"  select task_over_due_by, count(*)  from (    "
						+ "  select    "
						+ "   case  when datediff(:businessDate,s.due_date) between 0 AND 30 THEN 'ONE_MONTH'    "
						+ " 		when  datediff(:businessDate,s.due_date) between 31 AND 60 THEN 'TWO_MONTH'    "
						+ "         when  datediff(:businessDate,s.due_date) between 61 AND 90 THEN 'THREE_MONTH'    "
						//+ "         when  datediff(:businessDate,s.due_date) between 91 AND 120 THEN 'FOUR_MONTH'    "
						//+ "         when  datediff(:businessDate,s.due_date) between 121 AND 150 THEN 'FIVE_MONTH'    "
						//+ "         when  datediff(:businessDate,s.due_date) between 151 AND 180 THEN 'SIX_MONTH'    "
						+ "         ELSE 'MORE_THEN_THREE' END as task_over_due_by    "
						+ "     from task_details s where legal_entity_code=:legalEntityCode and due_date is not null  "
						+ "			and s.task_status='Open' and due_date < :businessDate " );
				if(!isDeptAsRMD )	
					query.append(" AND audit_type_code IN (:deptList) ");
				
				query.append("	AND audit_id in (select s.audit_id from audit_schedule s where legal_entity_code=:legalEntityCode and s.unit_id IN (:unitList)) "
						+ "    ) as ac group by task_over_due_by ");
						
				Query hqlQuery = session.createNativeQuery(query.toString())
						.setParameter("legalEntityCode", legalEntityCode)
						.setParameter("unitList", unitList)
						.setParameter("businessDate", businessDate);
				if(!isDeptAsRMD ) hqlQuery.setParameter("deptList", deptList);
				
				List lst=hqlQuery.list();
				overDueTaskMap = new HashMap();
				for ( Iterator iter = lst.iterator(); iter.hasNext(); ) {
					Object[] obji=(Object[])iter.next();
					overDueTaskMap.put(obji[0].toString(), Integer.parseInt(obji[1].toString()));
				}
				logger.info("taskSummaryMap Summary .. "+ overDueTaskMap);
			
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return overDueTaskMap;
	}

	public Map<String, String>  getHealthControlRiskSummaryDetails(int legalEntityCode,String userId,String role, String auditType, String unitId, Boolean isDeptAsRMD, List<String> deptList ,List<String> unitList)  {
	
		Session session=getSession();
	    session.setDefaultReadOnly(true);
	    Map<String, String> summaryMap = null;
		try {
			Date businessDate =businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
			logger.info("getHealthControlRiskSummaryDetails .. legalEntityCode:: "+ legalEntityCode+" userId::"+userId +" role::"+role+" auditType::"+auditType +" unitId:: "+unitId+"isDeptAsRMD .. "+isDeptAsRMD);
			logger.info(" deptList .. "+deptList );
			logger.info(" unitList .. "+unitList );
					
		   /*CURRENT YEAR dates*/
	       LocalDate financialYearStartDate  = dashboardDao.getFinancialYearStartDate(legalEntityCode);
	       LocalDate financialYearEndDate = financialYearStartDate.plusMonths(12).minusDays(1);
		   logger.info("FinancialYearStartDate :: "+financialYearStartDate +" FinancialYearEndDate.. "+financialYearEndDate);
		   
		   /*PREVIOUS YEAR  dates */
		   LocalDate previousFinancialYearStartDate = financialYearStartDate.minusMonths(12);
		   LocalDate previousFinancialYearEndDate = previousFinancialYearStartDate.plusMonths(12).minusDays(1);
		   logger.info("previousFinancialYearStartDate ...."+previousFinancialYearStartDate+" previousFinancialYearEndDate ...."+previousFinancialYearEndDate);
	       
			
			StringBuilder query= new StringBuilder(" "
					+ " SELECT 	cur.cnt as curr_cnt,"  // -0, Total Assessment Count
					+ "		   	cur.t1 as curr_total_risk, "	// -1,  Total Risks under the Above Assessments
					+ "			cur.i1 as curr_inhrt_risk_score, "	// -2,  Total Inherent Risk for all the Assessments (Sum of Inherent Risks of all Assessments )
					+ "			cur.c1 as curr_bucket_score, "  // curr_bucket_score -3  - SUM(Cntrl_Design_Eff * Cntrl_Oprt_Eff)
					+ " 	ROUND(cur.r1/cur.cnt,2) as curr_residul_risk_score,  "  // curr_residul_risk_score -4
					+ " 	cur.h1 as curr_health_index_score, ROUND(cur.h1/cur.cnt,2) as curr_health_score, "  // curr_health_score -6 // curr_health_index_score-> across all Assessments, curr_health_score-> Avg score
					//+ "		cur.p1 as curr_profile_score" 				// curr_profile_score -7
					+ "		ROUND(cur.p1/cur.cnt,2) as curr_profile_score" 				// curr_profile_score -7
					//+ "     ,(SELECT r.residual_risk_desc FROM maint_residual_risk r " 
					//+ "         WHERE legal_entity_code =:legalEntityCode AND (cur.r1 / cur.cnt) >= r.minimun_per AND (cur.r1 / cur.cnt) < r.maximum_per) as curr_risk_level, "  // curr_risk_level -8
					+ "     ,(SELECT h.health_index_desc FROM maint_health_index h " 
					+ "         WHERE legal_entity_code =:legalEntityCode AND ROUND(cur.h1/cur.cnt,2) >= h.minimun_per AND ROUND(cur.h1/cur.cnt,2) < if(h.maximum_per=100,101,h.maximum_per)) as curr_risk_level_health_index, "  // Health_Index_Risk -8
					+ "     (SELECT p.control_profile_desc FROM maint_control_profile p " 
					+ "         WHERE legal_entity_code =:legalEntityCode AND (cur.p1 / cur.cnt) >= p.minimun_per AND (cur.p1 / cur.cnt) < p.maximum_per) as curr_control_level "  // curr_control_level -9
					
					+ " ,prev.cnt as prev_cnt,prev.t1 as prev_total_risk, prev.i1 as prev_inhrt_risk_score, prev.c1 as prev_bucket_score, ROUND(prev.r1/prev.cnt,2) as prev_residul_risk_score,  " 
					+ " 	prev.h1 as prev_health_index_score, ROUND(prev.h1/prev.cnt,2) as prev_health_score, "
					+ "		ROUND(prev.p1/prev.cnt,2)  as prev_profile_score" 
					//+ "     ,(SELECT r.residual_risk_desc FROM maint_residual_risk r " 
					//+ "         WHERE legal_entity_code =:legalEntityCode AND (prev.r1 / prev.cnt) >= r.minimun_per AND (prev.r1 / prev.cnt) < r.maximum_per) as prev_risk_level, " 
					+ "     ,(SELECT h.health_index_desc FROM maint_health_index h " 
					+ "         WHERE legal_entity_code =:legalEntityCode AND ROUND(prev.h1/prev.cnt,2) >= h.minimun_per AND ROUND(prev.h1/prev.cnt,2) < if(h.maximum_per=100,101,h.maximum_per)) as prev_risk_level_health_index, "  // Health_Index_Risk -8
					+ "     (SELECT p.control_profile_desc FROM maint_control_profile p " 
					+ "         WHERE legal_entity_code =:legalEntityCode AND (prev.p1 / prev.cnt) >= p.minimun_per AND (prev.p1 / prev.cnt) < p.maximum_per) as prev_control_level " 
					+ " FROM " 
					+ "     (SELECT  " 
					+ "         COUNT(*) AS cnt, " 
					+ "             SUM(total_no_risk) AS t1, " 
					+ "             SUM(s.inhrt_risk_score) AS i1,  " 
					+ "             SUM(s.cntrl_cls_bucket_score) AS c1, " 
					+ "             ROUND(SUM(residul_risk_score),2) AS r1, " 
					+ "             SUM(health_index_score) AS h1,  " 
					+ "             ROUND(SUM(s.control_profile_score), 2) p1 " 
					+ "     FROM " 
					+ "         audit_schedule s " 
					+ "     WHERE " 
					+ "         legal_entity_code =:legalEntityCode " 
					+ "             AND audit_status = 'AC' " 
					+ "				AND audit_id in (select s.audit_id from audit_schedule s where legal_entity_code=:legalEntityCode and s.unit_id IN (:unitList)) "
					+ "             AND schedule_start_date BETWEEN :financialYearStartDate AND :financialYearEndDate " );
			if(!isDeptAsRMD ) query.append("      AND audit_type_code IN (:deptList) ");
			query.append("		) AS cur" );
			
			query.append( " ,(SELECT  " 
					+ "         COUNT(*) AS cnt, " 
					+ "             SUM(total_no_risk) AS t1, " 
					+ "             SUM(s.inhrt_risk_score) AS i1,  " 
					+ "             SUM(s.cntrl_cls_bucket_score) AS c1, " 
					+ "             ROUND(SUM(residul_risk_score),2) AS r1, " 
					+ "             SUM(health_index_score) AS h1,  " 
					+ "             ROUND(SUM(s.control_profile_score), 2) p1 " 
					+ "     FROM " 
					+ "         audit_schedule s " 
					+ "     WHERE " 
					+ "         legal_entity_code =:legalEntityCode " 
					+ "             AND audit_status = 'AC' " 
					+ "				AND audit_id in (select s.audit_id from audit_schedule s where legal_entity_code=:legalEntityCode and s.unit_id IN (:unitList)) "
					+ "             AND schedule_start_date BETWEEN :previousFinancialYearStartDate AND :previousFinancialYearEndDate " ); 
			if(!isDeptAsRMD ) query.append("      AND audit_type_code IN (:deptList) ");
			query.append("		) as prev " );

				Query hqlQuery = session.createNativeQuery(query.toString())
						.setParameter("legalEntityCode", legalEntityCode)
						.setParameter("unitList", unitList)
						.setParameter("financialYearStartDate", financialYearStartDate).setParameter("financialYearEndDate", financialYearEndDate)
						.setParameter("previousFinancialYearStartDate", previousFinancialYearStartDate).setParameter("previousFinancialYearEndDate", previousFinancialYearEndDate);
				if(!isDeptAsRMD ) hqlQuery.setParameter("deptList", deptList);
				
				List lst=hqlQuery.list();
				summaryMap = new HashMap();
				for ( Iterator iter = lst.iterator(); iter.hasNext(); ) {
					Object[] obj=(Object[])iter.next();
					if(obj[12] != null)summaryMap.put("PREV_RISK_SCORE", obj[12].toString());
					if(obj[2] != null)summaryMap.put("CURR_RISK_SCORE", obj[2].toString());
					if(obj[13] != null)summaryMap.put("PREV_CONTROL_SCORE", obj[13].toString());
					if(obj[3] != null)summaryMap.put("CURR_CONTROL_SCORE", obj[3].toString());
					if(obj[14] != null)summaryMap.put("PREV_RES_RISK_SCORE", obj[14].toString());
					if(obj[4] != null)summaryMap.put("CURR_RES_RISK_SCORE", obj[4].toString());
					if(obj[16] != null)summaryMap.put("PREV_HEALTH_INDEX", obj[16].toString());
					if(obj[6] != null)summaryMap.put("CURR_HEALTH_INDEX", obj[6].toString());
					if(obj[18] != null)summaryMap.put("PREV_RISK_LEVEL", obj[18].toString());
					if(obj[8] != null)summaryMap.put("CURR_RISK_LEVEL", obj[8].toString());
					if(obj[19] != null)summaryMap.put("PREV_CONTROL_LEVEL", obj[19].toString());
					if(obj[9] != null)summaryMap.put("CURR_CONTROL_LEVEL", obj[9].toString());
					if(obj[12] != null && obj[2] != null){ // INHERENT_RISK_SCORE
						double riskChng = (Double.parseDouble(obj[2].toString()) - Double.parseDouble(obj[2].toString())) /Double.parseDouble(obj[2].toString()) *100;
						summaryMap.put("CHNG_RISK_SCORE", riskChng+"");
						if(riskChng > 0 ) summaryMap.put("CHNG_RISK_COLOR", "red");
						else if(riskChng < 0) summaryMap.put("CHNG_RISK_COLOR", "green");
						else summaryMap.put("CHNG_RISK_COLOR", "darkorange");
					}else summaryMap.put("CHNG_RISK_COLOR", "darkorange");
					if(obj[13] != null && obj[3] != null){  // CONTROL_BUCKET_SCORE
						double cntrlChng = (Double.parseDouble(obj[3].toString()) - Double.parseDouble(obj[13].toString())) /Double.parseDouble(obj[3].toString()) *100;
						summaryMap.put("CHNG_CONTROL_SCORE", cntrlChng+"");
						if(cntrlChng > 0 ) summaryMap.put("CHNG_CONTROL_COLOR", "green");
						else if(cntrlChng < 0) summaryMap.put("CHNG_CONTROL_COLOR", "red");
						else summaryMap.put("CHNG_CONTROL_COLOR", "darkorange");
					}else summaryMap.put("CHNG_CONTROL_COLOR", "darkorange");
					
					if(obj[14] != null && obj[4] != null){  // RESIDUAL_RISK 
						double resRiskChng = (Double.parseDouble(obj[4].toString()) - Double.parseDouble(obj[14].toString())) /Double.parseDouble(obj[4].toString()) *100;
						summaryMap.put("CHNG_RES_RISK_SCORE", (Math.round(resRiskChng * 100.0) / 100.0)+"");
						if(resRiskChng > 0 ) summaryMap.put("CHNG_RES_RISK_COLOR", "red");
						else if(resRiskChng < 0) summaryMap.put("CHNG_RES_RISK_COLOR", "green");
						else summaryMap.put("CHNG_RES_RISK_COLOR", "darkorange");
					} //else summaryMap.put("CHNG_RES_RISK_COLOR", "AMBER");
					
					if(obj[14] != null && obj[4] != null){  // RISK_LEVEL
						double resRiskChng = Double.parseDouble(obj[4].toString()) - Double.parseDouble(obj[14].toString());
						if(obj[8] != null &&  obj[18] != null &&  !obj[8].toString().equalsIgnoreCase(obj[18].toString())) {
							if(resRiskChng > 0 ) summaryMap.put("CHNG_RISK_LEVEL_COLOR", "red");
							else if(resRiskChng < 0) summaryMap.put("CHNG_RISK_LEVEL_COLOR", "green");
							// else summaryMap.put("CHNG_RISK_LEVEL_COLOR", "AMBER");
						}else summaryMap.put("CHNG_RISK_LEVEL_COLOR", "darkorange");
					}
					
					if(obj[16] != null && obj[6] != null){  // HEALTH_INDEX
						//double hlthIndxChng = (Double.parseDouble(obj[6].toString()) - Double.parseDouble(obj[16].toString())) /Double.parseDouble(obj[6].toString()) *100;
						double hlthIndxChng = Double.parseDouble(obj[6].toString()) - Double.parseDouble(obj[16].toString());
						summaryMap.put("CHNG_HEALTH_INDEX", hlthIndxChng+"");
						if(hlthIndxChng > 0 ) summaryMap.put("CHNG_HEALTH_INDEX_COLOR", "green");
						else if(hlthIndxChng < 0) summaryMap.put("CHNG_HEALTH_INDEX_COLOR", "red");
						else summaryMap.put("CHNG_HEALTH_INDEX_COLOR", "darkorange");
					}//else summaryMap.put("CHNG_HEALTH_INDEX_COLOR", "darkorange");
					
					if(obj[17] != null && obj[7] != null){  // CONTROL_LEVEL
						double cntLvlChng = Double.parseDouble(obj[7].toString()) - Double.parseDouble(obj[17].toString());
						if(obj[9] != null &&  obj[19] != null &&  !obj[9].toString().equalsIgnoreCase(obj[19].toString())) {
							if(cntLvlChng > 0 ) summaryMap.put("CHNG_CONTROL_LEVEL_COLOR", "green");
							else if(cntLvlChng < 0) summaryMap.put("CHNG_CONTROL_LEVEL_COLOR", "red");
							// else summaryMap.put("CHNG_RISK_LEVEL_COLOR", "AMBER");
						}else summaryMap.put("CHNG_CONTROL_LEVEL_COLOR", "darkorange");
					}
					
					if(obj[1] != null) {
						int maxRisk = Integer.parseInt(obj[1].toString()) * 25;
						int minRisk = Integer.parseInt(obj[1].toString()) * 1;
						int maxControl = Integer.parseInt(obj[1].toString()) * 25;
						int minControl = Integer.parseInt(obj[1].toString()) * 1;
						double maxResidual = 25/1;
						double minResidual = (double)1/25;
						summaryMap.put("RISK_MINMAX", minRisk+"-"+maxRisk);
						summaryMap.put("CONTROL_MINMAX", minControl+"-"+maxControl);
					}
					double maxResidual = 25/1;
					double minResidual = (double)1/25;
					summaryMap.put("RESIDUALRISK_MINMAX", minResidual+"-"+maxResidual);
					summaryMap.put("HEALTHINDEX_MINMAX", 0+"-"+100);
					
					String currFYR= financialYearStartDate.toString().substring(0, 4)+"-"+financialYearEndDate.toString().substring(2,4);
					String prevFYR= previousFinancialYearStartDate.toString().substring(0, 4)+"-"+previousFinancialYearEndDate.toString().substring(2,4);
					summaryMap.put("PREV_FYR", prevFYR);
					summaryMap.put("CURR_FYR", currFYR);
					/*if(obj[2] != null)summaryMap.put("CHNG_RISK_SCORE", obj[2].toString());
					if(obj[2] != null)summaryMap.put("CHNG_CONTROL_SCORE", obj[2].toString());
					if(obj[2] != null)summaryMap.put("CHNG_RES_RISK_SCORE", obj[2].toString());
					if(obj[2] != null)summaryMap.put("CHNG_HEALTH_INDEX", obj[2].toString());*/
				}
				logger.info("dashboardSummaryDto Summary .. "+ summaryMap);
			
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return summaryMap;
	}

	public int getRCSAUnitsCount(int legalEntityCode,String units, String auditTypeCode,String plnStDate,String plnEnDate, Boolean isDeptAsRMD, List<String> deptList) {
		Session session=getSession();
		int RCSAUnitsCount = 0;
		try {
			logger.info("getAssessmentSummaryDtls legalEntityCode.. "+legalEntityCode + " units.. "+ units + "auditTypeCode.."+auditTypeCode+" plnStDate.."+plnStDate+" plnEnDate.."+plnEnDate);
			logger.info("isDeptAsRMD .."+ isDeptAsRMD +" deptList .."+ deptList);
			StringBuilder query= new StringBuilder(
					" SELECT COUNT(*) FROM maint_entity_audit_subgroup_mapping m WHERE m.legal_entity_code=:legalEntityCode and m.mapping_type='E' and m.audit_type_code <> 'RMD'  " 
					);
			query.append(" AND m.id in ("+units+") ");  //unit_ids in ("+units+")  aus.unit_id in (:units)
						
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				query.append(" AND m.audit_type_code =:auditTypeCode ");
			}else if(!isDeptAsRMD) {
				query.append(" AND m.audit_type_code in (:deptList) ");
			}	        
			
			Query hqlQuery= session.createNativeQuery(query.toString()).setParameter("legalEntityCode", legalEntityCode);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				hqlQuery.setParameter("auditTypeCode", auditTypeCode);
			}else if(!isDeptAsRMD) {
				hqlQuery.setParameter("deptList", deptList);
			}
						
			logger.info(" getEffortUtilized Qry is :: "+query.toString());
			RCSAUnitsCount = Integer.parseInt((hqlQuery).uniqueResult().toString());
			
		}catch (Exception e) {
			e.getStackTrace();
			throw e;
		}
		return  RCSAUnitsCount;
	}
	
	public Boolean isAssessmentProcessDoneFY(int legalEntityCode, LocalDate currFYStartDate, LocalDate currFYEndDate) {
		Session session=getSession();
		Boolean isAssessmentProcessDoneFYFlag=false;
		int leftOutAssessmentCount=0;
		try {
			logger.info("isAssessmentProcessDoneFY legalEntityCode.. "+legalEntityCode + " currFYStartDate.. "+ currFYStartDate + "currFYEndDate.."+currFYEndDate);
			StringBuilder query= new StringBuilder(
					" SELECT COUNT(audit_status) FROM audit_schedule WHERE "
					+ "  audit_status IN ('AP','AI','AS','AR') AND legal_entity_code=:legalEntityCode "
					+ "  AND schedule_start_date >=:currFYStartDate and schedule_end_date <=:currFYEndDate " 
			);
			
			Query hqlQuery= session.createNativeQuery(query.toString()).setParameter("legalEntityCode", legalEntityCode)
					.setParameter("currFYStartDate",currFYStartDate ).setParameter("currFYEndDate",currFYEndDate );
									
			logger.info(" isAssessmentProcessDoneFY Qry is :: "+hqlQuery.toString());
			leftOutAssessmentCount = Integer.parseInt((hqlQuery).uniqueResult().toString());
			
			if(leftOutAssessmentCount == 0) isAssessmentProcessDoneFYFlag=true;
			else isAssessmentProcessDoneFYFlag=false;
			logger.info("isAssessmentProcessDoneFYFlag ::"+isAssessmentProcessDoneFYFlag);
			
			
		}catch (Exception e) {
			e.getStackTrace();
			throw e;
		}
		return isAssessmentProcessDoneFYFlag;
	}
	
	/******************** New BaaSDos Dashboard implementation  start ********************/
	@Override
	public Map<String, Integer> getDeskComplianceRatingWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
				String zone, String unitId, List<String> unitIdlist, List<LocalDate>  financialYearList){
		
		logger.info("Inside Service getDeskComplianceRatingWidget .."+legalEntityCode +" userId .."+userId+" role .."+role+"financialYear .."+financialYear 
				+" auditTypeCode .."+auditTypeCode + "zone .."+zone +" unit.."+ unitId);
		Session session=getSession();		
		session.setDefaultReadOnly(true);
		try{
			/*StringBuilder strQuery = new StringBuilder(" select gp.value , count(sch.desk_compliance_rating) from general_parameter gp left join  audit_schedule sch "
					+" on gp.value = sch.desk_compliance_rating "
					+" and gp.legal_entity_code=sch.legal_entity_code ");
					strQuery.append(" and sch.financial_year = :financialYear  ");	 
					if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						strQuery.append(" and sch.audit_type_code = :auditTypeCode");
					}
					strQuery.append(" where gp.key_1= 'RATING'  "
					+" and gp.key_2= 'COMPLIANCE' "		
					+" and gp.legal_entity_code= :legalEntityCode ");				
					strQuery.append(" and sch.unit_id in (:unitId) ");				
					strQuery.append(" GROUP BY gp.value ");*/
			LocalDate financialYearStartDt =  financialYearList.get(0);
			LocalDate financialYearEndDt =  financialYearList.get(1);
			
			StringBuilder strQuery = new StringBuilder(" select "
					+ " upper(case when sch.desk_compliance_rating is null or sch.desk_compliance_rating='' or lower(sch.desk_compliance_rating)='null' then"
					+ " 'NA' else sch.desk_compliance_rating end)  as deskComplianceRating, "
					+ " count(sch.audit_id) from   audit_schedule sch ");
				 
					//strQuery.append(" Where sch.financial_year = :financialYear  ");
				strQuery.append("  "					 
					+ " Where ( Case when sch.actual_start_date IS NOT NULL "
					+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
					+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
					+ "  ");
					if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						strQuery.append(" and sch.audit_type_code = :auditTypeCode");
					}
					strQuery.append(" and sch.legal_entity_code= :legalEntityCode ");				
					strQuery.append(" and sch.unit_id in (:unitId) ");				
					strQuery.append(" GROUP BY deskComplianceRating ");
			 
			Query qry = session.createNativeQuery(strQuery.toString())
			.setParameter("legalEntityCode", legalEntityCode);
			//.setParameter("financialYearStartDt", financialYearStartDt, TemporalType.DATE)
			//.setParameter("financialYearEndDt", financialYear, TemporalType.DATE);
			//.setParameter("financialYear", financialYear, TemporalType.DATE);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}
					
			qry.setParameterList("unitId", unitIdlist);
			/*if(!BankAuditUtil.isEmptyString(unitId)){ 
				qry.setParameterList("unitId", unitIdlist);
			}
			else if(!BankAuditUtil.isEmptyString(zone)){ 
				qry.setParameterList("unitId", unitIdlist);
			}*/
						
			
			
			Map<String, Integer> deskComplianceRating = new HashMap<String, Integer>();
			List lst=qry.list();
			Iterator itr = lst.iterator();
			while(itr.hasNext()){
				Object[] obj=(Object[])itr.next();
				deskComplianceRating.put(String.valueOf(obj[0]), Integer.valueOf(String.valueOf(obj[1])));			
			}
			
			List<Object[]> lstRating = getDeskComplianceRatingsFromGeneralParameter(legalEntityCode);			 
			for (Object[] objects : lstRating) {
				deskComplianceRating.putIfAbsent(objects[0].toString(), 0);
			}
			
			return deskComplianceRating;
		}catch (Exception exception) {
			logger.error("Inside Service getDeskComplianceRatingWidget :: ", exception);
		}
		return null;
	}
	
	@Override
	public Map<String, Integer> getSupervisoryRatingWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId, List<String> unitIdlist, List<LocalDate>  financialYearList){
	
		logger.info("Inside Service getSupervisoryRatingWidget .."+legalEntityCode +" userId .."+userId+" role .."+role+"financialYear .."+financialYear 
				+" auditTypeCode .."+auditTypeCode + "zone .."+zone +" unit.."+ unitId);
		Session session=getSession();		
		session.setDefaultReadOnly(true);
		try{
			
			/*StringBuilder strQuery = new StringBuilder(" select gp.value , count(sch.effective_rating) from general_parameter gp left join  audit_schedule sch "
					+" on gp.value = sch.effective_rating "
					+" and gp.legal_entity_code=sch.legal_entity_code ");
					strQuery.append(" and sch.financial_year = :financialYear  "); 
					if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						strQuery.append(" and sch.audit_type_code = :auditTypeCode");
					}
					strQuery.append(" where gp.key_1= 'RATING'  "
					+" and gp.key_2= 'SUPERVISORY' "		
					+" and gp.legal_entity_code= :legalEntityCode ");			
					strQuery.append(" and sch.unit_id in (:unitId)");				
					strQuery.append(" GROUP BY gp.value ");*/
			
			LocalDate financialYearStartDt = financialYearList.get(0);
			LocalDate financialYearEndDt = financialYearList.get(1);
			StringBuilder strQuery = new StringBuilder(" select "
					+ "  (case when sch.effective_rating is null OR sch.effective_rating = '' OR lower(sch.effective_rating) = 'null' "
					+ " then 'NA' else  sch.effective_rating end) as effectiveRating  , count(sch.audit_id) "
					+ " from   audit_schedule sch ");
					//strQuery.append(" Where sch.financial_year = :financialYear  "); 
			strQuery.append("  " 
					+ " Where ( Case when sch.actual_start_date IS NOT NULL "
					+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
					+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
					+ "  ");
			
					strQuery.append(" and sch.legal_entity_code = :legalEntityCode  "); 
					if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						strQuery.append(" and sch.audit_type_code = :auditTypeCode");
					} 			
					strQuery.append(" and sch.unit_id in (:unitId)");				
					strQuery.append(" GROUP BY effectiveRating ");
			
			Query qry = session.createNativeQuery(strQuery.toString())
			.setParameter("legalEntityCode", legalEntityCode);
			//.setParameter("financialYearStartDt", financialYearStartDt, TemporalType.DATE)
			//.setParameter("financialYearEndDt", financialYear, TemporalType.DATE);
			//.setParameter("financialYear", financialYear, TemporalType.DATE);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}

			qry.setParameterList("unitId", unitIdlist);
			/*if(!BankAuditUtil.isEmptyString(unitId)){ 
				qry.setParameterList("unitId", unitIdlist);
			}
			else if(!BankAuditUtil.isEmptyString(zone)){ 
				qry.setParameterList("unitId", unitIdlist);
			}*/					
			
			Map<String, Integer> supervisoryRating = new HashMap<String, Integer>();
			List lst=qry.list();
			Iterator itr = lst.iterator();
			while(itr.hasNext()){
				Object[] obj=(Object[])itr.next();
				supervisoryRating.put(String.valueOf(obj[0]), Integer.valueOf(String.valueOf(obj[1])));			
			}
			
			List<Object[]> lstRating = getSupervisoryRatingsFromGeneralParameter(legalEntityCode); 
			for (Object[] objects : lstRating) {
				supervisoryRating.putIfAbsent(objects[0].toString(), 0);
			}
						
			return supervisoryRating;
		}catch (Exception exception) {
			logger.error("Inside Service getSupervisoryRatingWidget :: ", exception);
		}
		return null;
	}

	@Override
	public Map<String, Map<String, String>> getSupervisoryRatingMigrationWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId, List<String> unitIdlist, List<LocalDate> financialYearList){
		logger.info("Inside Service getSupervisoryRatingMigrationWidget .."+legalEntityCode +" userId .."+userId+" role .."+role+"financialYear .."+financialYear 
				+" auditTypeCode .."+auditTypeCode + "zone .."+zone +" unit.."+ unitId);
		Session session=getSession();		
		session.setDefaultReadOnly(true);
		try{
			//LocalDate financialYearStartDt = LocalDate.parse((financialYear.getYear()-1)+"-04-01");
			Map<String, Map<String, String>> supervisoryRatingMigration = new HashMap<String, Map<String, String>>();			
			
			//Get Supervisory Rating 			
			/*StringBuilder riskScorePercentageStrQry = new StringBuilder(" from RiskScorePercentage score where "
					+ " score.legalEntityCode= :legalEntityCode ");
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				riskScorePercentageStrQry.append("and score.auditTypeCode = :auditTypeCode ");
			}			
			//riskScorePercentageStrQry.append("group by score.riskCategoryDesc");			
			Query riskScorePercentageQry = session.createQuery(riskScorePercentageStrQry.toString());			
			riskScorePercentageQry.setParameter("legalEntityCode", Integer.parseInt(legalEntityCode));
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				riskScorePercentageQry.setParameter("auditTypeCode", auditTypeCode);
			}			 
			List<RiskScorePercentage> riskScorePercentageList =  riskScorePercentageQry.list();
			
			for (RiskScorePercentage riskScorePercentage : riskScorePercentageList) {
				StringBuilder strQuery = new StringBuilder(" Select rating, sum(improved), sum(stable), sum(worst), sum(maiden)  from(  "
						+" select  effective_rating as rating,  "

						+" (select count(sch2.effective_rating) From audit_schedule sch2 where sch2.audit_id = sch.prev_audit_id  "
						+" and  sch2.effective_rating in (select score1.risk_category_desc from  risk_score_percentage score1  "
								+ " where score1.audit_type_code= sch.audit_type_code  "
					            + " and score1.legal_entity_code= sch.legal_entity_code  "
					            + " and score1.rating_internal > :RatingInternal  ) ) as improved  ,  "		                				 
					        
						+" (select count(sch2.effective_rating) From audit_schedule sch2 where sch2.audit_id = sch.prev_audit_id   "
						+" and sch.effective_rating = sch2.effective_rating ) as stable, "
					        
					    +" (select count(sch2.effective_rating) From audit_schedule sch2 where sch2.audit_id = sch.prev_audit_id  "
						+" and sch2.effective_rating in (select score1.risk_category_desc from  risk_score_percentage score1  "
								+ " where score1.audit_type_code= sch.audit_type_code  "
					            + " and score1.legal_entity_code= sch.legal_entity_code  "
					            + " and score1.rating_internal < :RatingInternal  ) ) as worst,    "
					        
						+"  (select count(sch2.effective_rating) From audit_schedule sch2	where  sch.prev_audit_id is null "
					    +"   and sch2.audit_id = sch.audit_id and sch2.effective_rating = sch.effective_rating ) as maiden    "
					
						+" From audit_schedule sch    "
						+" where  sch.effective_rating = :Rating " ) ;
				
						strQuery.append(" and sch.financial_year = :financialYear  ");			
						strQuery.append(" and sch.legal_entity_code= :legalEntityCode ");					
					
				if(!BankAuditUtil.isEmptyString(auditTypeCode)){
					strQuery.append(" and sch.audit_type_code = :auditTypeCode");
				}	
				if(!BankAuditUtil.isEmptyString(zone)){
					//strQuery.append(" and sch.unit_id in (select  unit_code from maint_entity where )");
				}
				if(!BankAuditUtil.isEmptyString(unitId)){
					strQuery.append(" and sch.unit_id=:unitId ");
				}
				strQuery.append(" )temp group by rating  ");
				
				Query qry = session.createNativeQuery(strQuery.toString())
				.setParameter("RatingInternal", riskScorePercentage.getRatingInternal())		
				.setParameter("Rating", riskScorePercentage.getRiskCategoryDesc())
				.setParameter("legalEntityCode", legalEntityCode)
				.setParameter("financialYear", financialYear, TemporalType.DATE);
				
				if(!BankAuditUtil.isEmptyString(auditTypeCode)){
					qry.setParameter("auditTypeCode", auditTypeCode);
				}
				if(!BankAuditUtil.isEmptyString(zone)){
					
				}
				if(!BankAuditUtil.isEmptyString(unitId)){
					qry.setParameter("unitId", unitId);
				}	
				
				Map<String, String>  supervisoryRatingByValue = new HashMap<String, String>();
				List recordSet =   qry.list();
				if(recordSet.size()>0){
					Object[] tuple = (Object[]) recordSet.get(0); 
					supervisoryRatingByValue.put("improved", String.valueOf(tuple[1]));
					supervisoryRatingByValue.put("stable", String.valueOf(tuple[2]));
					supervisoryRatingByValue.put("worst", String.valueOf(tuple[3]));
					supervisoryRatingByValue.put("maiden", String.valueOf(tuple[4]));												
				}else{
					supervisoryRatingByValue.put("improved", "0");
					supervisoryRatingByValue.put("stable", "0");
					supervisoryRatingByValue.put("worst", "0");
					supervisoryRatingByValue.put("maiden", "0"); 
				}
				supervisoryRatingMigration.put(riskScorePercentage.getRiskCategoryDesc(), supervisoryRatingByValue);	
			}
			
			*/
			
			/*StringBuilder strQrySupRating = new StringBuilder(" select gp.value , gp.description from general_parameter gp  "	
					+" where gp.key_1= 'RATING'  "
					+" and gp.key_2= 'SUPERVISORY' "		
					+" and gp.legal_entity_code= :legalEntityCode ");
			Query qrySupRating = session.createNativeQuery(strQrySupRating.toString())
					.setParameter("legalEntityCode", legalEntityCode);
			List<Object[]> lst = qrySupRating.list();*/
			List<Object[]> lst = getSupervisoryRatingsFromGeneralParameter(legalEntityCode);
			LocalDate financialYearStartDt =  financialYearList.get(0);
			LocalDate financialYearEndDt = financialYearList.get(1);
			for (Object[] obj : lst) {
				String ratingValue = String.valueOf(obj[0]);  
				Integer ratingValueInt = Integer.valueOf(String.valueOf(obj[1])); //description
				StringBuilder strQuery = new StringBuilder(" Select rating, sum(improved), sum(stable), sum(worst), sum(maiden)  from(  "
						+" select  effective_rating as rating,  "

						+" (select count(sch2.effective_rating) From audit_schedule sch2 where sch2.audit_id = sch.prev_audit_id  "
						+" and  sch2.effective_rating in (select gp1.value from general_parameter gp1  "	
								+ " where gp1.key_1= 'RATING'  "
								+ " and gp1.key_2= 'SUPERVISORY' "		
								+ " and gp1.legal_entity_code = sch.legal_entity_code "
					            + " and gp1.description < :ratingValueInt  ) ) as improved  ,  "		                				 
					        
						+" (select count(sch2.effective_rating) From audit_schedule sch2 where sch2.audit_id = sch.prev_audit_id   "
						+" and sch.effective_rating = sch2.effective_rating ) as stable, "
					        
					    +" (select count(sch2.effective_rating) From audit_schedule sch2 where sch2.audit_id = sch.prev_audit_id  "
						+" and sch2.effective_rating in (select gp1.value from general_parameter gp1  "	
								+ " where gp1.key_1= 'RATING'  "
								+ " and gp1.key_2= 'SUPERVISORY' "		
								+ " and gp1.legal_entity_code = sch.legal_entity_code "
					            + " and gp1.description > :ratingValueInt  ) ) as worst,    "
					        
						+"  (select count(sch2.effective_rating) From audit_schedule sch2	where  sch.prev_audit_id is null "
					    +"   and sch2.audit_id = sch.audit_id and sch2.effective_rating = sch.effective_rating ) as maiden    "
					
						+" From audit_schedule sch    "
						+" where  sch.effective_rating = :Rating " ) ;
				
						//strQuery.append(" and sch.financial_year = :financialYear  ");	
						strQuery.append("  " 
								+ " AND ( Case when sch.actual_start_date IS NOT NULL "
								+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
								+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
								+ "  ");
						 
						strQuery.append(" and sch.legal_entity_code= :legalEntityCode ");					
					
						if(!BankAuditUtil.isEmptyString(auditTypeCode)){
							strQuery.append(" and sch.audit_type_code = :auditTypeCode");
						}	
						
						strQuery.append(" and sch.unit_id in (:unitId)");
						/*if(!BankAuditUtil.isEmptyString(unitId)){
							strQuery.append(" and sch.unit_id in (:unitId) ");
						}
						else if(!BankAuditUtil.isEmptyString(zone)){
							strQuery.append(" and sch.unit_id in (:unitId)");
						}*/	
						strQuery.append(" )temp group by rating  ");
						
				Query qry = session.createNativeQuery(strQuery.toString())
				.setParameter("ratingValueInt", ratingValueInt)		
				.setParameter("Rating", ratingValue)
				.setParameter("legalEntityCode", legalEntityCode);
				//.setParameter("financialYearStartDt", financialYearStartDt, TemporalType.DATE)
				//.setParameter("financialYearEndDt", financialYear, TemporalType.DATE);
				//.setParameter("financialYear", financialYear, TemporalType.DATE);
				
				if(!BankAuditUtil.isEmptyString(auditTypeCode)){
					qry.setParameter("auditTypeCode", auditTypeCode);
				}

				qry.setParameterList("unitId", unitIdlist);
				/*if(!BankAuditUtil.isEmptyString(unitId)){ 
					qry.setParameterList("unitId", unitIdlist);
				}
				else if(!BankAuditUtil.isEmptyString(zone)){ 
					qry.setParameterList("unitId", unitIdlist);
				}*/
				
				Map<String, String>  supervisoryRatingByValue = new HashMap<String, String>();
				List recordSet =   qry.list();
				if(recordSet.size()>0){
					Object[] tuple = (Object[]) recordSet.get(0); 
					supervisoryRatingByValue.put("improved", String.valueOf(tuple[1]));
					supervisoryRatingByValue.put("stable", String.valueOf(tuple[2]));
					supervisoryRatingByValue.put("worst", String.valueOf(tuple[3]));
					supervisoryRatingByValue.put("maiden", String.valueOf(tuple[4]));												
				}else{
					supervisoryRatingByValue.put("improved", "0");
					supervisoryRatingByValue.put("stable", "0");
					supervisoryRatingByValue.put("worst", "0");
					supervisoryRatingByValue.put("maiden", "0"); 
				}
				supervisoryRatingMigration.put(ratingValue, supervisoryRatingByValue);	
			}		 
			
			Map<String, String>  supervisoryRatingByValudImproved= new HashMap<String, String>();
			Map<String, String>  supervisoryRatingByValudStable= new HashMap<String, String>();
			Map<String, String>  supervisoryRatingByValudWorst= new HashMap<String, String>();
			Map<String, String>  supervisoryRatingByValudMaiden= new HashMap<String, String>();
			Map<String, Map<String, String>> supervisoryRatingMigrationToggle = new HashMap<String, Map<String, String>>();
			for (Map.Entry<String, Map<String, String>> entry: supervisoryRatingMigration.entrySet() ) {				
				for(Map.Entry<String, String> entryInner:entry.getValue().entrySet())
				{					
					if(entryInner.getKey().equals("improved")){						 
						supervisoryRatingByValudImproved.put(entry.getKey(), entryInner.getValue());
					}
					else if(entryInner.getKey().equals("stable")){						 
						supervisoryRatingByValudStable.put(entry.getKey(), entryInner.getValue());
					}
					else if(entryInner.getKey().equals("worst")){						 
						supervisoryRatingByValudWorst.put(entry.getKey(), entryInner.getValue());
					}
					else if(entryInner.getKey().equals("maiden")){						 
						supervisoryRatingByValudMaiden.put(entry.getKey(), entryInner.getValue());
					}
				}				
			}
			
			System.out.println(supervisoryRatingByValudImproved);
			supervisoryRatingMigrationToggle.put("improved", supervisoryRatingByValudImproved);			
			supervisoryRatingMigrationToggle.put("stable", supervisoryRatingByValudStable);
			supervisoryRatingMigrationToggle.put("worst", supervisoryRatingByValudWorst);
			supervisoryRatingMigrationToggle.put("maiden", supervisoryRatingByValudMaiden);	 			
			supervisoryRatingMigration.putAll(supervisoryRatingMigrationToggle);			
			return supervisoryRatingMigration;
		}catch (Exception exception) {
			logger.error("Inside Service getSupervisoryRatingMigrationWidget :: ", exception);
		}
		return null;
	}
	
	@Override
	public Map<String, String> getBudgetProgressWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
				String zone, String unitId, List<String> unitIdlist, List<LocalDate> financialYearList){
		
		logger.info("Inside Service getBudgetProgressWidget .."+legalEntityCode +" userId .."+userId+" role .."+role+"financialYear .."+financialYear 
				+" auditTypeCode .."+auditTypeCode + "zone .."+zone +" unit.."+ unitId);
		Session session=getSession();	
		session.setDefaultReadOnly(true);
		Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		//LocalDate financialYearStartDt = LocalDate.parse((financialYear.getYear()-1)+"-04-01");
		try{
			LocalDate financialYearStartDt = financialYearList.get(0);
			LocalDate financialYearEndDt = financialYearList.get(1);
			StringBuilder strQuery = new StringBuilder(" Select ifnull(sum(budgeted),0) as budgetedCount, ifnull(sum(initiated),0) as initiatedCount, "
					+ " ifnull(sum(submitted),0) as submittedCount,  ifnull(sum(finalised),0) as finalisedCount, "
					+ " ifnull(sum(dispatched),0) as dispatchedCount, ifnull(sum(due),0) as dueCount,"
					+ " ifnull(sum(planned),0) as plannedCount, ifnull(sum(exited),0) as exitedCount, "
					+ " ifnull(sum(reviewReady),0) as reviewReadyCount, "
					+ " ifnull(sum(completed),0) as completedCount from  "
						+" 	(Select   "
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1 "
								+" 	where sch1.audit_id=sch.audit_id and sch1.audit_status not in ('AD','AU','AN') ) as budgeted, "
								 
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1 "
								+" 	where sch1.audit_id=sch.audit_id and sch1.audit_status='AI' and sch1.observation_status is null ) as initiated, "							
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1 "
								+" 	where sch1.audit_id=sch.audit_id and sch1.audit_status='AP' and sch1.observation_status='AE' and sch1.report_status='RIP' ) as submitted, "							
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1 "
								+" 	where sch1.audit_id=sch.audit_id and sch1.report_status='RS') as finalised, "							
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1 "
								+" 	where sch1.audit_id=sch.audit_id and sch1.audit_status in ('AS', 'AC', 'AR', 'AW') and sch1.report_status in ('RD') ) as dispatched, "
								+ " " );
								
							strQuery.append(" 0 as due, "	);
							//used report date instead of actual end date ->>> report date = exit date
							/*strQuery.append("( SELECT COUNT(sch1.audit_id) FROM audit_schedule sch1 INNER JOIN maint_entity me ON "
										+"  me.unit_code=sch1.unit_id  "
										+" 		 WHERE  sch1.audit_id=sch.audit_id and sch1.audit_status NOT IN ('AD','AU','AN') AND  "
										+" 		 CASE WHEN me.unit_type IN('RRBC','RRBD')  "
										+" 		      THEN (CASE WHEN sch1.audit_status = 'AI' AND   sch1.observation_status!='AE'    " 
										+" 			 THEN DATE_ADD(IFNULL(sch1.actual_start_date, sch1.schedule_start_date), INTERVAL (sch1.duration+16) DAY ) <= :businessDate " 
										+" 			 WHEN (sch1.audit_status = 'AI' AND   sch1.observation_status='AE') OR (sch1.audit_status = 'AI' AND sch1.report_status='RS') "
										+" 			 THEN DATE_ADD(IFNULL(sch1.actual_end_date, sch1.schedule_end_date), INTERVAL 16 DAY ) <= :businessDate  "
										+" 					 END) "
										+" 		      ELSE  "
										+" 			(CASE WHEN sch1.audit_status = 'AI' AND   sch1.observation_status!='AE'     "
										+" 			 THEN DATE_ADD(IFNULL(sch1.actual_start_date, sch1.schedule_start_date), INTERVAL (sch1.duration+20) DAY ) <= :businessDate " 
										+" 			 WHEN (sch1.audit_status = 'AI' AND   sch1.observation_status='AE') OR (sch1.audit_status = 'AI' AND sch1.report_status='RS') "
										+" 			 THEN DATE_ADD(IFNULL(sch1.actual_end_date, sch1.schedule_end_date), INTERVAL 20 DAY ) <= :businessDate   "
										+" 					 END) "
										+" 			END )  as due, "	);*/						
								 
								
					strQuery.append(" 	(Select  count(sch1.audit_id) from audit_schedule sch1  where sch1.audit_id=sch.audit_id and sch1.audit_status='AP') as planned, "				
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1  where sch1.audit_id=sch.audit_id and sch1.audit_status='AI' "
								+"  and sch1.observation_status='AE' and sch1.report_status='RIP' ) as exited, "								
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1  where sch1.audit_id=sch.audit_id and sch1.audit_status='AI' "
								+"  and sch1.observation_status='AE' and sch1.report_status in ('RRR', 'FI', 'FS','RA','RR','RI','RAR','RC') ) as reviewReady, ");
								
					strQuery.append(" 	(Select  count(sch1.audit_id) from audit_schedule sch1 "
							+" 	where sch1.audit_id=sch.audit_id and  sch1.observation_status='AS' ) as completed " 
																
								+ "  "		
					+" 	from audit_schedule sch where ");		
					//strQuery.append("  sch.financial_year = :financialYear  ");	
					strQuery.append("  " 
					+ " ( Case when sch.actual_start_date IS NOT NULL "
					+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
					+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
					+ "  ");	
					//strQuery.append(" (sch.schedule_start_date between :financialYearStartDt and :financialYearEndDt)  ");	
					strQuery.append(" and sch.legal_entity_code= :legalEntityCode ");
					 			
					if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
					}	
					
					strQuery.append(" and sch.unit_id in (:unitId) ");
					/*if(!BankAuditUtil.isEmptyString(unitId)){
						strQuery.append(" and sch.unit_id in (:unitId) ");
					}
					else if(!BankAuditUtil.isEmptyString(zone)){
						strQuery.append(" and sch.unit_id in (:unitId) ");
					}else{
						strQuery.append(" and sch.unit_id in (:unitId) ");
					}	*/
					strQuery.append("   ) Tmp  ");
			
			Query qry = session.createNativeQuery(strQuery.toString())	
					//.setParameter("businessDate", businessDate, TemporalType.DATE)
					//.setParameter("financialYear", financialYear, TemporalType.DATE)
					//.setParameter("financialYearStartDt", financialYearStartDt, TemporalType.DATE)
					//.setParameter("financialYearEndDt", financialYear, TemporalType.DATE)
					.setParameter("legalEntityCode", legalEntityCode);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}

			qry.setParameterList("unitId", unitIdlist);
			/*if(!BankAuditUtil.isEmptyString(unitId)){ 
				qry.setParameterList("unitId", unitIdlist);
			}
			else if(!BankAuditUtil.isEmptyString(zone)){ 
				qry.setParameterList("unitId", unitIdlist);
			}*/					
			
			Map<String, String> budgetProgess = new HashMap<String, String>();
			List recordSet=qry.list();
			if(!recordSet.isEmpty() && recordSet.size()>0){
				Integer dueCountInspection = getInspectionDueCount(legalEntityCode, userId, role, financialYearEndDt, auditTypeCode, 
						zone, unitId, unitIdlist, financialYearList, businessDate);
				Object[] tuple = (Object[]) recordSet.get(0); 
				budgetProgess.put("budgeted", String.valueOf(tuple[0]));
				budgetProgess.put("initiated", String.valueOf(tuple[1]));
				budgetProgess.put("submittedCount", String.valueOf(tuple[2]));
				budgetProgess.put("finalisedCount", String.valueOf(tuple[3]));	
				budgetProgess.put("dispatchedCount", String.valueOf(tuple[4])); 
				budgetProgess.put("dueCount", dueCountInspection+"");
				budgetProgess.put("plannedCount", String.valueOf(tuple[6]));	
				budgetProgess.put("exitedCount", String.valueOf(tuple[7]));
				budgetProgess.put("reviewReadyCount", String.valueOf(tuple[8]));
				budgetProgess.put("completedCount", String.valueOf(tuple[9]));
					
			} 
			return budgetProgess;
		}catch (Exception exception) {
			logger.error("Inside Service getBudgetProgressWidget :: ", exception);
		}
		return null;
	}
	
	@Override
	public Map<String, String> getComplianceStatusWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
				String zone, String unitId, List<String> unitIdlist, List<LocalDate> financialYearList){
		
		logger.info("Inside Service getComplianceStatusWidget .."+legalEntityCode +" userId .."+userId+" role .."+role+"financialYear .."+financialYear 
				+" auditTypeCode .."+auditTypeCode + "zone .."+zone +" unit.."+ unitId);
		Session session=getSession();		
		session.setDefaultReadOnly(true);
		try{
			Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
			LocalDate financialYearStartDt = financialYearList.get(0);
			LocalDate financialYearEndDt = financialYearList.get(1);
			//LocalDate financialYearStartDt = LocalDate.parse((financialYear.getYear()-1)+"-04-01");
			StringBuilder strQuery = new StringBuilder("  Select ifnull(sum(received),0) as receivedCount, ifnull(sum(scrutinised),0) as scrutinisedCount, "
					+" 	 ifnull(sum(rated),0) as ratedCount, ifnull(sum(furtherCompliance),0) as furtherComplianceCount, "
					+" 	 ifnull(sum(closed),0) as closedCount, ifnull(sum(due),0) dueCount from "							 
						+" 	(Select  "
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1  "
								+" 	where sch1.audit_id=sch.audit_id and (sch1.audit_status='AR' OR sch1.review_status='WI') and sch1.respond_status ='RS') as received, " //and respond_status ='RS' and sch1.report_status ='RD' and observation_status ='AS'
							 
								+"	(Select  count(sch1.audit_id) from audit_schedule sch1  "
								+"	where sch1.audit_id=sch.audit_id  and sch1.review_status='WS' and sch1.audit_status='AW' ) as scrutinised,  "	
								
								+"	(Select  count(sch1.audit_id) from audit_schedule sch1  "
								+"	where sch1.audit_id=sch.audit_id and  (sch1.desk_compliance_rating is not null or sch1.desk_compliance_rating!='') ) as rated,  "
								
								/*+"	(Select count(distinct obs.audit_id) from audit_observation obs  "
								+"	where obs.audit_id=sch.audit_id  and  obs.review_status_attribute ='FC' and  sch.review_status='WS' and sch.audit_status='AW') as furtherCompliance,  "*/	
																
								+"	(Select count(distinct resRevCap.audit_id) from  audit_observation_respond_review_capture resRevCap  "
								+"	where resRevCap.audit_id=sch.audit_id  and  resRevCap.review_respond_status = 'Further Compliance' and  sch.review_status='WS' and sch.audit_status='AW') as furtherCompliance,  "
								
								+"	(Select  count(sch1.audit_id) from audit_schedule sch1  "
								+"	where sch1.audit_id=sch.audit_id and sch1.audit_status='AC' ) as closed, "
								+ " 0 as due "		
								
								/*+" 	(Select  count(sch1.audit_id) from audit_schedule sch1  "
								+"	 where sch1.audit_id=sch.audit_id and   sch1.report_dispatch_date IS NOT NULL  "
								//+"   AND sch1.report_status='RD' AND (sch1.respond_status IS NULL OR sch1.respond_status!='RS') "
								+"   AND  DATE_ADD(sch1.report_dispatch_date, INTERVAL ifnull(sch1.response_time,60) DAY ) <= :businessDate ) as due  "*/
 							 
					+" from audit_schedule sch  where  ");		
			
					//strQuery.append("   sch.financial_year = :financialYear  ");		
					strQuery.append("  "					 
							+ " ( Case when sch.actual_start_date IS NOT NULL "
							+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
							+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
							+ "  ");	
					strQuery.append(" and sch.legal_entity_code= :legalEntityCode ");
								
					if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						strQuery.append(" and sch.audit_type_code = :auditTypeCode");
					}	

					strQuery.append(" and sch.unit_id in (:unitId) ");
					/*if(!BankAuditUtil.isEmptyString(unitId)){
						strQuery.append(" and sch.unit_id in (:unitId) ");
					}
					else if(!BankAuditUtil.isEmptyString(zone)){
						strQuery.append(" and sch.unit_id in (:unitId)");
					}*/	
					strQuery.append("   ) Tmp  ");
			
			Query qry = session.createNativeQuery(strQuery.toString())
			.setParameter("legalEntityCode", legalEntityCode);
			//.setParameter("financialYearStartDt", financialYearStartDt, TemporalType.DATE)
			//.setParameter("financialYearEndDt", financialYear, TemporalType.DATE);
			//.setParameter("businessDate", businessDate, TemporalType.DATE);
			//.setParameter("financialYear", financialYear, TemporalType.DATE);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}

			qry.setParameterList("unitId", unitIdlist);
			/*if(!BankAuditUtil.isEmptyString(unitId)){ 
				qry.setParameterList("unitId", unitIdlist);
			}
			else if(!BankAuditUtil.isEmptyString(zone)){ 
				qry.setParameterList("unitId", unitIdlist);
			}	*/					
			
			Map<String, String> complianceStatus = new HashMap<String, String>();
			List recordSet=qry.list();
			if(!recordSet.isEmpty() && recordSet.size()>0){
				Integer dueCountCompliance = getcomplianceDueCount(legalEntityCode, userId, role, financialYearEndDt, auditTypeCode, zone, unitId, 
						unitIdlist, financialYearList, businessDate);
				Object[] tuple = (Object[]) recordSet.get(0); 
				complianceStatus.put("receivedCount", String.valueOf(tuple[0]));
				complianceStatus.put("scrutinisedCount", String.valueOf(tuple[1]));
				complianceStatus.put("ratedCount", String.valueOf(tuple[2]));
				complianceStatus.put("furtherComplianceCount", String.valueOf(tuple[3]));	
				complianceStatus.put("closedCount", String.valueOf(tuple[4]));
				complianceStatus.put("dueCount", dueCountCompliance+"");
				
			} 
			 
			return complianceStatus;
		}catch (Exception exception) {
			logger.error("Inside Service getComplianceStatusWidget :: ", exception);
		}
		return null;
	}
	
	@Override
	public Map<String, Map<String, Integer>> getFinancialParameterWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId, List<String> unitIdlist, List<LocalDate> financialYearList){ 
		  
		  logger.info("Inside Service getFinancialParameterWidget .."+legalEntityCode +" userId .."+userId+" role .."+role+"financialYear .."+financialYear 
					+" auditTypeCode .."+auditTypeCode + "zone .."+zone +" unit.."+ unitId);
			Session session=getSession();	
			session.setDefaultReadOnly(true);
			
			//get BOM id based on auditType
			String[] bomIdsArray = null;	 			
			 //bomIdsArray = new String[]{"CRAR","GrossNPA","NetNPA","RoA"};
			if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_RRB_CONTAINS)){	
				bomIdsArray = new String[]{"BOM-15","BOM-44","BOM-45","BOM-186"}; 
			}else if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_DCCB_CONTAIN)){
				bomIdsArray = new String[]{"BOMD59","BOMD183","BOMD502","BOMD370"};			
			}else if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_StCB_CONTAIN)){
				bomIdsArray = new String[]{"BOMS59","BOMS183","BOMS502","BOMS370"}; 
			}else if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_SCARDB_CONTAIN)){
				bomIdsArray = new String[]{""}; 
			}			
			List<String> bomIds = new ArrayList<>(Arrays.asList(bomIdsArray));		 
			LocalDate financialYearStartDt = financialYearList.get(0);
			LocalDate financialYearEndDt = financialYearList.get(1);
			try{ 
				//LocalDate financialYearStartDt = LocalDate.parse((financialYear.getYear()-1)+"-04-01");
				StringBuilder strQuery = new StringBuilder("  Select ifc.parameter_name_nabard, ifc.submitted_value_latest        "     
						+" from  audit_schedule sch inner join  ifc_ensure_baas_data ifc  "
						+" on ifc.audit_id=sch.audit_id and ifc.audit_type_code=sch.audit_type_code "
						+" and ifc.stage_of_file= :stageOfFile "
						+" and ifc.parameter_name_nabard in (:bomIds) " 
						+" where sch.legal_entity_code= :legalEntityCode  ");						
						//strQuery.append(" and  sch.financial_year = :financialYear ");
				strQuery.append("  "					 
						+ " AND ( Case when sch.actual_start_date IS NOT NULL "
						+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
						+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
						+ "  ");						 
				
					if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
					}				

					strQuery.append(" and sch.unit_id in (:unitId) ");
					/*if(!BankAuditUtil.isEmptyString(unitId)){
						strQuery.append(" and sch.unit_id in (:unitId) ");
					}
					else if(!BankAuditUtil.isEmptyString(zone)){
						strQuery.append(" and sch.unit_id in (:unitId)");
					}*/	
						 
				Query qry = session.createNativeQuery(strQuery.toString())
						.setParameter("legalEntityCode", legalEntityCode)
						//.setParameter("financialYearStartDt", financialYearStartDt, TemporalType.DATE)
						//.setParameter("financialYearEndDt", financialYear, TemporalType.DATE)
						//.setParameter("financialYear", financialYear , TemporalType.DATE)
						.setParameterList("bomIds", bomIds)
						.setParameter("stageOfFile", BankAuditConstant.STAGE_OF_FILE_LATEST);
				
				if(!BankAuditUtil.isEmptyString(auditTypeCode)){
					qry.setParameter("auditTypeCode", auditTypeCode);
				}

				qry.setParameterList("unitId", unitIdlist);
				/*if(!BankAuditUtil.isEmptyString(unitId)){ 
					qry.setParameterList("unitId", unitIdlist);
				}
				else if(!BankAuditUtil.isEmptyString(zone)){ 
					qry.setParameterList("unitId", unitIdlist);
				}*/			
				 
				List<Object[]> lst=qry.list(); 
								
				int inspectionwithNoCSV = getInspectionCountWithoutCSV(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId);
				Map<String, Integer> parameterCount = new HashMap<>();
				parameterCount.put("NA",  inspectionwithNoCSV);
				parameterCount.put("one", 0);
				parameterCount.put("two", 0);
				parameterCount.put("three", 0);
				parameterCount.put("four", 0);
				parameterCount.put("five", 0);				
				
				Map<String, Integer> parameterCountCRAR = new HashMap<>();
				parameterCountCRAR.putAll(parameterCount);
				
				Map<String, Integer> parameterCountRoA = new HashMap<>();
				parameterCountRoA.putAll(parameterCount);
				
				Map<String, Integer> parameterCountGrossNPA = new HashMap<>();
				parameterCountGrossNPA.putAll(parameterCount);
				
				Map<String, Integer> parameterCountNetNPA = new HashMap<>();
				parameterCountNetNPA.putAll(parameterCount);
				
				for (Object[] objects : lst) {
					String bomId = (String) objects[0]; 
					Double value = (objects[1]==null || ((String)objects[1]).equals(""))?null: Double.parseDouble((String)objects[1]);
					final String bomFirst =   bomIdsArray[0].toString();
					 if(bomIdsArray[0].toString().equalsIgnoreCase(bomId)){					 							
						if(value==null){  
							parameterCountCRAR.put("NA", parameterCountCRAR.get("NA") + 1);
						}else if(value<0){ 
							parameterCountCRAR.put("one", parameterCountCRAR.get("one") + 1);
						}else if(value>=0 && value<4){ 
							parameterCountCRAR.put("two", parameterCountCRAR.get("two") + 1);
						}else if(value>=4 && value<7){ 
							parameterCountCRAR.put("three", parameterCountCRAR.get("three") + 1);
						}else if(value>=7 && value<9){ 
							parameterCountCRAR.put("four", parameterCountCRAR.get("four") + 1);
						}else if(value>=9){ 
							parameterCountCRAR.put("five", parameterCountCRAR.get("five") + 1);
						}	 
					 }else if(bomIdsArray[1].toString().equalsIgnoreCase(bomId)){					 							
						if(value==null){  
							parameterCountGrossNPA.put("NA", parameterCountGrossNPA.get("NA") + 1);
						}else if(value<5){ 
							parameterCountGrossNPA.put("one", parameterCountGrossNPA.get("one") + 1);
						}else if(value>=5 && value<10){ 
							parameterCountGrossNPA.put("two", parameterCountGrossNPA.get("two") + 1);
						}else if(value>=10 && value<15){ 
							parameterCountGrossNPA.put("three", parameterCountGrossNPA.get("three") + 1);
						}else if(value>=15 && value<25){ 
							parameterCountGrossNPA.put("four", parameterCountGrossNPA.get("four") + 1);
						}else if(value>=25){ 
							parameterCountGrossNPA.put("five", parameterCountGrossNPA.get("five") + 1);
						}	 
					}else if(bomIdsArray[2].toString().equalsIgnoreCase(bomId)){					 							
						if(value==null){  
							parameterCountNetNPA.put("NA", parameterCountNetNPA.get("NA") + 1);
						}else if(value<3){ 
							parameterCountNetNPA.put("one",  parameterCountNetNPA.get("one") + 1);
						}else if(value>=3 && value<5){ 
							parameterCountNetNPA.put("two", parameterCountNetNPA.get("two") + 1);
						}else if(value>=5 && value<10){ 
							parameterCountNetNPA.put("three", parameterCountNetNPA.get("three") + 1);
						}else if(value>=10 && value<15){ 
							parameterCountNetNPA.put("four",  parameterCountNetNPA.get("four") + 1);
						}else if(value>=15){ 
							parameterCountNetNPA.put("five", parameterCountNetNPA.get("five") + 1);
						}	 
					}
					else if(bomIdsArray[3].toString().equalsIgnoreCase(bomId)){					 							
						if(value==null){  
							parameterCountRoA.put("NA", parameterCountRoA.get("NA") + 1);
						}else if(value<0){ 
							parameterCountRoA.put("one", parameterCountRoA.get("one") + 1);
						}else if(value>=0 && value<0.25){ 
							parameterCountRoA.put("two", parameterCountRoA.get("two") + 1);
						}else if(value>=0.25 && value<0.50){ 
							parameterCountRoA.put("three", parameterCountRoA.get("three") + 1);
						}else if(value>=0.50 && value<1){ 
							parameterCountRoA.put("four", parameterCountRoA.get("four") + 1);
						}else if(value>=1){ 
							parameterCountRoA.put("five", parameterCountRoA.get("five") + 1);
						}	 
					}
				}
				
				Map<String, Map<String, Integer>> financialParameter = new HashMap<>(); 
				financialParameter.put("CRAR", parameterCountCRAR);
				financialParameter.put("GrossNPA", parameterCountGrossNPA);
				financialParameter.put("NetNPA", parameterCountNetNPA);
				financialParameter.put("RoA", parameterCountRoA);				
				return financialParameter; 
			}catch (Exception exception) {
				exception.printStackTrace(System.out);
				logger.error("Inside Service getFinancialParameterWidget :: ", exception);
			}
		return null;		
	} 

	@Override
	public Map<String, Integer> getMyInspectionWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
				String zone, String unitId, List<LocalDate>  financialYearList){
		
		logger.info("Inside Service getMyInspectionWidget .."+legalEntityCode +" userId .."+userId+" role .."+role+"financialYear .."+financialYear 
				+" auditTypeCode .."+auditTypeCode + "zone .."+zone +" unit.."+ unitId);
		Session session=getSession();
		session.setDefaultReadOnly(true);
		try{
			/*StringBuilder strQuery = new StringBuilder("  "
					+ "select auditType.audit_type_code , count(sch.audit_type_code) from maint_audit_type_desc auditType left join  audit_schedule sch "
					+" on auditType.audit_type_code = sch.audit_type_code "
					+" and auditType.legal_entity_code=sch.legal_entity_code "
					+" and sch.financial_year = :financialYear "
					+" and sch.audit_id IN (SELECT t.audit_id FROM audit_team t WHERE t.audit_id=sch.audit_id "
							+ " and t.legal_entity_code =sch.legal_entity_code   and t.user_id=:userId  )  ");						
					strQuery.append(" where  "
					+"   auditType.legal_entity_code= :legalEntityCode ");
					if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
					}				
					 
					strQuery.append(" GROUP BY auditType.audit_type_code ");*/
			LocalDate financialYearStartDt = financialYearList.get(0);
			LocalDate financialYearEndDt = financialYearList.get(1);
		 	
			StringBuilder strQuery = new StringBuilder(" SELECT auditType.audit_type_code ,  IFNULL(auditSch.auditCount, 0) "
					+"  FROM maint_audit_type_desc auditType   "
						+"  LEFT JOIN( "
							+"  SELECT  sch.audit_type_code AS auditTypeCode, COUNT(sch.audit_id) AS auditCount  "
							+"  FROM audit_schedule sch  "
							+"  WHERE  "
							+"  sch.legal_entity_code = :legalEntityCode "); 
			strQuery.append("  "					 
					+ " And ( Case when sch.actual_start_date IS NOT NULL "
					+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
					+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
					+ "  ");				
			strQuery.append("  AND sch.audit_id IN (SELECT t.audit_id FROM audit_team t WHERE t.audit_id=sch.audit_id  "
								+"  AND t.legal_entity_code =sch.legal_entity_code   AND t.user_id= :userId  )  "
							+"  AND  (sch.audit_status NOT IN ('AP','AI','AU','AD','AN') "
									+ " OR (sch.audit_status ='AI' and sch.observation_status = 'AE')  "
									+ " OR sch.report_status in ('RD','RS') "
									+ " OR sch.audit_status in ('AC','AS','AW','AR','RI','RS','WI','WS'))   "
							+"  GROUP BY sch.audit_type_code	 "
							+"  ) auditSch	    "
						+"  ON 	auditSch.auditTypeCode =   auditType.audit_type_code			 "	
						+"  WHERE   "
						+"  auditType.legal_entity_code= :legalEntityCode   ");
			
					if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						strQuery.append(" AND auditType.audit_type_code = :auditTypeCode ");
					}
			
			Query qry = session.createNativeQuery(strQuery.toString())
			.setParameter("legalEntityCode", legalEntityCode)
			//.setParameter("financialYear", financialYear, TemporalType.DATE)
			.setParameter("userId", userId);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			} 		
			
			
			Map<String, Integer> deskComplianceRating = new HashMap<String, Integer>();
			List lst=qry.list();
			Iterator itr = lst.iterator();
			while(itr.hasNext()){
				Object[] obj=(Object[])itr.next();
				deskComplianceRating.put(String.valueOf(obj[0]), Integer.valueOf(String.valueOf(obj[1])));			
			}
			return deskComplianceRating;
		}catch (Exception exception) {
			logger.error("Inside Service getMyInspectionWidget :: ", exception);
		}
		return null;
	}
	
	@Override
	public List<AuditReportDynamicTable> getDynamicTableInstances(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
				String zone, String unitId, List<LocalDate>  financialYearList){
		logger.info("Inside Service getDynamicTableInstances .."+legalEntityCode +" userId .."+userId+" role .."+role+"financialYear .."+financialYear 
				+" auditTypeCode .."+auditTypeCode + "zone .."+zone +" unit.."+ unitId);
		Session session=getSession();	
		session.setDefaultReadOnly(true);
		
		try{ 
			 AuditSchedule auditSchedule = getLatestAuditOfInspector(legalEntityCode, userId, financialYear, auditTypeCode, financialYearList);
			 if(auditSchedule==null){
				 return new ArrayList<AuditReportDynamicTable>();
			 }
			 StringBuilder strQuery = new StringBuilder("  "
					+ "  Select dyTab as dtData , sch as auditScheduleData, "					 
					+ " (Select concat(u.userId , '-' , ifnull(u.firstName,''), ' ',ifnull(u.middleName,''),' ',ifnull(u.lastName,'') ) "
							+ " from  User u where u.legalEntityCode =dyTab.legalEntityCode and u.userId=dyTab.maker) as maker, "
					+ " (Select concat(unitCode , '-' , unitName) from  MaintEntity e where e.unitCode = sch.unitId "
							+ " and e.legalEntityCode =sch.legalEntityCode) as unitId  "					
					+ " from   AuditReportDynamicTable  dyTab"
					+ " RIGHT JOIN AuditSchedule sch "
					+ " ON  sch.auditId = dyTab.auditId  "					
					+ " Where sch.auditId = '"+auditSchedule.getAuditId()+"' "
					+ " ORDER BY dyTab.sequence ASC " );
			   					 
			Query qry = session.createQuery(strQuery.toString())
					//.setParameter("legalEntityCode", Integer.parseInt(legalEntityCode))
					//.setParameter("financialYear",  TemporalType.DATE)
					//.setParameter("userId", userId) 
					.setResultTransformer(new ResultTransformer() {				
						@Override
						public Object transformTuple(Object[] tuple, String[] aliases) {
							AuditReportDynamicTable auditReportDynamicTable=null; 
							if(tuple!=null && tuple[1]!=null){
																   
								  if(tuple[0]!=null){
									  auditReportDynamicTable = (AuditReportDynamicTable) tuple[0];
									  auditReportDynamicTable.setMaker(tuple[2].toString());
								  }else {
									  auditReportDynamicTable =  new AuditReportDynamicTable();
								  }
								  
								  auditReportDynamicTable.setAuditId(auditSchedule.getAuditId());
								  if(tuple[3]!=null){
									  auditReportDynamicTable.setUnitId(tuple[3].toString());
									  String unitName = tuple[3].toString();
									  unitName = unitName.substring(unitName.indexOf("-")+1);									  
									  auditReportDynamicTable.setUnitName(unitName);
								  }
							}							
							return auditReportDynamicTable;
						}
						
						@Override
						public List transformList(List collection) {
							return collection;
						}
					}); 
			
			/*if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			} */
			List lst=qry.list();
			 
			return lst; 
		}catch (Exception exception) {
			logger.error("Inside Service getDynamicTableInstances :: ", exception);
		}
		return null;
	}
	
	@Override
	public Map<String, Map<String, String>> getMyBudgetWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId, List<LocalDate>  financialYearList){
		logger.info("Inside Service getMyBudgetWidget .."+legalEntityCode +" userId .."+userId+" role .."+role+"financialYear .."+financialYear 
				+" auditTypeCode .."+auditTypeCode + "zone .."+zone +" unit.."+ unitId);
		Session session=getSession();		
		session.setDefaultReadOnly(true);
		try{		
			LocalDate financialYearStartDt = financialYearList.get(0);
			LocalDate financialYearEndDt = financialYearList.get(1);
			StringBuilder strQuery = new StringBuilder("  "
						+ "  Select userIO, sum(budgeted), sum(submitted) from ( "
						+ "    	(Select 'AIO'  as userIO,  " 
						 		+ " (Select  count(sch1.audit_id) from audit_schedule sch1  "
						 			+ " where sch1.audit_id=sch.audit_id and sch1.audit_status not in ('AD','AU','AN') ) as budgeted, " //and sch1.audit_status='AP' and sch1.observation_status is null and sch1.report_status is null ) as budgeted, "
						 		+ " (Select  count(sch1.audit_id) from audit_schedule sch1  "
						 			+ " where sch1.audit_id=sch.audit_id "
						 			/*+ " and ( (sch1.audit_status in ('AP', 'AI') and sch1.observation_status='AE' and sch1.report_status='RIP') "
						  				+ " OR sch1.report_status in ('RS', 'RD')"
						  				+ " OR sch1.audit_status in ('AS','AR','AW','AC','RI','RS','WI','WS') )"*/
						 			+"  AND  (sch.audit_status NOT IN ('AP','AI','AU','AD','AN') "
									+ " OR (sch.audit_status ='AI' and sch.observation_status = 'AE')  "
									+ " OR sch.report_status in ('RD','RS') "
									+ " OR sch.audit_status in ('AC','AS','AW','AR','RI','RS','WI','WS'))   "
						  			+ "    ) as submitted  "                             
							  + " from audit_schedule sch inner join  "
							  + " audit_team t on t.legal_entity_code=sch.legal_entity_code AND t.audit_id=sch.audit_id AND t.user_type='M'  and t.user_id=:userId "
							  + " Where sch.legal_entity_code = :legalEntityCode ");
					strQuery.append("  "					 
							+ " AND ( Case when sch.actual_start_date IS NOT NULL "
							+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
							+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
							+ "  ");
								if(!BankAuditUtil.isEmptyString(auditTypeCode)){
									strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
								}				
								 
								strQuery.append( " )");
							strQuery.append(" UNION ALL "							 
							  + " (Select 'PIO'  as userIO,  "
								  + " (Select  count(sch1.audit_id) from audit_schedule sch1  "
								  	  + " where sch1.audit_id=sch.audit_id and sch1.audit_status not in ('AD','AU','AN') ) as budgeted, " //and sch1.audit_status='AP' and sch1.observation_status is null and sch1.report_status is null ) as budgeted, "
								  + " (Select  count(sch1.audit_id) from audit_schedule sch1  "
									  + " where sch1.audit_id=sch.audit_id "
									  /*+ " and ( (sch1.audit_status in ('AP', 'AI') and sch1.observation_status='AE' and sch1.report_status='RIP') "
								  		+ " OR sch1.report_status in ('RS', 'RD') "
								  		+ " OR sch1.audit_status in ('AS','AR','AW','AC','RI','RS','WI','WS') )"*/
									  +"  AND  (sch.audit_status NOT IN ('AP','AI','AU','AD','AN') "
										+ " OR (sch.audit_status ='AI' and sch.observation_status = 'AE')  "
										+ " OR sch.report_status in ('RD','RS') "
										+ " OR sch.audit_status in ('AC','AS','AW','AR','RI','RS','WI','WS'))   "
								  	+ "    ) as submitted  "                             
							  + " from audit_schedule sch inner join  "
							  + " audit_team t on  "
							  + " t.legal_entity_code=sch.legal_entity_code AND t.audit_id=sch.audit_id AND t.user_type='L' and t.user_id=:userId "
							  + " Where sch.legal_entity_code = :legalEntityCode ");					
							strQuery.append("  "					 
									+ " AND ( Case when sch.actual_start_date IS NOT NULL "
									+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
									+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
									+ "  ");
								if(!BankAuditUtil.isEmptyString(auditTypeCode)){
									strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
								}				
								 
								strQuery.append( " )");
							strQuery.append( " ) as tmp  group by userIO  "	);					  
						 
				Query qry = session.createNativeQuery(strQuery.toString())
						.setParameter("legalEntityCode",  legalEntityCode)
						//.setParameter("financialYear", financialYear, TemporalType.DATE)
						.setParameter("userId", userId);
				
				if(!BankAuditUtil.isEmptyString(auditTypeCode)){
					qry.setParameter("auditTypeCode", auditTypeCode);
				}
				 		
				 
				List<Object[]> lst=qry.list();				 
				Map<String, Map<String, String>> myBudet = new HashMap<String, Map<String, String>>();
				for (Object[] objects : lst) {
					Object[] object = objects;
					Map<String, String> io = new HashMap<String, String>();
					io.put("Budgeted", String.valueOf(object[1]));
					io.put("Completed", String.valueOf(object[2]));
					myBudet.put(String.valueOf(object[0]), io);
				}
				
				if(!myBudet.isEmpty() || myBudet.size()==0){
					if(!myBudet.containsKey("PIO")){
						Map<String, String> io = new HashMap<String, String>();
						io.put("Budgeted", "0");
						io.put("Completed", "0");
						myBudet.put("PIO", io);
					}
					if(!myBudet.containsKey("AIO")){
						Map<String, String> io = new HashMap<String, String>();
						io.put("Budgeted", "0");
						io.put("Completed", "0");
						myBudet.put("AIO", io);
					}
				}
				
				return myBudet;
			
		}catch (Exception exception) {
			logger.error("Inside Service getMyBudgetWidget :: ", exception);
		}
		
		return null;
	}
	
	@Override
	public Map<String, String> getTopBandWidget(Integer legalEntityCode,  LocalDate financialYear,  String auditTypeCode, String unitId, List<LocalDate> financialYearList){
		
		logger.info("Inside Service getTopBandWidget .."+legalEntityCode  +"financialYear .."+financialYear 
				+" auditTypeCode .."+auditTypeCode +  " unit.."+ unitId);
		Session session=getSession();	
		session.setDefaultReadOnly(true); 
		try{
			LocalDate financialYearStartDt = financialYearList.get(0);
			LocalDate financialYearEndDt = financialYearList.get(1);
			StringBuilder strQuery = new StringBuilder(" Select ifnull(sum(budgeted),0) as budgetedCount,"
					+ " ifnull(sum(initiated),0) as initiatedCount, "
					+ " ifnull(sum(finalised),0) as finalisedCount, "
					+ " ifnull(sum(dispatched),0) as dispatchedCount,"
					+ " ifnull(sum(planned),0) as plannedCount, "
					+ " ifnull(sum(exited),0) as exitedCount, "
					+ " ifnull(sum(reviewReady),0) as reviewReadyCount,"
					+ " ifnull(sum(completed),0) as completedCount "
					+ " from  "
						+" 	(Select   "
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1 "
								+" 	where sch1.audit_id=sch.audit_id and sch1.audit_status not in ('AD','AU','AN') ) as budgeted, "
								 
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1 "
								+" 	where sch1.audit_id=sch.audit_id and sch1.audit_status='AI' and sch1.observation_status is null ) as initiated, "						 							
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1 "
								+" 	where sch1.audit_id=sch.audit_id and sch1.report_status='RS') as finalised, "							
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1 "
								+" 	where sch1.audit_id=sch.audit_id and sch1.report_status='RD') as dispatched, " 							
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1  where sch1.audit_id=sch.audit_id and sch1.audit_status='AP') as planned, "				
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1  where sch1.audit_id=sch.audit_id and sch1.audit_status='AI' "
								+"  and sch1.observation_status='AE' and sch1.report_status='RIP' ) as exited, "								
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1  where sch1.audit_id=sch.audit_id and sch1.audit_status='AI' "
								+"  and sch1.observation_status='AE' and sch1.report_status in ('RRR', 'FI', 'FS','RA','RR','RI','RAR','RC') ) as reviewReady, "
								+" 	(Select  count(sch1.audit_id) from audit_schedule sch1 "
								+" 	where sch1.audit_id=sch.audit_id and sch1.observation_status = 'AS' ) as completed "
								+ "  "		
					+" 	from audit_schedule sch where ");		
					
					strQuery.append("  "
							//+ " ( Case when sch.financial_year IS NOT NULL THEN  sch.financial_year = '"+financialYear+"' "
							+ " ( Case when sch.actual_start_date IS NOT NULL "
							+ " 		THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
							+ " 		ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
							+ "  ");		
					
					strQuery.append(" and sch.legal_entity_code= :legalEntityCode ");
								
					if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
					}	
					
					if(!BankAuditUtil.isEmptyString(unitId)){
						strQuery.append(" and sch.unit_id in ("+unitId+") ");
					} 
					
					strQuery.append("   ) Tmp  ");
			
			Query qry = session.createNativeQuery(strQuery.toString())	 
					//.setParameter("financialYear", financialYear, TemporalType.DATE)
					.setParameter("legalEntityCode", legalEntityCode);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}		
			
			Map<String, String> budgetProgess = new HashMap<String, String>();
			List recordSet=qry.list();
			if(!recordSet.isEmpty() && recordSet.size()>0){
				Object[] tuple = (Object[]) recordSet.get(0); 
				budgetProgess.put("budgeted", String.valueOf(tuple[0]));
				budgetProgess.put("initiated", String.valueOf(tuple[1])); 
				budgetProgess.put("finalisedCount", String.valueOf(tuple[2]));	
				budgetProgess.put("dispatchedCount", String.valueOf(tuple[3])); 		
				budgetProgess.put("plannedCount", String.valueOf(tuple[4]));	
				budgetProgess.put("exitedCount", String.valueOf(tuple[5]));
				budgetProgess.put("reviewReadyCount", String.valueOf(tuple[6]));
				budgetProgess.put("completedCount", String.valueOf(tuple[7]));
				budgetProgess.put("target", getTargetUnitCount(legalEntityCode, financialYear, auditTypeCode, unitId, financialYearList)+"");
			} 
			return budgetProgess;
		}catch (Exception exception) {
			logger.error("Inside Service getTopBandWidget :: ", exception);
		}
		return null;		
	}
		
	@Override
	public DataTableResponse getMyAuditSchedules(Integer legalEntityCode, String userId, String search, Integer orderColumn,
			String orderDirection, Integer page, Integer size,  String role) {
				 
		Session session=getSession();		
		session.setDefaultReadOnly(true);
		DataTableResponse dataTableResponse = new DataTableResponse();		
		try{
			/********************** 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 ********************************/
		
			List<String> rolesListInspector = Arrays.asList(("G2,G8,G12").split(","));  //Inspection
			List<String> rolesListCompliance = Arrays.asList(("G3,G31").split(","));	//Compliance or Response or bank user
			List<String> rolesListReviewer = Arrays.asList(("G4,G7").split(","));       //review/Scrutiny		
			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 t.userId from  AuditTeam t where t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
					
					+ " (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 AND e.classification=p.classification) as duration, "
					+ " (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  AND e.classification=p.classification  ) 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 , '-' , 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'  ) as complianceCount, "
					+ " (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='NA' ) as notApplicableCount, "
					 
					+ " (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  r.riskCategoryDesc from  RiskScorePercentage r where r.legalEntityCode =sch.legalEntityCode and sch.auditTypeCode=r.auditTypeCode and sch.assessedRating=r.riskCategoryCode) as assessedRating, " // Code with out description
					+ " (select group_concat(t.userId) from AuditTeam t where t.legalEntityCode=sch.legalEntityCode AND t.auditId=sch.auditId AND t.userType='M' ) AS teamMember,"
					+ " (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='N' ) as nonComplianceCount," //19
					 
					+ " (select concat(u.userId , '-' , u.firstName, ' ',ifnull(u.middleName,''),' ',ifnull(u.lastName,''))  from User u Inner join MaintEntity me on  u.userId=me.unitHeadUser "
							+ " and u.legalEntityCode=me.legalEntityCode where me.unitCode =sch.unitId and me.legalEntityCode =sch.legalEntityCode ) as unitHeadUser   "
					
					+ " from AuditSchedule sch where legalEntityCode =:legalEntityCode  ");
					
					if(rolesListInspector.contains(role)){
						queryString.append(" and   IFNULL(auditStatus,'NotNull') in ('AP','AI','AS','AR','AW','AC') "
								+ " and sch.auditId IN (SELECT t.auditId FROM AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userId=:userId  ) "
								+ " ORDER BY sch.actualStartDate asc, FIELD(sch.auditStatus, 'AI','AP','AS','AR','AW','AC') asc  ");
					}else if(rolesListCompliance.contains(role)){
						queryString.append(" and   IFNULL(sch.auditStatus,'NotNull') in ('AS','AR','AW','AC','AF') "
								+ " and sch.reportStatus='RD'  and sch.unitId IN (SELECT u.unitCode FROM User u WHERE u.unitCode=sch.unitId and  u.legalEntityCode =sch.legalEntityCode and u.userId=:userId  ) "
								+ " ORDER BY  FIELD(sch.auditStatus, 'AI','AS','AR','AW','AC','AF') asc ");
					}else if(rolesListReviewer.contains(role)){
						List<String> unitsList = maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode, "user", userId);  				  
						String unitsListToConcatinatedString="";	
						if(unitsList!=null &&!unitsList.isEmpty()){				 
						 unitsListToConcatinatedString =  String.join("','",unitsList); 
						}
						unitsListToConcatinatedString = "'"+unitsListToConcatinatedString+"'";
						queryString.append(" and (sch.unitId in ("+unitsListToConcatinatedString+") or sch.reportReviewer =:userId) "
								+ " and IFNULL(sch.auditStatus,'NotNull') in ('AS','AR','AW','AC','AF')"
								+ " and sch.respondStatus='RS' and  sch.respondedDate IS NOT NULL  ORDER BY respondedDate DESC   ");
					}
					
 			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.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");
									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[19]!=null){
									auditSchedule.setNonComplianceCount(Integer.parseInt(tuple[19].toString()));
								}else auditSchedule.setNonComplianceCount(0);
								
								if(tuple[20]!=null){
									auditSchedule.setUnitHead(tuple[20].toString());
								}
								
								if(tuple[16]!=null){
									auditSchedule.setEarlyStartAllowed(tuple[16].toString());
								}else auditSchedule.setEarlyStartAllowed("Y");
								
								if(tuple[17]!=null){
									auditSchedule.setAssessedRating(tuple[17].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());*/
								
								if(tuple[18]!=null){
									String teamMembers="";
									String[] members = tuple[18].toString().split(",");
									for (String member: members) {
										teamMembers+=member+"-"+userDtls.get(member)+",";
									}
									auditSchedule.setTeamMember(teamMembers.substring(0,teamMembers.length()-1));
								}
								
								/*if(auditSchedule.getUnitHead() != null) {
									auditSchedule.setUnitHead(auditSchedule.getUnitHead()+"-"+userDtls.get(auditSchedule.getUnitHead()));
								}*/
								
								System.out.println("Unit Head ...."+auditSchedule.getUnitHead());
							}
							return auditSchedule;
						}
						@Override
						public List transformList(List collection) {
							return collection;
						}
					})
 					.setParameter("legalEntityCode", legalEntityCode)
 					.setParameter("userId", userId);
 			/*if(rolesListReviewer.contains(role)){
 				List<String> unitsList = maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode, "user", userId);  				  
				String unitsListToConcatinatedString="";	
				if(unitsList!=null &&!unitsList.isEmpty()){				 
				 unitsListToConcatinatedString =  String.join("','",unitsList); 
				}
 				query.setParameter("units", "'"+unitsListToConcatinatedString+"'");
			}*/
			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);
	 
			
			dataTableResponse.setData(auditSchedule);
			dataTableResponse.setRecordsTotal(totalRecords);
			dataTableResponse.setRecordsFiltered(totalRecords);
			
		}catch(Exception exception) {
			logger.error("Inside Service getMyAuditSchedules :: ", exception);
		}
 		return dataTableResponse;
	 
	}
	
	@Override
	public List<DashboardDto> getNonComplianceItemWidgetYearWise(Integer legalEntityCode, String userId,  String role, LocalDate financialYear,
			String unitId, List<LocalDate>  financialYearList){
		Session session=getSession();		
		session.setDefaultReadOnly(true);
		List<DashboardDto> nonComplianceList = new ArrayList<>();
		try{
			List<String> rolesListInspector = Arrays.asList(("G2,G8,G12").split(","));  //Inspection
			List<String> rolesListCompliance = Arrays.asList(("G3,G31").split(","));	//Compliance or Response or bank user
			List<String> rolesListReviewer = Arrays.asList(("G4,G7").split(","));       //review/Scrutiny	
			
			//to get the for last three year
			LocalDate financialYearStartDt = financialYearList.get(0).minusYears(3);
			LocalDate financialYearEndDt = financialYearList.get(1); 
			
			/*List<LocalDate> financialYearList =  new ArrayList<>();
			financialYearList.add(financialYear);
			for(int year=1; year<=3 ; year++){
				financialYearList.add(financialYear.minusYears(year));
			}*/			 			 
			
			StringBuilder queryString=new StringBuilder(" SELECT COUNT(obs.compliance_category), sch.financial_year, grp.audit_group_name	"	
					+" 	FROM activity_process_finding_mapping a 	"
					+" 	INNER JOIN audit_observation obs ON obs.mapping_id = a.mapping_id 	AND obs.legal_entity_code=a.legal_entity_code 	"
					+" 		AND obs.compliance_category = :complianceCategory 	"
					+" 	INNER JOIN audit_schedule sch ON sch.audit_id=obs.audit_id	AND obs.legal_entity_code=sch.legal_entity_code 						"	
					+" 	INNER JOIN maint_audit_group grp ON  grp.audit_group_code = a.audit_group_code AND grp.legal_entity_code=sch.legal_entity_code 		 "
					+" 	WHERE sch.legal_entity_code = :legalEntityCode	"
					//+" 	AND financial_year IN (:financialYearList)  "
					
					+ "	");
			queryString.append(" AND ( Case when sch.actual_start_date IS NOT NULL "
					+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
					+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
					+ "  ");	
					if(rolesListCompliance.contains(role)){
						queryString.append(" AND sch.unit_id IN (SELECT u.unit_code FROM user u WHERE   	"
								+" 	 u.legal_entity_code =sch.legal_entity_code AND u.user_id = :userId )  ");
					}
					else if(rolesListInspector.contains(role)){
						queryString.append(" AND sch.audit_id IN (SELECT t.audit_id FROM AuditTeam t WHERE  "
								+ "  t.legal_entity_code =sch.legal_entity_code AND t.user_id=:userId  ) ");
					}
					queryString.append(" 	GROUP BY sch.financial_year, grp.audit_group_name	") ;
			
					Query query=(Query) session.createNativeQuery(queryString.toString())
							.setParameter("complianceCategory", BankAuditConstant.COMPLIANCE_NO)
							//.setParameterList("financialYearList", financialYearList)
							.setParameter("legalEntityCode", legalEntityCode);
							if(rolesListCompliance.contains(role)){
								query.setParameter("userId", userId);
							}
							query.setResultTransformer(new ResultTransformer() {									
									@Override
			 						public Object transformTuple(Object[] tuple, String[] aliases) {
										DashboardDto dashboardDto=new DashboardDto(); 
										if(tuple[0]!=null){
											dashboardDto.setNonComplianceCount(Integer.parseInt(tuple[0].toString()));
										
											if(tuple[1]!=null){
												dashboardDto.setFinancialYear(tuple[1].toString());
											}
											if(tuple[2]!=null){
												dashboardDto.setChapterName(tuple[2].toString());
											}
										}
										return dashboardDto;
									}
									
									@Override
									public List transformList(List collection) {
										return collection;
									}
								});
					
				nonComplianceList = query.list();
				
				Map<String, List<DashboardDto>> nonComplianceMap = 
						nonComplianceList.stream().collect(Collectors.groupingBy(DashboardDto::getChapterName));
				 			 
				nonComplianceList  = new ArrayList<>();				
				for(Entry<String, List<DashboardDto>> dataList : nonComplianceMap.entrySet()){
					List<DashboardDto> nonComplianceListByChapter = dataList.getValue();					
					
					DashboardDto dashboardDtoData =  new DashboardDto();	
					
					dashboardDtoData.setChapterName(dataList.getKey());						 				
					dashboardDtoData.setFinancialYear((financialYearEndDt.getYear())+"");
					dashboardDtoData.setFinancialYearPrev1((financialYearEndDt.getYear()-1)+""); 
					dashboardDtoData.setFinancialYearPrev2((financialYearEndDt.getYear()-2)+""); 
					dashboardDtoData.setFinancialYearPrev3((financialYearEndDt.getYear()-3)+""); 
					
					for (DashboardDto dashboardDto : nonComplianceListByChapter) {	
						if(dashboardDtoData.getFinancialYear().equals(dashboardDto.getFinancialYear())){ 
							dashboardDtoData.setNonComplianceCount(dashboardDto.getNonComplianceCount());
						}else if(dashboardDtoData.getFinancialYearPrev1().equals(dashboardDto.getFinancialYear())){ 
							dashboardDtoData.setNonComplianceCountPrev1(dashboardDto.getNonComplianceCount());
						}else if(dashboardDtoData.getFinancialYearPrev2().equals(dashboardDto.getFinancialYear())){ 
							dashboardDtoData.setNonComplianceCountPrev2(dashboardDto.getNonComplianceCount());
						}else if(dashboardDtoData.getFinancialYearPrev3().equals(dashboardDto.getFinancialYear())){ 
							dashboardDtoData.setNonComplianceCountPrev3(dashboardDto.getNonComplianceCount());
						}  
					}
					
					nonComplianceList.add(dashboardDtoData);
				}
					
		}catch (Exception exception) {
			logger.error("Inside Service getNonComplianceItemWidget :: ", exception);
		}
		return nonComplianceList;
	}
	 
	@Override
	public List<DashboardDto> getComplianceSubmittedWidgetYearWise(Integer legalEntityCode, String userId,  String role, LocalDate financialYear,
			String unitId, List<LocalDate>  financialYearList){
		
		logger.info("Inside Service getComplianceStatusWidgetYearWise .."+legalEntityCode +" userId .."+userId+" role .."+role+"financialYear .."+financialYear 
				+" unit.."+ unitId);
		Session session=getSession();		
		session.setDefaultReadOnly(true);
				 
		List<DashboardDto> listDashboardDto = new ArrayList<>();
		try{
			/*StringBuilder queryString = new StringBuilder("select  financial_year, "
					 + " responded_date as complianceSubmittedDate, "
					 + " DATE_ADD(ifnull(sch.actual_end_date, sch.schedule_end_date), INTERVAL 20 DAY ) as dueOn," 
					 + " CASE WHEN responded_date IS NULL THEN NULL "
					 		+ " ELSE DATEDIFF(responded_date, DATE_ADD(IFNULL(actual_end_date, schedule_end_date), INTERVAL 20 DAY )) "
					 		+ " END  AS delay "
					 + " from  audit_schedule sch   "
					 + " WHERE sch.legal_entity_code = :legalEntityCode	"
					 + " AND financial_year IN (:financialYear) 	 ");*/				
					 
			LocalDate financialYearStartDt = financialYearList.get(0);
			LocalDate financialYearEndDt = financialYearList.get(1);
		 	 
			StringBuilder queryString = new StringBuilder("select  financial_year, "
					 + " responded_date as complianceSubmittedDate, "
					 + " CASE WHEN report_dispatch_date IS  NOT NULL  "
					// + " 	    AND report_status='RD'  AND (respond_status IS NULL OR respond_status!='RS') "
					 + "      THEN DATE_ADD(report_dispatch_date, INTERVAL 60 DAY ) "
					 + "      ELSE '' END as dueOn  ," 				 
					 // disatch date + 60 < current date ==> due
					 // submittted/respond date  dated - due ==> delay
					 + " CASE WHEN responded_date IS NULL  or report_dispatch_date IS NULL THEN null "
					 		+ " ELSE DATEDIFF(responded_date, DATE_ADD(report_dispatch_date, INTERVAL 60 DAY ) ) "
					 		+ " END  AS delay,"
					 + " audit_id"
					 + " from  audit_schedule sch   "
					 + " WHERE sch.legal_entity_code = :legalEntityCode	"
					// + " AND financial_year IN (:financialYear) "
					 + " AND  report_dispatch_date IS  NOT NULL "
					 + "	 ");
					  queryString.append(" AND sch.unit_id IN (SELECT u.unit_code FROM user u WHERE   	"
								+" 	 u.legal_entity_code =sch.legal_entity_code AND u.user_id = :userId )  ");
					  queryString.append("  "					 
								+ " AND ( Case when sch.actual_start_date IS NOT NULL "
								+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
								+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
								+ "  ");	
								  
			Query query = session.createNativeQuery(queryString.toString())
						.setParameter("legalEntityCode", legalEntityCode)
						//.setParameter("financialYear", financialYear, TemporalType.DATE)
						.setParameter("userId", userId);
			
			query.setResultTransformer(new ResultTransformer() {									
				@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						DashboardDto dashboardDto=new DashboardDto(); 
						if(tuple[0]!=null){ 					 
							dashboardDto.setFinancialYear(tuple[0].toString());
						} 
						if(tuple[1]!=null){
							dashboardDto.setComplianceSubmittedOn(tuple[1].toString());
						}
						if(tuple[2]!=null){
							dashboardDto.setDueOn(tuple[2].toString());
						}
						if(tuple[3]!=null){
							dashboardDto.setDelay(Integer.parseInt(tuple[3].toString()));
						}else{
							dashboardDto.setDelay(0);
						}
						if(tuple[4]!=null){
							dashboardDto.setAuditId(tuple[4].toString());
						}
						
						return dashboardDto; 
				}
				
				@Override
				public List transformList(List collection) {
					return collection;
				}
			});
			  
			listDashboardDto = query.list();
			
		}catch (Exception exception) {
			logger.error("Inside Service getComplianceSubmittedWidgetYearWise :: ", exception);
		}
		
		return listDashboardDto;
	}
	
	@Override
	public List<DashboardDto> getPlanCalendarWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId, List<String> unitIdlist) {
		
		logger.info("Inside Service getPlanCalendarWidget .. .."+legalEntityCode +" userId .."+userId+" role .."+role+"financialYear .."+financialYear 
				+" auditTypeCode .."+auditTypeCode + "zone .."+zone +" unit.."+ unitId);
		logger.info("unitIdlist .. "+unitIdlist);
		Session session=getSession();		
		session.setDefaultReadOnly(true);
		//financialYear = financialYear.plusYears(1);
		List<DashboardDto> listDashboardDto = new ArrayList<>();
		try{
			
				/* StringBuilder strQry = new StringBuilder("   "
					+ " SELECT "
						+ " (SELECT CONCAT(atd.audit_type_code,'-',atd.audit_type_desc) FROM maint_audit_type_desc AS atd "
							+"  WHERE matd.audit_type_code=atd.audit_type_code AND matd.legal_entity_code=atd.legal_entity_code "
							+"  ) AS auditType, "
						//+ " (SELECT GROUP_CONCAT(IFNULL(ap1.planner_unit_code,'NoUnitFound') SEPARATOR ':##:') "
						//	+ " FROM audit_plan AS ap1 WHERE ap1.plan_end_date=MAX(ap.plan_end_date)) , "
						+ " (SELECT DISTINCT GROUP_CONCAT(CONCAT(e.unit_code , '-' , e.unit_name)) FROM maint_entity e	 "					 
						+ " 	WHERE e.unit_code IN (SELECT GROUP_CONCAT(IFNULL(ap1.planner_unit_code,''))  "
						+ " 			FROM audit_plan AS ap1 WHERE ap1.plan_end_date=MAX(ap.plan_end_date))) , "
						+ " DATE_ADD(MAX(plan_end_date),INTERVAL 1 DAY ) AS nextPlanStartDate, "
						+ "  DATEDIFF(DATE_ADD(MAX(plan_end_date),INTERVAL 1 DAY ), "
							+"  (SELECT bd.business_date FROM business_date AS bd WHERE bd.legal_entity_code=ap.legal_entity_code ) ) AS remainingDays   "			
					+ "  FROM maint_audit_type_desc AS matd  "
					+ "  LEFT OUTER JOIN  audit_plan AS ap "
					+ "  ON  matd.legal_entity_code=ap.legal_entity_code  "
					+ "  AND ap.plan_start_date >=:financialYear "
					+ "  AND matd.audit_type_code=ap.audit_type_code  ");
			 
					strQry.append(" AND ap.planner_unit_code in (:unitId) ");
					/*if(!BankAuditUtil.isEmptyString(unitId) || !BankAuditUtil.isEmptyString(zone)){
						strQry.append(" AND ap.planner_unit_code in (:unitId) ");
					}* /
					strQry.append("  WHERE matd.legal_entity_code =:legalEntityCode "
					+"  GROUP BY matd.audit_type_code   "); * /
			Query qry = session.createNativeQuery(strQry.toString())  // to show the Audits which are earliest to be planned. 
			.setParameter("legalEntityCode",legalEntityCode)
			.setParameter("financialYear", financialYear, TemporalType.DATE);
			qry.setParameterList("unitId", unitIdlist); 
			/ *if(!BankAuditUtil.isEmptyString(unitId) || !BankAuditUtil.isEmptyString(zone)){
				//List<String> unitIdlist = getUnitCodeList(legalEntityCode, unitId, zone);
				qry.setParameterList("unitId", unitIdlist); 
			}*/	
			
			StringBuilder strQry = new StringBuilder(" SELECT CONCAT(audit_type_code,'-',audit_type_desc) AS audit_name,  "
					+ "  CONCAT(unit_code,'-',unit_name) AS unit_name ,"
					+ "	 DATE_ADD(plan_end_date,INTERVAL 1 DAY ) AS nextPlanStartDate, "
					+ "  DATEDIFF(DATE_ADD(plan_end_date,INTERVAL 1 DAY ),(SELECT bd.business_date FROM business_date AS bd  "
					+ "			WHERE bd.legal_entity_code=legal_entity_code ) ) AS remainingDays  "
					+ "	FROM ( "
					+ " 	SELECT e.unit_code, e.unit_name, e.level_code, p.planner_unit_code,t.audit_type_code,t.audit_type_desc,p.plan_end_date,e.legal_entity_code  "
					+ "		FROM maint_entity e "
					+ " 	LEFT JOIN maint_audit_type_desc t ON e.legal_entity_code=t.legal_entity_code "
					+ " 	LEFT JOIN (SELECT * FROM audit_plan ap WHERE (planner_unit_code,audit_type_code,plan_end_date,legal_entity_code) IN ("
					+ " 			SELECT planner_unit_code,audit_type_code, MAX(plan_end_date),legal_entity_code	"
					+ " 				FROM audit_plan p GROUP BY p.planner_unit_code,audit_type_code,legal_entity_code)) p "
					+ "				ON e.unit_code=p.planner_unit_code AND p.audit_type_code=t.audit_type_code AND e.legal_entity_code=p.legal_entity_code "
					+ " 	JOIN (SELECT DISTINCT parent_unit_code,audit_type_code,e.legal_entity_code FROM maint_entity_audit_subgroup_mapping m, maint_entity e "
					+ " 			WHERE e.legal_entity_code=m.legal_entity_code AND m.id=e.unit_code AND m.mapping_type='E') m "
					+ " 		ON m.parent_unit_code=e.unit_code  AND m.parent_unit_code=p.planner_unit_code AND p.audit_type_code=m.audit_type_code "
					+ " 		AND e.legal_entity_code=m.legal_entity_code	"
					+ "  	WHERE e.legal_entity_code =:legalEntityCode   "
					+ "	 	AND p.planner_unit_code in (:unitLst) "
					+ "	) c ");
			
			Query qry = session.createNativeQuery(strQry.toString())  // to show the Audits which are earliest to be planned. 
					.setParameter("legalEntityCode",legalEntityCode).setParameter("unitLst",unitIdlist);
			
			qry.setResultTransformer(new ResultTransformer() {
				
				@Override
				public Object transformTuple(Object[] tuple, String[] aliases) {
					DashboardDto dashboardDto=null;
					if(tuple!=null){
						dashboardDto=new DashboardDto();
						
						if(tuple[0]!=null){
							dashboardDto.setAuditType(tuple[0].toString());
						}
						if(tuple[2]!=null){
							dashboardDto.setNextPlanStartDate((Date)tuple[2]);
							if(tuple[1]!=null){
								String unitNameList = tuple[1].toString();			 
								dashboardDto.setUnitNameList(unitNameList);
							}
						}
						if(tuple[3]!=null){
							dashboardDto.setRemainingDays(Integer.parseInt(tuple[3].toString()));
						}						
					}					
					return dashboardDto;
				}
				
				@Override
				public List transformList(List collection) {
					return collection;
				}
			});
			listDashboardDto = qry.list();
		}catch (Exception exception) {
			logger.error("Inside Service getPlanCalendarWidget :: ", exception);
			System.out.println(exception);
		}
		return listDashboardDto;
	}	
	
	@Override
	public List<DashboardDto> getScrutinyStatusWidget(Integer legalEntityCode, String userId,  String role, LocalDate financialYear,
			String unitId, List<LocalDate>  financialYearList){
		
		logger.info("Inside Service getScrutinyStatusWidget .."+legalEntityCode +" userId .."+userId+" role .."+role+"financialYear .."+financialYear 
				+" unit.."+ unitId);
		Session session=getSession();		
		session.setDefaultReadOnly(true);
         
		List<DashboardDto> listDashboardDto = new ArrayList<>();
		
		//Get Unit List
		List<String> unitsList = maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode, "user", userId);  				  
		String unitsListToConcatinatedString="";	
		if(unitsList!=null &&!unitsList.isEmpty()){				 
			unitsListToConcatinatedString =  String.join("','",unitsList); 
		}
		
		try{
			StringBuilder queryString = new StringBuilder(" SELECT  "
						 + " (SELECT CONCAT(unitCode , '-' , unitName) FROM  MaintEntity e WHERE e.unitCode = sch.unitId  "
						 + " 		 AND e.legalEntityCode = sch.legalEntityCode) AS unitId,  "
						 + " (SELECT COUNT(observationId) FROM AuditObservation obs WHERE obs.legalEntityCode = sch.legalEntityCode  "
						 		+" AND obs.auditId=sch.auditId AND complianceCategory='N') AS nonCompliance, "
						 + " (SELECT COUNT(observationId) FROM AuditObservation obs WHERE  obs.legalEntityCode = sch.legalEntityCode  "
						 		+" AND obs.auditId=sch.auditId AND reviewStatusAttribute='FC') AS furtherCompliance, "
						 + " (SELECT COUNT(observationId) FROM AuditObservation obs WHERE  obs.legalEntityCode = sch.legalEntityCode  "
						 		+" AND obs.auditId=sch.auditId AND reviewStatusAttribute='A') AS accepted, "
						 + " (SELECT COUNT(observationId) FROM AuditObservation obs WHERE  obs.legalEntityCode = sch.legalEntityCode  "
						 		+" AND obs.auditId=sch.auditId AND reviewStatusAttribute='R') AS reviewed, "
				 		 + " (SELECT COUNT(observationId) FROM AuditObservation obs WHERE  obs.legalEntityCode = sch.legalEntityCode  "
					 			+" AND obs.auditId=sch.auditId) AS observationCount,"
					 	 + " (select concat(at.auditTypeCode , '-' , at.auditTypeDesc) from MaintAuditTypeDesc at where at.auditTypeCode=sch.auditTypeCode "
					 	 		+ " and at.legalEntityCode= sch.legalEntityCode ) as auditTypeCode, "
						 + " sch as auditSchedule  "
						 + " FROM  AuditSchedule sch "
						 + " Where sch.respondedDate IS NOT NULL "
						 + " AND sch.legalEntityCode = :legalEntityCode "
						 + " AND (sch.unitId in ('"+unitsListToConcatinatedString+"') or sch.reportReviewer =:userId) "
						// + " AND sch.financialYear= '"+financialYear.getYear()+"-03-31"+"' "
						 + " ORDER BY  sch.respondedDate DESC ");					 
			 
			Query query = session.createQuery(queryString.toString())
						.setParameter("legalEntityCode",  legalEntityCode) 
						.setParameter("userId", userId) ;
						//.setParameter("units", "'"+unitsListToConcatinatedString+"'");
			
			query.setResultTransformer(new ResultTransformer() {									
				@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						DashboardDto dashboardDto = null; 
						if(tuple[7]!=null){ 					 
							dashboardDto=new DashboardDto(); 
							AuditSchedule auditSchedule =  (AuditSchedule)tuple[7];	
							dashboardDto.setAuditId(auditSchedule.getAuditId());
							dashboardDto.setAuditType(auditSchedule.getAuditTypeCode());
							dashboardDto.setFinancialYear(auditSchedule.getFinancialYear()+""); 
							if(tuple[0]!=null){
								dashboardDto.setUnitNameList(tuple[0].toString());
							}
							if(tuple[1]!=null){
								dashboardDto.setNonComplianceCount(Integer.parseInt(tuple[1].toString()));
							}
							if(tuple[2]!=null){
								dashboardDto.setFurtherComplianceCount(Integer.parseInt(tuple[2].toString()));
							}
							if(tuple[3]!=null){
								dashboardDto.setResponseAcceptCount(Integer.parseInt(tuple[3].toString()));
							}
							if(tuple[4]!=null){
								dashboardDto.setResponseReviewedCount(Integer.parseInt(tuple[4].toString()));
							}
							if(tuple[5]!=null){
								dashboardDto.setObservationCount(Integer.parseInt(tuple[5].toString()));
							}
							if(tuple[6]!=null){
								dashboardDto.setAuditType(tuple[6].toString());
							}
							
						} 				
						return dashboardDto; 
					}
				
				@Override
				public List transformList(List collection) {
					return collection;
				}
			});
			  
			listDashboardDto = query.setMaxResults(5).list();
			//listDashboardDto = query.list();
		}catch (Exception exception) {
			logger.error("Inside Service getScrutinyStatusWidget :: ", exception);
		}
		
		return listDashboardDto;
	}
	
	/*private int getInspectionCountWithoutCSV(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId){
		Session session=getSession();		
		session.setDefaultReadOnly(true);
		try{
			 
			StringBuilder strQuery = new StringBuilder("  Select count(sch.audit_id)  "
					+" from  audit_schedule sch "
					+" where sch.audit_id not in ( select doc.audit_id from audit_level_document_details doc "
							+ " where doc.document_type = :docType ) "  
					+" and sch.financial_year = :financialYear  "			  
					+" and sch.legal_entity_code= :legalEntityCode ");
					if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
					}	 
					 
			Query qry = session.createNativeQuery(strQuery.toString())
					.setParameter("legalEntityCode",  legalEntityCode)
					.setParameter("financialYear", financialYear , TemporalType.DATE)
					.setParameter("docType", BankAuditConstant.DOCUMENT_TYPE_IR_PART_AB);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}
			 
			 
			int count = ((BigInteger) qry.uniqueResult()).intValue();		 
				return count;  
			 
			
		}catch (Exception exception) {
			logger.error("Inside method getInspectionCountWithoutCSV", exception);
		}
		return 0;
	}*/
	
	@Override
	public Integer getWatchListForAudits(Integer legalEntityCode,  LocalDate financialYear,  String auditTypeCode,  String unitId) {	
		
		logger.info("Inside Service getWatchListForAudits .."+legalEntityCode  +"financialYear .."+financialYear 
				+" auditTypeCode .."+auditTypeCode +  " unit.."+ unitId);
		
		Session session=getSession();
		session.setDefaultReadOnly(true);
		int watchList=0; 
		
		List<AuditSchedule> auditScheduleList =  getLeastRatingAudits(legalEntityCode, financialYear, auditTypeCode, unitId);		
		List<String> auditIds = auditScheduleList.stream().map(AuditSchedule::getAuditId).collect(Collectors.toList());
		
		try { 			
			StringBuilder strQuery = new StringBuilder(" SELECT sch.audit_id, sch.prev_audit_id,"
					+ " sch.effective_rating as ratingCurrent, sch1.effective_rating as ratingPre"
					+ " FROM  audit_schedule sch INNER JOIN  "
					+ " audit_schedule sch1 ON  sch.prev_audit_id = sch1.audit_id   ");		
			strQuery.append(" Where sch.legal_entity_code= :legalEntityCode ");
			strQuery.append(" and sch.financial_year = :financialYear  ");	
			if(!auditIds.isEmpty() && auditIds.size()>0){
				strQuery.append(" and sch.audit_id NOT IN  (:auditIds) ");
			}
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
			}				
			if(!BankAuditUtil.isEmptyString(unitId)){
				strQuery.append(" and sch.unit_id in ("+unitId+") ");
			} 
			
			Query qry =session.createNativeQuery(strQuery.toString())
				.setParameter("legalEntityCode", legalEntityCode)
				.setParameter("financialYear",financialYear, TemporalType.DATE);
			
			if(!auditIds.isEmpty() && auditIds.size()>0){	
				qry.setParameterList("auditIds", auditIds);
			}
			if(!BankAuditUtil.isEmptyString(auditTypeCode))
				qry.setParameter("auditTypeCode", auditTypeCode);
			 		 
			List<Object[]> ratingAll = qry.list();
			if(!ratingAll.isEmpty() && ratingAll.size()>0){
				List<Object[]> supRatingList = getSupervisoryRatingsFromGeneralParameter(legalEntityCode); /// gp.value, gp.description -> Ascending order rating list
				//Map<String , List<String>> = supRatingList.stream().map(Object[0],"").co
				
				for (Object[] objects : ratingAll) {
					String ratingLatest = objects[2]==null?null:objects[2].toString();
					String ratingPre =  objects[3]==null?null:objects[3].toString();
					if(ratingLatest!=null && ratingPre!=null){
						int latestRatingValue = 0;
						int preRatingValue = 0; 
						for (Object[] ratingObj : supRatingList) {  
							preRatingValue++;
							if(ratingObj[0].toString().equalsIgnoreCase(ratingLatest)){
								latestRatingValue = preRatingValue;
							}
							if(ratingObj[0].toString().equalsIgnoreCase(ratingPre)){	 	 
								if(latestRatingValue!=0 && preRatingValue-latestRatingValue>1){
									watchList++;
								}
								break;
							}							 
						} 
					}
				}
			}
			watchList = watchList + auditScheduleList.size(); 
		}catch(Exception exception) {
			logger.error("Inside method getWatchListForAudits :: ", exception); 
		}
		return watchList;
	}
	
	@Override
	public Map<String, String> getAuthorizedLettersCount(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId, List<String> unitIdlist, List<LocalDate> financialYearList){	
		
		Session session=getSession();
		session.setDefaultReadOnly(true);
		
		LocalDate financialYearStartDt = financialYearList.get(0);
		LocalDate financialYearEndDt = financialYearList.get(1);
		StringBuilder strQuery = new StringBuilder("  SELECT g.value , COUNT(letters.letter_code)	  "
				+ "  FROM audit_letter_user_inputs letters   "
				+ "  INNER JOIN audit_schedule sch   "
				+ "  ON sch.audit_id = letters.audit_id "  
				+ "  AND sch.legal_entity_code = letters.legal_entity_code   "
				+ "  AND sch.audit_type_code = letters.audit_type_code "
				+ "  AND sch.legal_entity_code = letters.legal_entity_code");
		strQuery.append("  "					 
				+ " AND ( Case when sch.actual_start_date IS NOT NULL "
				+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
				+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
				+ "  ");
		if(!BankAuditUtil.isEmptyString(auditTypeCode)){
			strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
		}	
		strQuery.append(" and sch.unit_id in (:unitId) ");
		
		strQuery.append("  RIGHT JOIN general_parameter g  "
				+ "  ON  letters.legal_entity_code = g.legal_entity_code  "
				+ "  AND g.value=letters.letter_code "
				+ "  WHERE g.key_1 ='LETTER' AND key_2 IN('AUDIT','AUDIT_BEFORE')   "
				+ "  AND g.legal_entity_code= :legalEntityCode ");			
		
		strQuery.append(" GROUP BY g.value  ");	
		
		try{
			Query qry = session.createNativeQuery(strQuery.toString())	 
					.setParameter("legalEntityCode", legalEntityCode);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}
			qry.setParameterList("unitId", unitIdlist);
			Map<String, String> letterCountAuthorized = new TreeMap<String, String>();
			List<Object[]> recordSet=qry.list();
			if(!recordSet.isEmpty() && recordSet.size()>0){
				for (Object[] record : recordSet) {
					letterCountAuthorized.put(String.valueOf(record[0]), String.valueOf(record[1]) );	
				} 				
			}
			return letterCountAuthorized;			
		}
		catch (Exception exception) {
			logger.error("Inside method getAuthorizedLettersCount :: ", exception); 
		}
		return null;
	}
	
	@Override
	public Map<String, String> getUnAuthorizedLettersCount(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId, List<String> unitIdlist, List<LocalDate> financialYearList){	
		
		Session session=getSession();
		session.setDefaultReadOnly(true);
		
		LocalDate financialYearStartDt = financialYearList.get(0);
		LocalDate financialYearEndDt = financialYearList.get(1);
		StringBuilder strQuery = new StringBuilder("  SELECT  g.value , COUNT(letters.letter_code)	  "
				+ "  FROM audit_letter_user_inputs_wrk letters   "
				+ "  INNER JOIN audit_schedule sch   "
				+ "  ON sch.audit_id = letters.audit_id "  
				+ "  AND sch.legal_entity_code = letters.legal_entity_code   "
				+ "  AND sch.audit_type_code = letters.audit_type_code "
				+ "  AND sch.legal_entity_code = letters.legal_entity_code");
		 
		strQuery.append("  "					 
				+ " AND ( Case when sch.actual_start_date IS NOT NULL "
				+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
				+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
				+ "  ");
		if(!BankAuditUtil.isEmptyString(auditTypeCode)){
			strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
		}	
		strQuery.append(" and sch.unit_id in (:unitId) ");
		
		strQuery.append("  RIGHT JOIN general_parameter g  "
				+ "  ON  letters.legal_entity_code = g.legal_entity_code  "
				+ "  AND g.value=letters.letter_code "
				+ "  WHERE g.key_1 ='LETTER' AND key_2 IN('AUDIT','AUDIT_BEFORE')   "
				+ "  AND g.legal_entity_code= :legalEntityCode ");			
		
		strQuery.append(" GROUP BY g.value ");	
		
		try{
			Query qry = session.createNativeQuery(strQuery.toString())	 
					.setParameter("legalEntityCode", legalEntityCode);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}
			qry.setParameterList("unitId", unitIdlist);
			Map<String, String> letterCountUnAuthorized = new TreeMap<String, String>();
			List<Object[]> recordSet=qry.list();
			if(!recordSet.isEmpty() && recordSet.size()>0){
				for (Object[] record : recordSet) {
					letterCountUnAuthorized.put(String.valueOf(record[0]), String.valueOf(record[1]) );	
				} 				
			}
			return letterCountUnAuthorized;
			
		}
		catch (Exception exception) {
			logger.error("Inside method getUnAuthorizedLettersCount :: ", exception); 
		}
		return null;
	}
	
	@Override
	public Map<String, String> getAuthorizedSupportingDocumentCount(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId, List<String> unitIdlist, List<LocalDate> financialYearList){	
		
		Session session=getSession();
		session.setDefaultReadOnly(true);
		
		LocalDate financialYearStartDt = financialYearList.get(0);
		LocalDate financialYearEndDt = financialYearList.get(1);
		StringBuilder strQuery = new StringBuilder(" SELECT g.value, COUNT(doc.document_name) "
						 + "  FROM audit_document_details doc   "
						 + "  INNER JOIN audit_schedule sch  "
						 + "  ON doc.audit_id=sch.audit_id "
						 + "  AND doc.audit_type_code=sch.audit_type_code  "
						 + "  AND doc.legal_entity_code = sch.legal_entity_code ");
		strQuery.append("  "					 
						+ " AND  ( Case when sch.actual_start_date IS NOT NULL "
						+ "			THEN (sch.actual_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
						+ " 	  	ELSE (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "
						+ "  ");					
		 if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
			}	
		 strQuery.append(" and sch.unit_id in (:unitId) ");				
		 strQuery.append( "  RIGHT JOIN general_parameter g   "
					     + "  ON  doc.legal_entity_code = g.legal_entity_code "
					     + "  AND g.value=doc.document_name  "
					     + "  WHERE g.key_1 ='DOCUMENT' AND g.key_2='AUDIT' "
					     + "  and g.legal_entity_code= :legalEntityCode  ");
				
		 strQuery.append(" GROUP BY  g.value    ");	
		
		try{
			Query qry = session.createNativeQuery(strQuery.toString())	 
					.setParameter("legalEntityCode", legalEntityCode);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}
			qry.setParameterList("unitId", unitIdlist);
			Map<String, String> documentCount = new TreeMap<String, String>();
			List<Object[]> recordSet=qry.list();
			if(!recordSet.isEmpty() && recordSet.size()>0){
				for (Object[] record : recordSet) {
					documentCount.put(String.valueOf(record[0]), String.valueOf(record[1]) );	
				} 				
			} 
			return documentCount;
			
		}
		catch (Exception exception) {
			logger.error("Inside method getSupportingDocumnetCount :: ", exception); 
		}
		return null;
	}
	
	
	@Override
	public List<String> getUnitCodeList(Integer legalEntityCode, String unitId, String zone){
		
		Session session=getSession();		
		session.setDefaultReadOnly(true);
		List<String> unitCodeList = new ArrayList<>();
		try{
			
			StringBuilder strQuery = new StringBuilder(" select distinct unit_code from maint_entity where unit_code in ("  
					+ "	select distinct unit_code from maint_entity" 
					+ "	join ( " 
					+ "	select A.unit_code Aid," 
					+ "	B.unit_code Bid,"  
					+ "	C.unit_code Cid,"  
					+ "	D.unit_code Did,"  
					+ "	E.unit_code Eid,"  
					+ "	F.unit_code Fid,"  
					+ "	G.unit_code Gid,"  
					+ "	H.unit_code Hid "  
					+ "	FROM maint_entity A"  
					+ "	left join maint_entity B on B.parent_unit_code=A.unit_code and B.legal_entity_code=A.legal_entity_code"  
					+ "	left join maint_entity C on C.parent_unit_code=B.unit_code and C.legal_entity_code=B.legal_entity_code"  
					+ "	left join maint_entity D on D.parent_unit_code=C.unit_code and D.legal_entity_code=C.legal_entity_code"  
					+ "	left join maint_entity E on E.parent_unit_code=D.unit_code and E.legal_entity_code=D.legal_entity_code"  
					+ "	left join maint_entity F on F.parent_unit_code=E.unit_code and F.legal_entity_code=E.legal_entity_code"  
					+ "	left join maint_entity G on G.parent_unit_code=F.unit_code and G.legal_entity_code=F.legal_entity_code" 
					+ "	left join maint_entity H on H.parent_unit_code=G.unit_code and H.legal_entity_code=G.legal_entity_code "
					+ " Where " );
					
					if(!BankAuditUtil.isEmptyString(unitId)){
						strQuery.append("  A.unit_code=:unitParameter ");
					}else{
						strQuery.append( " A.unit_code in ( Select unit_code from maint_zone_mapping where zone_code = :unitParameter) ");
					}					
					strQuery.append( " and A.legal_entity_code=:legalEntityCode AND A.status='A' AND A.entity_status='A' "
							+ "		) Tmp" 
							+ "		where unit_code in (Aid,Bid,Cid,Did,Eid,Fid,Gid,Hid) AND status='A' AND entity_status='A' ) ");
			 
			/*StringBuilder stdrQuery = new StringBuilder("  select unit_code from maint_entity "
					+ " where ");
					if(!BankAuditUtil.isEmptyString(unitId)){
						strQuery.append( " parent_unit_code = :unitParameter ");
					}else{
						strQuery.append( " parent_unit_code in ( Select unit_code from maint_zone_mapping where zone_code = :unitParameter) ");
					}*/				 	 
					 
			Query qry = session.createNativeQuery(strQuery.toString())
					.setParameter("legalEntityCode",  legalEntityCode);
			if(!BankAuditUtil.isEmptyString(unitId)){
				qry.setParameter("unitParameter",  unitId);
			}else{
				qry.setParameter("unitParameter",  zone);
			} 	
			 
			unitCodeList = qry.list();			 
			
		}catch (Exception exception) {
			logger.error("Inside method getUnitCodeList :: ", exception);
		}
		if(!unitCodeList.isEmpty() && unitCodeList.size()>0){
			return unitCodeList;
		} 
		unitCodeList.add("NoData");
		return unitCodeList;
	}
	
	private Long getTargetUnitCount(Integer legalEntityCode,  LocalDate financialYear,  String auditTypeCode, String unitId, List<LocalDate> financialYearList){
		
		Session session=getSession();		
		session.setDefaultReadOnly(true);	
		
		LocalDate financialYearStartDt = financialYearList.get(0);
		LocalDate financialYearEndDt = financialYearList.get(1);
		StringBuilder strQuery = new StringBuilder(" SELECT SUM(targetPreYear) preYearTarget, SUM(targetCurrentYear) currentYearTarget FROM ( "
				+ " SELECT DISTINCT  unit_code, unitCount.unit_type, legalEntityCode ,  " 
					+ "	 unitClassification, unitCriticality , unitAditTypeCode,number_of_previous_year_inspection,number_of_previous_year_unit_inspected, p.frequency, "
					+ "	 (CASE WHEN  (number_of_previous_year_inspection >0 AND number_of_previous_year_unit_inspected< FLOOR(12/p.frequency) ) "
					+ "		THEN (FLOOR(12/p.frequency) - number_of_previous_year_unit_inspected)  ELSE 0 END ) AS targetPreYear ,   "
					+ "	 number_of_current_year_inspection	, number_of_current_year_unit_inspected ,  "
					+ "	 (CASE WHEN number_of_current_year_inspection>0 THEN FLOOR(12/p.frequency)  ELSE 0 END )AS targetCurrentYear"
					+ "  FROM (SELECT   "
				    + "	        me.unit_code, me.unit_type, me.legal_entity_code AS legalEntityCode, me.classification AS unitClassification,   "
				    + "	          me.u_criticality AS unitCriticality , a.audit_type_code AS unitAditTypeCode,  "
				    + "	        ( SELECT COUNT(audit_id)   "
				    + "	             FROM audit_schedule sch   WHERE sch.legal_entity_code = me.legal_entity_code         "            
				    + "	             AND me.unit_code = sch.unit_id   "                   
				    + "	             AND (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"')   "
				    + "	             AND sch.audit_status NOT IN ('AD','AU','AN')   ) AS number_of_previous_year_unit_inspected,    "
				    + "			(SELECT COUNT(audit_id)  "
				    + "        		 FROM audit_schedule sch   WHERE sch.legal_entity_code = me.legal_entity_code    "                 
			        + "         	 AND me.unit_code = sch.unit_id    "
			        + "        		AND (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') )  AS number_of_previous_year_inspection,     "
					+ "	    	( SELECT COUNT(audit_id)   "
				    + "	             FROM audit_schedule sch  WHERE sch.legal_entity_code = me.legal_entity_code    "                 
				    + "	             AND me.unit_code = sch.unit_id   "                   
				    + "	             AND (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"')   "
				    + "	             AND sch.audit_status NOT IN ('AD','AU','AN')   ) AS number_of_current_year_unit_inspected, "
				    + "			( SELECT COUNT(audit_id)        	  "	
				    + "	 			 FROM audit_schedule sch  WHERE sch.legal_entity_code = me.legal_entity_code    "	    
                    + "				 AND me.unit_code = sch.unit_id    "	
                    + "				 AND (sch.schedule_start_date between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') ) AS number_of_current_year_inspection	  "						  		
					+ "		  FROM  maint_entity me  ,maint_entity_audit_subgroup_mapping m, maint_audit_group a  "
					+ "		  WHERE me.legal_entity_code=4  AND a.legal_entity_code = m.legal_entity_code   "
					+ "			AND a.legal_entity_code = me.legal_entity_code   "
					+ "			AND m.audit_group_code = a.audit_group_code   "
					+ "			AND m.mapping_type = 'E'   "
					+ "			AND m.id = me.unit_code   ");
					//+ "			AND e.unit_code in (:unitsLst)   "
					if(!BankAuditUtil.isEmptyString(unitId)){
						strQuery.append(" and me.unit_code in ("+unitId+") ");
					} 
			strQuery.append( "	)AS unitCount   "			       
				+ "	 INNER JOIN maint_audit_parameter_derived p ON 	 unitCount.unit_type = p.unit_type  " 
				+ "	 AND legalEntityCode = p.legal_entity_code   "
				+ "	 AND unitClassification = p.classification  "
				+ "	 AND unitCriticality =p.u_criticality  "
				+ "	 AND unitAditTypeCode = p.audit_type_code  "
				/*+ "	 INNER JOIN risk_score_percentage score   "
				+ "	 ON score.legal_entity_code = p.legal_entity_code  " 
				+ "	 AND score.rating_internal  = 1    "
			    + "	 AND score.risk_category_code = p.rating   "
			    + "	 AND score.audit_type_code = p.audit_type_code  "   */       
				+ "	 WHERE p.legal_entity_code=:legalEntityCode   " 
				+ "	 AND p.revenue_leakage = 0  ");				
		if(!BankAuditUtil.isEmptyString(auditTypeCode)){
			strQuery.append(" and p.audit_type_code = :auditTypeCode ");
		}	
		
		strQuery.append(" ) as countTarget ");
		 
		try{
			Query qry = session.createNativeQuery(strQuery.toString())	 
					//.setParameter("financialYear", financialYear, TemporalType.DATE)
					.setParameter("legalEntityCode", legalEntityCode);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}		
			
			List<Object[]> countTarget = qry.list();
			if(countTarget!=null && countTarget.size()>0){
				
				Object[] countTargetArr = countTarget.get(0);
				Long preYearTarget =  ((Double)countTargetArr[0]).longValue();
				Long currentYearTarget =  ((Double)countTargetArr[1]).longValue();				
				return ( preYearTarget + currentYearTarget );
				
			}
			
		}catch (Exception exception) { 
			logger.error("Inside method getTargetUnitCount :: ", exception);
		}
		return (long) 0;
	}
		
	private List<AuditSchedule> getLeastRatingAudits(Integer legalEntityCode,  LocalDate financialYear,  String auditTypeCode, 
			  String unitId){
		 		
		Session session=getSession();
		session.setDefaultReadOnly(true);
		List<AuditSchedule> auditScheduleList = new ArrayList<AuditSchedule>();		
		List<Object[]> supRatingList = getSupervisoryRatingsFromGeneralParameter(legalEntityCode);
		if(supRatingList.isEmpty() || supRatingList.size()==0){
			return auditScheduleList;
		}
		
		Object[] obj = supRatingList.get(0);
		String ratingValue = String.valueOf(obj[0]);  
		//Integer ratingValueInt = Integer.valueOf(String.valueOf(obj[1])); //description
		try { 			
			StringBuilder strQuery = new StringBuilder(" FROM  AuditSchedule sch WHERE "
									+ " sch.effectiveRating = :ratingValue " );
			strQuery.append(" and sch.financialYear = '"+financialYear.getYear()+"-03-31"+"'  ");			
			strQuery.append(" and sch.legalEntityCode= :legalEntityCode ");
						
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				strQuery.append(" and sch.auditTypeCode = :auditTypeCode ");
			}				
			if(!BankAuditUtil.isEmptyString(unitId)){
				strQuery.append(" and sch.unitId in ("+unitId+") ");
			} 	
			
			Query qry =session.createQuery(strQuery.toString())
				.setParameter("legalEntityCode", legalEntityCode)
				.setParameter("ratingValue", ratingValue);			
				//.setParameter("financialYear",  );
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode))
				qry.setParameter("auditTypeCode", auditTypeCode);
			 		 
			auditScheduleList = qry.list();
			
		}catch(Exception exception) {
			logger.error("Inside method getLeastRatingAudits :: ", exception);
		}
		return auditScheduleList;
	}
	
	private List<Object[]>  getSupervisoryRatingsFromGeneralParameter(Integer legalEntityCode){
		Session session=getSession();
		session.setDefaultReadOnly(true); 		
		List<Object[]> lst =  new ArrayList<>();
		try { 			
			StringBuilder strQuery = new StringBuilder(" SELECT gp.value, gp.description FROM general_parameter gp  "
									+ " WHERE gp.legal_entity_code = :legalEntityCode AND gp.key_1= 'RATING'   "
									+ " AND gp.key_2= 'SUPERVISORY' "				 
									+ " ORDER BY  CAST(gp.description AS UNSIGNED) ASC " ); 			 
			
			Query qry =session.createNativeQuery(strQuery.toString())
				.setParameter("legalEntityCode", legalEntityCode);		 
				lst = qry.list();
			
		}catch(Exception exception) {
			logger.error("Inside method getSupervisoryRatingsFromGeneralParameter", exception);
		}
		return lst;
	}
	
	private List<Object[]>  getDeskComplianceRatingsFromGeneralParameter(Integer legalEntityCode){
		Session session=getSession();
		session.setDefaultReadOnly(true); 		
		List<Object[]> lst =  new ArrayList<>();
		try { 			
			StringBuilder strQuery = new StringBuilder(" SELECT gp.value, gp.description FROM general_parameter gp  "
									+ " WHERE gp.legal_entity_code = :legalEntityCode AND gp.key_1= 'RATING'   "
									+ " AND gp.key_2= 'COMPLIANCE' "				 
									+ " ORDER BY gp.value  ASC " ); 			 
			 
			Query qry =session.createNativeQuery(strQuery.toString())
				.setParameter("legalEntityCode", legalEntityCode);		 
				lst = qry.list();
			
		}catch(Exception exception) {
			logger.error("Inside method getDeskComplianceRatingsFromGeneralParameter", exception);
		}
		return lst;
	}
	
	private int getInspectionCountWithoutCSV(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId){
		Session session=getSession();		
		session.setDefaultReadOnly(true);
		try{
			 
			StringBuilder strQuery = new StringBuilder("  Select count(sch.audit_id)  "
					+" from  audit_schedule sch "
					+" where sch.audit_id not in ( select doc.audit_id from audit_level_document_details doc "
							+ " where doc.document_type = :docType ) "  
					+" and sch.financial_year = :financialYear  "			  
					+" and sch.legal_entity_code= :legalEntityCode ");
					if(!BankAuditUtil.isEmptyString(auditTypeCode)){
						strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
					}	 
					 
			Query qry = session.createNativeQuery(strQuery.toString())
					.setParameter("legalEntityCode",  legalEntityCode)
					.setParameter("financialYear", financialYear , TemporalType.DATE)
					.setParameter("docType", BankAuditConstant.DOCUMENT_TYPE_IR_PART_AB);
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}
			 
			 
			int count = ((BigInteger) qry.uniqueResult()).intValue();		 
				return count;  
			 
			
		}catch (Exception exception) {
			logger.error("Inside method getInspectionCountWithoutCSV :: ", exception);
		}
		return 0;
	}
		
	private AuditSchedule getLatestAuditOfInspector(Integer legalEntityCode, String userId,  LocalDate financialYear,  String auditTypeCode, List<LocalDate>  financialYearList){
		
		Session session=getSession();		
		session.setDefaultReadOnly(true);
		LocalDate financialYearStartDt = financialYearList.get(0);
		LocalDate financialYearEndDt = financialYearList.get(1);	
		logger.info("Inside getLatestAuditOfInspector .. "+auditTypeCode +" :: " +userId+ " :: " + financialYear);
		StringBuilder strQuery = new StringBuilder("From AuditSchedule sch  "	
						+ " where  "
						+ " (IFNULL(sch.actualStartDate, sch.scheduleStartDate) between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
						/*+ " ( Case when sch.actualStartDate IS NOT NULL "
								+ "			THEN (sch.actualStartDate between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') "
								+ " 	  	ELSE (sch.scheduleStartDate between '"+financialYearStartDt+"' and '"+financialYearEndDt+"') END )  "	*/							 
						+ " and sch.legalEntityCode= :legalEntityCode ");
						//+ " and sch.actualStartDate is not null ");
						if(!BankAuditUtil.isEmptyString(auditTypeCode)){
							strQuery.append( " and sch.auditTypeCode = :auditTypeCode ");
						}
						strQuery.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  ) "
						+ "  ORDER BY sch.actualStartDate DESC  " );
						/*+ " FIELD(auditStatus, 'AI','AP','AS','AR','AW','AC') ASC  )");*/
				 
		Query qry = session.createQuery(strQuery.toString())
				.setParameter("legalEntityCode",  legalEntityCode) 
				.setParameter("userId", userId);
		if(!BankAuditUtil.isEmptyString(auditTypeCode)){
			qry.setParameter("auditTypeCode", auditTypeCode);
		} 
		
		return (AuditSchedule) qry.setMaxResults(1).uniqueResult();
	}	
	
	//Get the inspection due count of inspection which are exited state
	private Integer getInspectionDueCount(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId, List<String> unitIdlist, List<LocalDate> financialYearList, Date businessDate){
		  	
		LocalDate financialYearEndDtPrev = financialYearList.get(1).minusYears(1);
		
		StringBuilder  strQuery = new StringBuilder();
		strQuery.append(" SELECT audit_id FROM audit_schedule sch INNER JOIN maint_entity me ON  "
						 	+ "  me.unit_code=sch.unit_id  "
						 	+ "  WHERE    sch.audit_status NOT IN ('AD','AU','AN')  "
						 	+ "  AND sch.report_date IS NOT NULL "
						 	+ "  AND ( CASE WHEN me.unit_type IN('RRBC','RRBD') "
						 	+ "  THEN DATE_ADD(sch.report_date, INTERVAL (IFNULL(sch.duration,0)+16) DAY ) <= :businessDate 	 "							
							+ "  ELSE DATE_ADD(sch.report_date, INTERVAL (IFNULL(sch.duration,0)+20) DAY ) <= :businessDate  END )  "	);
								
			strQuery.append("  AND sch.financial_year = :financialYear ");					 
			strQuery.append(" and sch.legal_entity_code= :legalEntityCode ");				 			
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
			}				
			strQuery.append(" and sch.unit_id in (:unitId) ");
			
		try{
			Session session=getSession();		
			session.setDefaultReadOnly(true);
			Query qry = session.createNativeQuery(strQuery.toString())	
					.setParameter("businessDate", businessDate, TemporalType.DATE) 
					.setParameter("financialYear", financialYearEndDtPrev, TemporalType.DATE)
					.setParameter("legalEntityCode", legalEntityCode);		
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}

			qry.setParameterList("unitId", unitIdlist);
			
			return qry.list().size();
			
		}catch (Exception exception) {
			logger.error("Inside getBudgetProgressDueCount :: ", exception);
		}	
		return 0;	
	}
	
	//Get the compliance due count of inspection which are in dispatched state state
	private Integer getcomplianceDueCount(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId, List<String> unitIdlist, List<LocalDate> financialYearList, Date businessDate){
		 		
		LocalDate financialYearEndDtPrev = financialYearList.get(1).minusYears(1);
	 
		StringBuilder  strQuery = new StringBuilder();
		strQuery.append(" SELECT audit_id FROM audit_schedule sch   "
							+ " where sch.report_dispatch_date IS NOT NULL"
							+ " AND DATE_ADD(sch.report_dispatch_date, INTERVAL ifnull(IFNULL(sch.response_time,0),60) DAY ) <= :businessDate"	);
								
		strQuery.append(" AND sch.financial_year = :financialYear ");					 
		strQuery.append(" AND sch.legal_entity_code= :legalEntityCode ");				 			
		if(!BankAuditUtil.isEmptyString(auditTypeCode)){
			strQuery.append(" and sch.audit_type_code = :auditTypeCode ");
		}				
		strQuery.append(" and sch.unit_id in (:unitId) ");
			
		try{
			Session session=getSession();		
			session.setDefaultReadOnly(true);
			Query qry = session.createNativeQuery(strQuery.toString())	
					.setParameter("businessDate", businessDate, TemporalType.DATE) 
					.setParameter("financialYear", financialYearEndDtPrev, TemporalType.DATE)
					.setParameter("legalEntityCode", legalEntityCode);		
			if(!BankAuditUtil.isEmptyString(auditTypeCode)){
				qry.setParameter("auditTypeCode", auditTypeCode);
			}

			qry.setParameterList("unitId", unitIdlist);
			
			return qry.list().size();
			
		}catch (Exception exception) {
			logger.error("Inside getcomplianceDueCount :: ", exception);
		}	
		return 0;	
	}
		
		
    // End of the Class 
}


class PeriodComparator implements Comparator<String>{

	@Override
     public int compare(String str1, String str2) {
    
		if((str1.startsWith("PREV")&&str2.startsWith("CUR"))||str2.startsWith("PREV")&&str1.startsWith("CUR")){
			return str2.compareTo(str1);
		}else if((str1.startsWith("PREV")&&str2.startsWith("PREV"))||(str1.startsWith("CUR")&&str2.startsWith("CUR"))){
			return str1.compareTo(str2);
		}
		
		return str1.compareTo(str2); 
		}
	}