package com.bankaudit.rest.process.service;

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.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

import org.jboss.logging.Logger;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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.DashboardSummaryDto;
import com.bankaudit.dto.process.PlanCalendarResponseDto;
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.MaintAuditTypeDesc;
import com.bankaudit.model.MaintEntity;
import com.bankaudit.model.MaintSeverityScale;
import com.bankaudit.model.MaintUsergroupRoles;
import com.bankaudit.model.User;
import com.bankaudit.process.model.AuditProcessV;
import com.bankaudit.process.model.AuditSchedule;
import com.bankaudit.rest.process.dao.DashboardDao;
import com.bankaudit.rest.process.dao.ReportDao;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.MaintAuditTypeDescService;
import com.bankaudit.service.MaintEntityService;
import com.bankaudit.service.MaintUsergroupRolesService;
import com.bankaudit.service.UserService;
import com.bankaudit.util.BankAuditUtil;
@Service
@Transactional("transactionManager")
public class DashboardServiceImpl implements DashboardService {

	@Autowired
	DashboardDao dashboardDao;
	
	@Autowired
	BusinessDateService businessDateService;
	
	@Autowired
	MaintEntityService maintEntityService;
	
	@Autowired
	MaintAuditTypeDescService maintAuditTypeDescService;
	
	@Autowired
	AuditProcessVService auditProcessVService;
	
	@Autowired
	MaintUsergroupRolesService maintUsergroupRolesService;
	
	@Autowired
	ReportDao reportDao;
	
	@Autowired
	UserService userService;
	
	static final Logger logger = Logger.getLogger(DashboardServiceImpl.class);
	
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, HashMap<String, Long>> getAuditStatus(Integer legalEntityCode, String auditType, String unitType,
			String criticality, String period, LocalDate fromDate, LocalDate toDate, String userId,String role) {

		Map<String,  HashMap<String, Long>> auditStatusResult=new HashMap<String ,  HashMap<String, Long>>();
		HashMap<String, Long> childMap=null;
        List<String> unitList=getUnitList(legalEntityCode, role,"user", userId);
		Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		List<AuditStatusGraphResponseDto> auditStatusGraphResponseDtos=null;
		if(period.equalsIgnoreCase("quarterly")){
			 auditStatusGraphResponseDtos=dashboardDao.getAuditStatusQuarterly( legalEntityCode,  auditType,  unitType,
					 criticality,  userId,businessDate,role,unitList);
			
		}else if (period.equalsIgnoreCase("halfYearly")) {
			 auditStatusGraphResponseDtos=dashboardDao.getAuditStatusHalfYearly( legalEntityCode,  auditType,  unitType,
					 criticality,  userId,businessDate,role,unitList);
			
		}else if (period.equalsIgnoreCase("yearly")) {
			 auditStatusGraphResponseDtos=dashboardDao.getAuditStatusYearly( legalEntityCode,  auditType,  unitType,
					 criticality,  userId,businessDate,role,unitList);
			
		}else if (period.equalsIgnoreCase("range")) {
			 auditStatusGraphResponseDtos=dashboardDao.getAuditStatusByRange( legalEntityCode,  auditType,  unitType,
					 criticality,  userId, fromDate,  toDate,role,unitList);
			
		}
		
		for (AuditStatusGraphResponseDto auditStatusGraphResponseDto : auditStatusGraphResponseDtos) {
			
			if(auditStatusResult.containsKey(auditStatusGraphResponseDto.getYtd())){
				 childMap=auditStatusResult.get(auditStatusGraphResponseDto.getYtd());
				if(childMap.containsKey(auditStatusGraphResponseDto.getAuditStatus())){
					Long childMapValue=childMap.get(auditStatusGraphResponseDto.getAuditStatus());
					childMap.put(auditStatusGraphResponseDto.getAuditStatus(), childMapValue+auditStatusGraphResponseDto.getCount());
					
				}else{
					/*childMap=new HashMap<String,Long>();*/
					childMap.put(auditStatusGraphResponseDto.getAuditStatus(), auditStatusGraphResponseDto.getCount());
					
					
					// if not contain the child  , create new and store 
				}
			}else {
				childMap=new HashMap<String,Long>();
				childMap.put(auditStatusGraphResponseDto.getAuditStatus(), auditStatusGraphResponseDto.getCount());
				auditStatusResult.put(auditStatusGraphResponseDto.getYtd(), childMap);
			}
		}
		
		System.out.println("auditStatusResult .... "+ auditStatusResult);
		
		for(String key:auditStatusResult.keySet()){
			Long planned =0L, initiated =0L, submitted=0L, responded=0L, closed=0L, total=0L;
			//System.out.println("key is .... "+ key);
			HashMap<String, Long>  map1=auditStatusResult.get(key);
			
			if(map1.containsKey("planned")) planned= map1.get("planned");
			if(map1.containsKey("initiated")) initiated= map1.get("initiated");
			if(map1.containsKey("submitted")) submitted= map1.get("submitted");
			if(map1.containsKey("responded")) responded= map1.get("responded");
			if(map1.containsKey("closed")) closed= map1.get("closed");
			
			System.out.println("planned .."+ planned+" initiated .."+initiated +" submitted.."+submitted);
			total =planned+initiated+submitted+responded+closed; // TotalPlan = Sum of ( Planned + Initiated + Submitted + Responded + Closed )
			System.out.println("total .."+ total);
			map1.put("total",total );
			if(! ("SM".equalsIgnoreCase(role) || "OPS".equalsIgnoreCase(role)) ) {
				map1.put("submitted",submitted + responded + closed  );  // Apart from SeniorManager & Operations we are 
				map1.remove("responded");
				map1.remove("closed");
			}
			
			/*total =planned+initiated+submitted+responded+closed; // TotalPlan = Sum of ( Planned + Initiated + Submitted + Responded + Closed )
			map1.put("planned",total );
			if(! ("SM".equalsIgnoreCase(role) || "OPS".equalsIgnoreCase(role)) ) {
				map1.put("submitted",submitted + responded + closed  );  // Apart from SeniorManager & Operations we are 
				map1.remove("responded");
				map1.remove("closed");
			}*/
			
			/*if(map1.containsKey("planned")){
				if(map1.containsKey("submitted")){
					map1.put("planned", map1.get("planned")+map1.get("submitted"));
				}
			}else{
				if(map1.containsKey("submitted")){
					map1.put("planned",map1.get("submitted"));
				}
			}*/
			
		}
		/*Map<String,HashMap<String, Long>> sorted1=new TreeMap<>(auditStatusResult);*/
		Map<String,HashMap<String, Long>> sorted2=new TreeMap<>(new AuditStatusComparator());
		sorted2.putAll(auditStatusResult);
		
		return sorted2;
	}

	@Override
	public DataTableResponse getAuditSchedules(int parseInt, String userId, String search, Integer orderColumn,
			String orderDirection, Integer page, Integer size,String role) {
		List<String> unitList=getUnitList(parseInt,role, "user", userId);
		return dashboardDao.getAuditSchedules( parseInt,  userId,  search,  orderColumn,
				 orderDirection,  page,  size, role,unitList);
	}

	@Override
	public Map<String, List<ScheduleVarianceGraphResponseDto>> getScheduleVariance(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId,String role, String unitType, String criticality) {
		
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		System.out.println("Inside getScheduleVariance .........."+legalEntityCode+" role.. "+role+" userId.."+userId);
		List<String> unitList=getUnitList(legalEntityCode, role,"user", userId);
		System.out.println("unitList .........."+unitList);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);

		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		
		if(period.equalsIgnoreCase("quarterly")){
			
			if(calendar.get(Calendar.MONTH)<=3) {
				fromDate=LocalDate.of(year+1, 1, 1);
				toDate=fromDate.plusMonths(3).minusDays(1);
			}else if(calendar.get(Calendar.MONTH)<=6){
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(3).minusDays(1);
			}else if(calendar.get(Calendar.MONTH)<=9){
				fromDate=LocalDate.of(year, 7, 1);
			    toDate=fromDate.plusMonths(3).minusDays(1);
			}else if(calendar.get(Calendar.MONTH)<=12){
				fromDate=LocalDate.of(year, 10, 1);
				toDate=fromDate.plusMonths(3).minusDays(1);
			} 
			
			
		}else if (period.equalsIgnoreCase("halfYearly")) {
			
			if(calendar.get(Calendar.MONTH)<=3 || (calendar.get(Calendar.MONTH)>=10 &&  calendar.get(Calendar.MONTH)<=12)) {
				fromDate=LocalDate.of(year, 10, 1);
				toDate=fromDate.plusMonths(6).minusDays(1);
			}else {
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(6).minusDays(1);
			}	
			
		}else if (period.equalsIgnoreCase("yearly")) {
			
			fromDate=LocalDate.of(year, 4, 1);
			toDate=fromDate.plusMonths(12).minusDays(1);
			
		}else if (period.equalsIgnoreCase("range")) {
			
		}
		
		
		
		List<ScheduleVarianceGraphResponseDto> listScheduleVariance= dashboardDao.getScheduleVariance( legalEntityCode,  auditType,  period,
				 fromDate,  toDate,  userId,role,unitList,  unitType, criticality);
		
		List<ScheduleVarianceGraphResponseDto> listScheduleDelay= dashboardDao.getScheduleDelay( legalEntityCode,  auditType,  period,
				 fromDate,  toDate,  userId,role,unitList,  unitType, criticality);
		
		Map<String,List<ScheduleVarianceGraphResponseDto>> result=new HashMap<>();
		result.put("ScheduleVariance", listScheduleVariance);
		result.put("ScheduleDelay", listScheduleDelay);
		return result;
	}

	@Override
	public List<RealTimeRectificationResponseDto> getRealTimeRectification(int legalEntityCode, String auditType,
			String period, LocalDate fromDate, LocalDate toDate, String userId, String role, String unitType, String criticality) {
		
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		List<String> unitList=getUnitList(legalEntityCode, role,"user", userId);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);

		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		
		if(period.equalsIgnoreCase("quarterly")){
			
			if(calendar.get(Calendar.MONTH)<=3) {
				fromDate=LocalDate.of(year+1, 1, 1);
				toDate=fromDate.plusMonths(3).minusDays(1);
			}else if(calendar.get(Calendar.MONTH)<=6){
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(3).minusDays(1);
			}else if(calendar.get(Calendar.MONTH)<=9){
				fromDate=LocalDate.of(year, 7, 1);
			    toDate=fromDate.plusMonths(3).minusDays(1);
			}else if(calendar.get(Calendar.MONTH)<=12){
				fromDate=LocalDate.of(year, 10, 1);
				toDate=fromDate.plusMonths(3).minusDays(1);
			} 
			
			
		}else if (period.equalsIgnoreCase("halfYearly")) {
			
			if(calendar.get(Calendar.MONTH)<=3 || (calendar.get(Calendar.MONTH)>=10 &&  calendar.get(Calendar.MONTH)<=12)) {
				fromDate=LocalDate.of(year, 10, 1);
				toDate=fromDate.plusMonths(6).minusDays(1);
			}else {
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(6).minusDays(1);
			}	
			
		}else if (period.equalsIgnoreCase("yearly")) {
			
			fromDate=LocalDate.of(year, 4, 1);
			toDate=fromDate.plusMonths(12).minusDays(1);
			
		}else if (period.equalsIgnoreCase("range")) {
			
		}
		
		
		
		return dashboardDao.getRealTimeRectification( legalEntityCode,  auditType,  period,
				 fromDate,  toDate,  userId,role,unitList,  unitType, criticality);
		
		
		
	
	}

	@Override
	public List<RatingVarianceGraphResponseDto> getRatingStatus(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, String unitType, String criticality) {
		
			Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
			Calendar calendar=Calendar.getInstance();
			calendar.setTime(businessDateTimestamp);
        
		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		
		if(period.equalsIgnoreCase("quarterly")){
			
			if(calendar.get(Calendar.MONTH)<=3) {
				fromDate=LocalDate.of(year+1, 1, 1);
				toDate=fromDate.plusMonths(3).minusDays(1);
			}else if(calendar.get(Calendar.MONTH)<=6){
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(3).minusDays(1);
			}else if(calendar.get(Calendar.MONTH)<=9){
				fromDate=LocalDate.of(year, 7, 1);
			    toDate=fromDate.plusMonths(3).minusDays(1);
			}else if(calendar.get(Calendar.MONTH)<=12){
				fromDate=LocalDate.of(year, 10, 1);
				toDate=fromDate.plusMonths(3).minusDays(1);
			} 
			
			
		}else if (period.equalsIgnoreCase("halfYearly")) {
			
			if(calendar.get(Calendar.MONTH)<=3 || (calendar.get(Calendar.MONTH)>=10 &&  calendar.get(Calendar.MONTH)<=12)) {
				fromDate=LocalDate.of(year, 10, 1);
				toDate=fromDate.plusMonths(6).minusDays(1);
			}else {
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(6).minusDays(1);
			}	
			
		}else if (period.equalsIgnoreCase("yearly")) {
			
			fromDate=LocalDate.of(year, 4, 1);
			toDate=fromDate.plusMonths(12).minusDays(1);
			
		}else if (period.equalsIgnoreCase("range")) {
			
		}
		List<String> unitList= getUnitList(legalEntityCode, role,"user", userId); //To get the list on all Units under the logged in User
		List<String> unitSpecificToAuditList= dashboardDao.getUnitsSpecificToAudit(legalEntityCode, auditType,unitList, "Y"); //To get the filtered list of Units for the specific Audit type
		List<String> auditsList= dashboardDao.getLatestAuditsToUnits(legalEntityCode, auditType,unitSpecificToAuditList,role, "Y"); //To get the list of Latest Audits for the above selected Units, from the Audit schedule table
		logger.info("unitList :: "+unitList.size()+ ":: "+unitList);
		logger.info("unitSpecificToAuditList :: "+unitSpecificToAuditList.size()+ ":: "+unitSpecificToAuditList);
		logger.info("auditsList :: "+auditsList.size()+ ":: "+auditsList);
		
		//return dashboardDao.getRatingStatus( legalEntityCode,  auditType,  period,
				// fromDate,  toDate,  userId,role,getUnitList(legalEntityCode, role,"user", userId),  unitType, criticality);
		return dashboardDao.getRatingStatus( legalEntityCode,  auditType,  period,
				fromDate,  toDate,  userId, role, unitSpecificToAuditList, auditsList,  unitType, criticality);
	}
	
	@Override
	public List<Map<String, HashMap<String,Long>>> getRatingVariance(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, String unitType, String criticality) {
		Map<String,LocalDate> mapDt =null;
		
		/*if(!BankAuditUtil.isEmptyString(period) && !period.equalsIgnoreCase("range")){
			DashboardServiceImpl dSrvImpl = new DashboardServiceImpl();
			mapDt =dSrvImpl.getFromToDates(legalEntityCode, period);
			fromDate = mapDt.get("fromDate");
			toDate = mapDt.get("toDate");
		}*/
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);
		
        
		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		if(!BankAuditUtil.isEmptyString(period)){
			if(period.equalsIgnoreCase("quarterly")){
				if(calendar.get(Calendar.MONTH)<=3) {
					fromDate=LocalDate.of(year+1, 1, 1);
					toDate=fromDate.plusMonths(3).minusDays(1);
				}else if(calendar.get(Calendar.MONTH)<=6){
					fromDate=LocalDate.of(year, 4, 1);
					toDate=fromDate.plusMonths(3).minusDays(1);
				}else if(calendar.get(Calendar.MONTH)<=9){
					fromDate=LocalDate.of(year, 7, 1);
				    toDate=fromDate.plusMonths(3).minusDays(1);
				}else if(calendar.get(Calendar.MONTH)<=12){
					fromDate=LocalDate.of(year, 10, 1);
					toDate=fromDate.plusMonths(3).minusDays(1);
				} 
			}else if (period.equalsIgnoreCase("halfYearly")) {
				if(calendar.get(Calendar.MONTH)<=3 || (calendar.get(Calendar.MONTH)>=10 &&  calendar.get(Calendar.MONTH)<=12)) {
					fromDate=LocalDate.of(year, 10, 1);
					toDate=fromDate.plusMonths(6).minusDays(1);
				}else {
					fromDate=LocalDate.of(year, 4, 1);
					toDate=fromDate.plusMonths(6).minusDays(1);
				}	
			}else if (period.equalsIgnoreCase("yearly")) {
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(12).minusDays(1);
			}else if (period.equalsIgnoreCase("range")) {
				
			}
		}
		
		List<String> unitList= getUnitList(legalEntityCode, role,"user", userId); //To get the list on all Units under the logged in User
		List<String> unitSpecificToAuditList= dashboardDao.getUnitsSpecificToAudit(legalEntityCode, auditType,unitList, "Y"); //To get the filtered list of Units for the specific Audit type
		List<String> auditsList= dashboardDao.getLatestAuditsToUnits(legalEntityCode, auditType,unitSpecificToAuditList,role, "Y"); //To get the list of Latest Audits for the above selected Units, from the Audit schedule table
		logger.info("unitList :: "+unitList.size()+ ":: "+unitList);
		logger.info("unitSpecificToAuditList :: "+unitSpecificToAuditList.size()+ ":: "+unitSpecificToAuditList);
		logger.info("auditsList :: "+auditsList.size()+ ":: "+auditsList);
		
		//return dashboardDao.getRatingVariance( legalEntityCode,  auditType,  period,fromDate,  toDate,  userId,role,getUnitList(legalEntityCode, role,"user", userId),  unitType, criticality);
		return dashboardDao.getRatingVariance( legalEntityCode,  auditType,  period,
				 fromDate,  toDate,  userId,role,unitList,auditsList,  unitType, criticality);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, HashMap<String, Long>> getMyAuditStatistics(Integer legalEntityCode, String auditType, String unitType,
			String criticality, String period, LocalDate fromDate, LocalDate toDate, String userId,String role) {

		Map<String,  HashMap<String, Long>> auditStatusResult=new HashMap<String ,  HashMap<String, Long>>();
		HashMap<String, Long> childMap=null;
        
		Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		List<AuditStatusGraphResponseDto> auditStatusGraphResponseDtos=null;
		auditStatusGraphResponseDtos=dashboardDao.getMyAuditStatistics( legalEntityCode,  auditType,  unitType,
					 criticality,  userId, businessDate);
		
		for (AuditStatusGraphResponseDto auditStatusGraphResponseDto : auditStatusGraphResponseDtos) {
				if(auditStatusResult.containsKey(auditStatusGraphResponseDto.getYtd())){
				 childMap=auditStatusResult.get(auditStatusGraphResponseDto.getYtd());
				if(childMap.containsKey(auditStatusGraphResponseDto.getAuditStatus())){
					Long childMapValue=childMap.get(auditStatusGraphResponseDto.getAuditStatus());
					childMap.put(auditStatusGraphResponseDto.getAuditStatus(), childMapValue+auditStatusGraphResponseDto.getCount());
					
				}else{
					/*childMap=new HashMap<String,Long>();*/
					childMap.put(auditStatusGraphResponseDto.getAuditStatus(), auditStatusGraphResponseDto.getCount());
					
					
					// if not contain the child  , create new and store 
				}
			}else {
				childMap=new HashMap<String,Long>();
				childMap.put(auditStatusGraphResponseDto.getAuditStatus(), auditStatusGraphResponseDto.getCount());
				auditStatusResult.put(auditStatusGraphResponseDto.getYtd(), childMap);
			}
		}
		
		System.out.println("auditStatusResult bfr ::"+auditStatusResult);
		for(String key:auditStatusResult.keySet()){
			System.out.println("key .."+key);
			HashMap<String, Long>  map1=auditStatusResult.get(key);
			if(map1.containsKey("planned")){
				if(map1.containsKey("submitted")){
					map1.put("planned", map1.get("planned")+map1.get("submitted"));
				}
				else map1.put("submitted",0l); // If there is no submitted Audit for the Auditor, then default it to 0
			}else{
				if(map1.containsKey("submitted")){
					map1.put("planned",map1.get("submitted"));
				}else { // If there is no Audit for the Auditor, then default it to 0
					map1.put("planned",0l);
					map1.put("submitted",0l);
				}
			}
		}
		
		//Now to check the Auditor is part of any Audit, in the Result set. Otherwise need to default it to 0
		if(auditStatusResult !=null) {
			HashMap<String, Long>  map1= new HashMap();
			map1.put("planned",0l);
			map1.put("submitted",0l);
			if(!auditStatusResult.containsKey("Lead")) {
				auditStatusResult.put("Lead", map1);
			}
			if(!auditStatusResult.containsKey("Member")) {
				auditStatusResult.put("Member", map1);
			}
		}
		
		System.out.println("auditStatusResult aftr ::"+auditStatusResult);
		return auditStatusResult;
	}
	
	private List<String> getUnitList(Integer legalEntityCode ,String role, String type,String userIdOrUnitId ){
		logger.info("userIdOrUnitId ::"+userIdOrUnitId+" type::"+type);
		List<String> maintEntities=maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode,type,userIdOrUnitId);
		return  maintEntities;
	}

	@Override
	public Map<String, BranchPerformanceResponseDto> getBranchPerformance(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, String unitType, String criticality) {
		
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);

		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		
		if(period.equalsIgnoreCase("quarterly")){
			
			if(calendar.get(Calendar.MONTH)<=3) {
				fromDate=LocalDate.of(year+1, 1, 1);
				toDate=fromDate.plusMonths(3).minusDays(1);
			}else if(calendar.get(Calendar.MONTH)<=6){
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(3).minusDays(1);
			}else if(calendar.get(Calendar.MONTH)<=9){
				fromDate=LocalDate.of(year, 7, 1);
			    toDate=fromDate.plusMonths(3).minusDays(1);
			}else if(calendar.get(Calendar.MONTH)<=12){
				fromDate=LocalDate.of(year, 10, 1);
				toDate=fromDate.plusMonths(3).minusDays(1);
			} 
			
			
		}else if (period.equalsIgnoreCase("halfYearly")) {
			
			if(calendar.get(Calendar.MONTH)<=3 || (calendar.get(Calendar.MONTH)>=10 &&  calendar.get(Calendar.MONTH)<=12)) {
				fromDate=LocalDate.of(year, 10, 1);
				toDate=fromDate.plusMonths(6).minusDays(1);
			}else {
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(6).minusDays(1);
			}	
			
		}else if (period.equalsIgnoreCase("yearly")) {
			
			fromDate=LocalDate.of(year, 4, 1);
			toDate=fromDate.plusMonths(12).minusDays(1);
			
		}else if (period.equalsIgnoreCase("range")) {
			
		}
		Map<String, BranchPerformanceResponseDto> branchPerformanceResponseDtos=new HashMap();
		BranchPerformanceResponseDto branchPerformanceResponseDto=null;
		
		List<MaintEntity> entities=maintEntityService.getImmediateChild(legalEntityCode, userId);
		List<String> unitList=null;
		
		System.out.println("Before calling DAO getBranchPerformance()........"); int cnt=0;
		for (MaintEntity maintEntity : entities) {
			unitList=getUnitList(legalEntityCode,role,"unit", maintEntity.getUnitCode());
			cnt++;System.out.println("unitList ...."+cnt+" -->"+unitList);
			unitList.add(maintEntity.getUnitCode());
			System.out.println("unitList Inclusion ...."+unitList);
			if(unitList!=null && !unitList.isEmpty()){
				branchPerformanceResponseDto= dashboardDao.getBranchPerformance( legalEntityCode,  auditType,  period,
						 fromDate,  toDate,  userId,role,unitList,  unitType, criticality);
				if(branchPerformanceResponseDto!=null){
					branchPerformanceResponseDtos.put(maintEntity.getUnitCode()+"-"+maintEntity.getUnitName(),branchPerformanceResponseDto);
				}
				
			}System.out.println("call getBranchPerformance ...."+branchPerformanceResponseDtos);
		}
		System.out.println("Finally branchPerformanceResponseDtos ...."+branchPerformanceResponseDtos);
		
		
		 return branchPerformanceResponseDtos;
	
	}

	
	/** This getBranchPerformanceForBU() used to provide the Number of Observations responded on or before Response Time for an Audit**/
	/** **/
	@Override
	public Map<String, List> getBranchPerformanceForBU(int legalEntityCode, String auditType, String userId,
			String role) {
		
		MaintEntity maintEntity=maintEntityService.getUniqueByUserId(legalEntityCode, userId);
		List<BranchPerformanceBUResponse> branchPerformanceBUResponses=null;
       
		List<String> planIds=new ArrayList<>();
    	List<String> auditIds=new ArrayList<>();
		Map<String, List> result=new HashMap<>(); 
		if(maintEntity!=null){
			if(!BankAuditUtil.isEmptyString(auditType)){
	        	
				AuditSchedule auditSchedule =dashboardDao.getLatestAuditId(legalEntityCode,auditType,maintEntity.getUnitCode());
				if(auditSchedule!=null){
					planIds.add(auditSchedule.getPlanId());
					auditIds.add(auditSchedule.getAuditId());
				}
				if(!auditIds.isEmpty()){
					//add to map
						
						result.put("CUR", dashboardDao.getBranchPerformanceForBU( legalEntityCode,  Arrays.asList(auditType),  userId,
				   				 role,planIds,auditIds));
					//
						
					String previousAuditId= auditProcessVService.previousAuditDetails(legalEntityCode, auditType, maintEntity.getUnitCode(), auditSchedule.getAuditId());
					
					
					
					if(!BankAuditUtil.isEmptyString(previousAuditId)){
						
						String[] ids= previousAuditId.split(",");
						
						result.put("PREV", dashboardDao.getBranchPerformanceForBU( legalEntityCode,  Arrays.asList(auditType),  userId,
				   				 role,Arrays.asList(ids[1]),Arrays.asList(ids[0])));
					}else{
						result.put("PREV", dashboardDao.getBranchPerformanceForBU( legalEntityCode,  Arrays.asList(auditType),  userId,
				   				 role,Arrays.asList(""),Arrays.asList("")));
					}
					
					
				}else{
					result.put("CUR", dashboardDao.getBranchPerformanceForBU( legalEntityCode,  Arrays.asList(auditType),  userId,
			   				 role,Arrays.asList(""),Arrays.asList("")));
					result.put("PREV", dashboardDao.getBranchPerformanceForBU( legalEntityCode,  Arrays.asList(auditType),  userId,
			   				 role,Arrays.asList(""),Arrays.asList("")));
				}
	              // previous year         	
	        }else{
	        	
	        	List<MaintAuditTypeDesc> auditTypeDescs=maintAuditTypeDescService.getMaintAuditTypeDescByLegalEntityCode(legalEntityCode);
	        	List<AuditSchedule> auditSchedules=new ArrayList<>();
	        	for (MaintAuditTypeDesc maintAuditTypeDesc : auditTypeDescs) {
	        		AuditSchedule auditSchedule =dashboardDao.getLatestAuditId(legalEntityCode,maintAuditTypeDesc.getAuditTypeCode(),maintEntity.getUnitCode());
	        	   if(auditSchedule!=null){
	        			planIds.add(auditSchedule.getPlanId());
	            		auditIds.add(auditSchedule.getAuditId()); 
	            		auditSchedules.add(auditSchedule);
	        	   }
				}
	        	
	        	List<String> auditTypes=auditSchedules.stream().map(AuditSchedule :: getAuditTypeCode).collect(Collectors.toList());
	        	 auditIds=auditSchedules.stream().map(AuditSchedule :: getAuditId).collect(Collectors.toList());
	        	 planIds=auditSchedules.stream().map(AuditSchedule :: getPlanId).collect(Collectors.toList());
	        	
	        	
	        	
	        	if(!auditIds.isEmpty()){
	        		result.put("CUR",dashboardDao.getBranchPerformanceForBU( legalEntityCode,  auditTypes,  userId,
			   				 role,planIds,auditIds));
	        		
	        		// to get previous 
	        		String previousAuditId;
	        		List<String> previousAuditIds=new ArrayList<>();
	        		List<String> previousPlanIds=new ArrayList<>();
	        		List<String> previousAuditTypes=new ArrayList<>();
	        		
	        		for (AuditSchedule auditSchedule : auditSchedules) {
						previousAuditId= auditProcessVService.previousAuditDetails(legalEntityCode, auditSchedule.getAuditTypeCode(), maintEntity.getUnitCode(),auditSchedule.getAuditId());
						if(!BankAuditUtil.isEmptyString(previousAuditId)){
							previousAuditIds.add(previousAuditId.split(",")[0]);
							previousPlanIds.add(previousAuditId.split(",")[1]);
							previousAuditTypes.add(previousAuditId.split(",")[2]);
						}
					
					}
	        		
					/*for (String auditTypeCode : auditTypes) {
						for (String auditId : auditIds) {
							previousAuditId= auditProcessVService.previousAuditDetails(legalEntityCode, auditTypeCode, maintEntity.getUnitCode(),auditId);
							if(!BankAuditUtil.isEmptyString(previousAuditId)){
								previousAuditIds.add(previousAuditId.split("-")[0]);
								previousPlanIds.add(previousAuditId.split("-")[1]);
							}
						}
					}*/
					
					if(!previousAuditIds.isEmpty()){
						
						result.put("PREV",dashboardDao.getBranchPerformanceForBU( legalEntityCode,  previousAuditTypes,  userId,
				   				 role,previousPlanIds,previousAuditIds));
						
					}else {
						result.put("PREV", dashboardDao.getBranchPerformanceForBU( legalEntityCode,  Arrays.asList(""),  userId,
				   				 role,Arrays.asList(""),Arrays.asList("")));
					}
					
				}else{
					result.put("CUR", dashboardDao.getBranchPerformanceForBU( legalEntityCode,  Arrays.asList(""),  userId,
			   				 role,Arrays.asList(""),Arrays.asList("")));
					result.put("PREV", dashboardDao.getBranchPerformanceForBU( legalEntityCode,  Arrays.asList(""),  userId,
			   				 role,Arrays.asList(""),Arrays.asList("")));
				}
	        	
	        }
		}
		
		//Iterating the map to segregate the Records at Criticality Type.
		Map<String, List> finalRespMap=new HashMap<>();
		 for (Map.Entry<String,List> entry : result.entrySet()) 
		 {
			 List<BranchPerformanceBUResponse> rectList=new ArrayList<BranchPerformanceBUResponse>();
				
				try {
					System.out.println("Before calling DAO BranchPerformanceBUResponse()........"+ entry.getValue().size()); int cnt=0;
					String critType=null; String critTypeTemp=null; String respType=null; Long totFind=0l; Long rectFind=0l; Long delayFind=0l;
					BranchPerformanceBUResponse tempbrResp=null;
					for (BranchPerformanceBUResponse brResp : (List<BranchPerformanceBUResponse>)entry.getValue()) {
						critType= brResp.getCriticality();cnt++;
						System.out.println("recNo:::::::::::::::::::::::::::::::::::::::"+cnt +"critType .."+critType+"  type ::" +brResp.getRespType());
						
						if(critType.equalsIgnoreCase(critTypeTemp)){
							System.out.println("Inside If");
							if("DELAY".equalsIgnoreCase(brResp.getRespType())) delayFind =brResp.getObservationCount();
							else if("RESPOND_ONTIME".equalsIgnoreCase(brResp.getRespType())) rectFind =brResp.getObservationCount();
							
						}else {
							System.out.println("Inside else");
							if(cnt != 1) {
								totFind = delayFind + rectFind ;
								
								tempbrResp.setTotalFindings(totFind);
								tempbrResp.setRespondedOnTimeFindings(rectFind);
								
								rectList.add(tempbrResp);
								delayFind=0l; rectFind=0l; totFind=0l;
							}	critTypeTemp = critType; tempbrResp = brResp;
								if("DELAY".equalsIgnoreCase(brResp.getRespType())) delayFind =brResp.getObservationCount();
								else if("RESPOND_ONTIME".equalsIgnoreCase(brResp.getRespType())) rectFind =brResp.getObservationCount();
						
						}
						
						if(cnt == entry.getValue().size()) {
							totFind = delayFind + rectFind;
							brResp.setTotalFindings(totFind);
							brResp.setRespondedOnTimeFindings(rectFind);
							
							rectList.add(brResp);
						}
					}finalRespMap.put(entry.getKey(), rectList);
				}	catch(Exception e) {
					e.printStackTrace();
				}
		 }
		
		return finalRespMap;
		
	}

	@Override
	public List<UnitBreakUpResponseDto> getUnitBreakUp(int legalEntityCode, String auditType, String unitType, String period,
			LocalDate fromDate, LocalDate toDate, String role, String userId, String criteria) {
		
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);
        
		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		
		if(!BankAuditUtil.isEmptyString(period)){
			if(period.equalsIgnoreCase("quarterly")){
				
				if(calendar.get(Calendar.MONTH)<=3) {
					fromDate=LocalDate.of(year+1, 1, 1);
					toDate=fromDate.plusMonths(3).minusDays(1);
				}else if(calendar.get(Calendar.MONTH)<=6){
					fromDate=LocalDate.of(year, 4, 1);
					toDate=fromDate.plusMonths(3).minusDays(1);
				}else if(calendar.get(Calendar.MONTH)<=9){
					fromDate=LocalDate.of(year, 7, 1);
				    toDate=fromDate.plusMonths(3).minusDays(1);
				}else if(calendar.get(Calendar.MONTH)<=12){
					fromDate=LocalDate.of(year, 10, 1);
					toDate=fromDate.plusMonths(3).minusDays(1);
				} 
				
				
			}else if (period.equalsIgnoreCase("halfYearly")) {
				
				if(calendar.get(Calendar.MONTH)<=3 || (calendar.get(Calendar.MONTH)>=10 &&  calendar.get(Calendar.MONTH)<=12)) {
					fromDate=LocalDate.of(year, 10, 1);
					toDate=fromDate.plusMonths(6).minusDays(1);
				}else {
					fromDate=LocalDate.of(year, 4, 1);
					toDate=fromDate.plusMonths(6).minusDays(1);
				}	
				
			}else if (period.equalsIgnoreCase("yearly")) {
				
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(12).minusDays(1);
				
			}else if (period.equalsIgnoreCase("range")) {
				
			}else{
				period="";
			}
		}else{
          period="";
		}
		List<UnitBreakUpResponseDto> untsBrkRspDto = null;
			
		if("C".equalsIgnoreCase(criteria) || "U".equalsIgnoreCase(criteria)) {  //C - Classification , U- Unit Type
			untsBrkRspDto= dashboardDao.getUnitBreakUpUnitTypeClassificatioWise( legalEntityCode,  auditType,  unitType,  period, fromDate,  toDate,  role,  userId, criteria);
		}else if("R".equalsIgnoreCase(criteria)) { // R - Revenue Leak
			List<String> unitList= getUnitList(legalEntityCode, role,"user", userId); //To get the list on all Units under the logged in User
			List<String> unitSpecificToAuditList= dashboardDao.getUnitsSpecificToAudit(legalEntityCode, auditType,unitList, "Y"); //To get the filtered list of Units for the specific Audit type
			List<String> auditsList= dashboardDao.getLatestAuditsToUnits(legalEntityCode, auditType,unitSpecificToAuditList,role, "Y"); //To get the list of Latest Audits for the above selected Units, from the Audit schedule table
			logger.info("unitList :: "+unitList.size()+ ":: "+unitList);
			logger.info("unitSpecificToAuditList :: "+unitSpecificToAuditList.size()+ ":: "+unitSpecificToAuditList);
			logger.info("auditsList :: "+auditsList.size()+ ":: "+auditsList);
			
			 untsBrkRspDto= dashboardDao.getUnitBreakUpRevenueWsie( legalEntityCode,  auditType,  unitType,  period, fromDate,  toDate,  role,  userId, criteria, auditsList);
		}else { // CR - Criticality
			untsBrkRspDto= dashboardDao.getUnitBreakUpCriticalityWise( legalEntityCode,  auditType,  unitType,  period, fromDate,  toDate,  role,  userId, criteria);
		}
		
		//return dashboardDao.getUnitBreakUp( legalEntityCode,  auditType,  unitType,  period, fromDate,  toDate,  role,  userId);
		return untsBrkRspDto;
	}
	
	@Override
	public List<PlanCalendarResponseDto> getPlanCalendar(int parseInt) {
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(parseInt);
		logger.info("businessDateTimestamp .."+businessDateTimestamp);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);

		logger.info("calendar .."+calendar +" Mnth.."+calendar.get(Calendar.MONTH)+" .."+Calendar.MONTH +" Yr.."+ Calendar.YEAR);
		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		LocalDate date =LocalDate.of(year, 04, 01);
		
		return dashboardDao.getPlanCalendar(parseInt,date);
	}
	
	@Override
	public Map<String, String> getResourcePlanningAuditorEffort(int legalEntityCode, String auditType, String userId,String role , String unitType, String criticality) {
		
		//List<MaintAuditTypeDesc> auditTypeDescs=maintAuditTypeDescService.getMaintAuditTypeDescByLegalEntityCode(legalEntityCode);
		//List<String> auditTypes=auditTypeDescs.stream().map(MaintAuditTypeDesc :: getAuditTypeCode).collect(Collectors.toList());
		
		Map<String, String> result=new HashMap(); 
		int LEeffortNeeded=0, LEeffortAvailable=0, LENeteffortAvailable=0, effortUtilized =0, totalAuditor =0, auditorNeeded =0;
		
		try {
			Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
			String startDate = BankAuditUtil.parseDateToString(businessDate);
			List<String> auditTypes = dashboardDao.getAuditTypes(legalEntityCode);
			String finYrEndDate = dashboardDao.getFinYrEndDate(legalEntityCode);
			logger.info("businessDate .... "+businessDate+" startDate .."+startDate);
			logger.info("auditTypes .... "+auditTypes+ "finYrEndDate .... "+finYrEndDate);
			Map<String, String> nextPlanStartDateMap =  new HashMap();
			
			
			List<AuditProcessV> auditProcessVlst = null;
			
			/****************************** Logic to Retrieve the Effort Required to perform the remaining Audits, for all Audit Type *******************/
			long startAuditAll= System.currentTimeMillis();
			for(String auditTypeCode : auditTypes) {
				long startAudit= System.currentTimeMillis();
				String nextPlanStartDate = dashboardDao.getNextPlanStartdate(legalEntityCode,auditTypeCode);
				logger.info("nxtPlnStDt .."+ (System.currentTimeMillis()-startAudit) +" auditTypeCode:: "+auditTypeCode+ " nextPlanStartDate ::"+nextPlanStartDate +" finYrEndDate:: "+finYrEndDate);
				
				long startAuditPrcV= System.currentTimeMillis();
				auditProcessVlst=auditProcessVService.getAuditProcessByAuditPlan(legalEntityCode,auditTypeCode,nextPlanStartDate+"T00:00:00.000Z", finYrEndDate+"T00:00:00.000Z",userId+"_RP");
				logger.info("auditProcessVlst .."+ (System.currentTimeMillis()-startAuditPrcV) +"size is "+ auditProcessVlst.size());
				
				long startAuditPrcVItr= System.currentTimeMillis();
				for(AuditProcessV auditProcessV: auditProcessVlst) {
					int unitWiseEffortNeeded =0;
					try{
						unitWiseEffortNeeded= Integer.parseInt(auditProcessV.getDuration().toString()) * Integer.parseInt(auditProcessV.getManDays().toString()); 
					}catch(Exception e) {
						e.printStackTrace();
					}
					LEeffortNeeded += unitWiseEffortNeeded;
				}
				logger.info("startAuditPrcVItr .."+ (System.currentTimeMillis()-startAuditPrcVItr));
				logger.info("LE effort after :: "+ auditTypeCode +" is ::"+ LEeffortNeeded);
				
				nextPlanStartDateMap.put(auditTypeCode, nextPlanStartDate);
			}
			logger.info("auditAll Time :: "+ (System.currentTimeMillis()-startAuditAll));
			/****** Effort Required logic, End Here *********/
			
			
			/************************** Logic to Retrieve the Effort Available (no of working days available for all the Auditor) ****************/
			long effAvl= System.currentTimeMillis();
			List<User> usrLst = dashboardDao.getListofAuditors(legalEntityCode , auditType);
			Map<String, Integer> unitWorkingDaysMap = new HashMap();
			totalAuditor= usrLst.size(); // This is providing the Total number of Auditors available in the LE
			logger.info("Size usrLst .. "+ usrLst.size());
			for(User usr: usrLst){
				if(unitWorkingDaysMap.containsKey(usr.getUnitCode())) LEeffortAvailable += unitWorkingDaysMap.get(usr.getUnitCode());
				else {
					int unitWorkingDays = dashboardDao.getUnitWorkingDays(legalEntityCode , usr.getUnitCode(),startDate,finYrEndDate);
					LEeffortAvailable += unitWorkingDays;
					unitWorkingDaysMap.put(usr.getUnitCode(),unitWorkingDays);
					//logger.info("Unit ::"+ usr.getUnitCode() +" working Days :: "+ unitWorkingDays);
				}
			}
			logger.info("Total Working days ::"+ LEeffortAvailable);
			logger.info("Effort Avbl :: "+ (System.currentTimeMillis()-effAvl));
			/****** Effort Available logic, End Here *********/
			
			/******************* Logic to Retrieve the Effort Utilized for the already scheduled plans (from starting date to NextPlanStartDate of Audit) *****/
			long effUtl= System.currentTimeMillis();
			if(nextPlanStartDateMap != null) {
				effortUtilized = dashboardDao.getEffortUtilized(legalEntityCode ,startDate, nextPlanStartDateMap,finYrEndDate);
			}logger.info("Effort Days utilized ::"+ effortUtilized);
			logger.info("Effort Utlzd :: "+ (System.currentTimeMillis()-effUtl));
			/****** Effort Utilized logic, End Here *********/			
						
			/******************** Logic to Retrieve the Effort Available at Head office, Required if AVIALABLE EFFORT is less the NEEDED EFFORT ********/
			LENeteffortAvailable = LEeffortAvailable - effortUtilized; 
			if(LENeteffortAvailable < LEeffortNeeded) {
				String getHeadOfficeUnitCode = dashboardDao.getHeadOfficeUnitCode(legalEntityCode);
				System.out.println("getHeadOfficeUnitCode .."+ getHeadOfficeUnitCode);
				auditorNeeded = (int)Math.ceil((LEeffortNeeded - LENeteffortAvailable)/ unitWorkingDaysMap.get(getHeadOfficeUnitCode));
			}		
			logger.info("Total Effor Resource Planning :: "+ (System.currentTimeMillis()- startAuditAll));
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		result.put("EFFORT_AVAILABLE", LENeteffortAvailable+"");
		result.put("EFFORT_NEEDED", LEeffortNeeded+"");
		result.put("AUDITOR_AVAILABLE", totalAuditor+"");
		result.put("AUDITOR_NEEDED", auditorNeeded+"");
		
		return result;
	}
	
	public Map<String, LocalDate> getFromToDates(int legalEntityCode, String period) {
		
		LocalDate fromDate=null, toDate=null;
		Map<String, LocalDate> map = new HashMap();
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);
		
        
		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		if(!BankAuditUtil.isEmptyString(period)){
			if(period.equalsIgnoreCase("quarterly")){
				if(calendar.get(Calendar.MONTH)<=3) {
					fromDate=LocalDate.of(year+1, 1, 1);
					toDate=fromDate.plusMonths(3).minusDays(1);
				}else if(calendar.get(Calendar.MONTH)<=6){
					fromDate=LocalDate.of(year, 4, 1);
					toDate=fromDate.plusMonths(3).minusDays(1);
				}else if(calendar.get(Calendar.MONTH)<=9){
					fromDate=LocalDate.of(year, 7, 1);
				    toDate=fromDate.plusMonths(3).minusDays(1);
				}else if(calendar.get(Calendar.MONTH)<=12){
					fromDate=LocalDate.of(year, 10, 1);
					toDate=fromDate.plusMonths(3).minusDays(1);
				} 
			}else if (period.equalsIgnoreCase("halfYearly")) {
				if(calendar.get(Calendar.MONTH)<=3 || (calendar.get(Calendar.MONTH)>=10 &&  calendar.get(Calendar.MONTH)<=12)) {
					fromDate=LocalDate.of(year, 10, 1);
					toDate=fromDate.plusMonths(6).minusDays(1);
				}else {
					fromDate=LocalDate.of(year, 4, 1);
					toDate=fromDate.plusMonths(6).minusDays(1);
				}	
			}else if (period.equalsIgnoreCase("yearly")) {
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(12).minusDays(1);
			}else if (period.equalsIgnoreCase("range")) {
				
			}
			map.put("fromDate", fromDate);
			map.put("toDate", toDate);
		}
		return map;
	}
	
	
	@Override
	public List<AuditSchedule> getAuditSummary(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, String unitType, String criticality) {
		
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		List<String> unitList = null;
		if(role != "BU") unitList=getUnitList(legalEntityCode, role,"user", userId);
		
		return dashboardDao.getAuditSummary( legalEntityCode,  auditType,  period,
				 fromDate,  toDate,  userId,role, unitList,  unitType, criticality);
	}
	
	@Override
	public List<BranchPerformanceBUResponse> getBranchPerformanceRectification(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, String criticality) {
		
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);

		Integer year=null;
		try {
			if( calendar.get(Calendar.MONTH)>=4){
				year=calendar.get(Calendar.YEAR);
			}else{
				year=calendar.get(Calendar.YEAR)-1;
			}
			
			
			if(period.equalsIgnoreCase("quarterly")){
				
				if(calendar.get(Calendar.MONTH)<=3) {
					fromDate=LocalDate.of(year+1, 1, 1);
					toDate=fromDate.plusMonths(3).minusDays(1);
				}else if(calendar.get(Calendar.MONTH)<=6){
					fromDate=LocalDate.of(year, 4, 1);
					toDate=fromDate.plusMonths(3).minusDays(1);
				}else if(calendar.get(Calendar.MONTH)<=9){
					fromDate=LocalDate.of(year, 7, 1);
				    toDate=fromDate.plusMonths(3).minusDays(1);
				}else if(calendar.get(Calendar.MONTH)<=12){
					fromDate=LocalDate.of(year, 10, 1);
					toDate=fromDate.plusMonths(3).minusDays(1);
				} 
			}else if (period.equalsIgnoreCase("halfYearly")) {
				
				if(calendar.get(Calendar.MONTH)<=3 || (calendar.get(Calendar.MONTH)>=10 &&  calendar.get(Calendar.MONTH)<=12)) {
					fromDate=LocalDate.of(year, 10, 1);
					toDate=fromDate.plusMonths(6).minusDays(1);
				}else {
					fromDate=LocalDate.of(year, 4, 1);
					toDate=fromDate.plusMonths(6).minusDays(1);
				}	
			}else if (period.equalsIgnoreCase("yearly")) {
				
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(12).minusDays(1);
			}else if (period.equalsIgnoreCase("ytd")) {
				
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(12).minusDays(1);
				
			}else if (period.equalsIgnoreCase("range")) {
				
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		
		List<BranchPerformanceBUResponse> list=dashboardDao.getBranchPerformanceRectification(legalEntityCode, auditType,	period, fromDate, toDate, userId, role,	criticality);
		List<BranchPerformanceBUResponse> rectList=new ArrayList<BranchPerformanceBUResponse>();
		
		try {
			System.out.println("Before calling DAO getBranchPerformanceRectification()........"+ list.size()); int cnt=0;
			String critType=null; String critTypeTemp=null; String respType=null; Long totFind=0l; Long rectFind=0l; Long delayFind=0l;
			BranchPerformanceBUResponse tempbrResp=null;
			for (BranchPerformanceBUResponse brResp : list) {
				critType= brResp.getCriticality();cnt++;
				System.out.println("recNo:::::::::::::::::::::::::::::::::::::::"+cnt +"critType .."+critType+"  type ::" +brResp.getRespType());
				
				if(critType.equalsIgnoreCase(critTypeTemp)){
					System.out.println("Inside If");
					if("DELAY".equalsIgnoreCase(brResp.getRespType())) delayFind =brResp.getObservationCount();
					else if("RECTIFIED".equalsIgnoreCase(brResp.getRespType())) rectFind =brResp.getObservationCount();
					
				}else {
					System.out.println("Inside else");
					if(cnt != 1) {
						totFind = delayFind + rectFind ;
						
						tempbrResp.setTotalFindings(totFind);
						tempbrResp.setRectifiedFindings(rectFind);
						
						rectList.add(tempbrResp);
						delayFind=0l; rectFind=0l; totFind=0l;
					}	critTypeTemp = critType; tempbrResp = brResp;
						if("DELAY".equalsIgnoreCase(brResp.getRespType())) delayFind =brResp.getObservationCount();
						else if("RECTIFIED".equalsIgnoreCase(brResp.getRespType())) rectFind =brResp.getObservationCount();
				
				}
				
				if(cnt == list.size()) {
					totFind = delayFind + rectFind;
					brResp.setTotalFindings(totFind);
					brResp.setRectifiedFindings(rectFind);
					
					rectList.add(brResp);
				}
			}
		}	catch(Exception e) {
			e.printStackTrace();
		}
		 return rectList;
	
	}
	
	@Override
	public List<Map<String, List<Map<String,Long>>>> getRatingTrend(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, String unitType, String criticality) {
		Map<String,LocalDate> mapDt =null;
		
		Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		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
		
		
		List<String> unitList= getUnitList(legalEntityCode, role,"user", userId); //To get the list on all Units under the logged in User
		List<String> unitSpecificToAuditList= dashboardDao.getUnitsSpecificToAudit(legalEntityCode, auditType,unitList, "Y"); //To get the filtered list of Units for the specific Audit type
		logger.info("unitList :: "+unitList.size()+ ":: "+unitList);
		logger.info("unitSpecificToAuditList :: "+unitSpecificToAuditList.size()+ ":: "+unitSpecificToAuditList);
		
		
		List<Map<String, List<Map<String,Long>>>>  lst= new ArrayList();
		List<Map<String,Long>> ratingCountByDateList =null;
		Map<String, Long> ratingMapTemp =null;
		if(period.equalsIgnoreCase("quarterly")){
			
		  /*PREVIOUS YEAR quarters*/
			LocalDate previousFinancialYearQ1StartDate = LocalDate.of(previousYear, 04, 1);
				
			LocalDate dateCompare =previousFinancialYearQ1StartDate.minusDays(1);
			int qtrCnt=0; String qtr=null;
			Map ratingQtrMap = null;
			do {
				dateCompare= dateCompare.plusMonths(3);
				logger.info("dateCompare :: "+qtrCnt+" :: "+ dateCompare);
				List<String> UnitsOpenByDateList= dashboardDao.getUnitsOpenByDateList(legalEntityCode, auditType, unitSpecificToAuditList,dateCompare);
				if(UnitsOpenByDateList != null && UnitsOpenByDateList.size() > 0) {
					List<String> auditsList= dashboardDao.getLatestByDateAuditsToUnits(legalEntityCode, auditType,UnitsOpenByDateList,role, "Y",dateCompare); //To get the list of Latest Audits for the above selected Units, from the Audit schedule table
					if(auditsList != null && auditsList.size() > 0) {
						ratingCountByDateList= dashboardDao.getRatingCountByDateForTrend(legalEntityCode,  auditType, role, UnitsOpenByDateList, auditsList,  unitType, criticality);
					}else {
						ratingCountByDateList = new ArrayList();
						ratingMapTemp = new HashMap();
						ratingMapTemp.put("U-UnRated",Long.parseLong(String.valueOf(UnitsOpenByDateList.size())));
						ratingCountByDateList.add(ratingMapTemp);
					}
				}else {
					ratingCountByDateList = new ArrayList();
					ratingMapTemp = new HashMap();
					ratingMapTemp.put("U-UnRated",0l);
					ratingCountByDateList.add(ratingMapTemp);
				}
				qtrCnt++;
				
				qtr=(qtrCnt == 1 ? "PREV_Q1":qtrCnt == 2 ? "PREV_Q2":qtrCnt == 3 ? "PREV_Q3":qtrCnt == 4 ? "PREV_Q4":qtrCnt == 5 ? "CUR_Q1":qtrCnt == 6 ? "CUR_Q2":qtrCnt == 7 ? "CUR_Q3":"CUR_Q4");
				ratingQtrMap = new HashMap<String, List<Map<String,Long>>>();
				ratingQtrMap.put(qtr,ratingCountByDateList);
				lst.add(ratingQtrMap);
			}while(bsnsDateLcl.compareTo(dateCompare) >= 0 && qtrCnt < 8 );
			logger.info("Quarterly lst :: "+lst);		
		}else if(period.equalsIgnoreCase("halfYearly")){
			LocalDate previousFinancialYearH1StartDate = LocalDate.of(previousYear, 04, 1);
					
			LocalDate dateCompare =previousFinancialYearH1StartDate.minusDays(1);
			int hlfYrCnt=0; String hlfYr=null;
			Map ratingHlfYrMap = null;
			do {
				dateCompare= dateCompare.plusMonths(6);
				logger.info("dateCompare :: "+hlfYrCnt+" :: "+ dateCompare);
				List<String> UnitsOpenByDateList= dashboardDao.getUnitsOpenByDateList(legalEntityCode, auditType, unitSpecificToAuditList,dateCompare);
				if(UnitsOpenByDateList != null && UnitsOpenByDateList.size() > 0) {
					List<String> auditsList= dashboardDao.getLatestByDateAuditsToUnits(legalEntityCode, auditType,UnitsOpenByDateList,role, "Y",dateCompare); //To get the list of Latest Audits for the above selected Units, from the Audit schedule table
					if(auditsList != null && auditsList.size() > 0) {
						ratingCountByDateList= dashboardDao.getRatingCountByDateForTrend(legalEntityCode,  auditType, role, UnitsOpenByDateList, auditsList,  unitType, criticality);
					}else {
						ratingCountByDateList = new ArrayList();
						ratingMapTemp = new HashMap();
						ratingMapTemp.put("U-UnRated",Long.parseLong(String.valueOf(UnitsOpenByDateList.size())));
						ratingCountByDateList.add(ratingMapTemp);
					}
				}else {
					ratingCountByDateList = new ArrayList();
					ratingMapTemp = new HashMap();
					ratingMapTemp.put("U-UnRated",0l);
					ratingCountByDateList.add(ratingMapTemp);
				}
				hlfYrCnt++;
				
				hlfYr=(hlfYrCnt == 1 ? "PREV_FIRST_HF":hlfYrCnt == 2 ? "PREV_SECOND_HF":hlfYrCnt == 3 ? "CUR_FIRST_HF":"CUR_SECOND_HF");
				ratingHlfYrMap = new HashMap<String, List<Map<String,Long>>>();
				ratingHlfYrMap.put(hlfYr,ratingCountByDateList);
				lst.add(ratingHlfYrMap);
			}while(bsnsDateLcl.compareTo(dateCompare) >= 0 && hlfYrCnt < 4 );
				logger.info("Hal Yearly lst :: "+lst);		
		}else if(period.equalsIgnoreCase("yearly")){
			LocalDate previousFinancialYearStartDate = LocalDate.of(previousYear, 04, 1);
				
			LocalDate dateCompare =previousFinancialYearStartDate.minusDays(1);
			int yrCnt=0; String yr=null;
			Map ratingYrMap = null;
			logger.info("Yearly .. previousFinancialYearStartDate "+ previousFinancialYearStartDate + " dateCompare .. "+dateCompare);
			do {
				dateCompare= dateCompare.plusMonths(12);
				logger.info("dateCompare :: "+yrCnt+" :: "+ dateCompare);
				List<String> UnitsOpenByDateList= dashboardDao.getUnitsOpenByDateList(legalEntityCode, auditType, unitSpecificToAuditList,dateCompare);
				if(UnitsOpenByDateList != null && UnitsOpenByDateList.size() > 0) {
					List<String> auditsList= dashboardDao.getLatestByDateAuditsToUnits(legalEntityCode, auditType,UnitsOpenByDateList,role, "Y",dateCompare); //To get the list of Latest Audits for the above selected Units, from the Audit schedule table
					if(auditsList != null && auditsList.size() > 0) {
						ratingCountByDateList= dashboardDao.getRatingCountByDateForTrend(legalEntityCode,  auditType, role, UnitsOpenByDateList, auditsList,  unitType, criticality);
					}else {
						ratingCountByDateList = new ArrayList();
						ratingMapTemp = new HashMap();
						ratingMapTemp.put("U-UnRated",Long.parseLong(String.valueOf(UnitsOpenByDateList.size())));
						ratingCountByDateList.add(ratingMapTemp);
					}
				}else {
					ratingCountByDateList = new ArrayList();
					ratingMapTemp = new HashMap();
					ratingMapTemp.put("U-UnRated",0l);
					ratingCountByDateList.add(ratingMapTemp);
				}
				yrCnt++;
				
				yr=(yrCnt == 1 ? "PREV_YR":"CUR_YR");
				ratingYrMap = new HashMap<String, List<Map<String,Long>>>();
				ratingYrMap.put(yr,ratingCountByDateList);
				lst.add(ratingYrMap);
			}while(bsnsDateLcl.compareTo(dateCompare) >= 0 && yrCnt < 2 );
			logger.info("Yearly lst :: "+lst);		
		}else if(period.equalsIgnoreCase("range")){
			Map ratingYrMap = null;
			List<String> auditsList = null;
			logger.info("dateCompare :: "+fromDate+" :: "+ toDate);
			
			/********************** To get the details as on From date *******************************************/
			List<String> UnitsOpenByDateList= dashboardDao.getUnitsOpenByDateList(legalEntityCode, auditType, unitSpecificToAuditList,fromDate);
			if(UnitsOpenByDateList != null && UnitsOpenByDateList.size() > 0) {
				auditsList= dashboardDao.getLatestByDateAuditsToUnits(legalEntityCode, auditType,UnitsOpenByDateList,role, "Y",fromDate); //To get the list of Latest Audits for the above selected Units, from the Audit schedule table
				if(auditsList != null && auditsList.size() > 0) {
					ratingCountByDateList= dashboardDao.getRatingCountByDateForTrend(legalEntityCode,  auditType, role, UnitsOpenByDateList, auditsList,  unitType, criticality);
				}else {
					ratingCountByDateList = new ArrayList();
					ratingMapTemp = new HashMap();
					ratingMapTemp.put("U-UnRated",Long.parseLong(String.valueOf(UnitsOpenByDateList.size())));
					ratingCountByDateList.add(ratingMapTemp);
				}
			}else {
				ratingCountByDateList = new ArrayList();
				ratingMapTemp = new HashMap();
				ratingMapTemp.put("U-UnRated",0l);
				ratingCountByDateList.add(ratingMapTemp);
			}
			
			
			ratingYrMap = new HashMap<String, List<Map<String,Long>>>();
			ratingYrMap.put(fromDate,ratingCountByDateList);
			lst.add(ratingYrMap);
			
			/********************** To get the details as on To date *******************************************/
			UnitsOpenByDateList= dashboardDao.getUnitsOpenByDateList(legalEntityCode, auditType, unitSpecificToAuditList,toDate);
			if(UnitsOpenByDateList != null && UnitsOpenByDateList.size() > 0) {
				auditsList= dashboardDao.getLatestByDateAuditsToUnits(legalEntityCode, auditType,UnitsOpenByDateList,role, "Y",toDate); //To get the list of Latest Audits for the above selected Units, from the Audit schedule table
				if(auditsList != null && auditsList.size() > 0) {
					ratingCountByDateList= dashboardDao.getRatingCountByDateForTrend(legalEntityCode,  auditType, role, UnitsOpenByDateList, auditsList,  unitType, criticality);
				}else {
					ratingCountByDateList = new ArrayList();
					ratingMapTemp = new HashMap();
					ratingMapTemp.put("U-UnRated",Long.parseLong(String.valueOf(UnitsOpenByDateList.size())));
					ratingCountByDateList.add(ratingMapTemp);
				}
			}else {
				ratingCountByDateList = new ArrayList();
				ratingMapTemp = new HashMap();
				ratingMapTemp.put("U-UnRated",0l);
				ratingCountByDateList.add(ratingMapTemp);
			}
			
			ratingYrMap = new HashMap<String, List<Map<String,Long>>>();
			ratingYrMap.put(toDate,ratingCountByDateList);
			lst.add(ratingYrMap);
			
			logger.info("Range lst :: "+lst);		
		}
		return lst;
	}
	
	public List<Map<String, Map<String,Long>>> getRatingTrendOld(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, String unitType, String criticality) {
		Map<String,LocalDate> mapDt =null;
		
		/*if(!BankAuditUtil.isEmptyString(period) && !period.equalsIgnoreCase("range")){
			DashboardServiceImpl dSrvImpl = new DashboardServiceImpl();
			mapDt =dSrvImpl.getFromToDates(legalEntityCode, period);
			fromDate = mapDt.get("fromDate");
			toDate = mapDt.get("toDate");
		}*/
		List<String> unitList=getUnitList(legalEntityCode, role,"user", userId);
		Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		List<Map<String, Map<String,Long>>>  lst=null;
		if(period.equalsIgnoreCase("quarterly")){
			 lst=dashboardDao.getRatingTrendQuarterly( legalEntityCode,  auditType,  period,
					 fromDate,  toDate,  userId,role,unitList,  unitType, criticality,businessDate);
		}else if (period.equalsIgnoreCase("halfYearly")) {
			 lst=dashboardDao.getRatingTrendHalfYearly( legalEntityCode,  auditType,  period,
					 fromDate,  toDate,  userId,role,unitList,  unitType, criticality,businessDate);
		}else if (period.equalsIgnoreCase("yearly")) {
			 lst=dashboardDao.getRatingTrendYearly( legalEntityCode,  auditType,  period,
					 fromDate,  toDate,  userId,role,unitList,  unitType, criticality,businessDate);
		}else if (period.equalsIgnoreCase("range")) {
			 lst=dashboardDao.getRatingTrendQuarterly( legalEntityCode,  auditType,  period,
					 fromDate,  toDate,  userId,role,unitList,  unitType, criticality,businessDate);
		}
		
		return lst;
	}
	
	@Override
	public Map<String,Integer> getUserDtlsforAdminDB(int legalEntityCode,String userId,String role) {
		Map<String, Integer> userSummaryMap = null;
		try {
			Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
			userSummaryMap =dashboardDao.getUserDtlsforAdminDB( legalEntityCode, userId,role, businessDate);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return userSummaryMap;
	}
	
	@Override
	public List<MaintUsergroupRoles> getRolewiseUsersCount(int legalEntityCode,String userId,String role) {
		List<MaintUsergroupRoles> listUserRoles = null;
		try {
			listUserRoles =dashboardDao.getRolewiseUsersCount( legalEntityCode, userId,role);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return listUserRoles;
	}
	
	@Override
	public Map<String,String> getAuditSummaryTrgtWtchlstTotal(int legalEntityCode,String userOrUnitCode,String type,String auditTypeCode) {
		
		Map<String,String> auditSummaryBoxMap = new HashMap<String,String>();
		List<String> unitsList = null;
  		String unitsListToConcatinatedString="";
  		List<MaintAuditTypeDesc> matdes= null;
		
  		try {
  				long start =System.currentTimeMillis();
  				Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
				logger.info("getAuditSummaryTrgtWtchlstTotal ...."+ legalEntityCode +" userOrUnitCode.... "+userOrUnitCode +" type...."+type+" auditTypeCode...."+auditTypeCode);
			//To get the List of Audit types
				long start1= System.currentTimeMillis();
				if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
					matdes = new ArrayList<MaintAuditTypeDesc>();
					matdes.add(maintAuditTypeDescService.getMaintAuditTypeDesc(legalEntityCode, auditTypeCode));
				}else {	
					matdes=maintAuditTypeDescService.getMaintAuditTypeDescByLegalEntityCode(legalEntityCode);
				}logger.info("matdes .."+ matdes);
				logger.info("=============================> getAuditNames Time taken "+ (System.currentTimeMillis() -start1));
			//End here
				
			//To get the List of Units, Jurisdictions wise
				long start2= System.currentTimeMillis();
				unitsList=maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode,"user",userOrUnitCode);
  				logger.info("unitsList .."+ unitsList);
  				logger.info("=============================> getJurisdictionUnits Time taken "+ (System.currentTimeMillis() -start2));
  			
  				long start21= System.currentTimeMillis();
  				if(unitsList!=null&&!unitsList.isEmpty()){ 
  					for (String unitId : unitsList) {
  						if(unitsListToConcatinatedString.length()==0) 
  							unitsListToConcatinatedString="'"+unitId+"'";	
  						unitsListToConcatinatedString+=",'"+unitId+"'";	
  					}
  				logger.info("unitsListToConcatinatedString .."+ unitsListToConcatinatedString);
  				logger.info("=============================> unitsListToConcatinatedString Time taken "+ (System.currentTimeMillis() -start21));	
  				//End here
  					
  				//To get the Count of Units Eligible for Auditing
  					long start31= System.currentTimeMillis();
  					Long allAuditUnits = auditProcessVService.getAllOperationAuditUnits(legalEntityCode,auditTypeCode, unitsListToConcatinatedString);
  	  				Long auditUnits = auditProcessVService.getOperationAuditUnits(legalEntityCode,auditTypeCode, unitsListToConcatinatedString);
  	  				logger.info("allAuditUnits .."+ allAuditUnits);
  	  				logger.info("auditUnits .."+ auditUnits);
  	  			logger.info("=============================> allAuditUnits Time taken "+ (System.currentTimeMillis() -start31));
  					
  	  			//To get the Financial Year details & Convert it into YYYY-MM-DD format
  	  				String curFinancialStartDate=null;
					String curFinancialEndDate=null;
					@SuppressWarnings("rawtypes")
  					Map currFinYrMap=null;

  					String planed = null;
  					String closed = null;	
  					String inProcess = null;
  	  				currFinYrMap=auditProcessVService.financialYearDates(legalEntityCode);
  					logger.info("financialYearDates .."+ currFinYrMap);
  					
  					curFinancialStartDate = (String)currFinYrMap.get("startDate")+"T00:00:00.000Z";
  					curFinancialEndDate =  (String)currFinYrMap.get("endDate")+"T00:00:00.000Z";
  					logger.info("financialYear start date : --> "+curFinancialStartDate +"financialYear end date: --> "+curFinancialEndDate);
  					
  					Date psDate = BankAuditUtil.parseDateTime(curFinancialStartDate);
  					Date peDate = BankAuditUtil.parseDateTime(curFinancialEndDate);
  					
  					String startDate = BankAuditUtil.parseDateToString(psDate);
  					String enDate = BankAuditUtil.parseDateToString(peDate); 
  					logger.info("plnStDate .. "+startDate +" plnEnDate .. "+enDate);
  				//Year formating ends here
  					
  				//To get the Target Audits for the Current Financial Year
  					long start5 = System.currentTimeMillis();
  					Map targetUnitAuditsUnitMap=dashboardDao.getTargetUnitAuditsUnitCount(legalEntityCode,unitsListToConcatinatedString,auditTypeCode,startDate,enDate);  
  					logger.info("targetUnits : --> "+targetUnitAuditsUnitMap);
  					logger.info("=======================>targetUnitAuditsUnitMap Time taken of "+ (System.currentTimeMillis() - start5));

  				//To get the Audit Details for the Current Financial Year
  					long start6 = System.currentTimeMillis();
  					Map mp = new HashMap();
  					if(unitsListToConcatinatedString!=null && unitsListToConcatinatedString.length()>0)
  					{
  						mp=auditProcessVService.jurisdictionByShedule(legalEntityCode,unitsListToConcatinatedString,auditTypeCode,startDate,enDate);
  						if(mp!=null && !mp.isEmpty()) {
  							planed =(String)mp.get("planed");
  							closed =  (String)mp.get("closed");
  							inProcess =  (String)mp.get("inProcess");
  						}
  					}
  					logger.info("Audit status count : --> "+mp);
  					logger.info("=======================>PlanDtls Time taken of "+ (System.currentTimeMillis() - start6));
  				//End here
  	  			
  				//To get the Watch List details for the Current Financial Year
  					long start7= System.currentTimeMillis();
  					int watchListCount = dashboardDao.getWatchListForAudits(legalEntityCode,auditTypeCode,startDate);
  					//String watchListCount ="0";
  					logger.info("watchListCount .... "+watchListCount);
  					logger.info("=======================>watchListCount Time taken of "+ (System.currentTimeMillis() - start7));
  				//End Here
  					
  					auditSummaryBoxMap.put("audits",((matdes!=null && !matdes.isEmpty())?matdes.size()+"":null));
  					auditSummaryBoxMap.put("NoOfAllUnits",allAuditUnits+"");  					
  					auditSummaryBoxMap.put("NoOfUnits", auditUnits+"");
  					auditSummaryBoxMap.put("target", targetUnitAuditsUnitMap.get("TARGET_AUDITS")+"");
  					auditSummaryBoxMap.put("planed", planed);
  					auditSummaryBoxMap.put("closed", closed);
  					auditSummaryBoxMap.put("inProcess", inProcess);
  					auditSummaryBoxMap.put("watchList", watchListCount+"");
  					
  					logger.info("=========================================> total time taken "+ (System.currentTimeMillis()-start));
  				}
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		return auditSummaryBoxMap;
	}
	
	//******************** for Audit Closure status **********************************//
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, HashMap<String, Long>> getAuditClosureStatus(Integer legalEntityCode, String auditType, String unitType,
			String criticality, String period, LocalDate fromDate, LocalDate toDate, String userId,String role) {

		Map<String,  HashMap<String, Long>> auditStatusResult=new HashMap<String ,  HashMap<String, Long>>();
		HashMap<String, Long> childMap=null;
        List<String> unitList=getUnitList(legalEntityCode, role,"user", userId);
		Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		List<AuditStatusGraphResponseDto> auditStatusGraphResponseDtos=null;
		if(period.equalsIgnoreCase("quarterly")){
			 auditStatusGraphResponseDtos=dashboardDao.getAuditClosureStatusQuarterly( legalEntityCode,  auditType,  unitType,
					 criticality,  userId,businessDate,role,unitList);
			
		}else if (period.equalsIgnoreCase("halfYearly")) {
			 auditStatusGraphResponseDtos=dashboardDao.getAuditClosureStatusHalfYearly( legalEntityCode,  auditType,  unitType,
					 criticality,  userId,businessDate,role,unitList);
			
		}else if (period.equalsIgnoreCase("yearly")) {
			 auditStatusGraphResponseDtos=dashboardDao.getAuditClosureStatusYearly( legalEntityCode,  auditType,  unitType,
					 criticality,  userId,businessDate,role,unitList);
			
		}else if (period.equalsIgnoreCase("range")) {
			 auditStatusGraphResponseDtos=dashboardDao.getAuditClosureStatusByRange( legalEntityCode,  auditType,  unitType,
					 criticality,  userId, fromDate,  toDate,role,unitList);
			
		}
		
		for (AuditStatusGraphResponseDto auditStatusGraphResponseDto : auditStatusGraphResponseDtos) {
			
			if(auditStatusResult.containsKey(auditStatusGraphResponseDto.getYtd())){
				 childMap=auditStatusResult.get(auditStatusGraphResponseDto.getYtd());
				if(childMap.containsKey(auditStatusGraphResponseDto.getAuditStatus())){
					Long childMapValue=childMap.get(auditStatusGraphResponseDto.getAuditStatus());
					childMap.put(auditStatusGraphResponseDto.getAuditStatus(), childMapValue+auditStatusGraphResponseDto.getCount());
					
				}else{
					/*childMap=new HashMap<String,Long>();*/
					childMap.put(auditStatusGraphResponseDto.getAuditStatus(), auditStatusGraphResponseDto.getCount());
					
					
					// if not contain the child  , create new and store 
				}
			}else {
				childMap=new HashMap<String,Long>();
				childMap.put(auditStatusGraphResponseDto.getAuditStatus(), auditStatusGraphResponseDto.getCount());
				auditStatusResult.put(auditStatusGraphResponseDto.getYtd(), childMap);
			}
		}
		
		System.out.println("auditStatusResult .... "+ auditStatusResult);
		
		for(String key:auditStatusResult.keySet()){
			Long days30 =0L, days60 =0L, days90=0L, days120=0L, days150=0L,days180=0L, days180Plus=0L, total=0L;
			//System.out.println("key is .... "+ key);
			HashMap<String, Long>  map1=auditStatusResult.get(key);
			
			if(map1.containsKey("30")) days30= map1.get("30"); else map1.put("30",0L);
			if(map1.containsKey("60")) days60= map1.get("60"); else map1.put("60",0L);
			if(map1.containsKey("90")) days90= map1.get("90"); else map1.put("90",0L);
			if(map1.containsKey("120")) days120= map1.get("120"); else map1.put("120",0L);
			if(map1.containsKey("150")) days150= map1.get("150"); else map1.put("150",0L);
			if(map1.containsKey("180")) days180= map1.get("180"); else map1.put("180",0L);
			if(map1.containsKey("180 and above")) days180Plus= map1.get("180 and above"); else map1.put("180 and above",0L);
			
			System.out.println("days30 .."+ days30+" days60 .."+days60 +" days150.."+days150);
			total =days30+days60+days90+days120+days150+days180+days180Plus; // TotalPlan = Sum of ( Planned + Initiated + Submitted + Responded + Closed )
			System.out.println("total .."+ total);
			map1.put("total",total );
			
			
			/*total =planned+initiated+submitted+responded+closed; // TotalPlan = Sum of ( Planned + Initiated + Submitted + Responded + Closed )
			map1.put("planned",total );
			if(! ("SM".equalsIgnoreCase(role) || "OPS".equalsIgnoreCase(role)) ) {
				map1.put("submitted",submitted + responded + closed  );  // Apart from SeniorManager & Operations we are 
				map1.remove("responded");
				map1.remove("closed");
			}*/
			
			/*if(map1.containsKey("planned")){
				if(map1.containsKey("submitted")){
					map1.put("planned", map1.get("planned")+map1.get("submitted"));
				}
			}else{
				if(map1.containsKey("submitted")){
					map1.put("planned",map1.get("submitted"));
				}
			}*/
			
		}
		/*Map<String,HashMap<String, Long>> sorted1=new TreeMap<>(auditStatusResult);*/
		Map<String,HashMap<String, Long>> sorted2=new TreeMap<>(new AuditStatusComparator());
		sorted2.putAll(auditStatusResult);
		
		return sorted2;
	}
	
	
	//*********************** for Audit Closure status, Method to delete , Temp/ Demo purpose ******//
	@SuppressWarnings("unchecked")
	@Override
	public List<List> getAuditClosureStatusTmp(Integer legalEntityCode, String auditType, String unitType,
			String criticality, String period, LocalDate fromDate, LocalDate toDate, String userId,String role) {

		//Map<String,  HashMap<String, Long>> auditStatusResult=new HashMap<String ,  HashMap<String, Long>>();
		//HashMap<String, Long> childMap=null;
        List<String> unitList=getUnitList(legalEntityCode, role,"user", userId);
		Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		//List<AuditStatusGraphResponseDto> auditStatusGraphResponseDtos=null;
		/*if(period.equalsIgnoreCase("quarterly")){
			 auditStatusGraphResponseDtos=dashboardDao.getAuditStatusQuarterly( legalEntityCode,  auditType,  unitType,
					 criticality,  userId,businessDate,role,unitList);
			
		}else if (period.equalsIgnoreCase("halfYearly")) {
			 auditStatusGraphResponseDtos=dashboardDao.getAuditStatusHalfYearly( legalEntityCode,  auditType,  unitType,
					 criticality,  userId,businessDate,role,unitList);
			
		}else if (period.equalsIgnoreCase("yearly")) {
			 auditStatusGraphResponseDtos=dashboardDao.getAuditClosureStatusYearly( legalEntityCode,  auditType,  unitType,
					 criticality,  userId,businessDate,role,unitList);
			
		}else if (period.equalsIgnoreCase("range")) {
			 auditStatusGraphResponseDtos=dashboardDao.getAuditStatusByRange( legalEntityCode,  auditType,  unitType,
					 criticality,  userId, fromDate,  toDate,role,unitList);
			
		}
		
		for (AuditStatusGraphResponseDto auditStatusGraphResponseDto : auditStatusGraphResponseDtos) {
			
			if(auditStatusResult.containsKey(auditStatusGraphResponseDto.getYtd())){
				 childMap=auditStatusResult.get(auditStatusGraphResponseDto.getYtd());
				if(childMap.containsKey(auditStatusGraphResponseDto.getAuditStatus())){
					Long childMapValue=childMap.get(auditStatusGraphResponseDto.getAuditStatus());
					childMap.put(auditStatusGraphResponseDto.getAuditStatus(), childMapValue+auditStatusGraphResponseDto.getCount());
					
				}else{
					childMap.put(auditStatusGraphResponseDto.getAuditStatus(), auditStatusGraphResponseDto.getCount());
					
					
					// if not contain the child  , create new and store 
				}
			}else {
				childMap=new HashMap<String,Long>();
				childMap.put(auditStatusGraphResponseDto.getAuditStatus(), auditStatusGraphResponseDto.getCount());
				auditStatusResult.put(auditStatusGraphResponseDto.getYtd(), childMap);
			}
		}
		
		System.out.println("auditStatusResult .... "+ auditStatusResult);
		
		for(String key:auditStatusResult.keySet()){
			Long planned =0L, initiated =0L, submitted=0L, responded=0L, closed=0L, total=0L;
			//System.out.println("key is .... "+ key);
			HashMap<String, Long>  map1=auditStatusResult.get(key);
			
			if(map1.containsKey("planned")) planned= map1.get("planned");
			if(map1.containsKey("initiated")) initiated= map1.get("initiated");
			if(map1.containsKey("submitted")) submitted= map1.get("submitted");
			if(map1.containsKey("responded")) responded= map1.get("responded");
			if(map1.containsKey("closed")) closed= map1.get("closed");
			
			System.out.println("planned .."+ planned+" initiated .."+initiated +" submitted.."+submitted);
			total =planned+initiated+submitted+responded+closed; // TotalPlan = Sum of ( Planned + Initiated + Submitted + Responded + Closed )
			System.out.println("total .."+ total);
			map1.put("total",total );
			if(! ("SM".equalsIgnoreCase(role) || "OPS".equalsIgnoreCase(role)) ) {
				map1.put("submitted",submitted + responded + closed  );  // Apart from SeniorManager & Operations we are 
				map1.remove("responded");
				map1.remove("closed");
			}
			*/
			
		/*
		 *total =planned+initiated+submitted+responded+closed; // TotalPlan = Sum of ( Planned + Initiated + Submitted + Responded + Closed )
			map1.put("planned",total );
			if(! ("SM".equalsIgnoreCase(role) || "OPS".equalsIgnoreCase(role)) ) {
				map1.put("submitted",submitted + responded + closed  );  // Apart from SeniorManager & Operations we are 
				map1.remove("responded");
				map1.remove("closed");
			}*/
			
			/*if(map1.containsKey("planned")){
				if(map1.containsKey("submitted")){
					map1.put("planned", map1.get("planned")+map1.get("submitted"));
				}
			}else{
				if(map1.containsKey("submitted")){
					map1.put("planned",map1.get("submitted"));
				}
			}*/
			
		//}
		/*Map<String,HashMap<String, Long>> sorted1=new TreeMap<>(auditStatusResult);*/
		//Map<String,HashMap<String, Long>> sorted2=new TreeMap<>(new AuditStatusComparator());
		//sorted2.putAll(auditStatusResult);
		
		//return sorted2;
		List<List> clsrLst = new ArrayList();
		clsrLst=dashboardDao.getAuditClosureStatusYearlyTmp( legalEntityCode,  auditType,  unitType,
				 criticality,  userId,businessDate,role,unitList);
		
		return clsrLst;
	}
	
	
	/****************************************************************************************************************************
	 **************************************         DASHBOARDS FOR RCSA NABARD           ****************************************
	 ****************************************************************************************************************************/
	
	@Override
	public Map<String,String> getAssessmentSummaryDtls(int legalEntityCode,String userId,String unitId,String role, String auditTypeCode) {
		
		Map<String,String> auditSummaryBoxMap = new HashMap<String,String>();
		List<String> unitsList = null;
  		String unitsListToConcatinatedString="";
  		List<MaintAuditTypeDesc> matdes= null;
  		int noOfUnits = 0;
		
  		try {
  				Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
				logger.info("getAuditSummaryTrgtWtchlstTotal ...."+ legalEntityCode +" userId.... "+userId +" role...."+role+" auditTypeCode...."+auditTypeCode);
			
				
			//To get the List of Units, Jurisdictions wise
				
				if("G6".equalsIgnoreCase(role) || "G1".equalsIgnoreCase(role))
					unitsList=maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode,"user",userId); //To get the list on all Units under the logged in User
				else{
					String unitCode= userService.getUnitIdforUser(legalEntityCode, userId);
					unitsList = new ArrayList();
					unitsList.add(unitCode);
				}
				//unitsList=maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode,"user",userId);
  				logger.info("unitsList .."+ unitsList);
  				noOfUnits = unitsList.size();
  				
  				if(unitsList!=null&&!unitsList.isEmpty()){ 
  					for (String unitId0 : unitsList) {
  						if(unitsListToConcatinatedString.length()==0) 
  							unitsListToConcatinatedString="'"+unitId0+"'";	
  						unitsListToConcatinatedString+=",'"+unitId0+"'";	
  					}
  				logger.info("unitsListToConcatinatedString .."+ unitsListToConcatinatedString);
  				//End here
  					
  	  			//To get the Financial Year details & Convert it into YYYY-MM-DD format
  	  				String curFinancialStartDate=null;
					String curFinancialEndDate=null;
					@SuppressWarnings("rawtypes")
  					Map currFinYrMap=null;

  					String planed = null;
  					String closed = null;	
  					String inProgress = null;
  					String notInitiated = null;
  	  				currFinYrMap=auditProcessVService.financialYearDates(legalEntityCode);
  					logger.info("financialYearDates .."+ currFinYrMap);
  					
  					curFinancialStartDate = (String)currFinYrMap.get("startDate")+"T00:00:00.000Z";
  					curFinancialEndDate =  (String)currFinYrMap.get("endDate")+"T00:00:00.000Z";
  					logger.info("financialYear start date : --> "+curFinancialStartDate +"financialYear end date: --> "+curFinancialEndDate);
  					
  					Date psDate = BankAuditUtil.parseDateTime(curFinancialStartDate);
  					Date peDate = BankAuditUtil.parseDateTime(curFinancialEndDate);
  					
  					String startDate = BankAuditUtil.parseDateToString(psDate);
  					String enDate = BankAuditUtil.parseDateToString(peDate); 
  					logger.info("plnStDate .. "+startDate +" plnEnDate .. "+enDate);
  				//Year formating ends here
  					
  				//To get the Audit Details for the Current Financial Year
  					List<String> deptList =null;
  					boolean isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, role, userId);
  					if(!isDeptAsRMD) {
  						deptList =reportDao.getDeptList(legalEntityCode, role, userId);
  						logger.info("deptList .."+ deptList);
  						if(deptList!=null && deptList.size() >0) {
  							deptList.add("XXXX");
  						}else {
  							deptList = new ArrayList();
  							deptList.add("XXXX");
  						}
  					}
  					logger.info("deptList .."+ deptList);
  					
  					Map mp = new HashMap();
  					if(unitsListToConcatinatedString!=null && unitsListToConcatinatedString.length()>0)
  					{
  						mp=dashboardDao.getAssessmentSummaryDtls(legalEntityCode,unitsListToConcatinatedString,auditTypeCode,startDate,enDate,isDeptAsRMD,deptList);
  						logger.info(" getAssessmentSummaryDtls --> "+mp);
  						if(mp!=null && !mp.isEmpty()) {
  							planed =(String)mp.get("PLANNED");
  							inProgress =  (String)mp.get("IN_PROGESS");
  							notInitiated = (String)mp.get("NOT_INITIATED");
  							closed =  (String)mp.get("CLOSED");
  							
  						}
  					}
  					logger.info("Audit status count : --> "+mp);
  				//End here
  					int RCSAUnitsCount =0;
  					if(unitsListToConcatinatedString!=null && unitsListToConcatinatedString.length()>0)
  					{
  						RCSAUnitsCount=dashboardDao.getRCSAUnitsCount(legalEntityCode,unitsListToConcatinatedString,auditTypeCode,startDate,enDate,isDeptAsRMD,deptList);
  					}
  					logger.info(" RCSAUnitsCount --> "+RCSAUnitsCount);
  					  					
  					//auditSummaryBoxMap.put("RCSAUnits", noOfUnits+"");
  					//auditSummaryBoxMap.put("RCSAUnits", deptList!=null?deptList.size()+"":"0");
  					auditSummaryBoxMap.put("RCSAUnits", RCSAUnitsCount+"");
  					auditSummaryBoxMap.put("PLANNED", planed);
  					auditSummaryBoxMap.put("NOT_INITIATED", notInitiated);
  					auditSummaryBoxMap.put("IN_PROGESS", inProgress);
  					auditSummaryBoxMap.put("CLOSED", closed);
  					
  				}
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		return auditSummaryBoxMap;
	}
	
	
	@Override
	public List<HashMap<String,String>> getRiskProfileDeptwise(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, String unitId) {
		Map<String,LocalDate> mapDt =null;
		logger.info("getRiskProfileProductwise .."+legalEntityCode+" :: "+auditType+" :: "+period+" :: "+fromDate+" :: "+toDate+" :: "+userId+" :: "+role+" :: "+unitId);
		
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);
		
		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		if(!BankAuditUtil.isEmptyString(period)){
			if (period.equalsIgnoreCase("yearly")) {
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(12).minusDays(1);
			}else if (period.equalsIgnoreCase("range")) {
				
			}
		}
		logger.info("fromDate .. "+fromDate +" todate .. "+ toDate);
		List<String> unitList = null;
		List<String> deptList= null;
		boolean isDeptAsRMD =false;
		if(!BankAuditUtil.isEmptyString(unitId)) {
			unitList = new ArrayList();
			unitList.add(unitId);
		}else if("G6".equalsIgnoreCase(role) || "G1".equalsIgnoreCase(role))
			unitList= getUnitList(legalEntityCode, role,"user", userId); //To get the list on all Units under the logged in User
		else{
			String unitCode= userService.getUnitIdforUser(legalEntityCode, userId);
			unitList = new ArrayList();
			unitList.add(unitCode);
		}
		if(!BankAuditUtil.isEmptyString(auditType)) {
			deptList = new ArrayList();
			deptList.add(auditType);
		}else {
			isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, role, userId);
			if(!isDeptAsRMD) 
				deptList =reportDao.getDeptList(legalEntityCode, role, userId);
		} logger.info("isDeptAsRMD .. "+isDeptAsRMD +" deptList .."+ deptList);
		logger.info("unitList :: "+unitList.size()+ ":: "+unitList);
		boolean isAssessmentProcessDoneFY= dashboardDao.isAssessmentProcessDoneFY(legalEntityCode,fromDate,toDate);
		logger.info("isAssessmentProcessDoneFY .. "+isAssessmentProcessDoneFY);
		logger.info("bfr toDate .. "+toDate +" :: "+ fromDate);
		if (!isAssessmentProcessDoneFY) {
			toDate=fromDate.minusDays(1);
			fromDate=toDate.minusMonths(12).plusDays(1);
		}
		logger.info("aftr toDate .. "+toDate +" :: "+ fromDate);
		
		if("G1".equalsIgnoreCase(role) || "G3".equalsIgnoreCase(role) || "G6".equalsIgnoreCase(role) )
			return dashboardDao.getRiskProfileDeptwise( legalEntityCode,  auditType,  period, fromDate,  toDate,  userId,role,isDeptAsRMD, unitList, deptList);
		else
			return dashboardDao.getRiskProfileProductwise( legalEntityCode,  auditType,  period, fromDate,  toDate,  userId,role,isDeptAsRMD, unitList, deptList);
	}
	
	@Override
	public List<HashMap<String,String>> getRiskProfileProductwise(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, String unitId) {
		Map<String,LocalDate> mapDt =null;
		logger.info("getRiskProfileProductwise .."+legalEntityCode+" :: "+auditType+" :: "+period+" :: "+fromDate+" :: "+toDate+" :: "+userId+" :: "+role+" :: "+unitId);
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);
		
		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		if(!BankAuditUtil.isEmptyString(period)){
			if (period.equalsIgnoreCase("yearly")) {
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(12).minusDays(1);
			}else if (period.equalsIgnoreCase("range")) {
				
			}
		}
		logger.info("fromDate .. "+fromDate +" todate .. "+ toDate);
		List<String> unitList = null;
		List<String> deptList= null;
		boolean isDeptAsRMD =false;
		if(!BankAuditUtil.isEmptyString(unitId)) {
			unitList = new ArrayList();
			unitList.add(unitId);
		}else if("G6".equalsIgnoreCase(role) || "G1".equalsIgnoreCase(role))
			unitList= getUnitList(legalEntityCode, role,"user", userId); //To get the list on all Units under the logged in User
		else{
			String unitCode= userService.getUnitIdforUser(legalEntityCode, userId);
			unitList = new ArrayList();
			unitList.add(unitCode);
		}
		if(!BankAuditUtil.isEmptyString(auditType)) {
			logger.info("auditType .."+auditType);
			deptList = new ArrayList();
			deptList.add(auditType);
		}else {
			isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, role, userId);
			if(!isDeptAsRMD) 
				deptList =reportDao.getDeptList(legalEntityCode, role, userId);
			
		} logger.info("isDeptAsRMD .. "+isDeptAsRMD +" deptList .."+ deptList);
		logger.info("unitList :: "+unitList.size()+ ":: "+unitList);
						
		//return dashboardDao.getRatingVariance( legalEntityCode,  auditType,  period,fromDate,  toDate,  userId,role,getUnitList(legalEntityCode, role,"user", userId),  unitType, criticality);
		return dashboardDao.getRiskProfileProductwise( legalEntityCode,  auditType,  period,
				 fromDate,  toDate,  userId,role,isDeptAsRMD, unitList, deptList);
	}
	
	@Override
	public List<HashMap<String,String>> getControlProfileDeptwise(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, String unitId) {
		Map<String,LocalDate> mapDt =null;
		
		logger.info("getRiskProfileProductwise .."+legalEntityCode+" :: "+auditType+" :: "+period+" :: "+fromDate+" :: "+toDate+" :: "+userId+" :: "+role+" :: "+unitId);
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);
		
		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		if(!BankAuditUtil.isEmptyString(period)){
			if (period.equalsIgnoreCase("yearly")) {
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(12).minusDays(1);
			}else if (period.equalsIgnoreCase("range")) {
				
			}
		}
		
		logger.info("fromDate .. "+fromDate +" todate .. "+ toDate);
		List<String> unitList = null;
		List<String> deptList= null;
		boolean isDeptAsRMD =false;
		if(!BankAuditUtil.isEmptyString(unitId)) {
			unitList = new ArrayList();
			unitList.add(unitId);
		}else if("G6".equalsIgnoreCase(role) || "G1".equalsIgnoreCase(role)) //// for OPS and Management user, allowed to see the data across all units under the Unit below.
			unitList= getUnitList(legalEntityCode, role,"user", userId); //To get the list on all Units under the logged in User
		else{ // Other than OPS and Management user, allowed to see the data for the particular Unit
			String unitCode= userService.getUnitIdforUser(legalEntityCode, userId);
			unitList = new ArrayList();
			unitList.add(unitCode);
		}
		if(!BankAuditUtil.isEmptyString(auditType)) {
			deptList = new ArrayList();
			deptList.add(auditType);
		}else {
			isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, role, userId);
			if(!isDeptAsRMD) 
				deptList =reportDao.getDeptList(legalEntityCode, role, userId);
		} logger.info("isDeptAsRMD .. "+isDeptAsRMD +" deptList .."+ deptList);
		logger.info("unitList :: "+unitList.size()+ ":: "+unitList);
		boolean isAssessmentProcessDoneFY= dashboardDao.isAssessmentProcessDoneFY(legalEntityCode,fromDate,toDate);
		logger.info("isAssessmentProcessDoneFY .. "+isAssessmentProcessDoneFY);
		logger.info("bfr .. "+fromDate +" :: "+ toDate);
		if (!isAssessmentProcessDoneFY) {
			toDate=fromDate.minusDays(1);
			fromDate=toDate.minusMonths(12).plusDays(1);
		}
		logger.info("aftr .. "+fromDate +" :: "+ toDate);
		
		if("G1".equalsIgnoreCase(role) || "G3".equalsIgnoreCase(role) || "G6".equalsIgnoreCase(role))
			return dashboardDao.getControlProfileDeptwise( legalEntityCode,  auditType,  period, fromDate,  toDate,  userId,role,isDeptAsRMD,unitList,deptList);
		else return dashboardDao.getControlProfileProductwise( legalEntityCode,  auditType,  period, fromDate,  toDate,  userId,role,isDeptAsRMD,unitList,deptList);
		
	}
	
	@Override
	public List<HashMap<String,String>> getControlProfileProductwise(int legalEntityCode, String auditType, String period,
			LocalDate fromDate, LocalDate toDate, String userId, String role, String unitId) {
		Map<String,LocalDate> mapDt =null;
		
		logger.info("getRiskProfileProductwise .."+legalEntityCode+" :: "+auditType+" :: "+period+" :: "+fromDate+" :: "+toDate+" :: "+userId+" :: "+role+" :: "+unitId);
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);
		
		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		if(!BankAuditUtil.isEmptyString(period)){
			if (period.equalsIgnoreCase("yearly")) {
				fromDate=LocalDate.of(year, 4, 1);
				toDate=fromDate.plusMonths(12).minusDays(1);
			}else if (period.equalsIgnoreCase("range")) {
				
			}
		}
		
		logger.info("fromDate .. "+fromDate +" todate .. "+ toDate);
		List<String> unitList = null;
		List<String> deptList= null;
		boolean isDeptAsRMD =false;
		if(!BankAuditUtil.isEmptyString(unitId)) {
			unitList = new ArrayList();
			unitList.add(unitId);
		}else if("G6".equalsIgnoreCase(role) || "G1".equalsIgnoreCase(role)) //// for OPS and Management user, allowed to see the data across all units under the Unit below.
			unitList= getUnitList(legalEntityCode, role,"user", userId); //To get the list on all Units under the logged in User
		else{ // Other than OPS and Management user, allowed to see the data for the particular Unit
			String unitCode= userService.getUnitIdforUser(legalEntityCode, userId);
			unitList = new ArrayList();
			unitList.add(unitCode);
		}
		if(!BankAuditUtil.isEmptyString(auditType)) {
			deptList = new ArrayList();
			deptList.add(auditType);
		}else {
			isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, role, userId);
			if(!isDeptAsRMD) 
				deptList =reportDao.getDeptList(legalEntityCode, role, userId);
		} logger.info("isDeptAsRMD .. "+isDeptAsRMD +" deptList .."+ deptList);
		logger.info("unitList :: "+unitList.size()+ ":: "+unitList);
		
		return dashboardDao.getControlProfileProductwise( legalEntityCode,  auditType,  period, fromDate,  toDate,  userId,role,isDeptAsRMD,unitList,deptList);
	}
	
	@Override
	public Map<String,Integer> getTaskStatistics(int legalEntityCode,String userId,String role, String auditType, String unitId) {
		Map<String, Integer> taskSummaryMap = null;
		boolean isDeptAsRMD =false;
		List<String> deptList = null;
		List<String> unitList = null;
		List<String> assessmentList = null;
		try {
			logger.info("Inside getTaskStatistics .. "+ legalEntityCode+" :: "+userId+" :: "+role+" :: "+ auditType+" :: "+ unitId);
			if("G6".equalsIgnoreCase(role) || "G1".equalsIgnoreCase(role)) //// for OPS and Management user, allowed to see the data across all units under the Unit below.
				if(!BankAuditUtil.isEmptyString(unitId)) { 
					unitList = new ArrayList(); unitList.add(unitId);
				}else unitList= getUnitList(legalEntityCode, role,"user", userId); //To get the list on all Units under the logged in User
			else{ // Other than OPS and Management user, allowed to see the data for the particular Unit
				String unitCode= userService.getUnitIdforUser(legalEntityCode, userId);
				unitList = new ArrayList();
				unitList.add(unitCode);
			}
			if(!BankAuditUtil.isEmptyString(auditType)) {
				deptList = new ArrayList();
				deptList.add(auditType);
			}else {
				isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, role, userId);
				if(!isDeptAsRMD) 
					deptList =reportDao.getDeptList(legalEntityCode, role, userId);
			} logger.info("isDeptAsRMD .. "+isDeptAsRMD +" deptList .."+ deptList);
			logger.info("unitList :: "+unitList.size()+ ":: "+unitList);
			
			/*logger.info("SrvcImpl getHealthIndexforRCSAUnits legalEntityCodeStr.. "+ legalEntityCode +" userId.."+ userId +" role.. "+ role + " asOfDate .. "+" NA" );
			isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, role, userId);
			if(!isDeptAsRMD) 
				deptList =reportDao.getDeptList(legalEntityCode, role, userId);
			logger.info("isDeptAsRMD .. "+isDeptAsRMD +" deptList .."+ deptList);
			unitList = getUnitList(legalEntityCode, role, "user", userId);*/
			assessmentList = reportDao.getAssessmentList(legalEntityCode, role, userId, null, isDeptAsRMD, deptList, unitList);
			taskSummaryMap =dashboardDao.getTaskStatistics( legalEntityCode, userId,role, auditType,unitId,isDeptAsRMD, deptList ,unitList);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return taskSummaryMap;
	}
	
	@Override
	public Map<String,Integer> getOverDueTaskStatistics(int legalEntityCode,String userId,String role, String auditType, String unitId) {
		Map<String, Integer> overDueTaskSummaryMap = null;
		boolean isDeptAsRMD =false;
		List<String> deptList = null;
		List<String> unitList = null;
		List<String> assessmentList = null;
		try {
			logger.info("Inside getOverDueTaskStatistics .. "+ legalEntityCode+" :: "+userId+" :: "+role+" :: "+ auditType+" :: "+ unitId);
			if("G6".equalsIgnoreCase(role) || "G1".equalsIgnoreCase(role)) //// for OPS and Management user, allowed to see the data across all units under the Unit below.
				if(!BankAuditUtil.isEmptyString(unitId)) { 
					unitList = new ArrayList(); unitList.add(unitId);
				}else unitList= getUnitList(legalEntityCode, role,"user", userId); //To get the list on all Units under the logged in User
			else{ // Other than OPS and Management user, allowed to see the data for the particular Unit
				String unitCode= userService.getUnitIdforUser(legalEntityCode, userId);
				unitList = new ArrayList();
				unitList.add(unitCode);
			}
			if(!BankAuditUtil.isEmptyString(auditType)) {
				deptList = new ArrayList();
				deptList.add(auditType);
			}else {
				isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, role, userId);
				if(!isDeptAsRMD) 
					deptList =reportDao.getDeptList(legalEntityCode, role, userId);
			} logger.info("isDeptAsRMD .. "+isDeptAsRMD +" deptList .."+ deptList);
			logger.info("unitList :: "+unitList.size()+ ":: "+unitList);
			
			/* Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
			logger.info("SrvcImpl getHealthIndexforRCSAUnits legalEntityCodeStr.. "+ legalEntityCode +" userId.."+ userId +" role.. "+ role + " asOfDate .. "+" NA" );
			isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, role, userId);
			if(!isDeptAsRMD) 
				deptList =reportDao.getDeptList(legalEntityCode, role, userId);
			logger.info("isDeptAsRMD .. "+isDeptAsRMD +" deptList .."+ deptList);
			unitList = getUnitList(legalEntityCode, role, "user", userId);*/
			
			//assessmentList = reportDao.getAssessmentList(legalEntityCode, role, userId, null, isDeptAsRMD, deptList, unitList); // Specific Assessment not required, ass Task is from the day of Inception 
			overDueTaskSummaryMap =dashboardDao.getOverDueTaskStatistics( legalEntityCode, userId,role, auditType,unitId,isDeptAsRMD, deptList ,unitList);
			
			if(!overDueTaskSummaryMap.containsKey("ONE_MONTH")) overDueTaskSummaryMap.put("ONE_MONTH", 0);
			if(!overDueTaskSummaryMap.containsKey("TWO_MONTH")) overDueTaskSummaryMap.put("TWO_MONTH", 0);
			if(!overDueTaskSummaryMap.containsKey("THREE_MONTH")) overDueTaskSummaryMap.put("THREE_MONTH", 0);
			if(!overDueTaskSummaryMap.containsKey("MORE_THEN_THREE")) overDueTaskSummaryMap.put("MORE_THEN_THREE", 0);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return overDueTaskSummaryMap;
	}
	
	@Override
	public Map<String, String> getHealthControlRiskSummaryDetails(int legalEntityCode,String userId,String role, String auditType, String unitId) {
		Map<String, String> healthControlRiskSummaryDetailsMap = null;
		boolean isDeptAsRMD =false;
		List<String> deptList = null;
		List<String> unitList = null;
		List<String> assessmentList = null;
		try {
			logger.info("Inside getHealthControlRiskSummaryDetails .. "+ legalEntityCode+" :: "+userId+" :: "+role+" :: "+ auditType+" :: "+ unitId);
			if("G6".equalsIgnoreCase(role) || "G1".equalsIgnoreCase(role)) // for OPS and Management user, allowed to see the data across all units under the Unit below.
				if(!BankAuditUtil.isEmptyString(unitId)) { 
					unitList = new ArrayList(); unitList.add(unitId);
				}else unitList= getUnitList(legalEntityCode, role,"user", userId); //To get the list on all Units under the logged in User
			else{ // Other than OPS and Management user, allowed to see the data for the particular Unit
				String unitCode= userService.getUnitIdforUser(legalEntityCode, userId);
				unitList = new ArrayList();
				unitList.add(unitCode);
			}
			if(!BankAuditUtil.isEmptyString(auditType)) {
				deptList = new ArrayList();
				deptList.add(auditType);
			}else {
				isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, role, userId);
				if(!isDeptAsRMD) 
					deptList =reportDao.getDeptList(legalEntityCode, role, userId);
			} logger.info("isDeptAsRMD .. "+isDeptAsRMD +" deptList .."+ deptList);
			logger.info("unitList :: "+unitList.size()+ ":: "+unitList);
			
			//Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
			/*logger.info("SrvcImpl getHealthIndexforRCSAUnits legalEntityCodeStr.. "+ legalEntityCode +" userId.."+ userId +" role.. "+ role + " asOfDate .. "+" NA" );
			isDeptAsRMD = reportDao.isDeptAsRMD(legalEntityCode, role, userId);
			if(!isDeptAsRMD) 
				deptList =reportDao.getDeptList(legalEntityCode, role, userId);
			logger.info("isDeptAsRMD .. "+isDeptAsRMD +" deptList .."+ deptList);
			unitList = getUnitList(legalEntityCode, role, "user", userId);*/
			//assessmentList = reportDao.getAssessmentList(legalEntityCode, role, userId, null, isDeptAsRMD, deptList, unitList);
			
			healthControlRiskSummaryDetailsMap =dashboardDao.getHealthControlRiskSummaryDetails( legalEntityCode, userId,role, auditType,unitId,isDeptAsRMD, deptList ,unitList);
			logger.info("healthControlRiskSummaryDetailsMap .. "+healthControlRiskSummaryDetailsMap);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return healthControlRiskSummaryDetailsMap;
	}
	
	@Override
	public Boolean isAssessmentProcessDoneFY(int legalEntityCode) {
		Date businessDateTimestamp=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
		logger.info("businessDateTimestamp .."+businessDateTimestamp);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(businessDateTimestamp);

		logger.info("calendar .."+calendar +" Mnth.."+calendar.get(Calendar.MONTH)+" .."+Calendar.MONTH +" Yr.."+ Calendar.YEAR);
		Integer year=null;
		if( calendar.get(Calendar.MONTH)>=4){
			year=calendar.get(Calendar.YEAR);
		}else{
			year=calendar.get(Calendar.YEAR)-1;
		}
		
		LocalDate currFYStartDate =LocalDate.of(year, 04, 01);
		LocalDate currFYEndDate=currFYStartDate.plusMonths(12).minusDays(1);
		logger.info("FYStart Date .. "+currFYStartDate +" FYEndDate .. "+currFYEndDate);
		
		return dashboardDao.isAssessmentProcessDoneFY(legalEntityCode, currFYStartDate, currFYEndDate);
	}
	
	/************************************ DASHBOARD for RCSA NABARD End here ***************************************/
	
	/******************** 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){
		return dashboardDao.getDeskComplianceRatingWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId);
	}
	
	@Override
	public Map<String, Integer> getSupervisoryRatingWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId){
		return dashboardDao.getSupervisoryRatingWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId);
	}
	
	@Override
	public Map<String, Map<String, String>> getSupervisoryRatingMigrationWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId){
		return dashboardDao.getSupervisoryRatingMigrationWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId);
	}
	
	@Override
	public Map<String, String> getBudgetProgressWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId){
		return dashboardDao.getBudgetProgressWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId);
	}
	
	@Override
	public Map<String, String> getComplianceStatusWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId){
		return dashboardDao.getComplianceStatusWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId);
	}*/
	
	@Override
	public Map<String, Object> getAllManagementWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId){
		Map<String, Object> managementWidget =  new HashMap<String, Object> ();
	 
		logger.info("getAllManagementWidget ServiceImpl .. "+ legalEntityCode+" :: "+ userId+" :: "+ role+" :: "+financialYear+" :: "+auditTypeCode+" :: "+zone+" :: "+unitId);
		List<String> unitIdlist = new ArrayList<String>(); 
		if(!BankAuditUtil.isEmptyString(zone) || !BankAuditUtil.isEmptyString(unitId)){
			unitIdlist = dashboardDao.getUnitCodeList(legalEntityCode, unitId, zone); 
		}else{
			unitIdlist = maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode, "user", userId);
		}
		//financialYear = financialYear.minusYears(1);
		List<LocalDate>  financialYearList = BankAuditUtil.getFinancialStartEndDatesFrom(financialYear);
		
		managementWidget.put("BudgetProgressWidget", dashboardDao.getBudgetProgressWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		managementWidget.put("DeskComplianceRatingWidget", dashboardDao.getDeskComplianceRatingWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		managementWidget.put("SupervisoryRatingWidget", dashboardDao.getSupervisoryRatingWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		managementWidget.put("ComplianceStatusWidget", dashboardDao.getComplianceStatusWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		managementWidget.put("SupervisoryRatingMigrationWidget", dashboardDao.getSupervisoryRatingMigrationWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		managementWidget.put("FinancialParameterWidget", dashboardDao.getFinancialParameterWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));		
		managementWidget.put("LettersCountAuthorized", dashboardDao.getAuthorizedLettersCount(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		managementWidget.put("LettersCountUnAuthorized", dashboardDao.getUnAuthorizedLettersCount(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList)); 
		managementWidget.put("SupportingDocumentCountAuthorized", dashboardDao.getAuthorizedSupportingDocumentCount(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList)); 
		
		return managementWidget;
	}
	
	@Override
	public Map<String, Object> getAllOperationalWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId){
		Map<String, Object> operationWidget =  new HashMap<String, Object> ();
		
		logger.info("getAllOperationalWidget ServiceImpl .. "+ legalEntityCode+" :: "+ userId+" :: "+ role+" :: "+financialYear+" :: "+auditTypeCode+" :: "+zone+" :: "+unitId);
		List<String> unitIdlist = new ArrayList<String>(); 
		if(!BankAuditUtil.isEmptyString(zone) || !BankAuditUtil.isEmptyString(unitId)){
			unitIdlist = dashboardDao.getUnitCodeList(legalEntityCode, unitId, zone); 
		}else{
			unitIdlist = maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode, "user", userId);
		}		
		//financialYear = financialYear.minusYears(1);	 
		List<LocalDate>  financialYearList = BankAuditUtil.getFinancialStartEndDatesFrom(financialYear);
		
		operationWidget.put("BudgetProgressWidget", dashboardDao.getBudgetProgressWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		operationWidget.put("DeskComplianceRatingWidget", dashboardDao.getDeskComplianceRatingWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		operationWidget.put("SupervisoryRatingWidget", dashboardDao.getSupervisoryRatingWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		operationWidget.put("ComplianceStatusWidget", dashboardDao.getComplianceStatusWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		operationWidget.put("PlanCalendarWidget", dashboardDao.getPlanCalendarWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist));
		operationWidget.put("FinancialParameterWidget", dashboardDao.getFinancialParameterWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		operationWidget.put("LettersCountAuthorized", dashboardDao.getAuthorizedLettersCount(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		operationWidget.put("LettersCountUnAuthorized", dashboardDao.getUnAuthorizedLettersCount(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList)); 
		operationWidget.put("SupportingDocumentCountAuthorized", dashboardDao.getAuthorizedSupportingDocumentCount(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList)); 
		
		return operationWidget;
	}
	
	@Override
	public Map<String, Object> getAllInspectorWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId){
		Map<String, Object> inspectorWidget =  new HashMap<String, Object> ();
		List<LocalDate>  financialYearList = BankAuditUtil.getFinancialStartEndDatesFrom(financialYear);
		inspectorWidget.put("MyInspections", dashboardDao.getMyInspectionWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, financialYearList));
		inspectorWidget.put("TableInstances", dashboardDao.getDynamicTableInstances(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, financialYearList));
		inspectorWidget.put("MyBudget", dashboardDao.getMyBudgetWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, financialYearList)); 
		
		return inspectorWidget;
	}
	
	@Override
	public Map<String, Object> getAllBankUserWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId){
		Map<String, Object> bankWidget =  new HashMap<String, Object> ();
		List<LocalDate>  financialYearList = BankAuditUtil.getFinancialStartEndDatesFrom(financialYear);
		bankWidget.put("NonComplianceItem", dashboardDao.getNonComplianceItemWidgetYearWise(legalEntityCode, userId, role, financialYear, unitId, financialYearList));
		bankWidget.put("ComplianceSubmittedStatus", dashboardDao.getComplianceSubmittedWidgetYearWise(legalEntityCode, userId, role, financialYear, unitId, financialYearList));
		 
		return bankWidget;
	}
	
	@Override
	public DataTableResponse getMyAuditSchedules(Integer legalEntityCode, String userId, String search, Integer orderColumn,
			String orderDirection, Integer page, Integer size,  String role){		
		return dashboardDao.getMyAuditSchedules(legalEntityCode, userId, search, orderColumn, orderDirection, page, size, role);
	}
	
	@Override
	public Map<String, Object> getScrutinyWidget(Integer legalEntityCode, String userId, String role, LocalDate financialYear,  String auditTypeCode, 
			String zone, String unitId){
		
		Map<String, Object> scrutinyWidget =  new HashMap<String, Object> ();
		
		List<String> unitIdlist = new ArrayList<String>(); 
		if(!BankAuditUtil.isEmptyString(zone) || !BankAuditUtil.isEmptyString(unitId)){
			unitIdlist = dashboardDao.getUnitCodeList(legalEntityCode, unitId, zone); 
		}else{
			unitIdlist = maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode, "user", userId);
		}
		List<LocalDate>  financialYearList = BankAuditUtil.getFinancialStartEndDatesFrom(financialYear);
		scrutinyWidget.put("DeskComplianceRatingWidget", dashboardDao.getDeskComplianceRatingWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));
		scrutinyWidget.put("ComplianceStatusWidget", dashboardDao.getComplianceStatusWidget(legalEntityCode, userId, role, financialYear, auditTypeCode, zone, unitId, unitIdlist, financialYearList));		
		scrutinyWidget.put("ScrutinyStatusWidget", dashboardDao.getScrutinyStatusWidget(legalEntityCode, userId, role, financialYear, unitId, financialYearList));		
		
		return scrutinyWidget;
	}
	
	//Top Band
	@Override
	public Map<String,String> getAuditSummaryTrgtWtchlstTotalTopBand(Integer legalEntityCode, String userOrUnitCode, String type,
			String auditTypeCode, LocalDate financialYear) {
		
		logger.info("getAuditSummaryTrgtWtchlstTotal ...."+ legalEntityCode +" userOrUnitCode.... "+userOrUnitCode 
				+" type.... "+type+" auditTypeCode.... "+auditTypeCode+" financialYear.... "+financialYear);
		 
		Map<String,String> auditSummaryBoxMap = new HashMap<String,String>();		
  		try{
  			long start =System.currentTimeMillis();
  			Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
			
			//To get the List of Units, Jurisdictions wise 
  			List<String> unitsList = maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode, type, userOrUnitCode);  				  
  			if(unitsList!=null &&!unitsList.isEmpty()){ 
  				 
  				String unitsListToConcatinatedString =  String.join("','",unitsList); 				 
  				unitsListToConcatinatedString = "'"+unitsListToConcatinatedString+"'";
  	  			//To get the Financial Year details & Convert it into YYYY-MM-DD format  				  
  				/*Map currFinYrMap=auditProcessVService.financialYearDates(legalEntityCode);   				
  	  			String curFinancialStartDate = (String)currFinYrMap.get("startDate")+"T00:00:00.000Z";
  	  			String curFinancialEndDate =  (String)currFinYrMap.get("endDate")+"T00:00:00.000Z";   					
  				Date psDate = BankAuditUtil.parseDateTime(curFinancialStartDate);
  				Date peDate = BankAuditUtil.parseDateTime(curFinancialEndDate);  					
  				String startDate = BankAuditUtil.parseDateToString(psDate);
  				String enDate = BankAuditUtil.parseDateToString(peDate);  */
  				//Year formating ends here
  					
  				//To get the List of Audit types 
  				List<MaintAuditTypeDesc> auditTypes= null;
  				if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
  					auditTypes = new ArrayList<MaintAuditTypeDesc>();
  					auditTypes.add(maintAuditTypeDescService.getMaintAuditTypeDesc(legalEntityCode, auditTypeCode));
  				}else {	
  					auditTypes = maintAuditTypeDescService.getMaintAuditTypeDescByLegalEntityCode(legalEntityCode);
  				} 
  					
  				//To get the Count of Units Eligible for Auditing 
  				Long allAuditUnits = auditProcessVService.getAllOperationAuditUnits(legalEntityCode,auditTypeCode, unitsListToConcatinatedString);
  	  			Long auditUnits = auditProcessVService.getOperationAuditUnits(legalEntityCode,auditTypeCode, unitsListToConcatinatedString);
  	  				
  				//To get the Target Audits for the Current Financial Year
  			    //Map targetUnitAuditsUnitMap=dashboardDao.getTargetUnitAuditsUnitCount(legalEntityCode,unitsListToConcatinatedString,auditTypeCode,startDate,enDate);  
  	  			/******************************* Target retrieval, for Top band  ************************************/
  	  				//To get the Financial Year details & Convert it into YYYY-MM-DD format
	  				String curFinancialStartDate=null;
	  				String curFinancialEndDate=null;
	  				@SuppressWarnings("rawtypes")
					Map currFinYrMap=null;

					String planed = null;
					String closed = null;	
					String inProcess = null;
	  				currFinYrMap=auditProcessVService.financialYearDates(legalEntityCode);
					logger.info("financialYearDates .."+ currFinYrMap);
					
					curFinancialStartDate = (String)currFinYrMap.get("startDate")+"T00:00:00.000Z";
					curFinancialEndDate =  (String)currFinYrMap.get("endDate")+"T00:00:00.000Z";
					logger.info("financialYear start date : --> "+curFinancialStartDate +"financialYear end date: --> "+curFinancialEndDate);
					
					Date psDate = BankAuditUtil.parseDateTime(curFinancialStartDate);
					Date peDate = BankAuditUtil.parseDateTime(curFinancialEndDate);
					
					String startDate = BankAuditUtil.parseDateToString(psDate);
					String enDate = BankAuditUtil.parseDateToString(peDate); 
					logger.info("plnStDate .. "+startDate +" plnEnDate .. "+enDate);
					//Year formating ends here
					
					//To get the Target Audits for the Current Financial Year
					Map targetUnitAuditsUnitMap=dashboardDao.getTargetUnitAuditsUnitCount(legalEntityCode,unitsListToConcatinatedString,auditTypeCode,startDate,enDate);  
					logger.info("targetUnits : --> "+targetUnitAuditsUnitMap);
				
  	  			/*******************************Target retrieval, for Top band  ************************************/
  	  			
  				//To get the Audit Details for the Current Financial Year  
				List<LocalDate>  financialYearList = BankAuditUtil.getFinancialStartEndDatesFrom(financialYear);
  				Map<String, String> audits = dashboardDao.getTopBandWidget(legalEntityCode, financialYear, auditTypeCode, unitsListToConcatinatedString, financialYearList);
  			   	  			
  				//To get the Watch List details for the Current Financial Year 
  				//int watchListCount = dashboardDao.getWatchListForAudits(legalEntityCode,auditTypeCode,startDate); 
  				int watchListCount = dashboardDao.getWatchListForAudits(legalEntityCode, financialYear, auditTypeCode, unitsListToConcatinatedString);					
  				
  				auditSummaryBoxMap.put("audits",((auditTypes!=null && !auditTypes.isEmpty())?auditTypes.size()+"":"0"));
  				auditSummaryBoxMap.put("NoOfAllUnits",allAuditUnits+"");  					
  				auditSummaryBoxMap.put("NoOfUnits", auditUnits+"");
  				//auditSummaryBoxMap.put("target", targetUnitAuditsUnitMap.get("TARGET_AUDITS")+"");  		
  				auditSummaryBoxMap.put("watchList", watchListCount+"");
  				auditSummaryBoxMap.putAll(audits);
  				logger.info("Target old .."+audits.get("target")+"" + " Target New .."+ targetUnitAuditsUnitMap.get("TARGET_AUDITS")+"");
  				auditSummaryBoxMap.put("target",targetUnitAuditsUnitMap.get("TARGET_AUDITS")+"");
  					 
  			}			
		}catch(Exception e) {
			e.printStackTrace();
		}
		return auditSummaryBoxMap;
	}	
		 
}



class AuditStatusComparator 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); 
	}
}
