"use strict";

appCore.controller("OverAllAssessmentAdminCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "$uibModal", "$document",
    function ($state, $scope, $http, $timeout, vServices, $uibModal, $document) {
        $scope.heroes = [];
        $scope.allOverallAssessment = [];
        $scope.selectedAssessment='';
        $scope.selectedHeroes='';
        $scope.itemToUpdate={ae_id:"0",ae_heroes:""};
        $scope.$root.page.title = "List of Heroes";    
        $scope.isAllSelected = false;
        $scope.showAssigned = 'all';
        $scope.managerList = [];
        $scope.isMultiManager = false;
        $scope.managerListToUpdate=[];
        $scope.assignedManagerWithName=[];

        $scope.options = [{label:'Show All',value:'all'},{label:'Show Checked',value:'checked'},{label:'Show Unchecked',value:'unchecked'}];
        var selectedHeroes = [];
        $scope.toggleAll = function() {
            var toggleStatus = $scope.isAllSelected;
            angular.forEach($scope.heroes, function(itm){ itm.is_overall = toggleStatus;});
            setValues();
            $scope.$root.callDataTable("#heroList", 200);
        }
        $scope.toggleOne = function(index){            
            setValues();
            $scope.showAssigned = 'all';
        }

        $scope.toggleAssigned = function($val){
            $scope.showAssigned = $scope.options[$val].value;            
        }

        $scope.handleOverallAssessment = function(){
            let temp = "";
            //console.log(JSON.stringify($scope.allOverallAssessment));
            $scope.allOverallAssessment.forEach(item=>{
                if($scope.selectedAssessment==item.ae_id){
                    temp = item.ae_heroes;
                    $scope.isMultiManager = item.is_multi_mngr;
                }
            })
            let counter = 0; //count all assigned heroes
            angular.forEach($scope.heroes, function(item){ 
                if(temp.indexOf(","+item.employeeid+",")>=0){
                    item.is_overall = true; counter++;
                }
                else{
                    item.is_overall = false;
                }
            });
            toastr.success("Total "+counter+" heroes.","Total Assigned heroes");
            vServices.callApi("employee/getAssignAssessment?assessment_id="+$scope.selectedAssessment, "GET",{}).then(res=> {
                $scope.assignedManagerWithName = JSON.parse(JSON.stringify(res));
                $scope.assignedManagerWithName.forEach(item=>{                    
                    item.lm_fn = item.emp_first_name;
                    item.lm_ln = item.emp_last_name;
                    item.lm_mn = item.emp_middle_name?item.emp_middle_name:'';
                });
                $scope.heroes.forEach(item=>{
                    let emp_id = item.employeeid;
                    let assessment_id = $scope.selectedAssessment;
                    let assignment = $scope.assignedManagerWithName.filter(x=>x.hero_id==emp_id && x.assessment_id==assessment_id);            
                    if(assignment.length>0 && $scope.isMultiManager){
                        item.emp_lm = assignment[0].manager_id;
                        item.lm_fn=assignment[0].lm_fn;
                        item.lm_mn=assignment[0].lm_mn;
                        item.lm_ln=assignment[0].lm_ln;
                    }    
                });
                $scope.$root.callDataTable("#heroList", 200);
            });
            setValues();
        }

        $scope.uncheckAllHeroes = function(){
            let assessmentId = $scope.itemToUpdate.ae_id;
            vServices.callApi("employee/uncheckAllHeroes?assessmentId="+assessmentId, "GET").then(res=> {
                if(res){
                    toastr.success("All heroes are removed from assessment.");
                    window.location.reload();
                }
            });
        }

        $scope.submitAssignment = function(){            
            if($scope.itemToUpdate.ae_id===""){
                toastr.error("Select an overall assessment from dropdown, then you can submit.");
            }
            else if($scope.itemToUpdate.ae_heroes==="" || $scope.itemToUpdate.ae_heroes===",,"){
                toastr.error("Select atleast one hero to submit");
            }
            else{
                let temp = [];
                temp.push($scope.itemToUpdate);
                if (confirm("You are about to assign assessment to "+$scope.managerListToUpdate.length+" heroes, are you sure ?")) {
                    vServices.callApi("employee/getAssessmentSchedule", "POST",$scope.itemToUpdate).then(res=> {
                        vServices.callApi("employee/getAssignAssessment", "POST",{data:JSON.stringify($scope.managerListToUpdate)}).then(res=> {
                            toastr.success("Selected assessment have been assigned to "+$scope.managerListToUpdate.length+" heroes");
                            window.location.reload();
                        });                    
                    })   
                } 
            }
        }

        const setValues = function(){
            selectedHeroes = [];
            $scope.managerListToUpdate = [];
            angular.forEach($scope.heroes, function(itm){                              
                if(itm.is_overall){                    
                    selectedHeroes.push(itm.employeeid);
                    $scope.managerListToUpdate.push({hero_id:itm.employeeid,manager_id:itm.emp_lm,assessment_id:$scope.selectedAssessment});
                }
            });
            $scope.selectedHeroes = ','+selectedHeroes.join(",")+',';            
            $scope.itemToUpdate.ae_id = $scope.selectedAssessment;
            $scope.itemToUpdate.ae_heroes = $scope.selectedHeroes;            
        }

        $scope.handleManagerChange = (index,manager_id)=>{
            let assignment2 = $scope.managerList.filter(item=>item.id==manager_id);
            $scope.heroes[index].emp_lm = manager_id;
            $scope.heroes[index].lm_fn=assignment2[0].emp_first_name;
            $scope.heroes[index].lm_mn=assignment2[0].emp_middle_name;
            $scope.heroes[index].lm_ln=assignment2[0].emp_last_name;
            setValues();
        }

        const init = function () {
            if($scope.selectedAssessment!=''){
                vServices.callApi("employee/getAssignAssessment?assessment_id="+$scope.selectedAssessment, "GET",{}).then(res=> {
                    $scope.assignedManagerWithName = JSON.parse(JSON.stringify(res));
                    $scope.assignedManagerWithName.forEach(item=>{                    
                        item.lm_fn = item.emp_first_name;
                        item.lm_ln = item.emp_last_name;
                        item.lm_mn = item.emp_middle_name?item.emp_middle_name:'';
                    });
                });
            }

            vServices.callApi("employee/getAllManagers", "GET", {}).then(function (res) {
                $scope.managerList = JSON.parse(JSON.stringify(res));
                $scope.managerList.forEach(manager=>{
                    manager.manager_name = manager.emp_first_name;
                    manager.emp_middle_name = manager.emp_middle_name?manager.emp_middle_name:'';
                    manager.manager_name += ' '+manager.emp_middle_name;                    
                    manager.manager_name += ' '+manager.emp_last_name;
                });
            });

            vServices.callApi("employee/all", "GET", {}).then(function (res) {
                if (res && res.length > 0) {
                    res.sort((a, b) => {
                        let prop = "emp_code";
                        return a[prop] > b[prop] ? 1 : a[prop] < b[prop] ? -1 : 0;
                    });
                    $scope.heroes = res;
                    
                    //fire when user save data and reload save data
                    if($scope.allOverallAssessment.length>0)
                    {
                        let temp = "";
                        $scope.allOverallAssessment.forEach(item=>{
                            if($scope.selectedAssessment==item.ae_id){
                                temp = item.ae_heroes;
                            }
                        });
                        angular.forEach($scope.heroes, function(item){ 
                            if(temp.indexOf(","+item.employeeid+",")>=0){
                                item.is_overall = true;
                            }
                            else{
                                item.is_overall = false;
                            }                       
                        });            
                    }
                    $scope.$root.callDataTable("#heroList", 200);                    
                }
            });
        };
        init();
        
        const getOverallAssessment = () =>{
            vServices.callApi('employee/getOverallAssessmentSchedule?status=active',"GET",{})
            .then(res=>{
                $scope.allOverallAssessment = res;                
                console.log($scope.allOverallAssessment);
            })
            .catch(error=>{
                console.error(error);
            });
        }
        getOverallAssessment();

    }

    
]);
