define(['app'], function (app) {

	app.directive('uploadImgFile', function ($rootScope) {
		return {
			restrict: 'A',
			scope: true,
			link: function (scope, element, attr) {
				element.on('change', function (event) {
					var files = event.target.files;

					if ($rootScope.imageFormat.indexOf(files[0].type) != -1) {
						$rootScope.uploadfile = files[0];
					}
					else {
						$rootScope.$apply(function () {
							$rootScope.modalShown = true;
							$rootScope.message = "Please select Image format only"
							angular.element("input[type='file']").val(null);
						})
					}

				})

			}
		}
	}
	)


	function readURL(input) {

		var num = current_imageObject.attr('data-id');
		if (input.files && input.files[0]) {
			var reader = new FileReader();

			reader.onload = function (e) {
				$('#store_image_' + num)
					.attr('src', e.target.result)
					.width(119)
					.height(112);
			}
			reader.readAsDataURL(input.files[0]);
		}
	}


	app.service("UploadFileService", function ($http, $rootScope, $timeout) {

		var service = {}
		service.upload = upload;
		var returnfun;
		function upload(formData, scope) {


			//console.log("File : ",formData);
			returnfun = scope
			$rootScope.loadingCont = true;

			var xhr;
			if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
				xhr = new XMLHttpRequest();
			}
			else {// code for IE6, IE5
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
			//this._scope['formLoad'] = false;
			xhr.upload.addEventListener("progress", uploadProgress, false)
			xhr.addEventListener("load", function (evt) {
				returnfun(evt.target.responseText);
			}, false)

			xhr.addEventListener("error", uploadFailed, false)
			xhr.addEventListener("abort", uploadCanceled, false)

			xhr.open("POST", "../services/bulletin.php")
			$rootScope.progressVisible = true
			xhr.send(formData);

		}

		function uploadProgress(evt) {
			$rootScope.$apply(function () {
				if (evt.lengthComputable) {
					//$rootScope.progress = Math.round((evt.loaded * 100 )/ evt.total)
				} else {

					//$rootScope.progress = 'unable to compute'
				}
			})

		}

		function uploadComplete(evt) {


			//scope.showAlert();

		}

		function uploadFailed(evt) {
			$rootScope.$apply(function () {
				$rootScope.loadingCont = false;
			})

		}

		function uploadCanceled(evt) {
			$rootScope.$apply(function () {
				$rootScope.loadingCont = false;
			})
		}


		return service;

	})

	app.controller('BulletinCtrl', function ($scope, $rootScope, AppData, $location, UploadFileService) {
		//Every module Set Same Variable//

		$rootScope.menucont = true;
		$rootScope.pageLoadComp = false;
		$scope.formLoad = false;
		$scope.listFound = false;
		$scope.pageData = bulletinData[$rootScope.selLanguage];
		$scope.formAction = "Add";
		$rootScope.sideselect = $scope.pageData.sidemenu[0];

		$scope.itemdetail = [];
		$scope.selectedIndex = null;
		$rootScope.cofirmWindow = false;
		$scope.submenu = $scope.pageData.sidemenu;
		$scope.tblheading = $rootScope.sideselect.headingText;
		$scope.url = "../senddata/log/";
		$scope.pageurl = "../senddata/bulletin/";
		$scope.commonurl = "../senddata/common/";
		$rootScope.imageFormat = ["image/jpeg", "image/png"]
		$rootScope.pdfFormat = ["application/pdf"];
		$rootScope.fileFormat = ["video/mp4", "application/pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx"];
		$rootScope.docFormat = ["doc", "docx", "xls", "xlsx", "ppt", "pptx"];
		$rootScope.uploadfile = '';


		//filter data
		$scope.common_filter = [];
		$scope.zonearr = [];
		$scope.regionList = [];
		$scope.dealerList = [];

		$scope.search_box = true;
		$rootScope.modalShown = false;
		$rootScope.cofirmWindow = false;
		//pagination
		$scope.viewby = '10';
		$scope.currentPage = 1;
		$scope.itemsPerPage = $scope.viewby;
		$scope.maxSize = 5; //Number of pager buttons to show
		$scope.choice = {};
		$scope.choice.filelang = '';

		//Check Session//
		$scope.formData = {}
		$rootScope.formData = {}
		$scope.formData.roleList = [];
		$rootScope.formData.roleList = [];

		$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;


		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("|");
					}
				}
				$scope.listFound = true;
				$scope.statusobj = res.item.status;
				$rootScope.username = res.item.username;

				$scope.bulletinList = function () {
					//var tobj = {};
					console.log($scope.listFound)
					$scope.searchvalue = ($scope.formData.mymodel != '') ? $scope.formData.mymodel : "";
					$scope.formData.funName = "bulletinlist";
					$scope.formData.lang = "en_us";
					if ($rootScope.sideselect.id == 1) {
						$scope.formData.pn = $scope.currentPage;
						$scope.formData.nr = $scope.itemsPerPage;
					} else {
						$scope.formData.pn = '';
						$scope.formData.nr = '';
					}
					$scope.formData.key = $scope.searchvalue;

					AppData.sendData($scope.pageurl, $scope.formData, function (res) {
						if (res.cont) {
							if (res.item != undefined) {

								$scope.bulletList = res.item.bulletin;
								$scope.totalItems = res.item.total_records;

								// $scope.listFound = true;
							}
						} else {
							$scope.listFound = false;

						}
					})
				}
				$scope.bulletinList();
				$scope.setPage = function (pageNo) {
					console.log(pageNo)
					$scope.currentPage = pageNo;
				};

				$scope.pageChanged = function () {
					console.log($scope.currentPage)
					$scope.bulletinList();
				};

				$scope.setItemsPerPage = function (num) {
					$scope.itemsPerPage = num;
					$scope.currentPage = 1; //reset to first page
					$scope.bulletinList();
				}
				$scope.filterData = function () {
					$scope.bulletinList();
				}

			} else {
				$location.path("/login");
			}
		})
		$scope.getRole = function () {
			var obj = {};
			// obj.funName = "role";
			obj.funName = "contentrole";
			obj.lang = $rootScope.selLanguage;
			obj.type = "dse"
			AppData.sendData($scope.commonurl, obj, function (res) {
				if (res.cont) {
					if (res.item != undefined) {
						$scope.role = res.item;
					}
				}
			})
		}
		$scope.getZone = function () {
			var zobj = {};
			zobj.funName = "zone";
			zobj.lang = $rootScope.selLanguage;
			AppData.sendData($scope.commonurl, zobj, function (res) {
				if (res.cont) {
					if (res.item != undefined) {
						$scope.zoneList = res.item;
					}
				}
			})
		}
		$scope.zoneChanged = function (item, i) {
			console.log(item)
			var obj = {};
			obj.cont = true;
			angular.forEach($scope.regionList, function (cityname, index) {
				if (item.zone == cityname.title) {
					angular.forEach(cityname.child, function (city, ind) {
						for (var k in $scope.formData.regionList) {
							if (city == k) {
								$scope.formData.regionList[k] = false;
							}
						}
					})
					console.log("helloooo", $scope.regionList)
					$scope.regionList.splice(index, 1);
					obj.cont = false;
				}
			})
			var fobj = {};
			fobj.lang = $rootScope.selLanguage;
			fobj.funName = "city";
			var zonename = item.zone;

			fobj.zone = (zonename == undefined) ? "" : zonename;
			if (obj.cont) {
				AppData.sendData($scope.commonurl, fobj, function (res) {
					$rootScope.pageLoadComp = true;
					if (res.cont) {
						if (res.item != undefined) {
							$scope.stateVisible = true;
							var arr = [];
							for (var id = 0; id < res.item.length; id++) {
								arr.push(res.item[id].city);
							}
							console.log(res.item, arr, "helloooo", $scope.regionList)
							$scope.regionList.push({ "title": zonename, "child": arr });
							console.log($scope.regionList)
						} else {
							$scope.regionList = [];
							$scope.dealerList = [];
							$scope.stateVisible = false;
							$scope.dealerVisible = false;
						}
					}
				});
			} else {

				//angular.forEach($scope.dealerList,function(item,index){
				if ($scope.dealerList.length != undefined) {
					for (i = 0; i < $scope.dealerList.length; i++) {
						for (var k in $scope.formData.regionList) {
							if ($scope.dealerList.length != undefined && $scope.dealerList.length > 0) {
								if (k == $scope.dealerList[i].title) {
									if ($scope.formData.regionList[k] == false) {
										angular.forEach($scope.dealerList[i].child, function (dealer, ind) {
											for (var j in $scope.formData.dealerList) {
												if (j == dealer.dealer_code) {
													$scope.formData.dealerList[j] = false;

												}
											}
											$scope.dealerList.splice(i, 1);
										})

									}
								}
							}
						}
					}
				}

			}


		}
		$scope.regionChanged = function (item, i) {
			console.log(item)
			var dobj = {};
			dobj.cont = true;
			if ($scope.dealerList != undefined) {
				angular.forEach($scope.dealerList, function (dealername, index) {
					if (item == dealername.title) {
						angular.forEach(dealername.child, function (dealer, ind) {
							for (var k in $scope.formData.dealerList) {
								if (dealer.dealer_code == k) {
									$scope.formData.dealerList[k] = false;
								}
							}
						})
						console.log("helloooo", $scope.dealerList)
						$scope.dealerList.splice(index, 1);
						dobj.cont = false;
					}
				})
			}

			var fobj = {};
			fobj.lang = $rootScope.selLanguage;
			fobj.funName = "dealer";
			var dealer_name = item;
			// if($scope.is_edit_dealer==false){

			// }else{
			// 	var dealer_name = item.toString();
			// 	$scope.is_edit_dealer= false;
			// }

			fobj.city = (dealer_name == undefined) ? "" : dealer_name;
			if (dobj.cont) {
				AppData.sendData($scope.commonurl, fobj, function (res) {
					$rootScope.pageLoadComp = true;
					if (res.cont) {
						if (res.item != undefined) {
							$scope.dealerVisible = true;
							var arr = [];
							for (var id = 0; id < res.item.length; id++) {
								var obj = {};
								obj.dealer_name = res.item[id].dealer_name;
								obj.dealer_code = res.item[id].dealer_code;
								arr.push(obj);
							}
							$scope.dealerList.push({ "title": dealer_name, "child": arr });
							console.log($scope.dealerList)
						} else {
							$scope.dealerVisible = false;
							$scope.dealerList = [];
						}
					}
				});
			} else {

			}

		}

		$scope.addFun = function () {
			$scope.formLoad = true;
			$scope.listFound = false;
			$scope.formAction = "Add";
			$scope.is_edit_region = false;
			$scope.is_edit_dealer = false;
			//$scope.title = $rootScope.sideselect.title[0];
			$scope.formData = {};
			$scope.zoneList = [];
			$scope.regionList = [];
			$scope.dealerList = [];
			$scope.formData.regionList = {};
			$scope.formData.dealerList = {};
			$rootScope.uploadfile = ""
			$scope.formData.roleList = [];
			$rootScope.formData.roleList = [];
			$scope.formLoad = true;
			$scope.formData.funName = "addbulletin";
			$scope.formTitle = "ADD BULLET-IN";
			angular.element("input[type='file']").val(null);
			$scope.getRole();
			$scope.getZone();

		}
		$rootScope.notifyChange = function () {
			if ($rootScope.formData.notification) {
				$rootScope.roleVisible = true;
				$rootScope.roleGroup = $scope.formData.roleList;
				if ($rootScope.roleGroup.length > 0) {
					angular.forEach($rootScope.roleGroup, function (element) {
						$rootScope.formData.roleList[element.id] = true;
					});
				}
			} else {
				$rootScope.roleVisible = false;
			}
		}
		$scope.deleterow = function (obj, i) {
			$scope.formData = obj;
			$scope.selectedIndex = i;
			$scope.deleteFun();
		}
		$scope.viewDetails = function () {
			console.log("here")
			var obj = {};
			obj.funName = "bulletindetails";
			obj.lang = $rootScope.selLanguage;
			obj.bulletin_id = $scope.formData.bulletin_id;
			AppData.sendData($scope.pageurl, obj, function (res) {
				$rootScope.pageLoadComp = true;
				if (res.cont) {
					$scope.formData = res.item;
					$scope.image_url = $scope.formData.image_url;
					$scope.formData.zoneList = {};
					$scope.formData.regionList = {};
					$scope.formData.dealerList = {};
					if ($scope.formData.filter_zone.length > 0) {
						angular.forEach($scope.formData.filter_zone, function (element, index) {
							console.log(element, "zoneee")
							$scope.formData.zoneList[element.zone] = true;
							if (element != '') {
								$scope.zoneChanged(element, index);
							}
						});
					} else {
						$scope.stateVisible = false;
						$scope.dealerVisible = false;

					}
					if ($scope.formData.filter_region.length > 0) {
						angular.forEach($scope.formData.filter_region, function (element, index) {
							$scope.formData.regionList[element.city] = true;
							if (element != '') {
								$scope.regionChanged(element['city'], index);
							}
						});
					} else {
						$scope.dealerVisible = false;
					}

					if ($scope.formData.filter_dealer.length > 0) {
						angular.forEach($scope.formData.filter_dealer, function (element) {
							console.log(element)
							$scope.formData.dealerList[element.dealer_code] = true;
						});
						$scope.dealerVisible = true;
					}
					$scope.formData.roleList = $scope.formData.filter_role_name;
					console.log($scope.formData.roleList, "$scope.formData.roleList ", $scope.formData.filter_role_name)
				}
			})

		}
		$scope.editFun = function () {
			$scope.filerequired = false;
			$scope.thmbrequired = false;
			$scope.formAction = "Edit";
			$scope.is_edit_region = true;
			$scope.is_edit_dealer = true;
			$(".clsbuttoncont .clsbutton").addClass("disable_btn");
			$scope.formLoad = true;
			$scope.listFound = false;
			angular.element("input[type='file']").val(null);
			if ($scope.selectedIndex != null) {

				$scope.formTitle = "EDIT BULLET-IN";
				$scope.getRole();
				$scope.getZone();
				$scope.viewDetails();

			} else {
				$rootScope.modalShown = true;
				$rootScope.message = $scope.pageData.errorMsg[0];
			}
		}
		$scope.editrow = function (obj, i) {
			$scope.formData = obj;
			$scope.formData.catename = obj.catename;
			$scope.selectedIndex = i;
			$scope.search_box = false;
			$scope.listFound = false;
			$scope.formLoad = true;
			$scope.formAction = "Edit";
			angular.element("input[type='file']").val(null);
			$rootScope.prodimage = '';
			$scope.editFun();
		}
		$scope.deleteFun = function () {
			if ($scope.selectedIndex != null) {
				$rootScope.cofirmWindow = true;
				$rootScope.modalShown = true;
				$rootScope.message = $scope.pageData.errorMsg[1];
			} else {
				$rootScope.modalShown = true;
				$rootScope.message = $scope.pageData.errorMsg[0];
			}
		}

		$scope.$on("confirmDelete", function () {
			$scope.formData.funName = "deletebulletin";
			$scope.url = $scope.pageurl
			$scope.formData.lang = $rootScope.selLanguage;
			AppData.sendData($scope.url, $scope.formData, function (res) {
				if (res.cont) {
					var index = $scope.bulletList.indexOf($scope.formData);
					if (index != -1) {
						$scope.bulletList.splice(index, 1);
					}
					$rootScope.modalShown = true;
					$rootScope.cofirmWindow = false;
					$rootScope.message = (res.mess);
				} else {
					$rootScope.modalShown = true;
					$rootScope.message = (res.mess);
				}
			})
		})
		$scope.onSearchChange = function () {
			$scope.bulletinList();
		}

		$scope.listClick = function (obj) {
			$scope.searchtext = '';
			$scope.formData = {}
			$scope.currentPage = 1;
			$(".clsbuttoncont .clsbutton").removeClass("disable_btn");
			$scope.formLoad = false;
			$rootScope.sideselect = obj;
			$scope.selectedIndex = null;
			$rootScope.sideselect.name = obj.name;
			$scope.tblheading = obj.headingText;
			$scope.bulletinList();

		}

		$scope.fieldValidation = function () {
			$scope.clearErrorMsg()
			$scope.role_error = ($scope.formData.roleList == undefined || $scope.formData.roleList == '') ? 'Please choose role' : '';
			// $scope.zone_error = ($scope.formData.zoneList == undefined || $scope.formData.zoneList == '') ? 'Please choose zone' : '';
			$scope.image_error = ($rootScope.uploadfile == undefined || $rootScope.uploadfile == '') ? 'Please upload the image' : '';
            $scope.segment_error = ($scope.formData.segment == undefined || $scope.formData.segment == '') ? 'Please any one' : '';
			//console.log($rootScope.uploadfile)
			return ($scope.role_error == '' && $scope.image_error=='' && $scope.segment_error=='') ? true : false;
		}
		$scope.clearErrorMsg = function () {
			$scope.role_error = '';
			$scope.zone_error = '';
			$scope.image_error = '';
            $scope.segment_error='';
			// $scope.topic_error = '';
		}

		$scope.formSubmit = function () {
			console.log($scope.fieldValidation())
			if ($scope.fieldValidation()) {
				var formData = new FormData();
				if ($scope.formAction == "Add") {
					formData.append("funName", "addbulletin");
				} else if ($scope.formAction == "Edit") {
					formData.append("bulletin_id", $scope.formData.bulletin_id);
					formData.append("funName", "updatebulletin");
				}
				formData.append("lang", $rootScope.selLanguage);
				formData.append("bulletin_title", $scope.formData.bulletin_title);
				formData.append("bulletin_sdesc", $scope.formData.bulletin_sdesc);
				formData.append("bulletin_desc", $scope.formData.bulletin_desc);
                formData.append("segment", $scope.formData.segment);
				formData.append("file", $rootScope.uploadfile);

				if ($scope.formData.cityList != undefined) {
					var cityarr = [];
					for (k in $scope.formData.cityList) {
						if ($scope.formData.cityList[k] == true) {
							cityarr.push(k)
						}
					}
					if (cityarr.length != 0) {
						formData.append("filter_city", cityarr.toString());
					}
				}
				if ($scope.formData.regionList != undefined) {
					var statearr = [];
					for (k in $scope.formData.regionList) {
						if ($scope.formData.regionList[k] == true) {
							statearr.push(k)
						}
					}
					if (statearr.length != 0) {
						formData.append("filter_region", statearr.toString());
					}
				}
				if ($scope.formData.dealerList != undefined) {
					var dealerarr = [];
					for (k in $scope.formData.dealerList) {
						if ($scope.formData.dealerList[k] == true) {
							dealerarr.push(k)
						}
					}
					if (dealerarr.length != 0) {
						formData.append("filter_dealer", dealerarr.toString());
					}
				}
				if ($scope.formData.zoneList != undefined) {
					var zonearr = [];
					for (k in $scope.formData.zoneList) {
						if ($scope.formData.zoneList[k] == true) {
							zonearr.push(k)
						}
					}
					if (zonearr.length != 0) {
						formData.append("filter_zone", zonearr.toString());
					}
				}
				if ($scope.formData.roleList.length != 0) {
					var rolearr = [];
					for (var id = 0; id < $scope.formData.roleList.length; id++) {
						rolearr.push($scope.formData.roleList[id].id)
					}
					formData.append("filter_role", rolearr.toString());
				}
				UploadFileService.upload(formData, function (data) {
					var response = JSON.parse(data)
					console.log(response, 'response')
					if (response.cont) {
						var obj = response.item;
						$scope.$apply(function () {
							$scope.formLoad = false;
							$scope.listFound = true;
							$scope.formData = {}
							$scope.bulletinList();
							$scope.selectedIndex = null;
							$rootScope.loadingCont = false;
							$rootScope.pageLoadComp = true;
							$rootScope.modalShown = true;
							$rootScope.message = response.mess;
						})
					} else {
						alert("alert")
						$rootScope.loadingCont = false;
						$rootScope.pageLoadComp = false;
					}
				});

			}

		} 
		$scope.closeForm = function () {
			$scope.formLoad = false;
			$scope.listFound = true;
			
			$scope.formData = {};
			$scope.selectedIndex = null;
			$scope.search_box = true;
			
			$scope.zoneList = [];
			$scope.regionList = [];
			$scope.dealerList = [];
			$scope.clearErrorMsg();
		} 
	});
}); 
