var GetCustomers, LoadDrivers, Export;
var dailyExportList = [], monthlyExportList = [], GetUserListDetails = [], GetReturnedUserListDetails=[];
var TaxiApp = angular.module('ManagementReports', ['ngStorage', 'ngDialog', 'ui.bootstrap'])
  function splitT(date) {

      var str = date.split("T");
      return str[0];
        }
  function splitDate(date) {

      var str = date.split("T");
      return str;
  }


  TaxiApp.controller('ManagementReportsCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'DailyDownloadsKPIsDetails', 'MonthlyDownloadsKPIsDetails', 'LostUsersList', 'ReturnedUsersList',

    function ($scope, $http, $sessionStorage, ngDialog, DailyDownloadsKPIsDetails, MonthlyDownloadsKPIsDetails, LostUsersList, ReturnedUsersList) {


        Localization(sessionStorage.selectedLanguage, 'allreport', $scope, sessionStorage);     
        $scope.loading = false;
        $scope.DisplayName = sessionStorage.UserName;       
        $scope.CompanyName = sessionStorage.value;
       // console.log(sessionStorage)
      
        if (sessionStorage.length == (undefined || 0)) {
            window.parent.location.href = "../../Index.html";
        }
        else {
            $scope.Role = sessionStorage.RoleType;
          
            if (sessionStorage.RoleType == "Organization Admin") {
                $('.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);
            }
            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);

            $scope.DailyDownloadsFromDate = formatDateToView(today);
            $scope.DailyDownloadsToDate = formatDateToView(today);
            $scope.DailyBookingsFromDate = formatDateToView(today);
            $scope.DailyBookingsToDate = formatDateToView(today);
            $scope.ChurnUsersFromDate = formatDateToView(today);
            $scope.ChurnUsersToDate = formatDateToView(today);
            $scope.LoyalCustomersFromDate = formatDateToView(today);
            $scope.LoyalCustomersToDate = formatDateToView(today);
            $scope.ChurnPeriod='w'
         


            function formatDateToView(date) {
                var dateParts = date.split(" ");
                if (dateParts.length > 0) {

                    var yafa = dateParts[0].split("-");
                    var newDate = yafa[1] + "-" + yafa[2] + "-" + yafa[0]
                    var date = new Date(newDate);
                    var year = date.getFullYear();
                    var month = ("0" + (date.getMonth() + 1)).slice(-2);
                    var day = ("0" + date.getDate()).slice(-2);
                    return new Date(month + "/" + day + "/" + year);

                }


            }

            $scope.CustomersBalanceList = "";
     
        
            var totalD = 0;

            $scope.calculateTotalDailyDownloadsR = function (filteredDailyDownloadsList) {
                if (filteredDailyDownloadsList != undefined) {
                    totalD = 0;
                    for (var i = 0; i < filteredDailyDownloadsList.length; i++) {
                        totalD += filteredDailyDownloadsList[i].TotalRegisteredUsers


                    }
                    return totalD;
                }
            }
           
            var totalD = 0;

            $scope.calculateTotalDailyDownloadsB = function (filteredDailyDownloadsList) {
                if (filteredDailyDownloadsList != undefined) {
                    totalD = 0;
                    for (var i = 0; i < filteredDailyDownloadsList.length; i++) {
                        totalD += filteredDailyDownloadsList[i].BookingRatio


                    }
                    return totalD;
                }
            }
            var totalD = 0;

            $scope.calculateTotalDailyDownloadsN = function (filteredDailyDownloadsList) {
                if (filteredDailyDownloadsList != undefined) {
                    totalD = 0;
                    for (var i = 0; i < filteredDailyDownloadsList.length; i++) {
                        totalD += filteredDailyDownloadsList[i].NoBooking


                    }
                    return totalD;
                }
            }

            $scope.CustomerBallanceDetails = {
             

            }
      
            loadContents(sessionStorage.ORGOID, sessionStorage.CompanyOID, sessionStorage.UserOID, 'DT', $scope);
            console.log($scope.DistrictList)
            $scope.SelectedDistrict = function (districtOid) {
                DistrictName = $.grep($scope.DistrictList, function (item) {

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

                DailyDownloads: function () {

                    var htmlTable = '<table style="direction: rtl;">';
                    htmlTable += '<thead><tr><th> <span > التاريخ </span></th><th> <span > عدد التنزيلات</span></th><th> <span >  عدد الطلبات</span></th><th> <span >عدد عدم الطلبات  </span></th></tr> </thead> <tbody>';

                    var row = "";

                    for (var i = 0; i < $scope.DailyDownloads.length; i++) {

                        var object = $scope.DailyDownloads[i];
                        row = '<tr class="even gradeC">'; 
                        row += "<td>" + object.FormatedDate + "</td>";
                        row += "<td>" + object.TotalRegisteredUsers + "</td>";
                        row += "<td>" + object.BookingRatio + "</td>";
                        row += "<td>" + object.NoBooking + "</td>";
                     
                        row += '</tr>';

                        htmlTable += row;
                        row = "";
                    }
                   
                    htmlTable += "</tbody></table>";


                    $(htmlTable).table2excel({

                        type:"Text",
                        name: "Worksheet Name",

                        filename: "التنزيلات اليومية " //do not include extension

                    });

                },
                MonthlyDownloads: function () {

                    var htmlTable = '<table style="direction: rtl;">';
                    htmlTable += '<thead><tr><th> <span > التاريخ </span></th><th> <span > عدد التنزيلات</span></th><th> <span >  عدد الطلبات</span></th><th> <span >عدد عدم الطلبات  </span></th></tr> </thead> <tbody>';

                    var row = "";

                    for (var i = 0; i < $scope.MonthlyDownloads.length; i++) {

                        var object = $scope.MonthlyDownloads[i];
                        row = '<tr class="even gradeC">';
                        row += "<td>" + object.MonthNumber + "</td>";
                        row += "<td>" + object.TotalRegisteredUsers + "</td>";
                        row += "<td>" + object.BookingRatio + "</td>";
                        row += "<td>" + object.NoBooking + "</td>";

                        row += '</tr>';

                        htmlTable += row;
                        row = "";
                    }

                    htmlTable += "</tbody></table>";


                    $(htmlTable).table2excel({

                        type: "Text",
                        name: "Worksheet Name",

                        filename: "التنزيلات الشهرية " //do not include extension

                    });

                },
                DailyBookings: function () {

                    var htmlTable = '<table style="direction: rtl;">';
                    htmlTable += '<thead><tr><th> <span > التاريخ </span></th><th> <span > عدد الطلبات</span></th><th> <span >عدد المستخدمين</span></th><th> <span >الطلبات المتكملة</span></th><th> <span >الطلبات الملغية من السائق</span></th><th> <span >الطلبات الملغية من المستخدمين</span></th><th> <span >الطلبات المرفوضة</span></th><th> <span >الطلبات لم يتم الرد عليها</span></th></tr> </thead> <tbody>';

                    var row = "";

                    for (var i = 0; i < $scope.DailyBookings.length; i++) {

                        var object = $scope.DailyBookings[i];
                        row = '<tr class="even gradeC">';
                        row += "<td>" + object.FormatedDate + "</td>";
                        row += "<td>" + object.TotalBookingRequests + "</td>";
                        row += "<td>" + object.CustomersCount + "</td>";
                        row += "<td>" + object.Completed_Trips + "</td>";
                        row += "<td>" + object.CanceledByDriver + "</td>";
                        row += "<td>" + object.CanceledByUser + "</td>";
                        row += "<td>" + object.Rejected + "</td>";
                        row += "<td>" + object.MissedBookings + "</td>";

                        row += '</tr>';

                        htmlTable += row;
                        row = "";
                    }

                    htmlTable += "</tbody></table>";


                    $(htmlTable).table2excel({

                        type: "Text",
                        name: "Worksheet Name",

                        filename: "الطلبات اليومية " //do not include extension

                    });
                },
                MonthlyBookings: function () {

                    var htmlTable = '<table style="direction: rtl;">';
                    htmlTable += '<thead><tr><th> <span > التاريخ </span></th><th> <span > عدد الطلبات</span></th><th> <span >عدد المستخدمين</span></th><th> <span >الطلبات المتكملة</span></th><th> <span >الطلبات الملغية من السائق</span></th><th> <span >الطلبات الملغية من المستخدمين</span></th><th> <span >الطلبات المرفوضة</span></th><th> <span >الطلبات لم يتم الرد عليها</span></th></tr> </thead> <tbody>';

                    var row = "";

                    for (var i = 0; i < $scope.MonthlyBookings.length; i++) {

                        var object = $scope.MonthlyBookings[i];
                        row = '<tr class="even gradeC">';
                        row += "<td>" + object.MonthNumber + "</td>";
                        row += "<td>" + object.TotalBookingRequests + "</td>";
                        row += "<td>" + object.CustomersCount + "</td>";
                        row += "<td>" + object.Completed_Trips + "</td>";
                        row += "<td>" + object.CanceledByDriver + "</td>";
                        row += "<td>" + object.CanceledByUser + "</td>";
                        row += "<td>" + object.Rejected + "</td>";
                        row += "<td>" + object.MissedBookings + "</td>";

                        row += '</tr>';

                        htmlTable += row;
                        row = "";
                    }

                    htmlTable += "</tbody></table>";


                    $(htmlTable).table2excel({

                        type: "Text",
                        name: "Worksheet Name",

                        filename: "الطلبات الشهرية " //do not include extension

                    });
                },
                DailyDownloadsDetails: function () {
                    var htmlTable = '<table style="direction: rtl;">';
                    htmlTable += '<thead><tr><th> <span > اسم المستخدم </span></th><th> <span > المحافظة </span></th><th> <span >رقم الهاتف </span></th></tr> </thead> <tbody>';

                    var row = "";

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

                        var object = dailyExportList[i];
                        row = '<tr class="even gradeC">';
                        row += "<td>" + object.CustomerName + "</td>";
                        row += "<td>" + object.DistrictName + "</td>";
                        row += "<td>" + object.MobileNo + "</td>";

                        row += '</tr>';

                        htmlTable += row;
                        row = "";
                    }

                    htmlTable += "</tbody></table>";


                    $(htmlTable).table2excel({

                        type: "Text",
                        name: "Worksheet Name",

                        filename: "تفاصيل التنزيلات اليومية "//do not include extension

                    });

                },
                MonthlyDownloadsDetails: function () {
                    var htmlTable = '<table style="direction: rtl;">';
                    htmlTable += '<thead><tr><th> <span > اسم المستخدم </span></th><th> <span > المحافظة </span></th><th> <span >رقم الهاتف </span></th></tr> </thead> <tbody>';

                    var row = "";

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

                        var object = monthlyExportList[i];
                        row = '<tr class="even gradeC">';
                        row += "<td>" + object.CustomerName + "</td>";
                        row += "<td>" + object.DistrictName + "</td>";
                        row += "<td>" + object.MobileNo + "</td>";

                        row += '</tr>';

                        htmlTable += row;
                        row = "";
                    }

                    htmlTable += "</tbody></table>";


                    $(htmlTable).table2excel({

                        type: "Text",
                        name: "Worksheet Name",

                        filename: "تفاصيل التنزيلات الشهرية " //do not include extension

                    });

                },
                ChurnUsers: function () {
                    var htmlTable = '<table style="direction: rtl;">';
                    htmlTable += '<thead><tr><th> <span >عدد المستخدمين </span></th><th> <span >عدد المستخدمين ذو الطلابات خلال اسبوع  </span></th><th> <span >عدد المستخدمين الين لم يطلبو بعد الاسبوع</span></th><th> <span >نسبة الخسارة</span></th></tr> </thead> <tbody>';

                    var row = "";

                   

                     
                        row = '<tr class="even gradeC">';
                        row += "<td>" + $scope.UsersHaveBookings + "</td>";
                        row += "<td>" + $scope.UsersContinueBookings + "</td>";
                        row += "<td>" + $scope.UsersLost + "</td>";
                        row += "<td>" + $scope.UsersLostRatio + "</td>";

                        row += '</tr>';

                        htmlTable += row;
                   
                 

                    htmlTable += "</tbody></table>";


                    $(htmlTable).table2excel({

                        type: "Text",
                        name: "Worksheet Name",

                        filename: "المستخدمين" //do not include extension

                    });

                },
                LostUsersDetails: function () {
                    var htmlTable = '<table style="direction: rtl;">';
                    htmlTable += '<thead><tr><th> <span >اسم المستخدم  </span></th><th> <span >تاريخ التسجيل</span></th><th> <span >الرقم</span></th></tr> </thead> <tbody>';

                    var row = "";

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

                        var object = GetUserListDetails[i];
                        row = '<tr class="even gradeC">';
                        row += "<td>" + object.CustomerName + "</td>";
                        row += "<td>" + object.CreatedAtFormated + "</td>";
                        row += "<td>" + object.MobileNo + "</td>";

                        row += '</tr>';

                        htmlTable += row;
                        row = "";
                    }




                    htmlTable += "</tbody></table>";


                    $(htmlTable).table2excel({

                        type: "Text",
                        name: "Worksheet Name",

                        filename: "المستخدمين الي خسرناهم" //do not include extension

                    });

                },
                LoyalCustomers: function () {

                    var htmlTable = '<table style="direction: rtl;">';
                    htmlTable += '<thead><tr><th> <span > اسم المستخدم </span></th><th> <span > الرقم </span></th><th> <span > تاريخ التسجيل</span></th><th> <span >مجموع الرحلات</span></th><th> <span >سعر الرحلات</span></th><th> <span >عدد الرحلات</span></th><th> <span >مسافة الرحلات</span></th></tr> </thead> <tbody>';

                    var row = "";

                    for (var i = 0; i < $scope.LoyalCustomers.length; i++) {

                        var object = $scope.LoyalCustomers[i];
                        row = '<tr class="even gradeC">';
                        row += "<td>" + object.CustomerName + "</td>";
                        row += "<td>" + object.CustomerNo + "</td>";
                        row += "<td>" + object.FormatedDate + "</td>";
                        row += "<td>" + object.TotalNumberOfTrips + "</td>";
                        row += "<td>" + object.tripcost + "</td>";
                        row += "<td>" + object.tripcount + "</td>";
                        row += "<td>" + object.tripdistance + "</td>";
                        row += '</tr>';

                        htmlTable += row;
                        row = "";
                    }

                    htmlTable += "</tbody></table>";


                    $(htmlTable).table2excel({

                        type: "Text",
                        name: "Worksheet Name",

                        filename: "المستخدمين الاوفياء" //do not include extension
                    });
                },
                ReturnedCustomers: function () {
                    var htmlTable = '<table style="direction: rtl;">';
                    htmlTable += '<thead><tr><th> <span >عدد المستخدمين </span></th><th> <span >عدد المستخدمين ذو الطلابات    </span></th><th> <span >عدد المستخدمين الين لم يطلبو  </span></th><th> <span >نسبة الخسارة</span></th><th> <span >عدد المستخدمين الي رجعو </span></th></tr> </thead> <tbody>';

                    var row = "";




                    row = '<tr class="even gradeC">';
                    row += "<td>" + $scope.ReturnedUsersHaveBookings + "</td>";
                    row += "<td>" + $scope.ReturnedUsersContinueBookings + "</td>";
                    row += "<td>" + $scope.ReturnedUsersLost + "</td>";
                    row += "<td>" + $scope.ReturnedUsersLostRatio + "</td>";
                    row += "<td>" + $scope.ReturnedUsersCount + "</td>";


                    row += '</tr>';

                    htmlTable += row;



                    htmlTable += "</tbody></table>";


                    $(htmlTable).table2excel({

                        type: "Text",
                        name: "Worksheet Name",

                        filename: "المستخدمين العائدون" //do not include extension

                    });

                },
                ReturnedUsersDetails: function () {
                    var htmlTable = '<table style="direction: rtl;">';
                    htmlTable += '<thead><tr><th> <span >اسم المستخدم  </span></th><th> <span >تاريخ التسجيل</span></th><th> <span >الرقم</span></th></tr> </thead> <tbody>';

                    var row = "";

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

                        var object = GetReturnedUserListDetails[i];
                        row = '<tr class="even gradeC">';
                        row += "<td>" + object.CustomerName + "</td>";
                        row += "<td>" + object.CreatedAtFormated + "</td>";
                        row += "<td>" + object.MobileNo + "</td>";

                        row += '</tr>';

                        htmlTable += row;
                        row = "";
                    }




                    htmlTable += "</tbody></table>";


                    $(htmlTable).table2excel({

                        type: "Text",
                        name: "Worksheet Name",

                        filename: "المستخدمين الي رجعو" //do not include extension

                    });

                },

            }
        }

        $("#viewDailyBookings").click(function () {
            var ciod;
            if ($scope.DailyBookingsDistrictName == undefined) {
                ciod = 0

            } else {
                ciod = $scope.DailyBookingsDistrictName
            }

            var obj = {
                'city': ciod,
                'fromDate': getFormattedFromDate($scope.DailyBookingsFromDate),
                'toDate': getFormattedFromDate($scope.DailyBookingsToDate),         
            }
            $scope.GetReport.DailyBookings(obj);
        });
        $("#viewMonthlyBookings").click(function () {
            var ciod;
            if ($scope.MonthlyBookingsDistrictName == undefined) {
                ciod = 0

            } else {
                ciod = $scope.MonthlyBookingsDistrictName
            }

            var obj = {
                'city': ciod,
                'fromDate': getFormattedFromDate($scope.MonthlyBookingsFromDate),
                'toDate': getFormattedToDate($scope.MonthlyBookingsToDate),



            }
            $scope.GetReport.MonthlyBookings(obj);
        });
        $("#viewaDailyDownloads").click(function () {
            var ciod;
            if ($scope.DailyDownloadsDistrictName == undefined) {
                ciod = 0

            } else {
                ciod = $scope.DailyDownloadsDistrictName
            }
           
            var obj = {
                'city': ciod,
                'fromDate': getFormattedFromDate($scope.DailyDownloadsFromDate),
                'toDate': getFormattedFromDate($scope.DailyDownloadsToDate),
                'order':"1",
                

            }
            $scope.GetReport.DailyDownloads(obj);
        });
        $("#viewaMonthlyDownloads").click(function () {
            var ciod;
            if ($scope.MonthlyDistrictName == undefined) {
                ciod = 0

            } else {
                ciod = $scope.MonthlyDistrictName
            }

            var obj = {
                'city': ciod,
                'fromDate': getFormattedFromDate($scope.MonthlyDownloadsFromDate),
                'toDate': getFormattedToDate($scope.MonthlyDownloadsToDate),
                'order': "1",


            }



         
            $scope.GetReport.MonthlyDownloads(obj);
        });
        $("#viewChurnUsers").click(function () {
            var ciod;
            if ($scope.ChurnUsersDistrictName == undefined) {
                ciod = 0

            } else {
                ciod = $scope.ChurnUsersDistrictName
            }

            var obj = {
                'city': ciod,
                'fromDate': getFormattedFromDate($scope.ChurnUsersFromDate),
                'toDate': getFormattedFromDate($scope.ChurnUsersToDate),
                'period': $scope.ChurnPeriod



            }
            $scope.GetReport.ChurnUsers(obj);
        });
        $("#viewLoyalCustomers").click(function () {
            var ciod;
            if ($scope.LoyalCusotmerDistrictName == undefined) {
                ciod = 0

            } else {
                ciod = $scope.LoyalCusotmerDistrictName
            }

            var obj = {
                'city': ciod,
                'fromDate': getFormattedFromDate($scope.LoyalCustomersFromDate),
                'toDate': getFormattedFromDate($scope.LoyalCustomersToDate),
                'bookingCount': $scope.LoyalCustomersBookingsCount



            }
            $scope.GetReport.LoyalCustomers(obj);
        });
        $("#viewReturnedCustomers").click(function () {

            // undefined District
            var ciod;
            if ($scope.ReturnedCustomersDistrictName == undefined) {
                ciod = 0

            } else {
                ciod = $scope.ReturnedCustomersDistrictName
            }

            // undefined from date to start from inifinty
             var ReturnedCustomersFromDate;
            if ($scope.ReturnedCustomersFromDate == undefined) {

                ReturnedCustomersFromDate = 0;
            } else {
                ReturnedCustomersFromDate = getFormattedFromDate($scope.ReturnedCustomersFromDate);

            }

        
            // undefined retrenedUntil date to inifinty end 

          
            var ReturnedCustomersretrenedUntil;
            if ($scope.ReturnedCustomersretrenedUntil == undefined) {

                ReturnedCustomersretrenedUntil = 0;
            } else {
                ReturnedCustomersretrenedUntil = getFormattedFromDate($scope.ReturnedCustomersretrenedUntil);

            }


            var obj = {
                'city': ciod,
                'fromDate': ReturnedCustomersFromDate,
                'toDate': getFormattedFromDate($scope.ReturnedCustomersToDate),
                'NoBookingStartDate': getFormattedFromDate($scope.ReturnedCustomersNoBookingStartDate),
                'retrenedUntil':ReturnedCustomersretrenedUntil,


            }
            $scope.GetReport.ReturnedCustomers(obj);
        });


        $scope.GetReport = {
            DailyDownloads: function (obj) {

                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "GetDailyDownloadsKPIs/" + obj.city + '/' + obj.fromDate + "/" + obj.toDate + "/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                       
                        data = JSON.parse(result.GetDailyDownloadsKPIsResult);

                        if (data.length > 0) {
                            $scope.DailyDownloads = data;                
                            for (var i = 0; i < $scope.DailyDownloads.length; i++) {
                                var date = $scope.DailyDownloads[i].DayDate;
                                date = date.split("T");
                                $scope.DailyDownloads[i].FormatedDate = date[0]
                            }
                           


                        }else{
                            $scope.DailyDownloads = [];
                          
                        }
                        $scope.loading = false;
                            $scope.$apply();
                    },
                    error: function () {
                        $scope.loading = false;

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


            },
            DailyDownloadsDetails: function (objDate, hasBooking) {
                var fdate, tdate;
                if (objDate == -1) {
                    fdate = getFormattedFromDate($scope.DailyDownloadsFromDate);
                    tdate = getFormattedFromDate($scope.DailyDownloadsToDate);


                } else {
                    var date = objDate.split("T")
                    fdate = date[0];
                    tdate = date[0]

                }
                var ciod;
                if ($scope.DailyDownloadsDistrictName == undefined) {
                    ciod = 0

                } else {
                    ciod = $scope.DailyDownloadsDistrictName
                }
                ngDialog.open({
                    template: 'DailyDownloadsKPIsDetails.html',
                    className: 'DriverBalanceD ngdialog-theme-default dialogforpopup',
                    controller: 'DailyDownloadsKPIsDetailsCtrl',
                    resolve: {
                        fdate: function () {
                            return fdate;
                        },
                        tdate: function () {
                            return tdate;
                        }
                        , hasBooking: function () {
                            return hasBooking;
                        }, ciod: function () {
                            return ciod;
                        }
                    }


                })

            },
            MonthlyDownloads: function (obj) {
                
                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "GetMonthlyDownloadsKPIs/" + obj.city + '/' + obj.fromDate + "/" + obj.toDate + "/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        data = JSON.parse(result.GetMonthlyDownloadsKPIsResult);
                        if (data.length > 0) {
                            $scope.MonthlyDownloads = data;
                        } else {
                            $scope.MonthlyDownloads = [];
                        }
                        $scope.loading = false;
                        $scope.$apply();
                    },
                    error: function () {
                        $scope.loading = false;
                        $scope.$apply();
                    }
                });


            },
            MonthlyDownloadsDetails: function (objDate, hasBooking) {
                var fdate, tdate;


                if (objDate == -1) {
                    fdate = getFormattedFromDate($scope.MonthlyDownloadsFromDate);
                    tdate = getFormattedToDate($scope.MonthlyDownloadsToDate);


                } else {
                
                    console.log(objDate)
                  
                    fdate = getFisrtDay(objDate);
                    tdate = getLastDay(objDate);

                }

                var ciod;
                if ($scope.MonthlyDistrictName == undefined) {
                    ciod = 0

                } else {
                    ciod = $scope.MonthlyDistrictName
                }
                ngDialog.open({
                    template: 'MonthlyDownloadsKPIsDetails.html',
                    className: 'DriverBalanceD ngdialog-theme-default dialogforpopup',
                    controller: 'MonthlyDownloadsKPIsDetailsCtrl',
                    resolve: {
                        fdate: function () {
                            return fdate;
                        },
                        tdate: function () {
                            return tdate;
                        }
                        , hasBooking: function () {
                            return hasBooking;
                        }
                        , ciod: function () {
                            return ciod;
                        }
                    }


                })

            },
            DailyBookings: function (obj) {

                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "GetDailyBookingsKPIs/" + obj.city + '/' + obj.fromDate + "/" + obj.toDate + "/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        data = JSON.parse(result.GetDailyBookingsKPIsResult);

                        if (data.length > 0) {
                            $scope.DailyBookings = data;
                            for (var i = 0; i < $scope.DailyBookings.length; i++) {
                                var date = $scope.DailyBookings[i].BookDay;
                                date = date.split("T");
                                $scope.DailyBookings[i].FormatedDate = date[0]
                            }                          
                        } else {
                            $scope.DailyBookings=[]
                        }
                            $scope.loading = false;
                            $scope.$apply();

                    },
                    error: function () {
                        $scope.loading = false;
                        $scope.$apply();
                    }
                });


            },
            MonthlyBookings: function (obj) {

                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "GetMonthlyBookingsKPIs/" + obj.city + '/' + obj.fromDate + "/" + obj.toDate + "/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        data = JSON.parse(result.GetMonthlyBookingsKPIsResult);

                        if (data.length > 0) {
                            $scope.MonthlyBookings = data;

                        } else {

                            $scope.MonthlyBookings=[]
                        }
                        $scope.loading = false;
                        $scope.$apply();
                    },
                    error: function () {
                        $scope.loading = false;

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


            },
            ChurnUsers: function (obj) {

                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "GetChurnUsersKPIs/" + obj.city + '/' + obj.fromDate + "/" + obj.toDate + "/" + obj.period + "/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        var data = result.GetChurnUsersKPIsResult.toString();
                        data = data.split("[");
                        $scope.LostUsersList = data[1];
                        $scope.LostUsersList = "[" + $scope.LostUsersList;
                        $scope.LostUsersList = JSON.parse($scope.LostUsersList);


                        var newdata = data[0].slice(1, -1);
                        var user_data = newdata.split(",");
                        $scope.UsersHaveBookings = user_data[0];

                        $scope.UsersContinueBookings = user_data[1];
                        $scope.UsersLost = user_data[0] - user_data[1];
                       
                        $scope.UsersLostRatio = user_data[2] * 100;
                        if (data.length > 0) {
                            console.log(data);
                            $scope.ChurnUsers = data;
                            //for (var i = 0; i < $scope.ChurnUsers.length; i++) {
                            //    var date = $scope.ChurnUsers[i].DayDate;
                            //    date = date.split("T");
                            //    $scope.ChurnUsers[i].FormatedDate = date[0]
                            //}





                        } else {
                            $scope.ChurnUsers = [];

                        }
                        $scope.loading = false;
                        $scope.$apply();
                    },
                    error: function () {
                        $scope.loading = false;

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


            },
            LostUsersDetails: function () {
              
                var obj = $scope.LostUsersList;
                ngDialog.open({
                    template: 'LostUsersList.html',
                    className: 'DriverBalanceD ngdialog-theme-default dialogforpopup',
                    controller: 'LostUsersListCtrl',
                    resolve: {
                        obj: function () {
                            return obj;
                        }
                    }


                })

            },
            LoyalCustomers: function (obj) {

                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "GetLoyalCustomers/" + obj.city + '/' + obj.fromDate + "/" + obj.toDate + "/" + obj.bookingCount + "/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        var data = JSON.parse(result.GetLoyalCustomersResult);
                     
                        if (data.length > 0) {
                            console.log(data)
                            $scope.LoyalCustomers = data;

                            for (var i = 0; i < $scope.LoyalCustomers.length; i++) {
                                var date = $scope.LoyalCustomers[i].JoinDate;
                                date = date.split("T");
                                $scope.LoyalCustomers[i].FormatedDate = date[0]
                            }


                      
                        } else {
                            $scope.LoyalCustomers = [];

                        }
                        $scope.loading = false;
                        $scope.$apply();
                    },
                    error: function () {
                        $scope.loading = false;

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


            },
            ReturnedCustomers: function (obj) {

                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "GetReturnedCustomers/" + obj.city + '/' + obj.fromDate + "/" + obj.toDate + "/" + obj.NoBookingStartDate + "/" + obj.retrenedUntil + "/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        var data = result.GetReturnedCustomersResult.toString();
                      //  var data = result.GetChurnUsersKPIsResult.toString();
                        data = data.split("[");


                        $scope.ReturnedCustomers = data[1]
                        $scope.ReturnedCustomers = "[" + $scope.ReturnedCustomers
                        $scope.ReturnedCustomers = JSON.parse($scope.ReturnedCustomers)

                        var newdata = data[0].slice(1, -1);
                        var user_data = newdata.split(",")

                        $scope.ReturnedUsersHaveBookings = user_data[0]

                        $scope.ReturnedUsersContinueBookings = user_data[1]
                        $scope.ReturnedUsersLost = user_data[0] - user_data[1]

                        $scope.ReturnedUsersLostRatio = user_data[2] * 100
                        $scope.ReturnedUsersCount = user_data[3]

                        $scope.loading = false;
                        $scope.$apply();
                    },
                    error: function () {
                        $scope.loading = false;

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


            },
            ReturnedUsersDetails: function () {
               
            
              
                var obj = $scope.ReturnedCustomers;
                ngDialog.open({
                    template: 'ReturnedUsersList.html',
                    className: 'DriverBalanceD ngdialog-theme-default dialogforpopup',
                    controller: 'ReturnedUsersListCtrl',
                    resolve: {
                        obj: function () {
                            return obj;
                        }
                    }


                })

            },
        }
       
    }])


  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 getFormattedToDate(tDate) {

      var year = tDate.getFullYear();
      var month = (1 + tDate.getMonth()).toString();

      var d = new Date(year, tDate.getMonth()+1, 0);

      month = month.length > 1 ? month : '0' + month;

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

  }

  function getFisrtDay(tDate) {

      var date = tDate.split("-")
      var month = date[1];
      var year = date[0];
   

      return year + '-' + month + '-01'  ;

  }

  function getLastDay(tDate) {

      var date = tDate.split("-")
      var month = date[1];
      var year = date[0];

      var d = new Date(year, month , 0);

   

      var day = d.getDate().toString();
      day = day.length > 1 ? day : '0' + 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
      }

  }


  TaxiApp.service('ReturnedUsersList', function ($modal) {
      var service = {};
      var self = this;
      service.open = function (obj) {
          var modalInstance = $modal.open({
              dialogClass: 'balance_details',
              templateUrl: 'ReturnedUsersList.html',
              controller: 'ReturnedUsersListCtrl',
              resolve: {
                  obj: function () {
                      return obj;
                  },

              }

          });

      };



      return service;

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

      function GetReturnedUsersListDetails() {

          $scope.GetReturnedListDetails = obj

          for (var i = 0; i < $scope.GetReturnedListDetails.length; i++) {

              var date = $scope.GetReturnedListDetails[i].CreatedAt;
              date = date.split("T");
              $scope.GetReturnedListDetails[i].CreatedAtFormated = date[0]

          }

          GetReturnedUserListDetails = $scope.GetReturnedListDetails

      }

      GetReturnedUsersListDetails();



      $scope.loading = true;

      $scope.ClickClose = function () {

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

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

      }



  })

  TaxiApp.service('LostUsersList', function ($modal) {
      var service = {};
      var self = this;
      service.open = function (obj) {
          var modalInstance = $modal.open({
              dialogClass: 'balance_details',
              templateUrl: 'LostUsersList.html',
              controller: 'LostUsersListCtrl',
              resolve: {
                  obj: function () {
                      return obj;
                  },
                 
              }

          });

      };



      return service;

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

      function GetLostUsersListDetails() {

          $scope.GetListDetails = obj

          for (var i = 0; i < $scope.GetListDetails.length; i++) {

              var date = $scope.GetListDetails[i].CreatedAt;
              date = date.split("T");
              $scope.GetListDetails[i].CreatedAtFormated = date[0]

          }
          GetUserListDetails = $scope.GetListDetails
         

      }

      GetLostUsersListDetails();



      $scope.loading = true;

      $scope.ClickClose = function () {

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

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

      }



  })



  TaxiApp.service('DailyDownloadsKPIsDetails', function ($modal) {
      var service = {};
      var self = this;
      service.open = function (fdate, tdate, hasBooking, ciod) {
          var modalInstance = $modal.open({
              dialogClass: 'balance_details',
              templateUrl: 'DailyDownloadsKPIsDetails.html',
              controller: 'DailyDownloadsKPIsDetailsCtrl',
              resolve: {
                  fdate: function () {
                      return fdate;
                  },
                  tdate: function () {
                      return tdate;
                  }
                        , hasBooking: function () {
                            return hasBooking;
                        }
                  , ciod: function () {
                      return ciod;
                  }
              }

          });

      };



      return service;

  })
  TaxiApp.controller('DailyDownloadsKPIsDetailsCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, fdate, tdate, hasBooking, ciod) {

      function GetDailyDownloadsKPIsDetails() {
         
    
      

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

              success: function (result) {
                  //var a = result;
                  $scope.loading = false;

                  var data = JSON.parse(result.GetDownloadsDetailsKPIsResult);
                  if (data.length > 0) {

                      $scope.cList = data;
                      dailyExportList = data
                  } else {
                      $scope.cList = [];
                  }
                       
                  $scope.$apply();
              }
          });

      }

      GetDailyDownloadsKPIsDetails();
      


      $scope.loading = true;

      $scope.ClickClose = function () {

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

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

      }



  })



  TaxiApp.service('MonthlyDownloadsKPIsDetails', function ($modal) {
      var service = {};
      var self = this;
      service.open = function (fdate, tdate, hasBooking, ciod) {
          var modalInstance = $modal.open({
              dialogClass: 'balance_details',
              templateUrl: 'MonthlyDownloadsKPIsDetails.html',
              controller: 'MonthlyDownloadsKPIsDetailsCtrl',
              resolve: {
                  fdate: function () {
                      return fdate;
                  },
                  tdate: function () {
                      return tdate;
                  }
                        , hasBooking: function () {
                            return hasBooking;
                        }, ciod: function () {
                            return ciod;
                        }

              }

          });

      };



      return service;

  })
  TaxiApp.controller('MonthlyDownloadsKPIsDetailsCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, fdate, tdate, hasBooking, ciod) {

     function GetMonthlyDownloadsKPIsDetails() {
          $.ajax({
              cache: true,
              url: ManagementServiceUrl + "GetDownloadsDetailsKPIs/" + ciod+"/" + fdate + "/" + tdate + "/" + hasBooking + "/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID,
              type: "GET",
              contentType: "application/javascript",
              dataType: "jsonp",

              success: function (result) {
                  //var a = result;
                  $scope.loading = false;
                  var data = JSON.parse(result.GetDownloadsDetailsKPIsResult);
                  if (data.length > 0) {
                      $scope.mList = data;
                      monthlyExportList= data
                  } else {
                      $scope.mList=[]

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

      }

      GetMonthlyDownloadsKPIsDetails();



      $scope.loading = true;

      $scope.ClickClose = function () {

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

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

      }



  })



