"use strict";

app.controller("ProjectHeroAddCtrl", [
    "$state", "$scope", "$http", "$timeout", "vServices", "filterFilter", "$uibModal", "$document", function ($state, $scope, $http, $timeout, vServices, filterFilter, $uibModal, $document) {
        $scope.$root.page.title = "Assign Hero to Project";
        $scope.dTable = null;
        $scope.params = $state.params;
        $scope.billingRatioOption = [
            {label: "Select", value: ""}, {label: "Full", value: "Full"}, {label: "Partial", value: "Partial"}
        ];
        $scope.emp_allocation_type = [{'value':1,'label':'Billing'},{'value':2,'label':'Shadow (Available)'},{'value':3,'label':'Shadow-I (Not Available)'},{'value':4,'label':'No Billing'}];
        $scope.billing_type = [{'value':1,'label':'Hourly'},{'value':2,'label':'Daily'}];
        $scope.allocation = {
            emp_id: 0, 
            proj_id: 0, 
            line_mngr_id: null, 
            proj_mngr_id: null, 
            isBillable: true, 
            billingRatio: "", 
            billableHours: 0, 
            partialHours: null, 
            fromDate: moment().format(moment().format("DD-MM-YYYY")),
            tentativeReleaseDate:null,
            emp_allocation_type : $scope.emp_allocation_type[0].value,
            billing_type : $scope.billing_type[0].value,
            billing_rate:0, 
            profile_id:0,
        };
        $scope.forecastProfile = [];
        
        $scope.minTeamEffort = [];
        $scope.designationOptions = [];
        $scope.managers = [];
        $scope.heroes = [];
        $scope.project = {
            "id": 0, "proj_name": "", "proj_description": "", "proj_start_date": "2001-01-01 00:00:00+05:30", "proj_expected_end_date": "2001-01-01 00:00:00+05:30", "proj_status": "active", "proj_resource_requirement_perday": 0, "proj_code": ""
        };
        const forFocus = (d) => $(document).find("#" + d).focus();

        $scope.billingCondition = true; $scope.checkBilling = (type) => { 
            if(type==1){ 
                $scope.billingCondition = true; 
            }else{ 
                $scope.billingCondition = false; 
            }
        };

        

		$scope.remaining_hours="";
		
        $scope.viewConditions = {btnTxt: 'View All', ico: 'fa-eye', viewAll: false, btnTxtCls: 'text-success'};
        $scope.viewConditionsHandler = () => {
            if ($scope.viewConditions.viewAll) {
                $scope.dTable.column(6).search('').draw();
                $scope.viewConditions = {btnTxt: 'Available Only', ico: 'fa-eye-slash', viewAll: false, btnTxtCls: 'text-danger'};
            } else {
                $scope.dTable.column(6).search('^(?![,.0]*$)\\d{1,4}(?:[.,]\\d{1,2})?$', true, false).draw();
                $scope.viewConditions = {btnTxt: 'View All', ico: 'fa-eye', viewAll: true, btnTxtCls: 'text-success'};
            }
        };

        $scope.addAllocation = () => {
            //const mobilePattern = new RegExp("^[0-9()+ -]*$");
            if (!$scope.allocation.emp_id || typeof $scope.allocation.emp_id === "object") {
                toastr.warning("Please select the hero", "Required", {timeOut: 5000});
                return false;
            }
            if (!$scope.allocation.line_mngr_id || typeof $scope.allocation.line_mngr_id === "object") {
                toastr.warning("Please select the manager", "Required", {timeOut: 5000});
                forFocus("line_mngr_id");
                return false;
            }
            if (!$scope.allocation.proj_mngr_id || typeof $scope.allocation.proj_mngr_id === "object") {
                toastr.warning("Please select the project manager", "Required", {timeOut: 5000});
                forFocus("proj_mngr_id");
                return false;
            }
            /*if (!$scope.allocation.billingRatio) {
              toastr.warning("Please select the billing ratio", "Required", {timeOut: 5000});
              forFocus("billingRatio");
              return false;
            }
            else if ($scope.allocation.billingRatio === "Partial" && !$scope.allocation.partialHours) {
              toastr.warning("Please fill the no. of hours", "Required", {timeOut: 5000});
              forFocus("partialHours");
              return false;
            }
            else if ($scope.allocation.billingRatio === "Full") {
              $scope.allocation.partialHours = 8;
            }*/
            $scope.allocation.isBillable = $scope.allocation.billableHours > 0;
            $scope.allocation.willActAs=$scope.allocation.willActAs.id;
            $scope.allocation.billingRatio = "Partial";
            vServices.callApi("allocation/add", "POST", $scope.allocation).then(function (res) {
                if (res) {
                    toastr.success(res, "Success!", {timeOut: 5000});
                    $scope.$root.updateMenu();
                    $state.go("projectView", {projectid: $state.params.projectid}, {reload: true});
                }
            });
        };

        const init = function () {
            if ($state.params && $state.params.projectid) {

                vServices.callApi("project/" + $state.params.projectid, "GET", {}).then((res) => {
                    if (res) {
                        $scope.project = res;
                        $scope.allocation.tentativeReleaseDate=$scope.project.proj_expected_end_date;
                        $scope.allocation.line_mngr_id = parseInt($scope.project.employeeid);
                        $scope.allocation.proj_mngr_id = parseInt($scope.project.employeeid);
                    }
                });
                vServices.callApi("project/designation/" + $state.params.projectid, "GET", {}).then((res) => {
                    if (res) $scope.minTeamEffort = res;
                });
                vServices.callApi("designation/all", "GET", {}).then((res) => {
                    if (res && res.length > 0) {
                        $scope.designationOptions = res;
                        $scope.designationOptions.unshift({
                            "id": 0, "desg_name": "Select", "desg_description": null
                        });
                        $scope.allocation.willActAs = $scope.designationOptions[0].id;
                    }
                });
                $scope.allocation.proj_id = $state.params.projectid;
                $scope.allocation.proj_mngr_id = $state.params.employeeid;
            }
            vServices.callApi("employee/manager/all", "GET", {}).then((res) => {
                if (res) {
                    $scope.managers = res;
                    $scope.managers.unshift({
                        "employeeid": 0, "emp_first_name": "Select", "emp_last_name": ""
                    });
                }
            });
            vServices.callApi("project/projectForecastProfile", "GET").then(function (res) {
                if (res.length>0){
                    $scope.forecastProfile = res;
                }
            });
	 
        };
		
		var initTimeBound = (intTimeout)=>{
			$timeout(()=>{
				if ($scope.myAccess.heroList) {
					vServices.callApi("employee/all", "GET", {}).then((res) => {
						if (res) {
							$scope.heroes = res;
							$scope.$root.callDataTable("#projectView", 1000, (t) => {
								try {
									$scope.dTable = t;
									//t.columns(6).data().flatten().filter(function (value, index) {return value === 1;});
									//t.column(6).search(0).draw();
									//$scope.dTable.column(6).search('^(?![,.0]*$)\\d{1,4}(?:[.,]\\d{1,2})?$', true, false).draw();
									// $scope.viewConditionsHandler();
								} catch (e) {
									console.error(e);
								}
							});
						}
					});
				} else {
					vServices.callApi("employee/get_tagged_employees/"+$scope.$root.gUser.id, "GET", {}).then((res) => {
						if (res) {
							$scope.heroes = res;
							$scope.$root.callDataTable("#projectView", 1000, (t) => {
								try {
									$scope.dTable = t;
									//t.columns(6).data().flatten().filter(function (value, index) {return value === 1;});
									//t.column(6).search(0).draw();
									//$scope.dTable.column(6).search('^(?![,.0]*$)\\d{1,4}(?:[.,]\\d{1,2})?$', true, false).draw();
									// $scope.viewConditionsHandler();
								} catch (e) {
									console.error(e);
								}
							});
						}
					});
				}
			},intTimeout);
		}
		
        init();
		$(document).ready(()=>{
			initTimeBound(1000);
		});
		
		////code 24-nov-2021
   $scope.openHeroProjectModel = (obj) => {
            vServices.callApi("allocation/allocationdata/" + $scope.allocation.emp_id, "GET", {}).then(function (total_hrs) {
                if(!total_hrs){
                    $scope.addAllocation();
                }
                else if(obj.partialHours < total_hrs[0].remaining_hours || obj.partialHours == total_hrs[0].remaining_hours){
                    $scope.addAllocation();
                }else{
                    let modalInstance = $uibModal.open({
                        animation: true,
                        ariaLabelledBy: "modal-title",
                        ariaDescribedBy: "modal-body",
                        templateUrl: "HeroProject.html",
                        controller: "HeroProjectCtrl",
                        controllerAs: "$scope",
                        size: "xl",//sm md lg
                        backdrop: "static",
                        resolve: {
                            data: () => {
                                return {
                                    hero: obj,
                                    total_hrs: total_hrs,
                                    // allocation: $scope.allProjects,
                                };
                            }
                        }
                    });
                }
            });
			
        };
        /* Model code end*/
 
}]).controller("HeroProjectCtrl", function ($uibModalInstance, data, $scope,vServices) {
    $scope.allProjectsAllocation = [];
    $scope.data = data;
    vServices.callApi("allocation/listbyempid/" + $scope.data.hero.emp_id, "GET", {}).then(function (projects) {
        if(projects){
            $scope.allProjectsAllocation = projects;
            console.log($scope.allProjectsAllocation);
        }
    });
    $scope.delHero = (d) => $uibModalInstance.close(d.hero);
    $scope.cancel = () => $uibModalInstance.dismiss("cancel");
});