
var TaxiApp = angular.module('PromotionCodeDiscount', ['ngStorage', 'ngDialog', 'ui.bootstrap'])
 

TaxiApp.controller('PromotionCodeDiscountCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'EditPromotionCodeDiscount', 'AddPromotionCodeDiscount',

    function ($scope, $http, $sessionStorage, ngDialog, EditPromotionCodeDiscount, AddPromotionCodeDiscount) {
        Localization(sessionStorage.selectedLanguage, 'allreport', $scope, sessionStorage);
      
        $scope.selectInstitution = function () {
            // console.log($scope.selectedInstitution);
            SelectedEnterprise = $scope.selectedInstitution.BookingStatus;

        }
        $scope.VehicleCurrentLocation = [];
      
        $scope.loading = false;
        $scope.DisplayName = sessionStorage.UserName;       
        $scope.CompanyName = sessionStorage.value;
        $scope.DistrictOID = sessionStorage.DistrictOID;
        if (sessionStorage.OrderId < 3) {
            window.location.href = "../../Access.html";
        }
        if (sessionStorage.length == (undefined || 0)) {
            window.parent.location.href = "../../Index.html";
        }
        else {
            $scope.Role = sessionStorage.RoleType;

            if (sessionStorage.OrderId > 2) {
                $('.tele').show();
            }
            else {
                $('.tele').hide();
            }

            $scope.Role = sessionStorage.RoleType;

            $scope.User = sessionStorage.Username;

            selectedCompany = 'undefined';
            if (sessionStorage.CompanyOID != undefined || sessionStorage.ORGOID != undefined) {
                loadDropDownFromAppConfig("COMPANY", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, 0, $scope);
            }
           
            function load() {
                $scope.FromDate = new Date();
                $scope.ToDate = new Date();
                //$scope.GetAllAcceptanceRecords();
            }
            load();

          


         
            function GetAllCodes() {
                var fdate = getFormattedFromDate($scope.FromDate);
            var todate = getFormattedFromDate($scope.ToDate);


                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "GetPromotionCode_DiscountList/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        //var a = result;
                        $scope.loading = false;
                        if (result.GetPromotionCode_DiscountListResult== "access_denied") {
                            window.parent.location.href = "../../Access.html";

                            return;
                        }
                        var data = JSON.parse(result.GetPromotionCode_DiscountListResult);
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].DiscountType == "P") {

                                data[i].DiscountAmount = data[i].DiscountAmount * 100;
                            }

                        }
                        console.log(data)
                       
                        
                        $scope.List = data;
                        $scope.$apply();
                    }
                });

            }
        GetAllCodes();

        $scope.PromotionCode = {
            edit: function (obj) {
                ngDialog.open({
                    windowClass: 'EditPromotionCodeDiscount',
                    templateUrl: 'EditPromotionCodeDiscount.html',
                    controller: 'EditPromotionCodeDiscountCtrl',
                    resolve: {
                        obj: function () {  return obj; }
                    },
                    className: 'customDialog ngdialog ngdialog-theme-default'


                });
            },
            add: function () {

                ngDialog.open({
                    windowClass: 'AddPromotionCodeDiscount',
                    templateUrl: 'AddPromotionCodeDiscount.html',
                    controller: 'AddPromotionCodeDiscountCtrl',
                    resolve: {
                      
                    },
                    className: 'customDialog ngdialog ngdialog-theme-default'


                });

            }

        }

        }
    
    }])


TaxiApp.service('EditPromotionCodeDiscount', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (idd) {
        var modalInstance = $modal.open({
            windowClass: 'EditPromotionCodeDiscount',
            templateUrl: 'EditPromotionCodeDiscount.html',
            controller: 'EditPromotionCodeDiscountCtrl',


        });

    };



    return service;
})
TaxiApp.controller('EditPromotionCodeDiscountCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, obj) {
    
    GetAllDistricts($scope)
    loadCurrencyTypes($scope);
    console.log(obj)
    $scope.eSelectedCurrency = function (cOid) {
        eCurrencyType = $.grep($scope.CurrencyTypes, function (item) {

            return item.OID == cOid;
        })[0].value;
    }
    
 



    $scope.isDistrictSelected = function (id) {

        var idsString = obj.DistrictCodesList;

        var idsArray = idsString.split("~");

        var isChecked = false;

        for (var i = 0; i < idsArray.length; i++) {

            var tempId = idsArray[i];

            if (tempId == id)
                isChecked = true;

        }

        return isChecked;

    }

    $scope.eCurrencyType = obj.CurrencyOID
    $scope.eCode = obj.PromoCodesList;
    $scope.DistrictName = obj.DistrictCodesList;
    $scope.eDiscountType = obj.DiscountType;

    $scope.eDiscountAmount = obj.DiscountAmount;
    $scope.eDiscountMaxValue = obj.DiscountMaxValue;

    $scope.eMaxUse = obj.CodeMaxUseCount;

   
    
    $scope.eFromDate = formatDateToView(obj.ActiveFrom_DT);
    $scope.eFromTime = formatTimeToView(obj.ActiveFrom_DT);




    $scope.eToDate = formatDateToView(obj.ActiveUntil_DT);
    $scope.eToTime = formatTimeToView(obj.ActiveUntil_DT);
    $scope.selection = {
        OIDs: {}
    };
     
    $scope.ClickClose = function () {

        // $modalInstance.dismiss('Cancel');

        $(".ngdialog-close").trigger("click");

    }
    //  console.log(obj);
    $scope.EditItem = function () {
      
        if ($scope.eCode != undefined && $scope.eDiscountType != undefined && $scope.eDiscountAmount != undefined && $scope.eDiscountMaxValue != undefined &&
            
           $scope.eFromDate != undefined && $scope.eFromTime != undefined && $scope.eToDate != undefined && $scope.eToTime != undefined && $scope.eMaxUse != undefined && $scope.eCurrencyType != undefined) {


            var arr = Object.keys($scope.selection.OIDs).map(function (k) {

                if ($scope.selection.OIDs[k] == true) {

                    return k;
                } else {

                    return -1000;
                }


            });

            var strictOIDS = "";
            for (var i = 0; i < arr.length; i++) {

                if (arr[i] != -1000)
                    strictOIDS += arr[i] + "~";

            }

            strictOIDS = strictOIDS.substring(0, strictOIDS.length - 1)



          
            var ConvertedeFromDate = formatDateToService($scope.eFromDate);
            var ConvertedeToDate = formatDateToService($scope.eToDate);



            var ConvertedeFromTime = formatTimeToService($scope.eFromTime);
            var ConvertedeToTime = formatTimeToService($scope.eToTime);


            var EFromDate = ConvertedeFromDate + " " + ConvertedeFromTime;
            var EToDate = ConvertedeToDate + " " + ConvertedeToTime;

            if ($scope.eDiscountType == "P") {
                $scope.eDiscountAmount = $scope.eDiscountAmount / 100;

            }
            var promoCreditObject = {}
            

         

            var temp = {
                promoDiscountObject: {
                    'OID':obj.OID,
                    'PromoCodesList': $scope.eCode,
                    'DistrictCodesList': strictOIDS,
                    'DiscountType':$scope.eDiscountType,
                    'DiscountAmount': $scope.eDiscountAmount,
                    'DiscountMaxValue': $scope.eDiscountMaxValue,
                    'ActiveFrom_DT': EFromDate,
                    'ActiveUntil_DT': EToDate,
                    'CodeMaxUseCount': $scope.eMaxUse,
                    'Is_Active': true,
                    'CurrencyOID': $scope.eCurrencyType,
                    'CreatedBy': sessionStorage.UserOID,
                    'TokenID': sessionStorage.TokenID
                  
                }
            }

            $.ajax({
                type: "POST",
                url: ManagementServiceUrl + "UpdatePromotionCode_Discount",
                data: JSON.stringify(temp),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data) {
                    if (data.UpdatePromotionCode_DiscountResult == "access_denied") {
                        window.parent.location.href = "../../Access.html";
                        return;
                    }
                    // $scope.clear();   
                    alert("تم تعديل  الموقع بنجاح");
                    $scope.ClickClose();
                   
                    $scope.loading = false;
                    $scope.$apply();
                },
                error: function (a, b, c) { console.log(a); }

            });

            
        
        }else {
            alert("ارجاء التاكد من تعبئة جميع الحقول ")
        }

    }




})
// Add Promotion Code


TaxiApp.service('AddPromotionCodeDiscount', function ($modal) {
    var service = {};
    var self = this;
    service.open = function () {
        var modalInstance = $modal.open({
            windowClass: 'AddPromotionCodeDiscount',
            templateUrl: 'AddPromotionCodeDiscount.html',
            controller: 'AddPromotionCodeDiscountCtrl',
            


        });

    };



    return service;
})
TaxiApp.controller('AddPromotionCodeDiscountCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window) {
   
    $scope.aFromDate = $scope.today
    $scope.aToDate = $scope.today;

    GetAllDistricts($scope)
    loadCurrencyTypes($scope);
    $scope.SelectedCurrency = function (cOid) {
        aCurrencyType = $.grep($scope.CurrencyTypes, function (item) {

            return item.OID == cOid;
        })[0].value;
    }

    $scope.SelectedDistrict = function (districtOid) {
        DistrictName = $.grep($scope.DistrictList, function (item) {

            return item.OID == districtOid;
        })[0].value;
    }
    $scope.selection = {
        OIDs: {  }
    };
    $scope.ClickClose = function () {

        // $modalInstance.dismiss('Cancel');

        $(".ngdialog-close").trigger("click");

    }
    //  console.log(obj);
    $scope.AddItem = function () {
     
        if ($scope.aCode != undefined && $scope.aDiscountType != undefined && $scope.aDiscountAmount != undefined && $scope.aDiscountMaxValue != undefined &&

           $scope.aFromDate != undefined && $scope.aFromTime != undefined && $scope.aToDate != undefined && $scope.aToTime != undefined && $scope.aMaxUse != undefined && $scope.aCurrencyType != undefined) {
            var arr = Object.keys($scope.selection.OIDs).map(function (k) {

                if ($scope.selection.OIDs[k] == true) {

                    return k;
                } else {

                    return -1000;
                }


            });

            var strictOIDS = "";
            for (var i = 0; i < arr.length; i++) {

                if (arr[i] != -1000)
                    strictOIDS += arr[i] + "~";

            }

            strictOIDS = strictOIDS.substring(0, strictOIDS.length - 1)

           
            
        

        
            var ConvertedeFromDate = formatDateToService($scope.aFromDate);
            var ConvertedeToDate = formatDateToService($scope.aToDate);



            var ConvertedeFromTime = formatTimeToService($scope.aFromTime);
            var ConvertedeToTime = formatTimeToService($scope.aToTime);


            var EFromDate = ConvertedeFromDate + " " + ConvertedeFromTime;
            var EToDate = ConvertedeToDate + " " + ConvertedeToTime;

            if ($scope.aDiscountType == "P") {
                $scope.aDiscountAmount = $scope.aDiscountAmount / 100;

            }
            var promoCreditObject = {}




            var temp = {
                promoDiscountObject: {
                    'PromoCodesList': $scope.aCode,
                    'DistrictCodesList': strictOIDS,
                    'DiscountType': $scope.aDiscountType,
                    'DiscountAmount': $scope.aDiscountAmount,
                    'DiscountMaxValue': $scope.aDiscountMaxValue,
                    'ActiveFrom_DT': EFromDate,
                    'ActiveUntil_DT': EToDate,
                    'CodeMaxUseCount': $scope.aMaxUse,
                    'Is_Active': true,
                    'CurrencyOID': $scope.aCurrencyType,
                    'CreatedBy': sessionStorage.UserOID,
                    'TokenID': sessionStorage.TokenID

                }
            }

            $.ajax({
                type: "POST",
                url: ManagementServiceUrl + "AddPromotionCode_Discount",
                data: JSON.stringify(temp),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data) {
                    if (data.AddPromotionCode_DiscountResult == "access_denied") {
                        window.parent.location.href = "../../Access.html";
                        return;
                    }
                    // $scope.clear();   
                    alert("تم اضافة  الكود بنجاح");
                    $scope.ClickClose();

                    $scope.loading = false;
                    $scope.$apply();
                },
                error: function (a, b, c) { console.log(a); }

            });



        } else {
            alert("ارجاء التاكد من تعبئة جميع الحقول ")
        }

    }





})

/*------------ FUNCTIONS  ---------------------*/

function formatDateToView(date) {


    var dateParts = date.split(" ");

    if (dateParts.length > 0) {

        var yafa = dateParts[0].split("-");

        var newDate = yafa[1] + "-" + yafa[0] + "-" + yafa[2]

        var date = new Date(newDate);

        var year = date.getFullYear();
        var month = ("0" + (date.getMonth() + 1)).slice(-2);
        var day = ("0" + date.getDate()).slice(-2);

        console.log(year + "/" + month + "/" + day);

        return new Date(month + "/" + day + "/" + year);

    }


}

function formatDateToService(date) {

    var date = new Date(date);

    var year = date.getFullYear();
    var month = ("0" + (date.getMonth() + 1)).slice(-2);
    var day = ("0" + date.getDate()).slice(-2);

    return day + "-" + month + "-" + year;


}



function formatTimeToView(date) {

    var dateParts = date.split(" ");

    if (dateParts.length > 0) {

        var yafa = dateParts[0].split("-");

        var newDate = yafa[1] + "-" + yafa[0] + "-" + yafa[2] + " " + dateParts[1]

        var date = new Date(newDate);



        return new Date(date.getTime());

    }


}

function formatTimeToService(date) {
    date = new Date(date);


    var minutes = ("0" + (date.getMinutes())).slice(-2);
    var hour = ("0" + date.getHours()).slice(-2);



    return hour + ":" + minutes;

}
function GetAllDistricts($scope) {
    $.ajax({
        cache: true,
        url: ManagementServiceUrl + "GetDistrictList/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID,
        type: "GET",
        contentType: "application/javascript",
        dataType: "jsonp",
        success: function (result) {
            if (result.GetDistrictListResult == "access_denied") {
                window.parent.location.href = "../../Access.html";
                return;
            }
            $scope.DistrictList = JSON.parse(result.GetDistrictListResult);
            $scope.loading = false;
            // console.log($scope.DistrictList);
            $scope.$apply();

        }
    });
}

function getFormattedFromDate(tDate) {

    var year = tDate.getFullYear();
    var month = (1 + tDate.getMonth()).toString();
    month = month.length > 1 ? month : '0' + month;
    var day = tDate.getDate().toString();
    day = day.length > 1 ? day : '0' + day;
    DatePart = year + month + day;
    return year + '-' + month + '-' + day;

}
function getDistrictName(id) {
    

    var districtName = "";
    for (var i = 0; i < $scope.DistrictList.length; i++) {


        var tempObject = $scope.DistrictList[i];


    }

}