"use strict";

appCore.controller("AssessmentCtrl", ["$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 = [];
        $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.Save = (isDraft = false, schedule = null) => {
            let btns = document.getElementsByClassName("savebtn");
            // btns.map(obj => obj.disabled = true);
            if (schedule) {
                    let dataResult = schedule.diaries.filter(o => o.imngr === 'hero').map((o) => o.data);
                    emptyHandler(dataResult).then((data) => {
                        data.map(o => {
                            o.as_status = isDraft ? 'draft' : 'active';
                            o.as_ae_id = schedule.ae_id
                        });
                        if (data) {
                            // console.log(data);
                            // return;
                            vServices.callApi("employee/add_assessment_submission", "POST", {myval: JSON.stringify(data)}).then((res) => {
                                if (res && res.error) {
                                    toastr.success(res.error, "Message");
                                } else if (res && res.message) {
                                    toastr.success(res.message, "Message");
                                    // init();
                                     document.getElementsByClassName("savebtn").map(obj => obj.disabled = false);
                                }
                                // $state.go("myDiaryList", {}, {reload: true});
                            });
                        }
                    }, (e) => {
                        console.log(e);
                    });
            } 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 = (res, aqData, aqDataDefault, schedule, scheduleIndex, cb) => {
            dupHandler = [];
            if (res) {
                res.forEach((o, i) => {
                    try {
                        if (dupHandler.indexOf(o.proj_id) === -1 && o.proj_id !== 116) {
                            dupHandler.push(o.proj_id);
                            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;

                            // set project id and manager id
                            data.map(d => {
                                d.as_proj_id = (!d.as_proj_id ? o.proj_id : d.as_proj_id) + '';
                                d.as_mngr_id = (!d.as_mngr_id ? o.proj_mngr_id : d.as_mngr_id) + '';
                            });

                            const imngr = parseInt(o.mngr_id) === parseInt($scope.$root.gUser.id) ? 'mngr' : 'hero';
                            if (imngr !== 'hero' && !$scope.opts.hasManager) $scope.opts.hasManager = true;


                            $scope.totalNum = function(num){
                                return num
                                .split('')
                                .filter(function(item, pos, self) {
                                  return self.indexOf(item) == pos;
                                })
                                .join('');
                            }

                            $scope.currentAssessmentSchedule[scheduleIndex].diaries.push({
                                projectid: o.proj_id,
                                proj_name: o.proj_name,
                                mngr_name: o.emp_first_name + ' ' + ' ' + o.emp_last_name,
                                mngr_id: o.mngr_id,
                                data: JSON.parse(JSON.stringify(data)),
                                open: false,
                                selHero: null,
                                imngr: imngr
                            });
                        }
                    } catch (e) {
                        console.log(e)
                    }
                });
                if (cb) cb();
            } else if (cb) {
                cb();
            }
        };

        parseOptions = (data) => {
            return new Promise(resolve => {
                let sum = 0;
                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].total = sum + parseInt(data[i].as_manager_answer);
                    data[i].as_answer = data[i].as_answer ? data[i].as_answer : '';
                    data[i].as_comments = data[i].as_comments ? data[i].as_comments : '';
                    data[i].as_manager_answer = data[i].as_manager_answer ? data[i].as_manager_answer : '';
                    data[i].as_manager_comments = data[i].as_manager_comments ? data[i].as_manager_comments : '';
                    data[i].as_manager_internal_comments = data[i].as_manager_internal_comments ? data[i].as_manager_internal_comments : '';
                    if (i === data.length - 1) resolve(data);
                });
            });
        };

        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/getCurrentAssessmentSchedule?emp_id=" + $scope.$root.gUser.id, "GET", {}).then((as) => {
                        as = as.map(o => {
                            o.open = false;
                            o.diaries = [];
                            return o
                        });
                        $scope.currentAssessmentSchedule = as;
                        vServices.callApi("/employee/assessmentQuestionsDefault", "GET", {}).then(function (aqDataDefault) {
                            vServices.callApi("/employee/assessmentQuestions", "GET", {}).then(function (aqData) {
                                // aqData = aqData.filter(o => o.as_ae_id ? o.as_ae_id === $scope.currentAssessmentSchedule.ae_id : true);
                                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},`));
                                           
                                            // aqDataFiltered.forEach((o, i) => {
                                            //     try {
                                            //         if (i === aqDataFiltered.length - 1) {
                                            vServices.callApi("allocation/assessmentschedule_allocation_by_employee/" + $scope.$root.gUser.id + '?isschedule=true&scheduleId=' + schedule.ae_id, "GET", {}).then((projList) => {
                                                createDiary(projList, aqDataFiltered, aqDataDefaultFiltered, schedule, s, () => {
                                                });
                                            });
                                            // }
                                            // } catch (e) {
                                            //     console.log(e, aqData[i]);
                                            // }
                                            // });
                                        });
                                    });
                                });
                            });
                        });
                    });
                    // 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();

    }])
;
