"use strict";
appCore.controller("AllAllocationCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "filterFilter",
	function ($state, $scope, $http, $timeout, vServices, filterFilter) {
		$scope.allallocation = [];
        $scope.accounts = [];
        $scope.projects = [];
        $scope.revenueCentre = [];
		$scope.$root.page.title = "List of Heroes";
		$scope.colOptions = {
			Pool100:{skills:true},
			PartialPool1:{skills:true},
			PartialPool2:{skills:true},
			AllocatedButNonBillable:{email:true,skills:true}
		};
		$scope.selectLM = '';
        $scope.selectAccount = '';
        $scope.selectRevenue = '';
        $scope.selectProject = '';
        $scope.projectManagers = [];
		$scope.designations = [];
		$scope.poolDatas = [];
		$scope.allPoolAllocation = [];
		$scope.allHeroes = [];
		$scope.currentMonth = moment().format("YYYY-MM");
		$scope.month='01';
		$scope.year='2022';
		
		$scope.poolStatus = (level) => level > 50 ? "badge-danger" : level > 20 ? "badge-warning" : "badge-success";

		$scope.updateActuallBilledHours = function(){
			let month1 = moment($scope.currentMonth).subtract(1, 'months').format('YYYY-MM');
			let month2 = moment($scope.currentMonth).subtract(2, 'months').format('YYYY-MM');
			let month3 = moment($scope.currentMonth).subtract(3, 'months').format('YYYY-MM');
			vServices.callApi('allocation/updateActuallBilledHours?month1='+month1+'&&month2='+month2+'&&month3='+month3,'GET',{}).then((res) => {
				if(res){
					toastr.success("Update Actuall Billed Hours Done.");
				}
			})
		}

		$scope.updateBillableHours = function(){
			vServices.callApi('allocation/updateAllocationsHours','GET',{}).then((res) => {
				if(res){
					toastr.success("Update Done.");
				}
			})
		}

		$scope.createReport = function(){
			const data = $scope.allallocation.map(item => ({
				'emp_id' : item.employeeid,
				'account_id' : parseInt(item.accountid),
				'revenue_centre_id' : parseInt(item.acc_revenue_center),
				'project_id' : item.proj_id,
				'line_manager_id' : item.linemgr ? item.linemgr.employeeid : 0,
				'proj_manager_id' : item.projmgr ? item.projmgr.employeeid : 0,
				'billable_hours' : parseInt(item.billableHours),
				'allocated_hours' : parseInt(item.partialHours),
				'overall_allocated_hours' : parseInt(item.overall_allocated_hours),
				'overall_billable_hours' : parseInt(item.overall_billable_hours),
				'hero_revenue_centre' : parseInt(item.emp_revenue_center),
				'last_allocation_date' : moment(item.lastAlloDate).format('YYYY-MM-DD'),
				'aging': parseInt(item.aging)
			}));
			vServices.callApi('allocation/createReportForAllAllocation','POST',{'myval':JSON.stringify(data)}).then((res) => {
				if(res){
					toastr.success("Report has been created.");
				}
			})
		}

	

		$scope.selLM = function($val){
			let value = $val;
			$scope.allallocation = $scope.allallocation.filter(
				x=>value==x.linemgr.employeeid
			)
        }

		$scope.selPM = function($val){
			let value = $val;
			$scope.allallocation = $scope.allallocation.filter(
				x=>value==x.projmgr.employeeid
			)
        }


        $scope.selRevenue = function($val){
            vServices.callApi("allocation/getAccountsByRevenueCentre?revenueId="+ $val , "GET", {}).then((res) => {
                $scope.accounts = res;
                document.getElementById("selectAccount").disabled = false;
            });
        }

        $scope.selProject = function($val){
            vServices.callApi("allocation/getDesignationsByProject?projectId="+ $val , "GET", {}).then((res) => {
				if(res){
					$scope.designations = res;
				}   
				document.getElementById('selectDesignation').disabled = false;
            });
			// get PM
			vServices.callApi("allocation/getPMByProjects?projectId="+ $val , "GET", {}).then((res) => {
				if(res){
					$scope.projectManagers = res;
				}   
				console.log($scope.projectManagers);
				document.getElementById('selectPM').disabled = false;
				document.getElementById('selectLM').disabled = false;
            });
        }
        
        $scope.selAccount = function($val){
            vServices.callApi("allocation/getProjectsByAccountId?accountId="+ $val , "GET", {}).then((res) => {
                $scope.projects = res;
                document.getElementById("selectProject").disabled = false;

            });
        }

		$scope.getListReport = function($month,$year){
            vServices.callApi("allocation/allAllocationGoogleReport?month="+$month+'&year='+$year, "GET", {}).then((res) => {
				toastr.success("Update Done.");
            });
        }

		const init = function () {
			vServices.callApi("allocation/getPMByProjects?projectId="+ true , "GET", {}).then((res) => {
				if(res){
					$scope.projectManagers = res;
				}  
			});

            vServices.callApi("allocation/getAllAllocationDataForDropdown", "GET", {}).then((res) => {
                // $scope.accounts = res.accounts;
                // $scope.projects = res.projects;
                $scope.revenueCentre = res.revenueCentre;
				$scope.designations = res.designations;
            });
			vServices.callApi("employee/all", "GET", {}).then((res) => {
				res.forEach(o => {
					try{
						o.linemgr = res.filter(k => k.employeeid === o.emp_lm).map(k2 => ({
							employeeid: k2.employeeid,
							emp_first_name: k2.emp_first_name,
							emp_last_name: k2.emp_last_name
						}));
						if(o.linemgr) o.linemgr = o.linemgr[o.linemgr.length-1];
					}catch(e){}
					return o;
				});
				vServices.callApi("allocation/allDataForAllAllocation", "GET", {}).then((allallocation) => {
					let sum = 0;
					// $scope.allallocation = allallocation;
					allallocation.forEach(i=>{
						i.billableHours = isNaN(i.billableHours)===false  ? i.billableHours : 0;
						i.partialHours = isNaN(i.partialHours)===false  ? i.partialHours : 0;
						i.overall_allocated_hours = isNaN(i.overall_allocated_hours)===false  ? i.overall_allocated_hours : 0;
						i.overall_billable_hours = isNaN(i.overall_billable_hours)===false || i.overall_billable_hours!='' ? i.overall_billable_hours : 0;
					});
					vServices.callApi("allocation/allshadow", "GET", {}).then((allshadow) => {
						if (allshadow) $scope.allshadow = allshadow;
						if (res && res.length > 0) {
							$scope.allHeroes=res;
							$scope.poolDatas.push({data: res.filter(o => o.emp_pool > 7 & o.emp_pool < 9)});	
							$scope.allPoolAllocation = $scope.poolDatas[0].data;
							$scope.allPoolAllocation.forEach(item=>{
								item.emp_desg = item.emp_designation;
								item.proj_name = '';
								item.projectid = '';
								item.acc_revenue_center = '';
								item.billableHours = 0; 
								item.partialHours = 0;
								item.accountid = 0;
								item.overall_allocated_hours = 0;
								item.overall_billable_hours = 0;

							})
							Array.prototype.push.apply(allallocation, $scope.allPoolAllocation);
							var onlyPool = allallocation.filter(o => o.emp_pool > 7 & o.emp_pool < 9);
							var empIds = onlyPool.map(x=>x.employeeid);
							vServices.callApi("employee/agingForHeroes", "POST", {'myVal':JSON.stringify(empIds)}).then((agingForHeroes) => {
								allallocation.forEach(i=>{
									var dated = agingForHeroes.find(x=> x.emp_id == i.employeeid);
									i.lastAlloDate =  dated ? dated.toDate : moment(i.emp_doj);
									i.aging = dated ? moment().diff(dated.toDate,'days') : 0;
								})
							});
							$scope.allallocation = allallocation;
							$scope.$root.callDataTable(".poolList", 1000);
						}
					});
				});
			});
		};
		init();
	}
]);
