var TaxiApp = angular.module('CompanyCustomersApp', ['ngStorage', 'ngDialog', 'angularSpinner', 'ui.bootstrap',  'angular-growl']);
var CustomersList;
var SelectedObj;
var EditFlag;
var EditItem;
var EditName;
var EditNo;
var Blocked;
var AddNewCustomer;
Number.prototype.pad = function (size) {
    var s = String(this);
    while (s.length < (size || 2)) { s = "0" + s; }
    return s;
}

TaxiApp.controller('CompanyCustomersCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'usSpinnerService', 'growl', 'AddCustomer','EditCustomer','ConfirmBlock',
    function ($scope, $http, $sessionStorage, ngDialog, usSpinnerService, growl, AddCustomer, EditCustomer, ConfirmBlock) {
        $scope.loading = false;
        $scope.injectedObject = {};
        var obj;
       

        var TokenID = sessionStorage.TokenID;
        var orgOID = sessionStorage.ORGOID;
        var userOID = sessionStorage.UserOID;
        var roleType = sessionStorage.RoleType;
        var roleID = sessionStorage.RoleID;
        var groupOID = 0, Status = "0,1";
        var OID = "0";
        var cOID, cName;
        var companyOID = sessionStorage.CompanyOID;
        $scope.logo = sessionStorage.Photo;
        $scope.DisplayName = sessionStorage.UserName;
        $scope.CompanyName = sessionStorage.value;
        var OLDpswd = sessionStorage.password;
        var cityOID = sessionStorage.CityID;
        var UserOID = sessionStorage.UserOID;
        //Check Whether user Logged in or not
        //CheckUserLogged();
        $scope.logo = sessionStorage.Photo;
        var Vehiclename, vehicle;
       
        if (sessionStorage.CompanyOID != undefined || sessionStorage.ORGOID != undefined) {
            loadDropDownFromAppConfig("COMPANY", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, 0, $scope);
            GetCompanyCityOID("CompanyCity", userOID, companyOID, orgOID, groupOID);
        }
        $scope.selectCompanydetails = function (obj) {
            sessionStorage.value = obj.Value;
            sessionStorage.value = obj.Value;
            window.location.href = "MapView.html";
        }
        if (sessionStorage.RoleType != "Superadmin" && sessionStorage.AllAdmins != null) {
            $scope.AdminList = JSON.parse(sessionStorage.AllAdmins);
            $scope.firstadmin = JSON.parse(sessionStorage.selectedadmin);

        }
        if (sessionStorage.length == (undefined || 0)) {

            window.parent.location.href = "../../Index.html";
        }
        $scope.User = sessionStorage.Username;
        //set cureentdate as default date in datepicker
        $scope.tdate = new Date();
        $scope.fdate = new Date();
        $scope.ScuedualList = [];
      
        Localization(sessionStorage.selectedLanguage, 'mapview', $scope, sessionStorage);

        $scope.value3 = 5;

        $scope.options2 = {
            from: 1,
            to: 10,
            floor: true,
            step: 1,
            dimension: " speed",
            vertical: false,
            callback: function (value, elt) {

            }
        };
        if (sessionStorage.RoleType == "Organization Admin") {
            $('.tele').show();
        }
        else {
            $('.tele').hide();
        }
       
       
        var Landmarks = {
            init: function (SelectedObj) {
                Landmarks.populate(SelectedObj);
            },
            populate: function (SelectedObj) {



                var LandMarks = document.getElementById('LandMarks');

                $.ajax({
                    cache: true,
                    url: WebsiteServiceUrl + "GetCustomerNameWithLandmark/" + SelectedObj.CustomerCallingNumber + "/" + sessionStorage.CompanyOID,
                    type: 'GET',
                    //jsonpCallback: "loginResponse",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    error: function () {
                        $scope.loading = false;
                    },
                    success: function (result) {
                        $scope.loading = false;
                       
                     
                        var response = JSON.parse(result.GetCustomerNameWithLandmarkResult);
                        for (var l = 0; l < response.landMarks.length; l++) {
                          //  console.log(response.landMarks[l].LandmarkName);
                            // Create the list item:
                           var Landmark_Item = document.createElement('div');
                            Landmark_Item.className = "Landmark_Item";
                            Landmark_ItemTitle = document.createElement('h5');
                            var lanmark_txt = document.createTextNode(response.landMarks[l].LandmarkName);
                            Landmark_ItemTitle.appendChild(lanmark_txt);
                            Landmark_Item.appendChild(Landmark_ItemTitle);
                            LandMarks.appendChild(Landmark_Item);

                        }

                       
                        $scope.$apply();


                    }
                });
             

            }


        }
        /*----------------------------      GetCompanyCustomers          ---------------*/

        var GetCompanyCustomers = {

            get: function(no,name) {
                $.ajax({
                    cache: true,
                    url: WebsiteServiceUrl + "CustomerSearch/" + no + "/" + sessionStorage.CompanyOID + "/" + name,
                    type: 'GET',
                    //jsonpCallback: "loginResponse",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    error: function () {
                        $scope.loading = false;
                    },
                    success: function (result) {

                        $scope.loading = false;
                       
                        var response = result.CustomerSearchResult.split('~');
                        var data = JSON.parse(response[0]);
                       
                        $scope.searchListResult = data;
                       


                        $scope.$apply();
                    
                    }
                });

            },
          
           
        }
        $("#viewall").click(function () {

            var no = $("#no").val();
            var name = $("#name").val();
            if (no == "" && name == "") {
               alert("ادخل الرقم او الاسم")
                
            } else {
                if (no == "") { no = 0 }
                if (name == "") { name = 0 }
                $(".ToBeHiddenTableTR").hide();
                GetCompanyCustomers.get(no, name);
            }
        });
        /*----------------------------      CustomerDetail          ---------------*/

        $scope.CustomerDetail = function (obj) {
            $(".CustomerName h4").html(obj.CustomerName)
            $("#cid").html(obj.CustomerId);
            if (obj.isBlackListed == true)
            {
              
                $(".blackListDiv label").html("الغاء الحظر");

            }
            if (obj.isBlackListed == false || obj.isBlackListed == null) {

                $(".blackListDiv label").html(" حظر");
                   
            }
            SelectedObj = obj;
           // console.log(SelectedObj)
            $('#LandMarks').empty();
            Landmarks.init(SelectedObj);
            if (!$('#Hidden').is(":visible")) {
                $("#Hidden").toggle();
            }
           

            
            }
        /*----------------------------      Edit          ---------------*/

          EditItem = {
              edit: function (obj) {
                 if (EditFlag == 0) {
                  
                     if (SelectedObj.isBlackListed == true) {
                         
                         SelectedObj.isBlackListed = false;
                     }

                     else {
                         SelectedObj.isBlackListed = true;


                     }


                 }
                 else if (EditFlag == 1) {

                     SelectedObj.CustomerName = EditName

                     SelectedObj.CustomerCallingNumber = EditNo

                 } 


                 var obj = {

                     "CustomerId": SelectedObj.CustomerId,
                     "CustomerName": SelectedObj.CustomerName,
                     "CustomerCallingNumber": SelectedObj.CustomerCallingNumber,
                     "TaxiCompanyID": SelectedObj.TaxiCompanyID,
                     "isBlackListed": SelectedObj.isBlackListed

                 }
                var annObj = {
                    
                    "customerObject": obj
               
                 };


                 $scope.loading = true;
                 $.ajax({
                     type: "POST",
                     url: WebsiteServiceUrl + "CustomerEdit",
                     data: JSON.stringify(annObj),
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     processData: true,
                     success: function (data) {

                         var x = data.CustomerEditResult.replace(/"/g, "");
                         if (x == 1) {
                             $scope.CustomerDetail(SelectedObj)
                            
                         }
                         else {
 alert("حدث خطا حاول مرة اخرى");
                          
                         }

                         $scope.loading = false;

                     }
                 });
                 
             }
         }
         $("#EditIcon").click(function () {

             $scope.EditCustomerItem();


         });
         $("#Block").click(function () {
             EditFlag = 0;
             $scope.BlockCustomerItem();

         });

    




         $("#newwbook").click(function () {

             $scope.AddCustomerItem();


         });
        
       
        /*----------------------------      Scope functions          ---------------*/
         $('input').keypress(function (evt) {
             if (evt.keyCode == 13) {//enter
                 iname = $(this).val();
                 if (iname !== 'Submit') {
                     var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
                     var index = fields.index(this);
                     if (index > -1 && (index + 1) < fields.length) {
                         fields.eq(index + 1).focus();
                     }
                     return false;
                 }
             }

         });
        
          $scope.AddCustomerItem = function () {
              AddCustomer.open();



          }
          $scope.EditCustomerItem = function () {
              EditCustomer.open();



          }
          $scope.BlockCustomerItem = function () {
              ConfirmBlock.open();



          }
}
        
])
/*----------------------------      AddCustomer          ---------------*/

TaxiApp.service('AddCustomer', function ($modal) {
    var service = {};
    var self = this;
    service.open = function () {

        var modalInstance = $modal.open({
            windowClass: 'AddCustomer',
            templateUrl: 'AddCustomer.html',
            controller: 'AddCustomerCtrl',
            resolve: {

            }

        });

    };

    return service;
});

TaxiApp.controller('AddCustomerCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, $modalInstance) {


    $scope.loading = true;
    //sessionStorage.selectcompany = "Group";

    $('#name').keypress(function (evt) {
       // console.log("sdf;sd;flk");
        if (evt.keyCode == 13) {//enter
            event.preventDefault();
            var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
            var index = fields.index(this);
            if (index > -1 && (index + 1) < fields.length) {
                fields.eq(index + 1).focus();

            }

        }
    });

    // LoadlanMark(orgOID, companyOID, sessionStorage.CityID);


    $scope.ClickClose = function () {

        $modalInstance.dismiss('Cancel');

    }
    $scope.AddNewDialog = function () {
        if (!$("#new_name").val() || !$("#new_number").val())
        {
            $(".HiddenMsg").show();
            $("#new_name").addClass('error');
            $("#new_number").addClass('error');
          
        }
        else {
            var value = $("#new_number").val()
            if (value.length >= 9 && value.length <= 10) {
                $(".HiddenMsg").hide();
                $("#new_name").removeClass('error');
                $("#new_number").removeClass('error');
                var NewName = $("#new_name").val();
                var NewNo = $("#new_number").val();

                var obj = {
                    "CustomerId": "0",
                    "CustomerName": NewName,
                    "CustomerCallingNumber": NewNo,
                    "TaxiCompanyID": sessionStorage.CompanyOID,
                    "isBlackListed": "false"
                }
                var annobj={
                    "customerObject": obj
                
                }
               // console.log(obj)
                $.ajax({
                    type: "POST",
                    url: WebsiteServiceUrl + "AddNewCustomer",
                    data: JSON.stringify(annobj),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    processData: true,
                    success: function (data) {
                        var x = data.AddNewCustomerResult.replace(/"/g, "");

                        if (x == 1) {
                            $(".HiddenMsg").html("تم اضافة الزبون بنجاح");
                            $(".HiddenMsg").css({ "color": "green", "font-size": "16px" })
                            $(".HiddenMsg").show()
                            setTimeout(function () { $modalInstance.dismiss('Cancel'); }, 1000);
                           
                        } else {
                            alert("حدث خطأ ، حاول مرة اخرى");
                        }

                        $scope.loading = false;

                    }
                });
              


               
            } else {
                $(".HiddenMsg").show();
                $("#new_number").addClass('error');
            }

        }

    }
   
  
     
   
})

/*----------------------------      EditCustomer          ---------------*/

TaxiApp.service('EditCustomer', function ($modal) {
    var service = {};
    var self = this;
    service.open = function () {

        var modalInstance = $modal.open({
            windowClass: 'EditCustomer',
            templateUrl: 'EditCustomer.html',
            controller: 'EditCustomerCtrl',
            resolve: {
                obj: function () {
                    return SelectedObj;
                }
            },
           

        });

    };

    return service;
});

TaxiApp.controller('EditCustomerCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, $modalInstance, obj) {


    

    $scope.ClickClose = function () {

        $modalInstance.dismiss('Cancel');

    }
  //  console.log(obj);
    $scope.EditDialog = function () {
        if (!$("#edit_name").val() || !$("#edit_number").val()) {
            $(".EditHiddenMsg").show();
            $("#edit_name").addClass('error');
            $("#edit_number").addClass('error');

        }
        else {
            var value = $("#edit_number").val()
            if (value.length >= 9 && value.length <= 10) {
                $(".EditHiddenMsg").hide();
                $("#edit_name").removeClass('error');
                $("#edit_number").removeClass('error');
                 EditName = $("#edit_name").val();
                 EditNo = $("#edit_number").val();
                EditFlag = 1;

                EditItem.edit(obj);


                $modalInstance.dismiss('Cancel');
            } else {
                $(".EditHiddenMsg").show();
                $("#edit_number").addClass('error');
            }

        }
    }
    




})
/*----------------------------      ConfirmBlock          ---------------*/

TaxiApp.service('ConfirmBlock', function ($modal) {
    var service = {};
    var self = this;
    service.open = function () {

        var modalInstance = $modal.open({
            windowClass: 'ConfirmBlock',
            templateUrl: 'ConfirmBlock.html',
            controller: 'ConfirmBlockCtrl',
            resolve: {
                obj: function () {
                    return SelectedObj;
                }
            },


        });

    };

    return service;
});

TaxiApp.controller('ConfirmBlockCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, $modalInstance, obj) {


   

    $scope.ClickClose = function () {

        $modalInstance.dismiss('Cancel');

    }
   // console.log(obj);
    $scope.BlockDialog = function () {
       
       
        
                EditFlag = 0;

                EditItem.edit(obj);


                $modalInstance.dismiss('Cancel');
          

     
    }





})
