"use strict";
appCore.controller("MyDiaryUtilityReportCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "$uibModal", "$document",
    function ($state, $scope, $http, $timeout, vServices, $uibModal, $document) {
        $scope.$root.page.title = "My Diary Unfilled Report";
        $scope.project = [];
        $scope.selectAll = {selected: false};
        $scope.CheckedId = "";
        $scope.tblheader = [];
        $scope.revenueCenters = [];
        $scope.showLockDiv = false;
        $scope.emp_status = false;
        $scope.myDiary = {default: [], project: [], heroes: [], datatable: []};
        $scope.monthRangeSelection = [{'value': '3', 'label': 'Last 3 Months'}, {'value': '6', 'label': "Last 6 months"}, {'value': '12', 'label': "Last 12 months"}];

        $scope.filter = {
            date: '',
            emp_id: [],
            logtype: [],
            revenueCenters: [],
            monthlyWorkingHours: 160
        };
        $scope.myDiaryLock = {
            LockTillDate: moment().format("DD-MM-YYYY")
        };
        $scope.$watch("filter.selType", (newValue, oldValue) => {
            $scope.filter.pageName = "My Diary Utility Report ";
            $scope.$root.page.title = "My Diary Utility Report  ";
        });
        let numOr0 = n => isNaN(n) ? 0 : n;
        $scope.updateEmployeesinRevenueCenter = () => $scope.filter.emp_id = $scope.employee.filter(o => $scope.filter.revenueCenters.includes(o.emp_revenue_center)).map(o => o.id);
        $scope.selectAllEmployee = () => $scope.filter.emp_id = $scope.employee.map(o => o.id);
        $scope.selectAllCategory = () => $scope.filter.logtype = $scope.logTypes.map(o => o.mydiarylogtypeid);
        $scope.selectAllrevenueCenters = () => $scope.filter.revenueCenters = $scope.revenueCenters.map(o => o.revenuecenterid);
        $scope.totalHoursNew = (a, k, d) => d && d.length > 0 ? d.map(o => o[k]).reduce((a, b) => parseFloat(numOr0(a)) + parseFloat(numOr0(b))) : null;
        $scope.totalHours = (a, k, d) => d.map(o => o[k]).reduce((a, b) => parseFloat(numOr0(a)) + parseFloat(numOr0(b)));
        $scope.condition = (i, d, data, c) => i === 0 ? true : (i > 0 && parseInt(d[c]) !== parseInt($scope.myDiary[data][i - 1][c]));


        const convertDataForProject = res => {
            if (res) {
                $scope.employee = [];
                // $scope.employee.push({id: 0, name: " Select Employee", emp_status: 'active'});
                //res = res.filter(emp => emp.emp_status === 'active');
                res.map((o) => $scope.employee.push({id: o.employeeid, name: o.emp_first_name + (o.emp_middle_name ? ' ' + o.emp_middle_name + ' ' : ' ') + o.emp_last_name + ' (' + o.emp_code + ')', emp_status: o.emp_status, emp_revenue_center: o.emp_revenue_center}));
                $scope.employee = $scope.$root.sort($scope.employee, 'name');
            }
        };

        const convertDataForMyDiary = res => {
            if (res) {
                let newResult = null, newResult1 = null, resHero = null;
                $scope.myDiary.datatable.map((o) => {
                    o.destroy();
                });
                // remove date from header
                document.querySelectorAll("#myDiaryDataTableView thead tr th.datehead").forEach(o => o.remove());

                $scope.myDiary = {default: [], project: [], heroes: [], datatable: []};
                // let res1 = $scope.$root.sort(res, "emp_first_name");
                $scope.myDiary.default = res;
                // $scope.myDiary.default = $scope.$root.sort(res1, "proj_name");
                //
                // newResult = res.map(o => o.proj_name + "~" + o.projectid).filter((v, i, s) => s.indexOf(v) === i).sort();
                //
                // newResult.forEach(o => {
                //     const proj = o.split("~");
                //     $scope.myDiary.project.push({name: proj[0], id: proj[1], data: res.filter(j => j.projectid === parseInt(proj[1]))});
                // });

                // newResult1 = res.map(o => o.emp_first_name + " " + o.emp_last_name + "-" + o.employeeid).filter((v, i, s) => s.indexOf(v) === i).sort();
                // resHero = $scope.$root.sort(res, "projectid");
                // newResult1.forEach(o => {
                //     const hero = o.split("-");
                //     $scope.myDiary.heroes.push({name: hero[0], id: hero[1], data: resHero.filter(j => j.employeeid === parseInt(hero[1]))});
                // });
                $scope.tblheader = [];

                // res[0].logged_hours.forEach((o)=>{
                //     console.log(o);
                // })
              /*  var headerLength = 1;
                for (let k = 1; k <= parseInt($scope.filter.date); k++) {
                    try {
                        headerLength++;
                        for (let i = 0; i < $scope.myDiary.default.length; i++) {
                            let o = $scope.myDiary.default[i];
                            let timeZone = o.logged_hours.length > 0 ? o.logged_hours[0].txn_month.slice(-6) : o.billingEfficiency.length > 0 ? o.billingEfficiency[0].billingefficiencymonth.slice(-6) : '';

                            if (k === 1) {
                                for (let j = 0; j < parseInt($scope.filter.date); j++) {
                                    let h = o.logged_hours;
                                    if (!o.logged_hours_new) o.logged_hours_new = [];
                                    let h2 = o.billingEfficiency;
                                    // if (!o.logged_hours_new) o.logged_hours_new = [];
                                    if (h2.length && h2.some(o => o.billingefficiencymonth == moment().subtract(j + 1, "month").format('YYYY-MM-01 00:00:00' + timeZone))) {
                                        o.logged_hours_new.push({val: h2.filter(o => o.billingefficiencymonth == moment().subtract(j + 1, "month").format('YYYY-MM-01 00:00:00' + timeZone))[0].billingefficiencysum});
                                        // break;
                                    } else o.logged_hours_new.push({val: '0'});

                                    // console.log(h ? h.txn_month : 'na')
                                    // debugger
                                    if (h.length && h.some(o => o.txn_month == moment().subtract(j + 1, "month").format('YYYY-MM-01 00:00:00' + timeZone))) {
                                        o.logged_hours_new.push({val: h.filter(o => o.txn_month == moment().subtract(j + 1, "month").format('YYYY-MM-01 00:00:00' + timeZone))[0].monthly_sum});
                                        o.logged_hours_new.push({val: Math.round((parseInt(h.filter(o => o.txn_month == moment().subtract(j + 1, "month").format('YYYY-MM-01 00:00:00' + timeZone))[0].monthly_sum) / parseInt($scope.filter.monthlyWorkingHours)) * 100)});
                                        // break;
                                    } else {
                                        // console.log(h)
                                        o.logged_hours_new.push({val: '0'});
                                        o.logged_hours_new.push({val: '0'});
                                    }

                                }
                            }
                            /!*if (!o.logged_hours || o.logged_hours.length === 0) {
                                if (!o.logged_hours_new) o.logged_hours_new = [];
                                o.logged_hours_new.push({val: '0'});
                                o.logged_hours_new.push({val: '0'});
                            }*!/
                        }
                        /!*$scope.myDiary.default = $scope.myDiary.default.forEach(o => o.logged_hours.forEach(h => {
                            let count = 0;
                            if (h.txn_month === moment().subtract(k, "month").format('YYYY-MM-DD 00:00:00'+timeZone)) {
                                return;
                            } else count++;
                            if (count === o.length) {
                                o.push({txn_month: moment().subtract(k, "month").format('YYYY-MM-DD 00:00:00'+timeZone), monthly_sum: '0'});
                                return;
                            }
                        }));*!/
                        var node = document.createElement("th");
                        var textnode = document.createTextNode(moment().subtract(k, "month").startOf("month").format('MMM YYYY') + ' - Actual Billed Hours(Total)');              // Create a text node
                        node.setAttribute("class", "datehead");
                        node.appendChild(textnode);                             // Append the text to <li>
                        //document.getElementById("myList").appendChild(node);    // Append <li> to <ul> with id="myList"

                        document.querySelector("#myDiaryDataTableView thead tr").appendChild(node);

                        //second
                        node = document.createElement("th");
                        textnode = document.createTextNode(moment().subtract(k, "month").startOf("month").format('MMM YYYY') + ' - Total Hours logged');              // Create a text node
                        node.setAttribute("class", "datehead");
                        node.appendChild(textnode);                             // Append the text to <li>
                        //document.getElementById("myList").appendChild(node);    // Append <li> to <ul> with id="myList"

                        document.querySelector("#myDiaryDataTableView thead tr").appendChild(node);
                        var textnode2 = document.createTextNode(moment().subtract(k, "month").startOf("month").format('MMM YYYY') + ' - Diary Percentage');              // Create a text node
                        // node.appendChild(textnode);
                        // texAppend the text to <li>
                        // textnode.textContent='adf';
                        var node2 = document.createElement("th");
                        node2.setAttribute("class", "datehead");

                        // var textnode = document.createTextNode(moment().subtract(k, "month").startOf("month").format('MMM YYYY') + ' - Total Hours logged');              // Create a text node
                        node2.appendChild(textnode2);                             // Append the text to <li>
                        document.querySelector("#myDiaryDataTableView thead tr").appendChild(node2);
                    } catch (e) {
                        console.error(e);
                    }
                    //console.log(k, res[0].logged_hours[k]);
                }
                ;
           */     // console.log($scope.myDiary.default);

                $scope.$root.callDataTable("#myDiaryDataTableView", 500, (t) => {
                    $scope.myDiary.datatable.push(t);
                }, {orientation: "landscape"});

                // $scope.tblheader = (res[0].logged_hours);
                // console.table($scope.tblheader);

            }

        };

        // const getData = (d, l, e) => vServices.callApi("mydiary/utility_report?date=" + d + "&logtype=" + l + "&emp_id=" + e, "GET", {}).then(res => convertDataForMyDiary(res));
        const getData = (d, l, e) => vServices.callApi("mydiary/utility_report?date=" + d + "&logtype=" + l + "&emp_id=" + e, "GET", {}).then(res => convertDataForMyDiary(res));
        $scope.dateChanged = () => {
            if (!$scope.filter.date) toastr.error("Please select valid month Range");
            else if (!$scope.filter.logtype) toastr.error("Please select valid Category");
            else if (!$scope.filter.emp_id) toastr.error("Please select valid Employee ");
            else getData(moment($scope.filter.date).format('MM-YYYY'), $scope.filter.logtype, $scope.filter.emp_id);
        };

        $scope.updateEmployeesForMonth = () => {
            let logtype = $scope.filter.logtype;
            let revenueCenters = $scope.filter.revenueCenters;
            let month = moment($scope.filter.date).format('MM-YYYY');
            vServices.callApi("/mydiary/allHeroesByRevenueAndLogType?revenueCenters=" + revenueCenters + "&logtype=" + logtype + "&month=" + month , "GET", {}).then(function (res) {
                if (res && res.length > 0) {
                    $scope.filter.emp_id = $scope.employee.filter(o => res.includes(o.id)).map(o => o.id);
                }
            });

        }

        $scope.selectActiveEmployee = (emp_status,employee)=>{
            let gotData = $scope.filter.emp_id;
            if(emp_status==true){
                let activeOnly = $scope.employee.filter(i=> i.emp_status=='active');
                $scope.filter.emp_id =  activeOnly.filter(o => gotData.includes(o.id)).map(o => o.id);
            }
            else{
                let logtype = $scope.filter.logtype;
                let revenueCenters = $scope.filter.revenueCenters;
                let month = moment($scope.filter.date).format('MM-YYYY');
                vServices.callApi("/mydiary/allHeroesByRevenueAndLogType?revenueCenters=" + revenueCenters + "&logtype=" + logtype + "&month=" + month , "GET", {}).then(function (res) {
                    if (res && res.length > 0) {
                        $scope.filter.emp_id = $scope.employee.filter(o => res.includes(o.id)).map(o => o.id);
                    }
                });
            }
        }


        const init = () => {
            // getData();
            vServices.callApi("mydiary/all_logtypes", "GET", {}).then((res) => {
                if (res) {
                    $scope.logTypes = res;
                    // $scope.logTypes.unshift({mydiarylogtypeid: "0", lt_name: "Select", lt_description: "", lt_status: "active"});
                }
            });
            // vServices.callApi("employee/limited", "GET", {}).then(res => convertDataForProject(res));
            vServices.callApi("employee/allEmployeeData", "GET", {}).then(res => convertDataForProject(res));
            vServices.callApi("/account/all_revenue_centers", "GET", {}).then(function (res) {
                if (res && res.length > 0) {
                    $scope.revenueCenters = res;
                }
            });
        };

        init();

    }
]);
