"use strict";

appCore.controller("OverallAssessmentCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "filterFilter", "$uibModal",
    function ($state, $scope, $http, $timeout, vServices, filterFilter, $uibModal) {
        let dupHandler = [], createDiary = null, init = null, emptyHandler = null, parseOptions = null;
        $scope.monthEnd = moment().endOf('month').format("DD-MM-YYYY");
        $scope.diaries = [];
        $scope.empInfo = {};
        $scope.total = 0;
        $scope.currentAssessmentSchedule = null;
        $scope.hideManagerInfo = true;
        $scope.$root.page.title = "Self's Assessment Entry";
        $scope.createButton = {heading: "Self's Assessment Entry", text: "Submit", icon: "fa-save", today: new Date()};
        $scope.opts = {
            hideManagerInfo: false,
            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.heroGoals = [];
        $scope.Save = (isDraft = false, schedule = null) => {
            // $('#modal-pop-up').modal('show');
            let btns = document.getElementsByClassName("savebtn");
            // btns.map(obj => obj.disabled = true);  
            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 (schedule) {
                let isFormValid = true;
                schedule.diaries.forEach(item=>{
                    if((item.is_required===true && (item.as_answer==='' || item.as_answer==undefined)) && 
                        (item.aq_type !== 'section') && 
                        (!item.manager_only && !item.rms_team_only)){
                        isFormValid = false;
                    }
                });
                if(!isFormValid && !isDraft){
                    toastr.error("Please fill all required fields","Alert!");
                    return false;
                }

                vServices.callApi("employee/getAssignAssessmentById?assessment_id="+schedule.ae_id+"&hero_id="+$scope.empInfo.employeeid, "GET", {}).then(sd => {
                    let otherManagerId = sd.length>0?sd[0].manager_id:$scope.empInfo.emp_lm;
                    schedule.diaries.forEach(item=>{
                        item.as_ae_id = parseInt(schedule.ae_id,10);
                        item.as_proj_id = "0";
                        item.as_status = isDraft ? 'draft' : 'active';
                        item.as_mngr_id = schedule.is_multi_mngr==true ? otherManagerId : $scope.empInfo.emp_lm;
                    });

                    vServices.callApi("employee/add_assessment_submission", "POST", {myval: JSON.stringify(schedule.diaries)}).then((res) => {
                        if (res && res.error) {
                            toastr.success(res.error, "Message");
                        } 
                        else if (res && res.message) {
                            toastr.success(printMessage, "Message");
                            $state.go("assessmentDiaryList", {}, {reload: true});
                            init();                                                                                    
                        }
                    });
                });
            }
            else {

            }
        };

        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 ((v.as_answer && !v.as_comments) || (!v.as_answer && v.as_comments)) {
                            toastr.error("Sorry, there seems to be some issue in your filled data, kindly re-check the data and/or required fields.");
                            reject(false);
                            return;
                        }*/
                        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);
                        }
                    }
                }
            });
        };

        createDiary = (aqData, aqDataDefault, schedule, scheduleIndex, cb) => {
            
            try 
            {                            
                let data = JSON.parse(JSON.stringify(aqData));
                const aqDataDefault2 = JSON.parse(JSON.stringify(aqDataDefault));

                // get current project id
                //data = data.filter(d => parseInt(d.as_proj_id) === parseInt(o.proj_id));
                //check if duplicate questions, filter according to scheduleid
                data = data.filter(o1 => {
                    if (o1.as_ae_id && o1.as_ae_id == schedule.ae_id) return o1;
                });

                // set defult if submission not exist
                data = data && data.length > 0 ? data : aqDataDefault2;

                $scope.currentAssessmentSchedule[scheduleIndex].diaries = JSON.parse(JSON.stringify(data));

                let counter = 0;
                aqData.forEach(item => {
                    if(item.as_ae_id == schedule.ae_id){
                        // counter += item.as_manager_answer != '' ? parseInt(item.as_manager_answer,10) : 0;
                        counter += item.as_manager_answer && isNaN(item.as_manager_answer)===false ?parseInt(item.as_manager_answer,10):0;
                    }
                    
                });
                $scope.currentAssessmentSchedule[scheduleIndex].total = counter;
            } 
            catch (e) {
                console.log(e)
            }        
            if (cb) cb();    
        };


        parseOptions = (data) => {
            return new Promise(resolve => {
                data.forEach((o, i) => {
                    try {
                        data[i].aq_options = data[i].aq_options ? JSON.parse(data[i].aq_options.replace(/\\\\"/g, '"')) : {};
                    } catch (e) {
                        data[i].aq_options = {};
                    }
                    data[i].as_answer = data[i].as_answer ? $scope.htmlEntities(data[i].as_answer) : '';
                    data[i].as_comments = data[i].as_comments ? $scope.htmlEntities(data[i].as_comments) : '';
                    data[i].as_manager_answer = data[i].as_manager_answer ? $scope.htmlEntities(data[i].as_manager_answer) : '';
                    data[i].as_manager_comments = data[i].as_manager_comments ? $scope.htmlEntities(data[i].as_manager_comments) : '';
                    data[i].as_manager_internal_comments = data[i].as_manager_internal_comments ? $scope.htmlEntities(data[i].as_manager_internal_comments) : '';
                    if (i === data.length - 1) resolve(data);
                });
            });
        };




        
    $scope.pdfData = [];
    $scope.saveAsPDF = (id,data) =>{
        let currentAssessment = data.filter(x=>x.ae_id==id);
        let data1 = currentAssessment[0];
        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>`+data1.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">`+  data1.total + '/'+ data1.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(data1.cdate).format('MMM-YYYY') + `</span>
                </td>
            </tr>
            <tr class="bg-blue">                                    
            <td colspan="4" class="text-center"> </td>
        </tr>
        </thead>
        <tbody>`;
        let sequence = data1.diaries;
        sequence.sort(function(a, b) {
            return a.sequence - b.sequence;
        });
        let i;
        let j = 1;
        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 `+ j + '.) ' + 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 `+ j + '.) '+ $scope.htmlEntities(answer[0].value) + `</span>
                        </td>
                        </tr>`;
                html += `<tr>                                  
                        <td colspan="6">
                            <span class="text-blue pointer">Manager A `+ j + '.) '+ $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 `+ j + '.) ' + 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 `+ j + '.) '+ $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 `+ j + '.) '+ $scope.htmlEntities(sequence[i].as_manager_answer) + `</span>
                        </td>
                        </tr>`;
            }
            j++;
        }
        if(data1.one_to_one[0]){
            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">`+  data1.one_to_one[0].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">`+  data1.one_to_one[0].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(data1.one_to_one[0].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+25]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin,canvas_image_width,canvas_image_height + 450);
        
        
        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";
    }


        init = () => {
            //toastr.info("Please select the project to fill assessment");
            vServices.callApi(`employee/${$scope.$root.gUser.id}`, "GET", {}).then((emp_info) => {
                    $scope.empInfo = emp_info;
                    
                    vServices.callApi("employee/getOverallAssessmentByEmpId?emp_id=" + $scope.$root.gUser.id, "GET", {}).then((as) => {
                        as = as.map(o => {
                            o.open = true;
                            o.diaries = [];
                            return o
                        });
                        $scope.currentAssessmentSchedule = as;
                        vServices.callApi("/employee/assessmentQuestionsDefault", "GET", {}).then(function (aqDataDefault) {
                            vServices.callApi("/employee/assessmentQuestions", "GET", {}).then(function (aqData) { 
                                parseOptions(aqData).then(aqData => {
                                    parseOptions(aqDataDefault).then(aqDataDefault => {
                                        $scope.currentAssessmentSchedule.forEach((schedule, s) => {
                                            let aqDataFiltered = aqData.filter(o => schedule.ae_questions.includes(`,${o.aq_id},`));
                                            let aqDataDefaultFiltered = aqDataDefault.filter(o => schedule.ae_questions.includes(`,${o.aq_id},`));
                                            
                                            // To create questions should be in sequence.
                                            let trimQuestions = schedule.ae_questions.replace(/(^,)|(,$)/g, "").split(",");
                                            aqDataFiltered.forEach(item => {
                                                item.sequence = trimQuestions.indexOf(''+ item.aq_id + '');
                                                item.sequence = item.sequence+1;
                                                
                                            });
                                            aqDataDefaultFiltered.forEach(item => {
                                                item.sequence = trimQuestions.indexOf(''+ item.aq_id + '');
                                                item.sequence = item.sequence+1;
                                                
                                            });
                                            createDiary(aqDataFiltered, aqDataDefaultFiltered, schedule, s, () => {});                                              
                                        });
                                        $state.go("assessmentDiaryList", {}, {reload: true});                                 
                                    });
                                });
                            });
                        });

                        //   // For One To One Overall Assessment For Hero
                        
                        $scope.currentAssessmentSchedule.forEach((schedule, s) => {
                            vServices.callApi(`employee/get_one_to_one_for_hero?assessement_id=`+ schedule.ae_id + "&hero_id=" + $scope.$root.gUser.id, "GET").then((res) => {
                                if(res){                                    // $scope.onetoOne = res;
                                   $scope.currentAssessmentSchedule[s].one_to_one = res
                               }
                                else{
                                    $scope.currentAssessmentSchedule[s].one_to_one = res
                                }
                            });
                        });

                        // One To One End

                        // To fetch hero goals

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

                        // Goals End
                    });                    
                }
            );
        };

        if ($scope.$root.gUser.id > 1 && init) {
            init();
        }
    }
    
])
