"use strict";
appCore.controller("MyDiaryBillingEfficiencyCtrl", ["$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.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.projectStatus = [{ 'value': 'active', 'label': 'Active' }, { 'value': 'inactive', 'label': 'Inactive' },
        { 'value': 'hold', 'label': 'Hold' },
        { 'value': 'delivered', 'label': 'Delivered' },
        { 'value': 'upcoming', 'label': 'Upcoming' }];
        $scope.filter = {
            date: '',
            proj_id: [],
            revenueCenters: [],
            selectedMonthBusinessDays: 20,
            projStatus: '',
        };
        $scope.myDiaryLock = {
            LockTillDate: moment().format("DD-MM-YYYY")
        };
        $scope.$watch("filter.selType", (newValue, oldValue) => {
            $scope.filter.pageName = "My Diary Billing Efficiency Report ";
            $scope.$root.page.title = "My Diary Billing Efficiency Report  ";
        });
        let numOr0 = n => isNaN(n) ? 0 : n;
        $scope.updateProjectsinRevenueCenter = () => {
            $scope.filter.projStatus = $scope.projectStatus[0].value;
            $scope.filter.proj_id = $scope.projects.filter(o => $scope.filter.revenueCenters.includes(o.acc_revenue_center) && o.proj_status == 'active').map(o => o.id);
        }
        $scope.selectAllProjects = () => $scope.filter.proj_id = $scope.projects.map(o => o.id);
        $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]));

        $scope.projectsFiltered = [];
        const convertDataForProject = res => {
            if (res) {
                $scope.projects = [];
                // $scope.employee.push({id: 0, name: " Select Employee", emp_status: 'active'});
                // res = res.filter(emp => emp.emp_status === 'active');
                res.map((o) => $scope.projects.push({ id: o.projectid, name: o.proj_name, proj_status: o.proj_status, acc_revenue_center: o.acc_revenue_center, rc_name: o.rc_name }));
                $scope.projects = $scope.$root.sort($scope.projects, 'name');
                $scope.projectsFiltered = $scope.projects;
            }
        };
        $scope.Save = (islocked) => {
            console.log($scope.myDiary.default);
            let data = $scope.myDiary.default.filter(o => !isNaN(o.actualbilledhours) && !o.islocked).map(o => {
                return { billingcenterallocationid: o.billingcenterallocationid ? o.billingcenterallocationid : null, allocationid: o.allocationid, date: moment($scope.filter.date).format('DD-MM-YYYY'), islocked: islocked, actualbilledhours: o.actualbilledhours }
            });
            console.log(data);
            vServices.callApi("mydiary/addbillingefficiency", "POST", { myval: JSON.stringify(data) }).then((res) => {
                if (res) {
                    toastr.success("Success");
                    $scope.dateChanged();
                }
            });
        }, (e) => {
            console.log(e);
        };
        $scope.dateChanged = () => {
            if (!$scope.filter.date) toastr.error("Please select valid month Range");
            else if (!$scope.filter.proj_id || $scope.filter.proj_id.length === 0) toastr.error("Please select valid Project ");
            else getData(moment($scope.filter.date).format('MM-YYYY'), $scope.filter.proj_id);
        };

        const convertDataForMyDiary = res => {
            console.log(res);
            $scope.formattedDate = moment($scope.filter.date).format('MMM-YYYY');
            if (res) {
                vServices.callApi("mydiary/billing_efficiency?date=" + moment($scope.filter.date).format('DD-MM-YYYY') + "&allocationid=" + res.map(o => o.allocationid).join(","), "GET", {}).then((res2) => {
                    $scope.myDiary.datatable.map((o) => {
                        o.destroy();
                    });
                    $scope.myDiary = { default: [], project: [], heroes: [], datatable: [] };
                    if (res2 && res2.length > 0) {
                        let merged = [];
                        for (let i = 0; i < res.length; i++) {
                            merged.push({
                                ...res[i],
                                ...(res2.find((itmInner) => itmInner.billingcenterallocationid == res[i].allocationid))
                            }
                            );
                        }
                        res = merged;
                    }
                    //commented, making it 160
                    // $scope.selectedMonthBusinessDays = moment($scope.filter.date).endOf('month').businessDaysIntoMonth();
                    // $scope.filter.selectedMonthBusinessDays = 160;
                    res.forEach(x => {
                        x.actualbilledhours = !isNaN(x.actualbilledhours) ? parseFloat(x.actualbilledhours) : 0;
                    })
                    $scope.myDiary.default = res;
                    $scope.myDiary.default.forEach(function (d) {
                        if (d.actualbilledhours) d.actualbilledhoursfromdb = true;
                        d.actualbilledhours = !d.actualbilledhours && d.actualbilledhours !== 0 ? $scope.filter.selectedMonthBusinessDays * d.actualbilledhours : d.actualbilledhours
                        // Code Fixed By Syed Mohd Bilal Rais :: 19 July 2021
                        // d.actualbilledhours = !d.actualbilledhours && d.actualbilledhours !== 0 ? $scope.filter.selectedMonthBusinessDays * d.billableHours : d.actualbilledhours
                    });
                    $scope.myDiary.default = res.filter((v, i, a) => a.findIndex(t => (t.emp_id === v.emp_id && t.proj_id === v.proj_id)) === i);
                    $scope.totalPartialHours = $scope.myDiary.default.filter(o => !isNaN(parseInt(o.partialHours))).map(o => parseInt(o.partialHours) * 20).reduce((prev, next) => prev + next);
                    $scope.totalSOWHours = $scope.myDiary.default.filter(o => !isNaN(parseInt(o.billableHours))).map(o => parseInt(o.billableHours) * 20).reduce((prev, next) => prev + next);
                    $scope.totalActualBilledHours = $scope.myDiary.default.filter(o => !isNaN(parseInt(o.mngr_sum))).map(o => parseInt(o.mngr_sum)).reduce((prev, next) => prev + next);
                    console.log(res);
                    $scope.$root.callDataTable("#myDiaryDataTableView", 100, (t) => {
                        $scope.myDiary.datatable.push(t);
                    }, { orientation: "landscape" });

                });
            }

        };

        // 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, p) => vServices.callApi("mydiary/billing_efficiency_report?date=" + d + "&proj_id=" + p, "GET", {}).then(res => convertDataForMyDiary(res));


        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("project/all", "GET", {}).then(res => convertDataForProject(res));
            vServices.callApi("/account/all_revenue_centers", "GET", {}).then(function (res) {
                if (res && res.length > 0) {
                    $scope.revenueCenters = res;
                }
            });
            setTimeout(function () {
                if (!$scope.myAccess.billingEfficiencyReportGlobal && $scope.myAccess.billingEfficiencyReportAus) {
                    $scope.revenueCenters = $scope.revenueCenters.filter(rc => rc.rc_name === "AUS");
                    $scope.projects = $scope.projects.filter(proj => proj.rc_name === "AUS");
                }
            }, 2000);
        };

        init();

        $scope.filterStatus = () => {
            $scope.filter.proj_id = $scope.projects.filter(o => $scope.filter.revenueCenters.includes(o.acc_revenue_center) && o.proj_status == $scope.filter.projStatus).map(o => o.id);
        }

    }
]);
