"use strict";
// Overall Assessment Dashboard
appCore.controller("OverallAssessmentDashboardCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "filterFilter", '$uibModal',
    function ($state, $scope, $http, $timeout, vServices, filterFilter, $uibModal) {
        $scope.$root.page.title = "Assessment Dashboard";
        $scope.createButton = {heading: "Add", text: "Submit", icon: "fa-save", today: new Date()};
        $scope.assessmentSchedules = [];
        $scope.filterStatus = 'active';
        $scope.empInfoObj = {};        
        $scope.isSuperAdmin = $scope.$root.gUser.emp_acls.split(',').indexOf('27')>=0?'true':'false';
        $scope.allMailTemplates = [];
        $scope.template_name = '';
        $scope.colOptions = {comment: true, other_comment: true,questions:false};

       
        const init = () => {
            $scope.isSuperAdmin = $scope.$root.gUser.emp_acls.split(',').indexOf('27')>=0?'true':'false';
            vServices.callApi("employee/"+$scope.$root.gUser.id, "GET", {}).then(empInfo=>{
                $scope.empInfoObj = empInfo;
                vServices.callApi("/employee/getOverallAssessmentDashboard", "GET", {}).then(ad => {
                if(ad && ad.length>0){
                    //console.log(JSON.stringify(ad));            
                    const assessmentList = JSON.parse(JSON.stringify(ad));
                    $scope.assessmentSchedules = assessmentList;                     
                    $scope.assessmentSchedules.forEach(item => {
                        //Only for hero and his align manager
                        vServices.callApi("employee/getOverallAssessmentScheduleForManagers?assessment_id="+item.ae_id+"&heroes_id=" + item.ae_heroes +"&manger_id="+$scope.$root.gUser.id+"&is_assessment_manager="+$scope.empInfoObj.is_assessment_manager+"&is_admin="+$scope.isSuperAdmin, "GET", {}).then((data) => {
                            item.heroes = JSON.parse(JSON.stringify(data.heroes));
                            item.heroes.forEach(hd=>{
                                hd.as_sub = data.submissions.filter(x=>x.as_emp_id==hd.id && x.as_ae_id==item.ae_id);
                                
                                let counter = 0;
								let heroCounter = 0;

                                var additionalRoles = '';
                                var proRating = '';
                                var recommend = '';
                                var inpRes = '';
                                var brnTeam = '';
                                var kra = '';
                                // var selfTime,mngrTime;
                                //sum score of manager
                                hd.as_sub.forEach(sub=>{                                    
                                    counter += sub.as_manager_answer!=null && isNaN(sub.as_manager_answer)===false ?parseInt(sub.as_manager_answer,10):0;
									heroCounter += sub.as_answer!=null && isNaN(sub.as_answer)===false && sub.as_answer <= 5 ?parseInt(sub.as_answer,10):0;
                                    
                                     
                                    if(sub.as_aq_id == "60")
                                    additionalRoles = sub.as_manager_answer;

                                    if(sub.as_aq_id == "61")
                                    proRating = sub.as_manager_answer;

                                    if(sub.as_aq_id == "90")
                                    recommend = sub.as_manager_answer;

                                    if(sub.as_aq_id == "91")
                                    inpRes = sub.as_manager_answer;

                                    if(sub.as_aq_id == "92")
                                    brnTeam = sub.as_manager_answer;

                                    if(sub.as_aq_id == "93")
                                    kra = sub.as_manager_answer;

                                    // selfTime = sub.as_createdAt;
                                    // mngrTime = sub.as_updatedAt;
                                    
                                });
                                hd.additionalRoles = additionalRoles;
                                hd.proRating = proRating;
                                hd.recommend = recommend;
                                hd.inpRes = inpRes;
                                hd.brnTeam = brnTeam;
                                hd.kra = kra;

                                hd.score = counter;
								hd.heroScore = heroCounter;
                                hd.as_status = hd.as_sub.length>0 && hd.as_sub[0].as_status;
                                hd.as_manager_status = hd.as_sub.length>0 && hd.as_sub[0].as_manager_status;
                                hd.as_ae_id = hd.as_sub.length>0 && hd.as_sub[0].as_ae_id;
                                hd.as_mngr_id = hd.as_sub.length>0 && hd.as_sub[0].as_mngr_id;                                
                                hd.one2one = data.one2tone.filter(x=>x.hero_id==hd.id && x.assessment_id==item.ae_id);
                                hd.one2oneStatus = hd.one2one.length>0?hd.one2one[0].one_to_one:'No'; 
                                hd.grades = data.grades.filter(x=>x.hero_id==hd.id && x.assessment_id==item.ae_id);
                            });                            
                            $scope.$root.callDataTable(".assessmentDashboard",9999); 
                                                                                
                        });

                        //Only for assessment manager(skip manager/hr)

                    });  
                    

                }
            });
            })
                

            // Code for hard refresh
            if( window.localStorage )
            {
                //check if reloaded once already
                if( !localStorage.getItem('firstLoad') )
                {
                    //if not reloaded once, then set firstload to true
                    localStorage['firstLoad'] = true;
                    //reload the webpage using reload() method
                    window.location.reload();
                }
                else{
                    localStorage.removeItem('firstLoad');
                }
            }
        }
        init();

        // To send mail
        // Created By Syed Mohd Bilal Rais
        // 10 October 2021

        $scope.sendMail = (jsonQ, idx = null) => {

            // console.log(jsonQ);
            let modalInstance = $uibModal.open({
                animation: true,
                templateUrl: 'modelAssessmentScheduleMails2.html',
                controller: 'modelAssessmentScheduleMails2Ctrl',
                size: 'xl',//sm md,lg,xl
                controllerAs: "$scope",
                backdrop: "static",
                keyboard  : false,
                resolve: {
                    data: () => {
                        return {idx, single: JSON.parse(JSON.stringify(jsonQ))};
                    }
                }
            });
            
            modalInstance.result.then(function (counter) {
                toastr.success('Mails Send successfully to '+ counter.counter + ' heroes.');
            }, () => {
                //$log.info('Modal dismissed at: ' + new Date());
            });
        };

        $scope.sendMailToManagers = (jsonQ, idx = null) => {

            // console.log(jsonQ);
            let modalInstance = $uibModal.open({
                animation: true,
                templateUrl: 'modelAssessmentScheduleMailsManagers.html',
                controller: 'modelAssessmentScheduleMailsManagersCtrl',
                size: 'xl',//sm md,lg,xl
                controllerAs: "$scope",
                backdrop: "static",
                keyboard  : false,
                resolve: {
                    data: () => {
                        return {idx, single: JSON.parse(JSON.stringify(jsonQ))};
                    }
                }
            });
            
            modalInstance.result.then(function (counter) {
                toastr.success('Mails Send successfully to '+ counter.counter + ' heroes.');
            }, () => {
                //$log.info('Modal dismissed at: ' + new Date());
            });
        };

        $scope.reviewButton = (assessmentId,heroId) => {
            vServices.callApi("employee/redoHeroAssessment?assessmentId="+assessmentId+"&heroId=" + heroId, "GET", {}).then((res) => {
                if(res){
                    window.location.reload();
                }
            })
        }
        $scope.reviewButtonForManager = (assessmentId,ManagerId,heroId) => {
            vServices.callApi("employee/redoManagerAssessment?assessmentId="+assessmentId+"&ManagerId=" + ManagerId+"&heroId="+heroId, "GET", {}).then((res) => {
                if(res){
                    window.location.reload();
                }
            })
        }

        $scope.overallCompleteAssessment = (assessmentId,heroId) => {
            vServices.callApi("employee/overallCompleteAssessment?assessmentId="+assessmentId+"&heroId=" + heroId, "GET", {}).then((res) => {
                if(res){
                    window.location.reload();
                }
            })
        }
    }
])

	// // Created By Syed Mohd Bilal Rais
	.controller('modelAssessmentScheduleMails2Ctrl', function ($scope, $uibModalInstance, data, vServices) {
		$scope.cancel = () => $uibModalInstance.dismiss(false);
		$scope.data = data;// single idx
		$scope.data.sendmail = [];
		$scope.mInfo = {
			head_icon: "fas fa-plus-circle",
			head_title: "Assessment Mails Status",
			btn_icon: "fas fa-save",
			btn_title: "Send Mail",
			today: new Date()
		};

        vServices.callApi("/employee/all_email_templates", "GET", {}).then(res => {
            $scope.allMailTemplates = res;
        });

		$scope.toggleAll = function() {
			var toggleStatus = !$scope.isAllSelected;
			angular.forEach($scope.data.sendmail, function(itm){ itm.check = toggleStatus; });
		 }
        let alreadyCompleted;
        alreadyCompleted = $scope.data.single.heroes.filter(x=> x.as_status=='active');
        let sortedHeroes = alreadyCompleted.map(i=>
            i.id
        );
		vServices.callApi("/employee/getAssessmentMailDetails?id="+$scope.data.single.ae_id, "GET", {}).then(data => {
			$scope.data.sendmail = JSON.parse(JSON.stringify(data));
			$scope.data.sendmail.heroes.forEach( h => {
				h.emp_id = h.emp_id;
				h.ae_id = $scope.data.single.ae_id;
				h.check = false;
				h.id = data.mails_data.filter(x=>x.hero_id==h.emp_id);
                h.last_mail_sent = data.last_update.filter(x=>x.hero_id==h.emp_id);
				if(h.id.length > 0){
					data.mails_data.forEach(i=>{
						if(h.emp_id == i.hero_id){
							h.timestamp = moment(i.timestamp).format('DD-MMM-YYYY');
						}
					});
				}else{
					h.timestamp = 'Not Send';
				}
                data.last_update.forEach(i=>{
					if(h.emp_id == i.hero_id){
						h.mail2 = moment(i.mail2).format('DD-MMM-YYYY');
					}
				});
			});
            let filteretedArray = $scope.data.sendmail.heroes.filter(x => !sortedHeroes.includes(x.emp_id));
			$scope.data.sendmail = filteretedArray;
		});


		$scope.send = () => {
            let counter = 0;
            data.sendmail.forEach(i=>{
                if(i.check==true){
                    counter+=1;
                }
            });
            if($scope.template_id == '' || $scope.template_id == 'undefined'){
                toastr.error("Please fill all required fields","Alert");
                return false;
            }else{
                vServices.callApi("/employee/postAssessmentMailReminder", "POST", {myval: JSON.stringify(data) , template_name : $scope.template_name  }).then(data => {
                	$uibModalInstance.close({
                        counter : counter
                	});
                });
            }

		}
	})


    .controller('modelAssessmentScheduleMailsManagersCtrl', function ($scope, $uibModalInstance, data, vServices) {
		$scope.cancel = () => $uibModalInstance.dismiss(false);
		$scope.data = data;// single idx
		$scope.data.sendmail = [];
		$scope.mInfo = {
			head_icon: "fas fa-plus-circle",
			head_title: "Assessment Mails Status",
			btn_icon: "fas fa-save",
			btn_title: "Send Mail",
			today: new Date()
		};
        // let heroesArrayFilter = $scope.data.single.heroes.filter(i=> i.as_manager_status == false);
        let heroesArray = $scope.data.single.heroes.map(item=>
                    item.emp_lm
            );
        vServices.callApi("/employee/getAssessmentMailManagersDetails", "POST", {'myval':JSON.stringify(heroesArray) , 'assessmentId': $scope.data.single.ae_id }).then(res => {
            if(res.mails_data.length == 0 && res.last_update.length == 0){
                res.managers.forEach( h => {
                    h.emp_id = h.emp_id;
                    h.ae_id = $scope.data.single.ae_id;
                    h.check = false;
                    h.timestamp = 'Not Send';
                });
                $scope.data.sendmail = res.managers;
            }
            if(res.mails_data.length > 0 && res.last_update.length == 0){
                res.managers.forEach( h => {
                    h.emp_id = h.emp_id;
                    h.ae_id = $scope.data.single.ae_id;
                    h.check = false;
                    h.id = res.mails_data.filter(x=>x.manager_id==h.emp_id);
                    if(h.id.length > 0){
                        res.mails_data.forEach(i=>{
                            if(h.emp_id == i.manager_id){
                                h.timestamp = moment(i.timestamp).format('DD-MMM-YYYY');
                            }
                        });
                    }else{
                        h.timestamp = 'Not Send';
                    }
                });
                $scope.data.sendmail = res.managers;
            }
            if(res.mails_data.length > 0 && res.last_update.length > 0){
                res.managers.forEach( h => {
                    h.emp_id = h.emp_id;
                    h.ae_id = $scope.data.single.ae_id;
                    h.check = false;
                    h.id = res.mails_data.filter(x=>x.manager_id==h.emp_id);
                    h.last_mail_sent = res.last_update.filter(x=>x.manager_id==h.emp_id);
                    if(h.id.length > 0){
                        res.mails_data.forEach(i=>{
                            if(h.emp_id == i.manager_id){
                                h.timestamp = moment(i.timestamp).format('DD-MMM-YYYY');
                            }
                        });
                    }else{
                        h.timestamp = 'Not Send';
                    }
                    res.last_update.forEach(i=>{
                        if(h.emp_id == i.manager_id){
                            h.mail2 = moment(i.mail2).format('DD-MMM-YYYY');
                        }
                    });
                });
                $scope.data.sendmail = res.managers;
            }


        });
        

        vServices.callApi("/employee/all_email_templates", "GET", {}).then(res => {
            $scope.allMailTemplates = res;
        });

		$scope.toggleAll = function() {
			var toggleStatus = !$scope.isAllSelected;
			angular.forEach($scope.data.sendmail, function(itm){ itm.check = toggleStatus; });
		 }

		$scope.send = () => {
            let counter = 0;
            data.sendmail.forEach(i=>{
                if(i.check==true){
                    counter+=1;
                }
            });
            if($scope.template_id == '' || $scope.template_id == 'undefined'){
                toastr.error("Please fill all required fields","Alert");
                return false;
            }else{
                window.alert("You have selected "+ counter + " managers.");
                vServices.callApi("/employee/postAssessmentMailToManagers", "POST", {myval: JSON.stringify(data) , template_name : $scope.template_name  }).then(data => {
                	$uibModalInstance.close({
                        counter : counter
                	});
                });
            }
		}
	})