"use strict";

appCore.controller("AssessmentManagerReplyCtrl", ["$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.diariesDataAll = [];
        $scope.hideManagerInfo = true;
        $scope.$root.page.title = "Assessment Reply";
        $scope.createButton = {heading: "Assessment Reply", text: "Submit", icon: "fa-save", today: new Date()};
        $scope.opts = {
            hideManagerInfo: true,
            tab: 'hero',//hero,mngr
            hasManager: false,
            idx: null,
            obj: null,
        };



        // Created By Syed Bilal 
        // 27 July 2021
        // To save/draft assessment by manager

        $scope.Save = (isDraft = false) => {
            document.getElementById("savebtn").disabled = true;
            let dataREs = $scope.diariesDataAll;
            dataREs.map(o => o.as_manager_status = isDraft ? 'draft' : 'active');
            console.log(dataREs);
            if (dataREs) {
                    vServices.callApi("employee/add_assessment_submission_manager", "POST", {myval: JSON.stringify(dataREs)}).then((res) => {
                        if (res) {
                            toastr.success(res, "Message");
                            init();
                            document.getElementById("savebtn").disabled = false;
                        }
                    });
            }
        };

        // $scope.Save = (isDraft = false) => {
        //     document.getElementById("savebtn").disabled = true;
        //     console.log($scope.diariesDataAll);
        //     console.log($scope.diaries);
        //     let dataResult = $scope.diaries.filter(o => o.imngr === 'hero').map((o) => o.data);
        //     emptyHandler(dataResult).then((data) => {
        //         data.map(o => o.as_manager_status = isDraft ? 'draft' : 'active');
        //         if (data) {
        //             // console.log(data);
        //             vServices.callApi("employee/add_assessment_submission_manager", "POST", {myval: JSON.stringify(data)}).then((res) => {
        //                 if (res) {
        //                     // console.log(res);
        //                     toastr.success(res, "Message");
        //                     init();
        //                     document.getElementById("savebtn").disabled = false;
        //                 }
        //                 // $state.go("myDiaryList", {}, {reload: true});
        //             });
        //         }
        //     }, (e) => {
        //         console.log(e);
        //     });
        // };

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

        $scope.createDataSingle = (o, aqData, cb) => {
            if (o) {
                try {
                    dupHandler.push(o.projectid);
                    let data = JSON.parse(JSON.stringify(aqData));
                    // console.log(o.projectid)
                    // data = data.filter(d => d.as_proj_id === o.projectid);
                    // data.filter((v,i,a)=>a.findIndex(t=>(t.as_proj_id === v.as_proj_id))===i);
                    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();
            }
        };

        init = () => {
            $scope.diaries = [];
            let dupHandler = [];

            // Added By Bilal
            vServices.callApi("/employee/getAssessmenByProjectHero?proj_id=" + $state.params.projectid + "&emp_id=" + $state.params.employeeid + "&scheduleid=" + $state.params.scheduleid, "GET", {}).then(function (res){
                // if (diariesDataAll) {                    
                //     console.log($scope.diariesDataAll);
                //     // $scope.logTypes.unshift({mydiarylogtypeid: "0", lt_name: "Select", lt_description: "", lt_status: "active"});
                // }

                res.forEach((o, i) => {
                    res[i].aq_options = res[i].aq_options ? JSON.parse(res[i].aq_options.replace(/\\\\"/g, '"')) : {};
                    res[i].as_answer = res[i].as_answer ? res[i].as_answer : '';
                    res[i].as_comments = res[i].as_comments ? res[i].as_comments : '';
                    res[i].as_manager_answer = res[i].as_manager_answer ? res[i].as_manager_answer : '';
                    res[i].as_manager_comments = res[i].as_manager_comments ? res[i].as_manager_comments : '';
                    res[i].as_manager_internal_comments = res[i].as_manager_internal_comments ? res[i].as_manager_internal_comments : '';
                });
                $scope.diariesDataAll = res;
                // console.log(diariesDataAll);
            });
            // Added By Bilal

            vServices.callApi(`employee/${$state.params.employeeid}`, "GET", {}).then((emp_info) => {
                $scope.empInfo = emp_info;
                vServices.callApi("/employee/assessmentQuestions?proj_id=" + $state.params.projectid + "&emp_id=" + $state.params.employeeid + "&scheduleid=" + $state.params.scheduleid, "GET", {}).then(function (aqData) {
                    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 ? aqData[i].as_answer : '';
                        aqData[i].as_comments = aqData[i].as_comments ? aqData[i].as_comments : '';
                        aqData[i].as_manager_answer = aqData[i].as_manager_answer ? aqData[i].as_manager_answer : '';
                        aqData[i].as_manager_comments = aqData[i].as_manager_comments ? aqData[i].as_manager_comments : '';
                        aqData[i].as_manager_internal_comments = aqData[i].as_manager_internal_comments ? aqData[i].as_manager_internal_comments : '';
                        if (i === aqData.length - 1) {
                            vServices.callApi("project/" + $state.params.projectid, "GET", {}).then((projectDetails) => {
                                // console.log(projectDetails);
                                vServices.callApi("employee/getAssessmentSchedulebyId?scheduleid=" + $state.params.scheduleid, "GET", {}).then((schedule) => {
                                    let aqDataFiltered = aqData.filter(o => schedule.ae_questions.includes(`,${o.aq_id},`));
                                    $scope.createDataSingle(projectDetails, aqDataFiltered, () => {
                                    });
                                });
                            });
                        }
                    });
                    // console.log('ff' + aqData);
                });
            });
            
            // vServices.callApi("allocation/projects_multiple?proj_id=1,2,3,4,5,6,7,8,9", "GET", {}).then((res) => {
            //     if (res) {
            //         $scope.logTypes = res;
            //         // $scope.logTypes.unshift({mydiarylogtypeid: "0", lt_name: "Select", lt_description: "", lt_status: "active"});
            //     }
            // });
        };

        if ($scope.$root.gUser.id > 1) init();

    }]);
