define(['app'], function (app) {
	app.controller('SetsalesReportCtrl', function ($scope, $rootScope, AppData, $location) {
		$rootScope.menucont = true;
		$rootScope.pageLoadComp = false;
		$scope.formLoad = false;
		$scope.listFound = false;
		$scope.pageData = setSalesReportData[$rootScope.selLanguage];
		$scope.submenu = $scope.pageData.sidemenu;
		$scope.url = "../senddata/log/";
		$scope.pageurl = "../senddata/report/";
		$scope.exporturl = "../senddata/reportdownload/";
		$scope.commonurl = "../senddata/common/";
		$rootScope.sideselect = $scope.pageData.sidemenu[0];
		//Check Session//
		$scope.formData = {}
		$rootScope.formData = {}
		// $scope.userReport=[];
		//pagination
		$scope.viewby = '10';
		$scope.currentPage = 1;
		$scope.itemsPerPage = $scope.viewby;
		$scope.maxSize = 5; //Number of pager buttons to show
		$scope.currentDate = moment().format("YYYY-MM-DD");
		$scope.startingDate = moment().startOf('month').format('YYYY-MM-DD');
		$scope.monthpicker = moment().format("MMM YYYY");
		
		$scope.formData.ismenuload = "Yes";
		if ($rootScope.items == undefined || $rootScope.items == null) {
			$scope.formData.ismenuload = "No";
		}

		$scope.formData.funName = "checksession";
		$scope.formData.lang = $rootScope.selLanguage;
		$scope.formData.start = 0;
		$scope.formData.limit = 2;
		$scope.formData.regtype = 1;
		AppData.sendData($scope.url, $scope.formData, function (res) {
			if (res.cont) {
				if ($rootScope.items == undefined || $rootScope.items == null) {
					$rootScope.items = res.item.control;

				}
				for (var i = 0; i < $rootScope.items.length; i++) {
					if ($location.path() == $rootScope.items[i].modulepath) {
						$rootScope.modulename = $rootScope.items[i].modulename;
						$scope.usercontrol = String($rootScope.items[i].permission).split("|");
					}
				}
				angular.element(document.querySelector('.table_area')).bind('scroll', function(){
					$('.datepicker').datepicker("hide")
				  })
				$scope.getZm();
			} else {
				$location.path("/login");
			}
		})
		$scope.fsubmit = function(){
			console.log("gere")
		}
		///////////// Zone Data /////////////////
		$scope.getZm = function () {
			$scope.formData = {}
			$scope.formData.zm_email = "all";
			$scope.rmInactive = true;
			$scope.amInactive = true;
			var zobj = {};
			zobj.funName = "zmlist";
			zobj.lang = $rootScope.selLanguage;
			AppData.sendData($scope.commonurl, zobj, function (res) {
				$scope.zmuser_list = res.item;
				$scope.zmChange()
			})
		}
		$scope.zmChange = function () {
			$scope.formData.rm_email = "all";
			$scope.formData.am_email = "all";
			if ($scope.formData.zm_email == "all") {
				$scope.rmInactive = true;
				$scope.amInactive = true;
				$scope.setSalesData()
			} else {
				$scope.rmInactive = false;
				$scope.amInactive = true;
				$scope.getRm();
			}
		}
		///////////// Regional Data //////////////
		$scope.getRm = function () {
			$scope.formData.rm_email = "all";
			var robj = {};
			robj.funName = "rmlist";
			robj.lang = $rootScope.selLanguage;
			robj.zm_email = $scope.formData.zm_email;
			AppData.sendData($scope.commonurl, robj, function (res) {
				$scope.rmuser_list = res.item;
				$scope.rmChange()
			})
		}
		$scope.rmChange = function () {
			$scope.formData.am_email = "all"
			if ($scope.formData.rm_email == "all") {
				$scope.amInactive = true;
				$scope.setSalesData()
			} else {
				$scope.amInactive = false;
				$scope.getAm();
			}
		}
		//////////// Area Manager Data ///////////////////
		$scope.getAm = function () {
			var aobj = {};
			aobj.funName = "amlist";
			aobj.lang = $rootScope.selLanguage;
			aobj.rm_email = $scope.formData.rm_email;
			AppData.sendData($scope.commonurl, aobj, function (res) {
				$scope.amuser_list = res.item;
				$scope.amChange()
			})
		}
		$scope.amChange = function () {
			$scope.setSalesData()
		}
		$scope.chartData = function(){
			$scope.setSalesData()
		}
		$scope.selectStatus = function () { 
			console.log($scope.formData.regtype);
			$scope.setSalesData();
		}
		//////////////// User setsales  Report ////////////////////
		$scope.setSalesData = function () {
			$scope.val = $("#startDate").val();
			console.log($scope.val)
			if($scope.val=='' || $scope.val==undefined){
				$('#startDate').datepicker("setDate", "today" );
				$scope.startMonth=moment($scope.startingMonth).format("M");
				$scope.startYear=moment($scope.startingMonth).format("YYYY");
				$scope.monthpicker = moment().format("MMM YYYY")
			}else{
				$scope.monthpicker = moment($("#startDate").val()).format("MMM YYYY")
				$scope.startMonth=moment($("#startDate").val()).format("M");
				$scope.startYear=moment($("#startDate").val()).format("YYYY");
			}
			console.log(moment($scope.startingMonth).format("M"))
			console.log(moment($scope.startingMonth).format("YYYY"))
			// $scope.formData.funName = "setsalestarget_report_v2";
			$scope.formData.funName = "setsalestarget_report_v3";
			$scope.formData.lang = $rootScope.selLanguage;
			$scope.formData.month = $scope.startMonth;
			$scope.formData.year = $scope.startYear;
			
			AppData.sendData($scope.pageurl, $scope.formData, function (res) {
				if (res.cont) {
					$scope.setSalesReportvalue=[];
					$scope.setSalesReport = res.item;
					$scope.setSalesReportvalue = [$scope.setSalesReport.total,$scope.setSalesReport.approved]
					$rootScope.modulename =  'report';
					
					if (Math.max(...$scope.setSalesReportvalue) != 0) {
						$scope.showLegend = true;
						$scope.barChart();
					}else{
						$scope.showLegend = false;
						$('.inner-chart').html('');
						$('.inner-chart').html("<h4 class='text-center' >No data found</h4>");
					}
				}

			})
		}
		$scope.getRandomColor = function () {
			var color = Math.floor(0x1000000 * Math.random()).toString(16);
			return '#' + ('000000' + color).slice(-6);
		}
		$scope.barChart = function () {
			var maxValue = 0;
			if (Math.max.apply(Math, $scope.setSalesReportvalue) == 0) {
				maxValue += 10
			} else {
				maxValue += Math.max.apply(Math, $scope.setSalesReportvalue);
			}
			$('.inner-chart').html('');
			$('.inner-chart').html('<canvas id="setsalesChart"></canvas>');
			Chart.defaults.global.legend.display = false;
			var ctx = document.getElementById("setsalesChart").getContext('2d');
			var data = {
				labels : ["Sales Target","Approved Target"],
				datasets : [
				  {
					label : "Sales",
					data : $scope.setSalesReportvalue,
					backgroundColor: [
						'rgba(0, 99, 132, 0.6)',
						'rgba(90, 99, 132, 0.6)'					  ],
					  borderColor: [
						'rgba(0, 99, 132, 1)',
						'rgba(90, 99, 132, 1)'
					  ],
					borderWidth : 1,
				  }
				  
				]
			  };
			
			  var options = {
				tooltips: {
					callbacks: {
					  title: function(tooltipItem, data) {
						  console.log(tooltipItem,data)
						  if(tooltipItem[0].xLabel=="Sales Target"){
							data.datasets[0].label = "Sales"
						  }else{
							data.datasets[0].label = "Approved"
						  }
						// return data['labels'][tooltipItem[0]['index']];
					  },
					 
					},
					
				  },
				scales : {
				  yAxes : [{
					ticks : {
						min: 0,
						suggestedMin: 0,
						fontColor: "rgba(0,0,0,0.5)",
						fontStyle: "bold",
						maxTicksLimit: 5,
						padding: 20,
						max: maxValue,
					}
				  }]
				}
			  };
			
			  var chart = new Chart( ctx, {
				type : "bar",
				data : data,
				options : options
			  });
			

		}
		
		$scope.exportData = function () {
			$scope.formData.funName = "setsalestarget_report_list_v2";
			AppData.sendData($scope.exporturl, $scope.formData, function (res) {
				if (res.cont) {
					$('body').append("<iframe id='fileDownload' src='" + res.item.report_url + "' ></iframe>");
					var setO = setTimeout(function () {
						clearTimeout(setO);
						$('#fileDownload').remove();
					}, 2000);
				}

			})
		}
		$scope.exportTableData = function () {
			// $scope.formData.funName = "setsalestarget_report_v2";
			$scope.formData.funName = "setsalestarget_report_v3";
			AppData.sendData($scope.exporturl, $scope.formData, function (res) {
				if (res.cont) {
					$('body').append("<iframe id='fileDownload' src='" + res.item.report_url + "' ></iframe>");
					var setO = setTimeout(function () {
						clearTimeout(setO);
						$('#fileDownload').remove();
					}, 2000);
				}
			})
		}
	});
}); 
