var GetCustomers, LoadDrivers, Export;
var DriverTypelist = [],list = [];
var TaxiApp = angular.module('FinancialReport', ['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('FinancialReportCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog',

    function ($scope, $http, $sessionStorage, ngDialog) {


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

        }
      
        $scope.VehicleCurrentLocation = [];
        $scope.DealerList = "0";
        $scope.BlockList = "0";
        $scope.ChooseDateType = "0";
        $scope.loading = false;
        $scope.DisplayName = sessionStorage.UserName;       
        $scope.CompanyName = sessionStorage.value;
       // console.log(sessionStorage)
        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();
            }
            var filteredList = [];
            $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.FromDate=formatDateToView(today);
            $scope.ToDate = formatDateToView(today);
            $scope.DriverFromDate = formatDateToView(today);
            $scope.DriverToDate = formatDateToView(today);
            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.calculateTotalDrivers = function (filteredDriverList) {
                if (filteredDriverList != undefined) {
                    totalD = 0;
                    for (var i = 0; i < filteredDriverList.length; i++) {
                        totalD += filteredDriverList[i].Amount


                    }
                    return Math.round(totalD * 100) / 100;
                }
            }
            var totalC = 0;
            $scope.calculateTotalCustomers = function (filteredList) {
                if (filteredList != undefined) {
                    totalC = 0;
                    for (var i = 0; i < filteredList.length; i++) {
                        totalC += filteredList[i].Amount


                    }
                    return Math.round(totalC * 100) / 100;
                }
            }
       
            $scope.selectCompanydetails = function (obj) {
                sessionStorage.CompanyOID = obj.OID;
                sessionStorage.value = obj.Value;
                window.location.href = "Management.html";
            }

 
        
        
            Export = {

                Customers: 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 = "";

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

                        var object = $scope.CustomerBallanceDetails[i];
                        row = '<tr class="even gradeC">'; 
                        row += "<td>" + object.Transaction_ID + "</td>";
                        row += "<td>" + object.Time + "</td>";
                        row += "<td>" + object.Amount + "</td>";
                        row += "<td>" + object.TransactionName + "</td>";
                        row += "<td>" + object.Notes + "</td>";
                      
                        row += '</tr>';

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


                    $(htmlTable).table2excel({

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

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

                    });

                },
                Drivers: 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 = "";

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

                        var object = $scope.DriverBallanceDetails[i];
                        row = '<tr class="even gradeC">';
                        row += "<td>" + object.Transaction_ID + "</td>";
                        row += "<td>" + object.Time + "</td>";
                        row += "<td>" + object.Amount + "</td>";
                        row += "<td>" + object.TypeText + "</td>";
                        row += "<td>" + object.Notes + "</td>";

                        row += '</tr>';

                        htmlTable += row;
                        row = "";
                    }

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


                    $(htmlTable).table2excel({

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

                        filename: "حركات السائقين" //do not include extension

                    });

                }
            }
          
         
        
   

        }
        /*----------------------------      GetCompanyCustomers          ---------------*/
    
        $scope.changedValue = function (item) {
            $(".ChooseDate").fadeOut(500);
            if (item == "true") {

                $(".ChooseDate").fadeIn(500);

            } 
        }
    
        var timepicker = new TimePicker(['FromTime', 'ToTime', 'DriverFromTime', 'DriverToTime'], {
            lang: 'en',
            theme: 'dark'
        });

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



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



        });
        var selectedList="";
        $("#viewall").click(function () {
            selectedList="";
            if ($("#DriverMEssage").val() == "") {
                list = [];
                $scope.CustomerBallanceDetails.length = 0;

            } else {
                for (var i = 0; i < list.length; i++) {

                    if (i == list.length) {
                        selectedList += list[i]

                    } else {
                        selectedList += list[i] + "~";
                    }

                }
                //   console.log(selectedList);


                var obj = {
                    'OID': selectedList,
                    'fromDate': getFormattedFromDate($scope.FromDate) + " " + formatTime($("#FromTime").val()),
                    'toDate': getFormattedFromDate($scope.ToDate) + " " + formatTime($("#ToTime").val()),


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

        var selectedDriverList = "";
        $("#ViewDrivers").click(function () {
            selectedDriverList = ""
            if ($("#DriverPayementTypes").val() == "") {
                DriverTypelist = [];
                $scope.DriverBallanceDetails.length = 0;

            } else {
                for (var i = 0; i < DriverTypelist.length; i++) {
                    if (i == DriverTypelist.length) {
                        selectedDriverList += DriverTypelist[i]

                    } else {
                        selectedDriverList += DriverTypelist[i] + "~";
                    }
                }

                var obj = {
                    'OID': selectedDriverList,
                    'fromDate': getFormattedFromDate($scope.DriverFromDate) + " " + formatTime($("#DriverFromTime").val()),
                    'toDate': getFormattedFromDate($scope.DriverToDate) + " " + formatTime($("#DriverToTime").val()),
                }
                $scope.GetReport.driver(obj);
            }
            
           // console.log(selectedDriverList);


            
        });


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

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

                    success: function (result) {

                        if (result.GetCustomerBallanceDetailsResult == "access_denied") {
                            window.parent.location.href = "../../Access.html";
                            return;
                        }
                        data = JSON.parse(result.GetCustomerBallanceDetailsResult);

                        if (data.length > 0) {
                            $scope.CustomerBallanceDetails = data;
                            for (var i = 0 ; i < $scope.CustomerBallanceDetails.length; i++) {
                                var date = splitDate($scope.CustomerBallanceDetails[i].Transaction_DateTime)
                                var time = date[1].substring(0, 5);
                                $scope.CustomerBallanceDetails[i].Time = date[0] + "   " + time
                                //console.log($scope.DriverBallanceDetails[i].Time)
                            }
                            


                        } else {

                            $scope.CustomerBallanceDetails = [];
                        }
                        $scope.loading = false;

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


            },
            driver: function (obj) {

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

                    success: function (result) {
                        if (result.GetDriverBallanceDetailsResult == "access_denied") {
                            window.parent.location.href = "../../Access.html";
                            return;
                        }
                        data = JSON.parse(result.GetDriverBallanceDetailsResult);

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


                            for (var i = 0 ; i < $scope.DriverBallanceDetails.length; i++) {
                                var date = splitDate($scope.DriverBallanceDetails[i].Transaction_DateTime)
                                var time = date[1].substring(0, 5);
                                $scope.DriverBallanceDetails[i].Time = date[0] + "   " + time
                                //console.log($scope.DriverBallanceDetails[i].Time)
                            }
                         


                        } else {
                            $scope.DriverBallanceDetails = [];
                        }
                        $scope.loading = false;

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

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


            },

        }
        

        GetAllCustomerTransactiontTypes($scope);
       
        $scope.fillTypesList = function (TypesList) {


            $scope.AllCustomerTransactiontTypes = JSON.parse(TypesList.GetAllCustomerTransactiontTypesResult);
         //   console.log($scope.AllCustomerTransactiontTypes);
            var AllCustomerTransactiontTypesType = [];

            AllCustomerTransactiontTypesType[0] = {
                label: "الحركات الموجبة",
                value:"-1",
                TransactionSign: "+",

            }
            AllCustomerTransactiontTypesType[1] = {
                label: "الحركات السالبة",
                value: "-2",
                TransactionSign: "-",

            }
            for (var i = 0; i < $scope.AllCustomerTransactiontTypes.length; i++) {
              //  AllCustomerTransactiontTypesType.push()
                AllCustomerTransactiontTypesType[i+2] = {
                    label: $scope.AllCustomerTransactiontTypes[i].TransactionName + "   [ " + $scope.AllCustomerTransactiontTypes[i].TransactionSign + " ] ",
                    value: $scope.AllCustomerTransactiontTypes[i].OID,
                    TransactionSign: $scope.AllCustomerTransactiontTypes[i].TransactionSign,
                    TransactionAmout: $scope.AllCustomerTransactiontTypes[i].TransactionSign,
                 
                }
            }
            //console.log($scope.AllCustomerTransactiontTypes)
            var test = AllCustomerTransactiontTypesType;
             $scope.typesList = $("#DriverMEssage").mSelectDBox({
                "list": test,
                "multiple": true,
                "autoComplete": true,
                "name": "a",
                "onselect": function (msdbContext, event) {

                    var selectedId = arguments[1].listItem.value;

                    var isSelected = arguments[1].listItem.selected;

                   // console.log(test);

                    if (selectedId == "-1") {

                        if (isSelected) {

                            $scope.changeSelectedItemsStatus("+", true, test);

                        } else {

                            $scope.changeSelectedItemsStatus("+", false, test);

                        }

                    } else if (selectedId == "-2") {

                        if (isSelected) {

                            $scope.changeSelectedItemsStatus("-", true, test);

                        } else {

                            $scope.changeSelectedItemsStatus("-", false, test);
                        }
                    } else {
                       
                        if (isSelected) {
                            list.push(selectedId)
                        } else {

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

                                if (list[i] == selectedId) {
                                    list.splice(i, 1);
                                }
                            }
                        }

                    }

                }
             });

            

        }
            
          
       
        $scope.ClearList = function () {
      
            $("#DriverMEssage").mSelectDBox('select', { "value": "" });
        }
        $scope.changeSelectedItemsStatus = function (sign, status, test) {
            list = [];
            for (var i = 0; i < test.length; i++) {

                var object = test[i];

                if (object.value == "-1" && object.TransactionSign == sign) {

                    if (status) {

                        list.push("-1");
                    } else {
                        list=[]
                    }

                } else if (object.value == "-2" && object.TransactionSign == sign) {

                    if (status) {

                        list.push("-2");
                    } else {

                        list = []
                    }


                } else {

                    if (object.TransactionSign == sign && status) {

                        object.selected = status;
                        list.push(object.value);

                    } else if(object.TransactionSign != sign && object.selected) {

                        list.push(object.value);
                    }
                }

            }

          
            $("#DriverMEssage").mSelectDBox('select', { "value": list });
            

           

        }
      /*--------------------------------------------    -----------------------------------------*/  
        GetDriverAllPaymentTypes($scope);

        $scope.fillDriverTypesList = function (TypesList) {


            $scope.GetDriverAllPaymentTypesList = JSON.parse(TypesList.GetDriverAllPaymentTypesResult);
          //  console.log($scope.GetDriverAllPaymentTypesList);
            var AllDriverTransactiontTypesType = [];

            AllDriverTransactiontTypesType[0] = {
                label: "الحركات الموجبة",
                value: "-1",
                TransactionSign: "+",

            }
            AllDriverTransactiontTypesType[1] = {
                label: "الحركات السالبة",
                value: "-2",
                TransactionSign: "-",

            }
            for (var i = 0; i < $scope.GetDriverAllPaymentTypesList.length; i++) {
                //  AllDriverTransactiontTypesType.push()
                    AllDriverTransactiontTypesType[i + 2] = {
                        label: $scope.GetDriverAllPaymentTypesList[i].PaymentType + "   [ " + $scope.GetDriverAllPaymentTypesList[i].TransactionSign + " ] ",
                    value: $scope.GetDriverAllPaymentTypesList[i].OID,
                    TransactionSign: $scope.GetDriverAllPaymentTypesList[i].TransactionSign,
                 //   TransactionAmout: $scope.GetDriverAllPaymentTypesList[i].TransactionSign,

                }
            }
        
            //console.log($scope.AllCustomerTransactiontTypes)
            var test = AllDriverTransactiontTypesType;
            $scope.typesList = $("#DriverPayementTypes").mSelectDBox({
                "list": test,
                "multiple": true,
                "autoComplete": true,
                "name": "a",
                "onselect": function (msdbContext, event) {

                    var selectedId = arguments[1].listItem.value;

                    var isSelected = arguments[1].listItem.selected;

                    // console.log(test);

                    if (selectedId == "-1") {

                        if (isSelected) {

                            $scope.changeSelectedDriverItemsStatus("+", true, test);

                        } else {

                            $scope.changeSelectedDriverItemsStatus("+", false, test);

                        }

                    } else if (selectedId == "-2") {

                        if (isSelected) {

                            $scope.changeSelectedDriverItemsStatus("-", true, test);

                        } else {

                            $scope.changeSelectedDriverItemsStatus("-", false, test);
                        }
                    } else {
                        if (isSelected) {
                            DriverTypelist.push(selectedId)
                        } else {

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

                                if (DriverTypelist[i] == selectedId) {
                                    DriverTypelist.splice(i, 1);
                                }
                            }
                        }
                      
                    }

                    //  console.log("selected Id " + selectedId+"  ,   Is Selected ="+isSelected);
                }
            });



        }

    
       
        $scope.ClearDriverList = function () {

            $("#DriverPayementTypes").mSelectDBox('select', { "value": "" });
        }
        $scope.changeSelectedDriverItemsStatus = function (sign, status, test) {
            DriverTypelist = [];
            for (var i = 0; i < test.length; i++) {

                var object = test[i];

                if (object.value == "-1" && object.TransactionSign == sign) {

                    if (status) {

                        DriverTypelist.push("-1");
                    } else {
                        DriverTypelist = []
                    }

                } else if (object.value == "-2" && object.TransactionSign == sign) {

                    if (status) {

                        DriverTypelist.push("-2");
                    } else {

                        DriverTypelist = []
                    }


                } else {

                    if (object.TransactionSign == sign && status) {

                        object.selected = status;
                        DriverTypelist.push(object.value);

                    } else if (object.TransactionSign != sign && object.selected) {

                        DriverTypelist.push(object.value);
                    }
                }

            }


            $("#DriverPayementTypes").mSelectDBox('select', { "value": DriverTypelist });




        }
    }])


  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
      }

  }
