var TaxiApp = angular.module('Users', ['ngStorage', 'ngDialog', 'angularUtils.directives.dirPagination', 'ui.bootstrap']);
var company, TariffList;


TaxiApp.controller('UsersCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog',
    function ($scope, $http, $sessionStorage, ngDialog, $confirm) {
        $scope.Role = sessionStorage.RoleType;
        $scope.RoleID = sessionStorage.RoleID;
        $scope.DisplayName = sessionStorage.UserName;
        $scope.CompanyName = sessionStorage.value;
        if (sessionStorage.OrderId < 2) {
            window.location.href = "../../Access.html";
        }
        else {
            Localization(sessionStorage.selectedLanguage, 'user', $scope, sessionStorage);
            $scope.loading = true;
            // $('.driveradd').hide();

            if (sessionStorage.length == (undefined || 0)) {
                window.parent.location.href = "../../Index.html";
            }
            else {
                var TokenID = sessionStorage.TokenID;
                var orgOID = sessionStorage.ORGOID;
                var userOID = sessionStorage.UserOID;
                var roleType = sessionStorage.RoleType;
                var roleID = sessionStorage.RoleID;
                var companyOID = sessionStorage.CompanyOID;

                $scope.Role = sessionStorage.RoleType;



                if (sessionStorage.CompanyOID != undefined || sessionStorage.ORGOID != undefined) {
                    loadDropDownFromAppConfig("COMPANY", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, 0, $scope);
                }

                loadContents(sessionStorage.ORGOID, sessionStorage.CompanyOID, sessionStorage.UserOID, 'DT', $scope);
                function loadDropDown(tableName, UserOID, companyId, OrgOID, groupOID) {
                    $.ajax({
                        cache: true,
                        url: ComonServiceUrl + "GetDropDownListMaster/" + tableName + "/" + UserOID + "/" + companyId + "/" + OrgOID + "/" + groupOID,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",
                        success: function (result) {

                        


                        }
                    });
                }

                loadDropDownFromAppConfig("ROLETYPE", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, roleID, $scope);


                $scope.currentPage = 1

                $scope.Users = {
                    add: function () {
                        $scope.e_OID = '';
                        $scope.e_Fname = '';
                        $scope.e_Lname = '';
                        $scope.e_LoginStatus = null;
                        $scope.e_Mobile = '';
                        $scope.e_RoleOID = null;
                        $('#AddUser').modal('toggle');
                    },
                    createNew: function (e) {
                        if ($scope.e_RepeatPassword == '' || $scope.e_Password == ''
                            || $scope.e_UserName == '' || $scope.e_Fname == ''
                             ||
                            $scope.e_LoginStatus == null ||
                            $scope.e_Mobile == '' ||
                            $scope.e_RoleOID == null) {
                            openDialog("يجب ادخال جميع البيانات المطلوبة");
                            return;
                        }
                        if ($scope.e_Password == '' || $scope.e_RepeatPassword == '') {
                            openDialog("يجب ادخال كلمة المرور واعادة تاكيد الكلمة المدخلة");
                            return;
                        }

                        if ($scope.e_Password != $scope.e_RepeatPassword) {
                            openDialog("كلمة المرور الثانية مختلفة عن الأولى");
                            return;
                        }

                        var userdata = {};
                        var usrobj = {
                            "OID": 0,
                            "ContactName": $scope.e_Fname,
                            "ContactPhone": $scope.e_Mobile,
                            "FirstName": $scope.e_Fname,
                            "LastName": $scope.e_Lname,
                            "RoleOID": $scope.e_RoleOID,
                            "CompanyId": $scope.e_Company,
                            "UserName": $scope.e_UserName.toLowerCase(),
                            "Password": Base64.encode($scope.e_Password.toLowerCase()),
                            "IsLocked": $scope.e_LoginStatus,
                            "OrgOID": sessionStorage.ORGOID,
                            "CreatedBy": sessionStorage.UserOID,
                            "TokenID": sessionStorage.TokenID
                        };
                        userdata["oUserObject"] = usrobj;

                        $scope.loading = true;
                        $.ajax({
                            type: "POST",
                            url: ManagementServiceUrl + "CreateUser",
                            data: JSON.stringify(userdata),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (data) {
                                if (data.CreateUserResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                var result = JSON.parse(data.CreateUserResult);
                                if (result == "-1") {
                                    openDialog("اسم المستخدم موجود مسبقا");
                                    return;
                                }
                                if (result == "success") {
                                    openDialog("تم اضافة مستخدم جديد");
                                 
                                    $scope.loading = false;
                                    $scope.Users.get();
                                    $('#AddUser').modal('toggle');

                                    return;
                                }

                                 openDialog("حدث خطأ");
                                $('#AddUser').modal('toggle');
                               
                            },
                        });

                    },

                    edit: function (e) {
                        $('#EditUser').modal('toggle');
                        $scope.e_OID = e.OID;
                        $scope.e_Fname = e.FirstName;
                        $scope.e_Lname = e.LastName;
                        $scope.e_LoginStatus = e.IsLocked;
                        $scope.e_Mobile = e.ContactPhone;
                        $scope.e_RoleOID = e.RoleOID;
                        $scope.e_Company = e.CompanyId;

                    },
                    saveEdits: function (e) {
                        if ($scope.e_Fname == '' ||  $scope.e_LoginStatus == null || $scope.e_Mobile == '' || $scope.e_RoleOID== null ){
                            openDialog("يجب ادخال جميع البيانات المطلوبة");
                            return;
                        }
                        var userdata = {};
                        var usrobj = {
                            "OID": $scope.e_OID,
                            "ContactName": $scope.e_Fname,
                            "ContactPhone": $scope.e_Mobile,
                            "FirstName": $scope.e_Fname,
                            "LastName": $scope.e_Lname,
                            "RoleOID": $scope.e_RoleOID,
                            "CreatedBy": sessionStorage.UserOID,
                            "CompanyId": sessionStorage.CompanyOID,
                            "IsLocked": $scope.e_LoginStatus,
                            "TokenID": sessionStorage.TokenID
                        };
                        userdata["oUserObject"] = usrobj;

                        $scope.loading = true;
                        $.ajax({
                            type: "POST",
                            url: ManagementServiceUrl + "ModifyUser",
                            data: JSON.stringify(userdata),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (data) {
                                if (data.ModifyUserResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                openDialog("تم تعديل بيانات المستخدم");
                                $('#EditUser').modal('toggle');
                                $scope.loading = false;
                                $scope.Users.get();
                            },
                        });

                    },
                    reset: function (e) {
                      
                        $scope.e_Password = '';
                        $scope.e_RepeatPassword = '';
                        $scope.e_OID = e.OID;
                        $('#ResetPassword').modal('toggle');


                    },
                    resetPassword: function (e) {
                        if ($scope.e_Password == '' || $scope.e_RepeatPassword == '') {
                            openDialog("يجب ادخال كلمة المرور واعادة تاكيد الكلمة المدخلة");
                            return;
                        }

                        if ($scope.e_Password != $scope.e_RepeatPassword) {
                            openDialog("كلمة المرور الثانية مختلفة عن الأولى");
                            return;
                        }
                        var userdata = {};
                        var usrobj = {
                            "OID": $scope.e_OID,
                            "Password": Base64.encode($scope.e_Password.toLowerCase()),
                            "CreatedBy": sessionStorage.UserOID,
                            "TokenID": sessionStorage.TokenID
                        };
                        userdata["oUserObject"] = usrobj;

                        $scope.loading = true;
                        $.ajax({
                            type: "POST",
                            url: ManagementServiceUrl + "ResetPassword",
                            data: JSON.stringify(userdata),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (data) {
                                if (data.ResetPasswordResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                openDialog("تم تعديل كلمة المرور");
                                $('#ResetPassword').modal('toggle');
                                $scope.loading = false;
                                $scope.Users.get();
                            },
                        });

                    },

                    save: function () {
                        if ($scope.e_Mobile == null || $scope.e_Mobile == 'undefined' || $scope.e_Mobile.length < 10) {
                            alert('يرجى ادخال رقم جوال صحيح  ');
                            return;
                        }
                        var make = {
                            "mobile": $scope.e_Mobile,
                           
                            "CreatedBy": sessionStorage.UserOID,
                            "TokenID": sessionStorage.TokenID

                        }
                        var obj = {};

                        obj["obj"] = make;
                        $.ajax({
                            type: "POST",
                            url: ManagementServiceUrl + "WaslAddException",
                            data: JSON.stringify(obj),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (data) {
                                if (data.WaslAddExceptionResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                var res = JSON.parse(data.WaslAddExceptionResult);
                                // var str = "Hello world, welcome to the universe.";

                                //  console.log(res)
                                if (res = 'success') {
                                    $('#AddException').modal('toggle');
                                    $scope.Exceptions.get()

                                } else {
                                    alert(res + "حدث خطأ  ")

                                }
                            }
                        });
                    },
                    get: function () {
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "GetUsersList/" + companyOID+"/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                if (result.GetUsersListResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                $scope.UsersList = JSON.parse(result.GetUsersListResult);
                                //  console.log($scope.driverList)

                                $scope.loading = false;
                                $scope.$apply();
                            }
                        });
                    },
                    remove: function (e) {
                        $scope.loading = true;
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "DeleteUser/" + e.OID + "/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                if (result.DeleteUserResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                $scope.Users.get();

                               
                                //  console.log($scope.driverList)


                                $scope.loading = false;
                                $scope.$apply();
                            }
                        });


                    },

                }

                $scope.Users.get()

                $scope.selectRole = function (roleid) {
                   
                }

                function openDialog(text) {
                    var dialog = ngDialog.open({
                        template:
                            '<p>' + text + '</p>' +
                            '<div class="ngdialog-buttons"><button type="button" class="ngdialog-button ngdialog-button-Success" ng-click="closeThisDialog(1)">Ok</button></div>',
                        plain: true
                    });
                    dialog.closePromise.then(function (data) {
                        console.log('ngDialog closed' + (data.value === 1 ? ' using the button' : '') + ' and notified by promise: ' + data.id);
                    });
                }

            }
        }
    }]);



