"use strict";
appCore.controller("MyDiaryReportCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "$uibModal", "$document", function ($state, $scope, $http, $timeout, vServices, $uibModal, $document) {
    $scope.$root.page.title = "My Diary Report";
    $scope.project = [];
    $scope.selectAll = {selected: false};
    $scope.CheckedId = '';
    $scope.showLockDiv = false;
    $scope.myDiary = {default: [], project: [], heroes: [], datatable: []};
    $scope.filter = {
        fromDate: moment().subtract(2, "days").format("DD-MM-YYYY"),
        toDate: moment().format("DD-MM-YYYY"),
        project: 0,
        pageName: "My Diary Report",
        selType: "Default",
        type: [{val: "View Type"}, {val: "Default"}, {val: "Project",}, {val: "Hero",}]
    };
    $scope.myDiaryLock={
        LockTillDate : moment().format("DD-MM-YYYY")
    };
    $scope.empACL = $scope.$root.gUser.emp_acls;
    $scope.$watch("filter.selType", (newValue, oldValue) => {
        $scope.filter.pageName = "My Diary Report of " + newValue + " View";
        $scope.$root.page.title = "My Diary Report of " + newValue + " View " + $scope.filter.fromDate + " - " + $scope.filter.toDate;
    });
    $scope.projStatus = [
        {label: "Select", value: ""},
        {label: "Active", value: "active"},
        {label: "Inactive", value: "inactive"},
        {label: "Hold", value: "hold"},
        {label: "Delivered", value: "delivered"},
        // {label: "Upcoming", value: "upcoming"},
    ];
    $scope.selStatus = 'active';
    let numOr0 = n => isNaN(n) ? 0 : n;

    $scope.selectStatus = (val) =>{
        $scope.selStatus = val;
        if(val==''){
            vServices.callApi("project/all", "GET", {}).then(res => convertDataForProject(res));
        }else{
            vServices.callApi("project/all?status="+val, "GET", {}).then(res => convertDataForProject(res));
        }
        
    }

    $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(($scope.empACL.search("64") != -1 || $scope.empACL.search("65") != -1 || $scope.empACL.search("66") != -1) && $scope.empACL.search("31") != -1){
            vServices.callApi("project/getAllRevenueCenterAdmin?emp_acls=" + $scope.empACL, "GET", {}).then(function (res1) {
              if(res1){
                $scope.project = [];
                res1.forEach(o=>{
                        o.id = o.projectid;
                        o.name = o.proj_name;
                        o.proj_status = o.proj_status;
                        o.proj_mydiaryLockDate= o.proj_mydiaryLockDate
                });
                $scope.project = res1;
                $scope.filter.project = $scope.project[0];
              }
            });
          }
          else{
            if (res) {
                $scope.project = [];
                $scope.project.push({id: 0, name: " Select Project", proj_status: $scope.selStatus});
                res = $scope.$root.sort(res,'proj_name');
                // res = res.filter(proj => proj.proj_status == $scope.selStatus);
                res.map((o) => $scope.project.push({id: o.projectid, name: o.proj_name, proj_status: o.proj_status, proj_mydiaryLockDate: o.proj_mydiaryLockDate}));
                $scope.filter.project = $scope.project[0];
                // console.log( $scope.filter.project);
            }
          }

    };
    $scope.clickSelectAll = function () {
        angular.forEach($scope.myDiary.default, function (value) {
            value.selected = $scope.selectAll.selected;
            if ($scope.selectAll.selected) {
                if ($scope.CheckedId.length == 0) {
                    $scope.CheckedId = value.mydiaryid;
                }
                else {
                    $scope.CheckedId += ", " + value.mydiaryid;
                }
            }
        });
        if (!$scope.selectAll.selected) $scope.CheckedId = '';
    }
    $scope.updateLockedDate = function () {
        if (!$scope.myDiaryLock.LockTillDate) toastr.error("Please provide valid Date to Lock.");
        else vServices.callApi("mydiary/lock", "PUT", {proj_id: $scope.filter.project.id, lock_date: $scope.myDiaryLock.LockTillDate}).then((res) => {
            if (res) {
                //toastr.success(res, "Message");
            }
            $state.go($state.current, {}, {reload: true});
        });
    }
    $scope.Checked = function () {
        $scope.CheckedId = "";
        $scope.selectAll.selected = true;
        angular.forEach($scope.myDiary.default, function (value) {
            if (value.selected) {
                if ($scope.CheckedId.length == 0) {
                    $scope.CheckedId = value.mydiaryid;
                }
                else {
                    $scope.CheckedId += ", " + value.mydiaryid;
                }
            }
            else $scope.selectAll.selected = false;
        });
    }

    const convertDataForMyDiary = res => {
        if (res) {
            let newResult = null, newResult1 = null, resHero = null;
            $scope.myDiary.datatable.map((o) => {
                o.destroy();
            });

            $scope.myDiary = {default: [], project: [], heroes: [], datatable: []};
            let res1 = $scope.$root.sort(res, "emp_first_name");
            $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.$root.callDataTable(".myDiaryDataTableView", $scope.filter.selType === 'Default' ? 500 : 1000, (t) => {
                $scope.myDiary.datatable.push(t);
            }, {orientation: "landscape"});
        }
    };

    $scope.selType = (val) =>{
        $scope.$root.callDataTable(".myDiaryDataTableView", $scope.filter.selType === val ? 500 : 1000, (t) => {
            $scope.myDiary.datatable.push(t);
        }, {orientation: "landscape"});
    }

    const getData = (p, f, t) => {
        const _fromDate = $scope.$root.convertDate2DateTimeUTC(f, 'DD-MM-YYYY','00:00:00');
        const _toDate = $scope.$root.convertDate2DateTimeUTC(t, 'DD-MM-YYYY','23:59:59');
        const url = `mydiary/all?project=${p}&fromDate=${encodeURIComponent(_fromDate)}&toDate=${encodeURIComponent(_toDate)}`;
        vServices.callApi(url, "GET", {}).then(res => convertDataForMyDiary(res));
    }
    $scope.dateChanged = (first = false) => {
        if (!first) {
            $scope.showLockDiv = $scope.filter.project.id > 0 ? true : false;
            if (!$scope.filter.fromDate) toastr.error("Please provide valid FromDate");
            else if (!$scope.filter.toDate) toastr.error("Please provide valid toDate");
            else getData($scope.filter.project.id, $scope.filter.fromDate, $scope.filter.toDate);
        }
    }

    const init = () => {
        $scope.dateChanged(true);
        vServices.callApi("project/all?status="+'active', "GET", {}).then(res => convertDataForProject(res));
    };

    init();

}]);
