"use strict";

appCore.controller("OverallAssessmentManagerReplyCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "filterFilter", "$uibModal",
    function ($state, $scope, $http, $timeout, vServices, filterFilter, $uibModal) {
        let dupHandler = [], createDiary = null, init = null, emptyHandler = null;
        $scope.monthEnd = moment().endOf('month').format("DD-MM-YYYY");
        $scope.diaries = [];
        $scope.assessmentObj={};
        $scope.diariesDataAll = [];
        $scope.allGrades = [];
        $scope.hideManagerInfo = true;
        $scope.isModalOpen = false;
        $scope.isManagerReply = false;
        $scope.loggedInUser = {};
        $scope.isAssignedManager = false;
        $scope.isHrReply=false;
        $scope.isOne2OneOpen = false;
        $scope.skipManagerOrHrId='';
        $scope.assessmentManagerList = [];
        $scope.allreadySubmmited = [];
        $scope.$root.page.title = "Assessment Reply";
        $scope.createButton = {heading: "Assessment Reply", text: "Submit Feedback", icon: "fa-save", today: new Date()};
        $scope.opts = {
            hideManagerInfo: true,
            tab: 'hero',//hero,mngr
            hasManager: false,
            idx: null,
            obj: null,
        };
        $scope.htmlEntities = (str) => {
            return String(str).replace(/&#039;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
        };
        
        $scope.assessmentSummary = {
            hero_id:$state.params.employeeid,
            manager_id:$scope.assessmentObj.as_mngr_id,
            assessment_id:$state.params.scheduleid,
            comment:'',
            other_comment:'',
            hero_score:0,
            manager_score:0,
            total_score:0,
            grade:'',
            is_complete:false
        };
        $scope.today = moment().format("DD-MM-YYYY");
        $scope.onetoOne = {};
        $scope.heroGoals = [];

        $scope.isSuperAdmin = $scope.$root.gUser.id==1 || $scope.$root.gUser.emp_acls.split(',').indexOf('1')>=0?true:false;
        // Created By Syed Bilal 
        // 27 July 2021
        // To save/draft assessment by manager

        $scope.openOneToOneModal = ()=>{
            $scope.isOne2OneOpen = true;
        }

        $scope.Save = (isDraft = false) => {
            let dataREs = $scope.diariesDataAll;
            let printMessage =  '';
            if(isDraft == true){
                printMessage = 'Your input has been saved in draft successfully. It is not visible to your team member yet.';
            } 
            if(isDraft == false){
                printMessage = 'Your assessment has been submitted successfully.';
            } 
                        
            if (dataREs) {
                let isFormValid = true;
                dataREs.forEach(item=>{
                    if((item.is_required===true && (item.as_manager_answer=='' || item.as_manager_answer==undefined)) && 
                    (item.aq_manager_reply==true && !item.manager_only && !item.rms_team_only) && 
                    (item.aq_type !== 'section')){
                        isFormValid = false;
                    }

                    if((item.is_required===true && (item.as_manager_answer==='' || item.as_manager_answer===undefined)) && 
                    (item.manager_only && $scope.isAssignedManager) && 
                    (item.aq_type !== 'section')){
                        isFormValid = false;                        
                    }

                    if((item.is_required===true && (item.as_manager_answer=='' || item.as_manager_answer==undefined)) && 
                        (item.rms_team_only && $scope.loggedInUser.is_rms_team) && (item.aq_type !== 'section')){
                        isFormValid = false;
                        console.log('hr answer-2, '+item.as_manager_answer);
                    }
                    //console.log(item.aq_name+'=='+item.as_manager_answer)
                });                

                if(!isFormValid && !isDraft){
                    toastr.error("Please fill all required fields","Alert!");
                    return false;
                }
                // && $scope.loggedInUser.is_rms_team!==true 
                dataREs.map(o => o.as_manager_status = !isDraft && o.rms_team_only!==true ? 'active' : 'draft');
                dataREs.map(o => o.as_hr_status = !isDraft && o.rms_team_only===true && $scope.loggedInUser.is_rms_team===true ? 'active' : 'draft');
                vServices.callApi("employee/add_assessment_submission_manager", "POST", {myval: JSON.stringify(dataREs)}).then((res) => {
                    if (res) {
                        toastr.success(printMessage, "Message");
                        init();                                                
                        document.getElementById("savebtn").disabled = true;
                    }
                });
            }
        };

        $scope.submitOneToOne = () => {
            let dataREs = $scope.onetoOne;
            if(dataREs.one_to_one == 'yes' && dataREs.notes == ''){
                toastr.error("Notes cannot be empty.","Alert!");
                return false;
            }
            if (dataREs) {
                vServices.callApi("employee/addOneToOne", "POST", dataREs).then((res) => {
                    if (res) {
                        toastr.success("One to One Meeting has been Added.");
                        init();
                        document.getElementById("savebtnonetoone").disabled = false;
                    }else{
                        toastr.error("One to One and Date Fields are Mandatory.");
                        init();
                    }
                });
            }
        };

        emptyHandler = (dataResult) => {
            let finalResult = [];
            return new Promise((resolve, reject) => {
                if (dataResult.length === 0) reject(false)
                for (let j = 0; j < dataResult.length; j++) {
                    var data = dataResult[j];
                    for (let i = 0; i < data.length; i++) {
                        let v = data[i];
                        /*if (v.as_answer && v.as_comments)*/
                        finalResult.push(v);                        
                        if (i === data.length - 1 && j === dataResult.length - 1) {
                            finalResult.length < 1 ? toastr.error("No Data to Save!") : toastr.success('Success! Added ' + finalResult.length + ' records.');
                            finalResult.length > 0 ? resolve(finalResult) : reject(false);
                        }
                    }
                }
            });
        };

        $scope.createDataSingle = (o, aqData, cb) => {
            if (o) {
                try {
                    dupHandler.push(o.projectid);
                    let data = JSON.parse(JSON.stringify(aqData));
                    
                    data.map(d => d.as_proj_id = !d.as_proj_id ? o.projectid : d.as_proj_id);
                    data.map(d => d.as_mngr_id = !d.as_mngr_id ? o.emp_pm : d.as_mngr_id);
                    data = data.filter(d => parseInt(d.as_proj_id) === parseInt(o.projectid));
                    const imngr = parseInt(o.mngr_id) === parseInt($scope.$root.gUser.id) ? 'mngr' : 'hero';
                    if (imngr !== 'hero' && !$scope.opts.hasManager) $scope.opts.hasManager = true;
                    $scope.diaries.push({
                        projectid: o.projectid,
                        proj_name: o.proj_name,
                        mngr_id: o.mngr_id,
                        data: data,
                        open: true,
                        selHero: null,
                        imngr: imngr
                    });
                } catch (e) {
                    console.log(e)
                }
                if (cb) cb();
            } else if (cb) {
                cb();
            }
        };

        const skipManager = ()=>{
            vServices.callApi("employee/getSkipManagerSubmission?scheduleid="+$state.params.scheduleid+"&hero_id="+$state.params.employeeid+"&hero_manager_id="+$scope.$root.gUser.id, "GET", {}).then(res => {
                $scope.allreadySubmmited = JSON.parse(JSON.stringify(res));
                $scope.allreadySubmmited.forEach(item=>{
                    item.emp_middle_name = item.emp_middle_name!=null?item.emp_middle_name:'';
                })
            });
        }
        
        init = () => {
            $scope.diaries = [];
            //get logged in user info
            vServices.callApi('employee/'+$scope.$root.gUser.id, "GET", {}).then((loggedInUser) => {
                $scope.loggedInUser = JSON.parse(JSON.stringify(loggedInUser));                
            });
            // get skip manager
            skipManager();
            
            vServices.callApi(`employee/${$state.params.employeeid}`, "GET", {}).then((emp_info) => {
                $scope.empInfo = JSON.parse(JSON.stringify(emp_info));
            
                $scope.empInfo.is_rms_team = $scope.empInfo.is_rms_team?$scope.empInfo.is_rms_team:false;
                $scope.empInfo.is_admin = $scope.empInfo.is_admin?$scope.empInfo.is_admin:false;
                $scope.isAssignedManager = $scope.empInfo.emp_lm===$scope.$root.gUser.id;

                vServices.callApi("employee/getAssessmentSummary?assessment_id="+$state.params.scheduleid+"&hero_id="+$state.params.employeeid, "GET", {}).then(assSummary => {
                    if(assSummary.length>0){                        
                        $scope.assessmentSummary = JSON.parse(JSON.stringify(assSummary[0]));
                    }                    
                });
                //get assessment schedule by id
                vServices.callApi("employee/getAssessmentScheduleById?scheduleid="+$state.params.scheduleid, "GET", {}).then(assObj => {                    
                    $scope.assessmentObj = assObj;
                    
                    let trimQuestions = $scope.assessmentObj.ae_questions?$scope.assessmentObj.ae_questions.replace(/(^,)|(,$)/g, "").split(","):[];
                    
                    //set assessment summary field value
                    $scope.assessmentSummary.total_score = $scope.assessmentObj.total_score;
                    
                    vServices.callApi("/employee/assessmentQuestionsOverall?emp_id=" + $state.params.employeeid + "&scheduleid=" + $state.params.scheduleid, "GET", {}).then(function (aqData) {
                        let heroScore = 0;
                        let managerScore = 0;                            
                        aqData.forEach((o, i) => {
                            aqData[i].aq_options = aqData[i].aq_options ? JSON.parse(aqData[i].aq_options.replace(/\\\\"/g, '"')) : {};
                            aqData[i].as_answer = aqData[i].as_answer ? $scope.htmlEntities(aqData[i].as_answer) : '';
                            aqData[i].as_comments = aqData[i].as_comments ? $scope.htmlEntities(aqData[i].as_comments) : '';
                            aqData[i].as_manager_answer = aqData[i].as_manager_answer ? $scope.htmlEntities(aqData[i].as_manager_answer) : '';
                            aqData[i].as_manager_comments = aqData[i].as_manager_comments ? $scope.htmlEntities(aqData[i].as_manager_comments) : '';
                            aqData[i].as_manager_internal_comments = aqData[i].as_manager_internal_comments ? $scope.htmlEntities(aqData[i].as_manager_internal_comments) : '';
                            if(aqData[i].as_manager_status == 'active'){
                                $scope.isManagerReply = true;                                
                                $scope.assessmentSummary.manager_id = aqData[i].as_mngr_id?aqData[i].as_mngr_id:0;
                            }

                            if((aqData[i].rms_team_only) && aqData[i].aq_type!='section' && aqData[i].as_hr_status==='active'){
                                $scope.isHrReply = true;
                            }
                            
                            if(aqData[i].aq_type=='tf' && aqData[i].as_manager_answer!=''){
                                aqData[i].as_manager_answer = aqData[i].as_manager_answer=="1"||aqData[i].as_manager_answer=="true"?true:false;                                
                            }
                            if(aqData[i].aq_type=='tf' && aqData[i].as_answer!=''){                                
                                aqData[i].as_answer = aqData[i].as_answer=="1"||aqData[i].as_answer=="true"?true:false;                                
                            }                                                        

                            aqData[i].sequence = trimQuestions.indexOf(''+ aqData[i].aq_id + '');
                            aqData[i].sequence = aqData[i].sequence+1;
                            //sum score
                            heroScore += aqData[i].as_answer && !isNaN(aqData[i].as_answer) ? parseInt(aqData[i].as_answer,10) : 0;
                            managerScore += aqData[i].as_manager_answer && !isNaN(aqData[i].as_manager_answer) ? parseInt(aqData[i].as_manager_answer,10) : 0;
                        });
                        $scope.assessmentSummary.hero_score = heroScore;
                        $scope.assessmentSummary.manager_score = managerScore;
                        $scope.diariesDataAll = aqData;
                    });
                });
            });
            
            // One to One

            vServices.callApi(`employee/get_one_to_one?assessement_id=`+ $state.params.scheduleid + "&hero_id=" + $state.params.employeeid, "GET").then((res) => {
                // console.log(res);
                if(res.length > 0){
                    $scope.onetoOne = res[0];
                }
                else{
                    $scope.onetoOne = {
                        one_to_one : '',
                        date : $scope.today,
                        notes : '',
                        hero_id : parseInt($state.params.employeeid),
                        assessment_id : parseInt($state.params.scheduleid),
                        manager_id : $scope.$root.gUser.id,
                        status : false,
                    };
                }
            });
                
          
            //get assessment schedule by id
            vServices.callApi("employee/getAssessmentManager", "GET", {}).then(res => {
                const temp = JSON.parse(JSON.stringify(res));
                const temp2 = [];
                temp.forEach(item=>{
                    // if($scope.$root.gUser.id!=item.id){                        
                        item.emp_middle_name = item.emp_middle_name?item.emp_middle_name:'';
                        temp2.push(item);
                    // }
                })
                $scope.assessmentManagerList = temp2;
            });

              // To fetch hero goals

              vServices.callApi("goal/getGoalList?hero_id="+$state.params.employeeid, "GET", {}).then(function (res) {
                if(res){
                    $scope.heroGoals = res;
                }           
            });

            // Goals End

            // Get assessment grade list
            vServices.callApi(`employee/assessment_master`, "GET", {}).then((res) => {
                $scope.allGrades = res;
            });
        };

        if ($scope.$root.gUser.id > 0) { // now super admin able to view form detail
            init();
        }

        $scope.openModal = ()=>{
            $scope.isModalOpen = true;
        }
        $scope.cancel = ()=>{
            $scope.isModalOpen = false;
            $scope.isOne2OneOpen = false;
        }
        $scope.handleAssessmentManagerChange = ($val)=>{
            if($scope.allreadySubmmited && $scope.allreadySubmmited.length>0){
                let temp = $scope.allreadySubmmited.filter(x=>x.assessment_manager_id==$val);
                if(temp.length>0){
                    toastr.error("Alread submmited");
                    return false;
                }
            }
            $scope.skipManagerOrHrId = $val;
        }        

        $scope.sendMail = () =>{
            /*
            $scope.skipManagerOrHrId // assessment manager id
            $scope.$root.gUser.id // manager id
            $state.params.employeeid //hero id
            $state.params.scheduleid// assessment schedule id*/
            if($scope.skipManagerOrHrId){
                let dataToInsert = {
                    "assessment_manager_id" : $scope.skipManagerOrHrId,
                    "hero_id" : $state.params.employeeid,
                    "assessment_id" : $state.params.scheduleid,
                    "hero_manager_id" :$scope.$root.gUser.id 
                };
                vServices.callApi("employee/getAssessmentSubmissionToSkipManage", "POST", dataToInsert).then(res => {
                    toastr.success("Your request have been submmited.", "Message");
                    $scope.isModalOpen = false;
                    skipManager();
                });
            }
            else{
                toastr.error("Please select skip manage/hr.","Message");
            }
        }
        
        

        //Submit assessment summary form
        $scope.submitAssessmentSummaryData = (isComplete)=>{
            if(!$scope.assessmentSummary.grade){
                toastr.error("Please fill all required fields");
                return false;
            }
            else if(!$scope.assessmentSummary.comment){
                toastr.error("Please fill all required fields");
                return false;
            }
            else if(!$scope.isManagerReply){
                toastr.error("Sorry, you can complete this before manager submission.");
                return false;
            }
            $scope.assessmentSummary.is_complete = isComplete;
            vServices.callApi("employee/postAssessmentSummary", "POST", $scope.assessmentSummary).then(res => {                
                if(res){
                    $scope.assessmentSummary = res;
                }
                toastr.success("Assessment form has been closed.", "Message");            
            });
        }
        //Submit assessment summary form end
        $scope.pdfData = [];
        $scope.saveAsPDF = (assessmentData,assessmentReplies) =>{
            let data1 = assessmentReplies;
            let html = ` <table id="dvTable" class="table table-bordered table-striped table-sm">
            <thead>
                <tr class="bg-blue">                                    
                    <td colspan="6" class="text-center"><strong>`+assessmentData.ae_name+`</strong> </td>
                </tr>
                <tr>
                    <td class="text-center bg-default" colspan="1">
                    <span class="text-center"><strong>Hero Name</strong></span>
                    </td>                                  
                    <td class="text-center" colspan="1">
                        <span class="text-center">`+  $scope.empInfo.emp_first_name + ' ' +  $scope.empInfo.emp_middle_name + ' ' +  $scope.empInfo.emp_last_name  + `</span>
                    </td>
                    <td class="text-center bg-default" colspan="1">
                    <span class="text-center"><strong>Employee Code</strong></span>
                    </td>                                  
                    <td class="text-center" colspan="1">
                        <span class="text-center">`+  $scope.empInfo.emp_code + `</span>
                    </td>
                    <td class="text-center bg-default" colspan="1">
                    <span class="text-center"><strong>Score</strong></span>
                    </td>                                  
                    <td class="text-center" colspan="1">
                        <span class="text-center">`+  $scope.assessmentSummary.manager_score + '/'+ assessmentData.total_score + `</span>
                    </td>
                </tr>
                <tr>
                    <td class="text-center bg-default">
                    <span class="text-center"><strong>Designation</strong></span>
                    </td>                                  
                    <td class="text-center">
                        <span class="text-center">`+  $scope.empInfo.emp_designation + `</span>
                    </td>
                    <td class="text-center bg-default">
                    <span class="text-center"><strong>Manager Name</strong></span>
                    </td>                                  
                    <td class="text-center">
                        <span class="text-center">`+  $scope.empInfo.lm_fn + ' ' +  $scope.empInfo.lm_mn + ' ' +  $scope.empInfo.lm_ln  + `</span>
                    </td>
                    <td class="text-center bg-default" colspan="1">
                    <span class="text-center"><strong>Assessment Date</strong></span>
                    </td>                                  
                    <td class="text-center" colspan="1">
                        <span class="text-center">`+  moment(assessmentData.cdate).format('MMM-YYYY') + `</span>
                    </td>
                </tr>
                <tr class="bg-blue">                                    
                <td colspan="4" class="text-center"> </td>
            </tr>
            </thead>
            <tbody>`;
            let sequence = data1;
            sequence.sort(function(a, b) {
                return a.sequence - b.sequence;
            });
            let i;
            for(i = 0; i < sequence.length ; i++){
                if(sequence[i].aq_type == 'section'){
                    html += `<tr class="bg-blue">                                  
                            <td class="bg-blue" colspan="6">
                                <span class=""><strong>` + sequence[i].aq_name + `</strong></span>
                            </td>
                            </tr>`;
                }
                if(sequence[i].aq_type == 'dropdown_scale'){
                    html += `<tr>                                  
                            <td colspan="6">
                                <span class="text-blue pointer"><strong>Q `+ i + '.) ' + sequence[i].aq_name + `</strong></span>
                            </td>
                            </tr>`;
                    let answer = sequence[i].aq_options.filter(x=> x.key == sequence[i].as_answer);
                    let manager_answer = sequence[i].aq_options.filter(x=> x.key == sequence[i].as_manager_answer);
                    html += `<tr>                                  
                            <td colspan="6">
                                <span class="text-blue pointer">Hero A `+ i + '.) '+ $scope.htmlEntities(answer[0].value) + `</span>
                            </td>
                            </tr>`;
                    html += `<tr>                                  
                            <td colspan="6">
                                <span class="text-blue pointer">Manager A `+ i + '.) '+ $scope.htmlEntities(manager_answer[0].value) + `</span>
                            </td>
                            </tr>`;
                }
                if(sequence[i].aq_type != 'section' && sequence[i].aq_type != 'dropdown_scale'){
                    html += `<tr>                                  
                            <td colspan="6">
                                <span class="text-blue pointer"><strong>Q `+ i + '.) ' + sequence[i].aq_name + `</strong></span>
                            </td>
                            </tr>`;
                    html += `<tr>                                  
                            <td colspan="6">
                                <span class="text-blue pointer" style="white-space:pre-wrap;">Hero A `+ i + '.) '+ $scope.htmlEntities(sequence[i].as_answer) + `</span>
                            </td>
                            </tr>`;
                    html += `<tr>                                  
                            <td colspan="6">
                                <span class="text-blue pointer" style="white-space:pre-wrap;">Manager A `+ i + '.) '+ $scope.htmlEntities(sequence[i].as_manager_answer) + `</span>
                            </td>
                            </tr>`;
                }
            }
            if($scope.onetoOne.status){
                html += `<tr class="bg-blue">                                  
                <td class="bg-blue" colspan="6">
                    <span>One to One Meeting</span>
                </td>
                </tr>
                <tr>
                    <td class="text-center bg-default" colspan="1">
                    <span class="text-center"><strong>Meeting Completed</strong></span>
                    </td>                                  
                    <td class="text-center" colspan="1">
                        <span class="text-center">`+  $scope.onetoOne.one_to_one + `</span>
                    </td>
                    <td class="text-center bg-default" colspan="1">
                        <span class="text-center"><strong>Date</strong></span>
                    </td>                                  
                    <td class="text-center" colspan="1">
                        <span class="text-center">`+  $scope.onetoOne.date  + `</span>
                    </td>
                    <td class="text-center bg-default" colspan="1">
                    <span class="text-center"><strong>Comment</strong></span>
                    </td>  
                    <td class="text-center" colspan="1">
                        <span class="text-center">`+  $scope.htmlEntities($scope.onetoOne.notes)  + `</span>
                    </td>
                </tr>`;
            }            
            html += `</tbody>
        </table>`;
    
        document.getElementById("print").innerHTML = html;
    
        var HTML_Width = $(".canvas_div_pdf").width();
        var HTML_Height = $(".canvas_div_pdf").height();
        var top_left_margin = 15;
        var PDF_Width = HTML_Width+(top_left_margin*2);
        var PDF_Height = (PDF_Width*1.5)+(top_left_margin*2);
        var canvas_image_width = HTML_Width;
        var canvas_image_height = HTML_Height;
        
        var totalPDFPages = Math.ceil(HTML_Height/PDF_Height)-1;
        
        
        html2canvas($(".canvas_div_pdf")[0],{allowTaint:false}).then(function(canvas) {
            canvas.getContext('2d');
            
            // console.log(canvas.height+"  "+canvas.width);
            
            var imgData = canvas.toDataURL("image/jpeg", 1.0);
            var pdf = new jsPDF('p', 'pt',  [PDF_Width, PDF_Height + 21]);
            pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin,canvas_image_width,canvas_image_height + 400);
            
            
            for (var i = 1; i <= totalPDFPages; i++) { 
                pdf.addPage(PDF_Width, PDF_Height);
                pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*20),canvas_image_width,canvas_image_height);
            }   
            pdf.save($scope.empInfo.emp_code + "_Assessment.pdf");
        });
            document.getElementById('print').style.display = "none";
        }
    }    

    //check is manager reply and one-to-one meeting done

])
