var BreakCount=0;
var TaxiApp = angular.module('AcceptanceReport', ['ngStorage', 'ngDialog', 'ui.bootstrap'])
 

TaxiApp.controller('AcceptanceReportCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'getAvailableTime',

    function ($scope, $http, $sessionStorage, ngDialog, getAvailableTime) {
        Localization(sessionStorage.selectedLanguage, 'allreport', $scope, sessionStorage);
      
        $scope.selectInstitution = function () {
            SelectedEnterprise = $scope.selectedInstitution.BookingStatus;

        }
        $scope.VehicleCurrentLocation = [];
        $scope.DeserveCompensationList = [];
      
        $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();
            loadContents(sessionStorage.ORGOID, sessionStorage.CompanyOID, sessionStorage.UserOID, 'DT', $scope);
            $scope.ShowAll = function (tst) {

                if (tst) {
                    $scope.AcceptanceList = $scope.DeserveCompensationList;

                } else {

                    $scope.AcceptanceList = $scope.List;
                }

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

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

            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 padTime(t) {

                var s = t;
                while (s.length <  2)
                { s = "0" + s; }
                return s;
           

            }
            function formatTime(Time) {
                if (Time != "") {
                  var str = Time.split(':');
                var h = padTime(str[0]);
                var m = padTime(str[1]);

                return h+"~"+m
                }
             
            }
            var timepicker = new TimePicker(['FromTime', 'ToTime'], {
                lang: 'en',
                theme: 'dark'
            });

            timepicker.on('change', function (evt) {



                var value = (evt.hour || '00') + ':' + (evt.minute || '00');
                evt.element.value = value;

             

            });
         
        function GetAllAcceptanceRecords() {
            var fdate = getFormattedFromDate($scope.FromDate);
            var todate = getFormattedFromDate($scope.ToDate);
            var fromtime = formatTime($("#FromTime").val());
            var totime = formatTime($("#ToTime").val());

            var FromDate = fdate + " " + fromtime
            var ToDate = todate + " " + totime
                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "AcceptanceReport/" + $scope.DistrictName + "/0/" + FromDate + "/" + ToDate+"/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        if (result.AcceptanceReportResult == "access_denied") {
                            window.parent.location.href = "../../Access.html";
                            return;
                        }
                        $scope.DeserveCompensationList = [];

                        //var a = result;
                        $scope.loading = false;
                        var data = JSON.parse(result.AcceptanceReportResult);
                        $scope.List = data;
                        for (var i = 0; i < data.length; i++) {
                            if (
                                data[i].RejectedBookingsCount == 0
                               // && data[i].TripsAssginedButNotAccepted==0
                                &&data[i].CanceledByDriver == 0
                                && data[i].AcceptancePercent>=80
                                && (data[i].AvargeRating ==null || data[i].AvargeRating > 3)) {
                               $scope.DeserveCompensationList.push(data[i]);
                            }



                        


                        }
                        $scope.AcceptanceList = $scope.List;
                        $scope.$apply();
                    }
                });

            }
        
        GetAllAcceptanceRecords();

        $scope.CustomReload = function () {
            GetAllAcceptanceRecords();
        }
        $scope.getAvailableTime = {
            get: function (DriverEimiNo, DNAME) {
                ngDialog.open({
                    template: 'getAvailableTime.html',
                    className: 'balance_details ngdialog-theme-default dialogforpopup',
                    controller: 'getAvailableTimeCtrl',
                    resolve: {
                        DriverEimiNo: function () {
                            return DriverEimiNo;
                        },
                        DNAME: function () {
                            return DNAME;
                        }

                    },

                    onOpenCallback: function () {


                    }
                });

              
            }
        }
          
        }
      
    }])


TaxiApp.service('getAvailableTime', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (DriverEimiNo, DNAME) {
        var modalInstance = $modal.open({
            className: 'getAvailableTime',
            templateUrl: 'getAvailableTime.html',
            controller: 'getAvailableTimeCtrl',
            resolve: {
                DriverEimiNo: function () {
                    return DriverEimiNo;
                },
                DNAME: function () {
                    return DNAME;
                }

            }

        });

    };



    return service;

})
TaxiApp.controller('getAvailableTimeCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, DriverEimiNo, DNAME) {

    

    var StatusList = [],status_obj={};

   
    function formatTime(Time) {
        if (Time != "") {
            var str = Time.split(':');
            var h = padTime(str[0]);
            var m = padTime(str[1]);

            return h+"~"+m
        }
             
    }
    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 padTime(t) {

        var s = t;
        while (s.length < 2)
        { s = "0" + s; }
        return s;


    }
  
    var fdate =$("#fdate").val();
    var todate = $("#tdate").val();
    var fromtime = formatTime($("#FromTime").val());
    var totime = formatTime($("#ToTime").val());

    $scope.SelectedDriverName = DNAME;
    $scope.SelectedDate = fdate;

    $scope.SelctedFromTime = $("#FromTime").val();
    $scope.SelctedToTime = $("#ToTime").val();
    var FromDate = fdate + " " + fromtime
    var ToDate = todate + " " + totime
    $.ajax({
        cache: true,
        url: ManagementServiceUrl + "GetDriverDayStatus/" + DriverEimiNo + "/" + fdate+"/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID,
        type: "GET",
        contentType: "application/javascript",
        dataType: "jsonp",

        success: function (result) {
            if (result.GetDriverDayStatusResult == "access_denied") {
                window.parent.location.href = "../../Access.html";
                return;
            }
            //var a = result;
            $scope.loading = false;
            var dashlist = JSON.parse(result.GetDriverDayStatusResult);
            BreakCount=0;
            for (var i = 0; i < dashlist.length; i++) {

                var ChangeTime = dashlist[i].ChangeTime;
                var str = ChangeTime.split(":")
                var prev ;
                if (i < dashlist.length - 1 ) {
                    prev = dashlist[i + 1].ChangeTime;
                }
                else {
                    prev = dashlist[i].ChangeTime;
                }
                
                var str2 = prev.split(":")
                      if (dashlist[i].ApplicationStatus == 2) {                     
                          status_obj={
                                     x: 1,
                                     low: Date.UTC(2010, 0, 1, str[0], str[1], str[2]),
                                     high: Date.UTC(2010, 0, 1, str2[0], str2[1], str2[2]),
                                     color: 'black'
                         };

                         StatusList.push(status_obj);
                     }
                     else if (dashlist[i].ApplicationStatus == 4) {                          
                              status_obj = {
                                   x: 2,
                                   low: Date.UTC(2010, 0, 1, str[0], str[1], str[2]),
                                   high: Date.UTC(2010, 0, 1, str2[0], str2[1], str2[2]),
                                   color: 'gray'
                              };

                             StatusList.push(status_obj);
                     }
                     else if (dashlist[i].ApplicationStatus == 1 || dashlist[i].ApplicationStatus == 0) {
                          // Offline
                         if (dashlist[i].DriverStatus == "0" && dashlist[i].IsBooked == "0") {
                            
                                 status_obj = {
                                      x: 1,
                                      low: Date.UTC(2010, 0, 1, str[0], str[1], str[2]),
                                      high: Date.UTC(2010, 0, 1, str2[0], str2[1], str2[2]),
                                      color: 'black'
                            };                   
                          StatusList.push(status_obj);
                         }
                                        
                         else if ((dashlist[i].DriverStatus == "3" && dashlist[i].IsBooked == "1" && dashlist[i].BusyOnCustomerApp == "1") ) { // Accepted- Purple 
                                    status_obj = {
                                              x: 3,
                                              low: Date.UTC(2010, 0, 1, str[0], str[1], str[2]),
                                              high: Date.UTC(2010, 0, 1, str2[0], str2[1], str2[2]),
                                              color: 'purple'
                                          };

                                    StatusList.push(status_obj);                                      
                         }
                         else if ((dashlist[i].DriverStatus == "1" && dashlist[i].IsBooked == "1" && dashlist[i].BusyOnCustomerApp == "1") ) { // inway- red 
                             status_obj = {
                                 x: 3,
                                 low: Date.UTC(2010, 0, 1, str[0], str[1], str[2]),
                                 high: Date.UTC(2010, 0, 1, str2[0], str2[1], str2[2]),
                                 color: 'red'
                             };

                             StatusList.push(status_obj);
                          
                         }
                         else if ((dashlist[i].DriverStatus == "1" && dashlist[i].IsBooked == "0" && dashlist[i].BusyOnCustomerApp == "1")   // Online- Green
                           || (dashlist[i].DriverStatus == "1" && dashlist[i].IsBooked == "0" && dashlist[i].BusyOnCustomerApp == "0")  ) {// Assigned- Green 
                             status_obj = {
                                 x: 3,
                                 low: Date.UTC(2010, 0, 1, str[0], str[1], str[2]),
                                 high: Date.UTC(2010, 0, 1, str2[0], str2[1], str2[2]),
                                 color: 'green'
                             };

                             StatusList.push(status_obj);
                            
                         }
                         else if ((dashlist[i].DriverStatus == "4" && dashlist[i].IsBooked == "0" && dashlist[i].BusyOnCustomerApp == "1")  ) {// Assigned- Blue 
                             status_obj = {
                                 x: 3,
                                 low: Date.UTC(2010, 0, 1, str[0], str[1], str[2]),
                                 high: Date.UTC(2010, 0, 1, str2[0], str2[1], str2[2]),
                                 color: 'blue'
                             };
                             StatusList.push(status_obj);
                         
                         }
                        else if ((dashlist[i].DriverStatus == "1" && dashlist[i].IsBooked == "1" && dashlist[i].BusyOnCustomerApp == "0")
                                 || (dashlist[i].DriverStatus == "4" && dashlist[i].IsBooked == "0" && dashlist[i].BusyOnCustomerApp == "0")
                                 || (dashlist[i].DriverStatus == "3" && dashlist[i].IsBooked == "1" && dashlist[i].BusyOnCustomerApp == "0") ) {
                                       status_obj = {
                                              x: 4,
                                              low: Date.UTC(2010, 0, 1, str[0], str[1], str[2]),
                                              high: Date.UTC(2010, 0, 1, str2[0], str2[1], str2[2]),
                                              color: 'red'
                                          };

                                          StatusList.push(status_obj);
                                       
                                      }
                                     
                                      else if (dashlist[i].DriverStatus == "2" && dashlist[i].IsBooked == "0") {
                                       
                                          status_obj = {
                                              x: 0,
                                              low: Date.UTC(2010, 0, 1, str[0], str[1], str[2]),
                                              high: Date.UTC(2010, 0, 1, str2[0], str2[1], str2[2]),
                                              color: 'skyblue'
                                          };
                                          BreakCount++;
                                          StatusList.push(status_obj);
                                      }
                                      else if ((dashlist[i].DriverStatus == "0" && dashlist[i].IsBooked == "0")
                                            || (dashlist[i].DriverStatus == '0' && dashlist[i].IsBooked == '1')) {
                                        
                                          status_obj = {
                                              x: 1,
                                              low: Date.UTC(2010, 0, 1, str[0], str[1], str[2]),
                                              high: Date.UTC(2010, 0, 1, str2[0], str2[1], str2[2]),
                                              color: 'black'
                                          };

                                          StatusList.push(status_obj);
                                      }                                
                                  }
                     }
            
            $scope.$apply();
        }
    });

    setTimeout(function () {
        var Year = 2010, Month = 1, Day = 1;

      //  console.log(StatusList);

        $('#graph').highcharts({
            exporting: {
                enabled: false
            },
            chart: {
                type: 'columnrange',
                inverted: true,
                zoomType: 'xy'
            },
            title: {
                text: ''
            },
            yAxis: {
                min: Date.UTC(2010, 0, 1, 0, 0, 0),
                max: Date.UTC(2010, 0, 2, 0, 0, 0),
                type: 'datetime',
                tickPositioner: function() {
                    var info = this.tickPositions.info;
                    var positions = [];
                    for (i = Date.UTC(2010, 0, 1, 0, 0, 0); i <= Date.UTC(2010, 0, 2, 0, 0, 0); i += 3600 * 1000) {
                        positions.push(i);
                    }
                    positions.info = info;
                    return positions;
                },
            
                lineWidth: 1,
                dateTimeLabelFormats: {
                    day: '%H:%M'
                },
                startOnTick: false,
                endOnTick:false,
                title: {
                    enabled: false
                }
            },
            xAxis: {
                categories: ['Break  '+ BreakCount, 'Offline', 'Out of Network', 'Online', 'Busy'],
                
            },
            legend: {
                enabled: false
            },
            plotOptions: {
                series: {
                    pointWidth: 10,
                }
            },
            series: [{

                data: StatusList,
             
            }],
            tooltip: {
                formatter: function () {
                  //  console.log(this);
                    return '<b>' + this.x + '</b> started at <b>' + Highcharts.dateFormat('%H:%M', this.point.low) + '</b> and ended at <b>' + Highcharts.dateFormat('%H:%M', this.point.high) + '</b>';
                },
                positioner: function (w, h, p) {
                    return {
                        x: p.plotX + this.chart.hoverSeries.pointXOffset + this.chart.plotLeft - w / 2 + this.chart.hoverSeries.barW / 2,
                        y: p.plotY -35
                    };
                }
            },

       
        });
     
    }, 500);

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

        success: function (result) {
            if (result.GetAVATimeResult == "access_denied") {
                window.parent.location.href = "../../Access.html";
                return;
            }
            //var a = result;
            $scope.loading = false;
            var data = JSON.parse(result.GetAVATimeResult);
            $scope.List = data;

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

    $scope.loading = true;
   

    $scope.ClickClose = function () {

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

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

    }


    $scope.show = function () {
        alert();
       
    }
})

