Number.prototype.pad = function (size) {
    var s = String(this);
    while (s.length < (size || 2)) { s = "0" + s; }
    return s;
}

var EditItemClass;
var CancelBooking;
var map;
var obj;
var data;
var TaxiApp = angular.module('DailyBooking', ['ngStorage', 'ngDialog', 'ui.bootstrap'])
     .filter('split', function () {
         return function (input, splitChar, splitIndex) {
             // do some bounds checking here to ensure it has that index
             return input.split(splitChar)[splitIndex];
         }
     })
.filter('formatTime', function ($filter) {
    return function (time) {
        var parts = time.split(':');
        var date = new Date(0, 0, 0, parts[0], parts[1], parts[2]);
        return $filter('date')(date, 'h:mm');
    };
});

TaxiApp.controller('DailyBookingCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'EditItem', 'CancelBookingItem',

   

    function ($scope, $http, $sessionStorage, ngDialog, EditItem, CancelBookingItem) {
        Localization(sessionStorage.selectedLanguage, 'allreport', $scope, sessionStorage);
        var total=0;
        $scope.calculateTotal = function (filteredList) {
            if (filteredList != null) {
            total = 0;
            for (var i = 0; i < filteredList.length; i++) {
                total += filteredList[i].Amount


            }
            return Math.round(total * 100) / 100;
        } else {
            return 0;
        }
        }
        $scope.calculateCount = function (filteredList) {
            if (filteredList != null)
                return filteredList.length;
            return 0;
        }

        $scope.EditItemClass =  {
            EditItem: function (id, status, price, isDept) {
                //EditItem.open(id, status, price, isDept);

                ngDialog.open({
                    template: 'EditItem.html',
                    windowClass: 'EditItem',
                    controller: 'EditItemCtrl',
                    resolve: {
                        idd: function () {
                            return id;
                        }
                            ,
                        price: function () {
                            return price;
                        }
                            ,
                        status: function () {
                            return status;
                        }
                            ,
                        isDepit: function () {
                            return isDept;
                        },
                        scope: function () {
                            return $scope;
                        }
                    }


                });

            }
        }
        var notificationLayer = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });

        map = new ol.Map({
            logo: {
                src: 'assets/img/logo.png',
                href: 'http://www.arttech.ps'
            },
            controls: ol.control.defaults({ attribution: true }).extend([
                   new ol.control.FullScreen()
            ]),
            interactions: ol.interaction.defaults({ doubleClickZoom: false }),

            layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM()
            }), notificationLayer
            ],
            target: 'bookingmap',
            pixelRatio: 1,
            view: new ol.View({
                center: ol.proj.transform([parseFloat(32), parseFloat(31)], 'EPSG:4326', 'EPSG:3857'),
                zoom: 8,
                minZoom: 1,
                maxZoom: 16
            })
        });
        setInterval(function () { map.updateSize(); }, 10);

        

        $scope.CancelBooking = {
            cancel: function (bookingId,imei,driverOId) {
                //EditItem.open(id, status, price, isDept);

                ngDialog.open({
                    template: 'CancelBookingItem.html',
                    windowClass: 'CancelBookingItem',
                    controller: 'CancelBookingItemCtrl',
                    resolve: {
                        bookingId: function () {
                            return bookingId;
                        }
                   ,
                        imei: function () {
                            return imei;
                        }
                   ,
                        driverOId: function () {
                            return driverOId;
                        }

                    }


                });

            }
        }
        $scope.selectInstitution = function () {
            SelectedEnterprise = $scope.selectedInstitution.BookingStatus;

        }
        $scope.loading = false;
        $scope.BookingList = "";
        $scope.DisplayName = sessionStorage.UserName;
        $scope.DailyBookingCtrl = "";
        var Vehiclename, vehicle;
       
        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;
            //set cureentdate as default date in datepicker
            status = '0';
            bookedBy = 'undefined';

            var now = new Date();

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

            var today = now.getFullYear() + "-" + (month) + "-" + (day);

            $('#fdate').val(today);


          
            setInterval(function () {
                if ($scope.selectedStatus == "inprogress") {
                    $scope.loadDailyBooking();
                }
            }, 15000);

            $scope.selectBookedBy = function (selectedBookedBy) {
                bookedBy = selectedBookedBy == '' ? 'undefined' : selectedBookedBy;
            }
            $scope.selectedStatus = "inprogress";
            $scope.selectStatus = function (st) {
                $scope.loadDailyBooking();
            }


            $scope.fnExcelReport = function () {
                    let table = document.getElementById("DailyBookingTable");
                    TableToExcel.convert(table, { // html code may contain multiple tables so here we are refering to 1st table tag
                        name: `export.xlsx`, // fileName you could use any name
                        sheet: {
                            name: 'Sheet 1' // sheetName
                        }
                    });
          
                
            },

           
            $scope.loadDailyBooking = function () {
                fdate = $('#fdate').val();
                todate = $('#fdate').val();
                $.ajax({
                    cache: true,
                    url: WebsiteServiceUrl + "DailyBookings/" + $scope.selectedStatus + "/" + fdate + "/" + sessionStorage.CompanyOID + "/" + bookedBy,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                      data = JSON.parse(result.DailyBookingsResult);
                        $scope.BookingList = [];
                        if (data.length > 0) {

                        for (var i = 0; i < data.length; i++) {
                            var date = new Date(Date.parse(data[i].Book_DateTime));
                            data[i].PickUpTime = date.getHours().pad() + ":" + date.getMinutes().pad();
                            //206827
                            switch (data[i].BookingStatus) {
                                case "B":
                                    if (data[i].ToPlace == null) {
                                        data[i].BookingStatusDesc = "بانتظار استلام السائق";
                                        data[i].color = "#d0d0f4";
                                        data[i].colorFont = "#333";

                                    } else {
                                        data[i].BookingStatusDesc = "قيد التوصيل";
                                        data[i].color = "#E56D54";
                                        data[i].colorFont = "#333";

                                    }
                                    break;
                                case "A":
                                    if (data[i].ToPlace == null) {
                                        data[i].BookingStatusDesc = "باتجاه الزبون";
                                        data[i].color = "#C27ECE";
                                        data[i].colorFont = "#333";

                                    } else {
                                        data[i].BookingStatusDesc = "قيد التوصيل";
                                        data[i].color = "#E56D54";
                                        data[i].colorFont = "#333";

                                    }

                                    break;
                                case "C":
                                    data[i].BookingStatusDesc = "ملغى";
                                    data[i].color = "#80b4e1";
                                    data[i].colorFont = "#333";


                                    break;
                                case "E":
                                    data[i].BookingStatusDesc = "مكتمل";
                                    // data[i].color = "#fff000";

                                    break;
                                case "R":
                                    data[i].BookingStatusDesc = "مرفوض";
                                    data[i].color = "#AEABAF";
                                    data[i].colorFont = "#333";


                                    break;
                                case "Q":
                                    data[i].BookingStatusDesc = "استعلام";
                                    data[i].color = "green";
                                    data[i].colorFont = "#333";

                                    break;
                                default:
                            }  
                            if (data[i].BookedFrom == "customer_app_D" || data[i].BookedFrom == "customer_app_O") {
                                data[i].border = "1px solid #ddd";
                                data[i].borderC = "6px solid #ffc83e";
                                data[i].BorderR = "0px solid transparent "
                                data[i].BorderL = "0px solid transparent"
                            }

                            }

                        }
                        $scope.loading = false;
                        $scope.BookingList = data;

                        $scope.$apply();
                    },
                    error: function () {
                        $scope.loading = false;
                        $scope.BookingList = [];
                        $scope.$apply();
                    }
                });
            }
            $scope.loadDailyBooking();
            $scope.GetCustomerLocation = {
                get: function (indx) {
                    $('#myModal').modal('toggle');

                    ViewCustomerLocation(data[indx].CustomerLat, data[indx].CustomerLong);
                }
            }
            function ViewCustomerLocation(lat, long) {
                notificationLayer.getSource().clear();
                var myLatLng = ol.proj.transform([parseFloat(long), parseFloat(lat)], 'EPSG:4326', 'EPSG:3857');
                var iconFeature = new ol.Feature({
                    geometry: new ol.geom.Point(myLatLng),

                });


                iconStyle = [new ol.style.Style({
                    image: new ol.style.Icon({
                        //anchor: [12, 0.5],
                        size: [50, 50],
                        //  scale: 0.037,
                        // rotation: parseInt(data[n].Direction) * Math.PI / 180,
                        //anchorXUnits: 'pixel',
                        //anchorYUnits: 'fraction',
                        src: 'assets/img/CustomerIcon.png'
                    })
                })];

                iconFeature.setStyle(iconStyle);

                notificationLayer.getSource().addFeature(iconFeature);
                map.getView().fit(notificationLayer.getSource().getExtent(), map.getSize());
                //  setInterval(function () { map.updateSize(); }, 500);


            }
        }
      
    
    }])
TaxiApp.service('EditItem', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (idd, status, price, isDept) {
        var modalInstance = $modal.open({
            windowClass: 'EditItem',
            templateUrl: 'EditItem.html',
            controller: 'EditItemCtrl',
            resolve: {
                idd: function () {
                    return idd;
                }
                    ,
                price: function () {
                    return price;
                }
                    ,
                status: function () {
                    return status;
                }
                    ,
                isDepit: function () {
                    return isDept;
                }
            }

        });

    };
  

   
    return service;

})
TaxiApp.controller('EditItemCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, idd, price, status, isDepit) {


    $scope.loading = true;
    
    $scope.BookingPrice = price;
    $scope.BookingStatus = status;
    $scope.BookingIsDepit = isDepit;

  
    $scope.ClickClose = function () {

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

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

    }

   
    $scope.Edit = function ($idd, $price, $status, $isDepit) {
        var amount = $('#EditDialogAmount').val();
        var status = $('#EditDialogStatus').find(":selected").val();
        var isDebit = $('#isDebit').is(':checked');
        
        $.ajax({
            cache: true,
            url: WebsiteServiceUrl + "EditBookingPriceAndStatus/" + idd + "/" + sessionStorage.CompanyOID + "/" + status + "/" + amount + "/" + isDebit,
            type: "GET",
            contentType: "application/javascript",
            dataType: "jsonp",
            success: function (result) {
            },
            error: function () {
            }
        });
        $scope.ClickClose();

    }
})


TaxiApp.service('CancelBookingItem', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (bookingId, imei, driverOId) {
        var modalInstance = $modal.open({
            windowClass: 'CancelBookingItem',
            templateUrl: 'CancelBookingItem.html',
            controller: 'CancelBookingItemCtrl',
            resolve: {
                bookingId: function () {
                    return bookingId;
                }
                    ,
                imei: function () {
                    return imei;
                }
                    ,
                driverOId: function () {
                    return driverOId;
                }
                   
            }
            

        });

    };
  

   
    return service;
})
TaxiApp.controller('CancelBookingItemCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, bookingId,imei,driverOId) {


    $scope.loading = true;

   
    
    $scope.ClickClose = function () {

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

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

    }

    $scope.cancelCurrentBooking = function (bookinid, imei, driveroid) {
        $.ajax({
            cache: true,
            url: WebsiteServiceUrl + "CancelBookingFromMapView/" + bookinid + "/C",
            type: "GET",
            contentType: "application/javascript",
            dataType: "jsonp",
            success: function (result) {

                $.ajax({
                    cache: true,
                    url: WebsiteServiceUrl + "SaveAnnouncementforCancel/" + sessionStorage.CompanyOID + "/" + sessionStorage.ORGOID + "/" + bookinid + "/" + imei + "/" + driveroid,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    error: function () {
                    },
                    success: function (result) {
                        $scope.loadDailyBooking();

                    }
                });

            }
        })
    };
    $scope.CancelBtn = function () {
       // alert(bookingId + "---" + imei + "---" + driverOId);
        $scope.cancelCurrentBooking(bookingId, imei, driverOId);
        $scope.ClickClose();

    }
})

