import { Component, OnInit } from '@angular/core';
import { MdDialog } from '@angular/material';
import { Router } from '@angular/router';
import { ContactService } from '../../contact.service';
declare var $: any;
declare var moment : any;

@Component({
  selector: 'app-daily-logs',
  templateUrl: './daily-logs.component.html',
  styleUrls: ['./daily-logs.component.scss']
})
export class DailyLogsComponent implements OnInit {
  deviceArr: any = [];
  showSelectdevice: boolean = false;
  identifier = 'daily_report';
  reportArr: any[];
  ingData: any
  from1: any;
  to1: any;
  from2: any;
  to2: any;
  too: any;
  date1: any;
  Fromdate: any;
  todate: any;
  options = [];
  option: any;
  dataSelect: any = [];
  from: any;
  to: any;
  before: any;
  mb: any;
  logoutbut: boolean;
  dealer: boolean;
  superAdmin: Boolean = false;


  fs: any;
  ls: any;
  emailid: any;
  or: any;
  useridd: any;
  device_data: any;
  time: any;
  Load: Boolean = false;
  final: any;
  custtype: any;
  cust: boolean = false;
  devicess: any;
  finall: any;
  logo: any;
  text: any;
  test: number;
  data_descip:any;

  constructor(private contactService: ContactService, private router: Router, public dialog: MdDialog) { }

  ngOnInit() {
    this.dataSelect = [];
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;

    this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
    this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.mb = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    // this.getDevices();
    // this.dailyReport();
    if (this.custtype == true) {
      this.cust = true;
    }
    if (this.mb.charAt(0) == "n") {
      this.mb = ' '
    }
    if (window.localStorage['Custumer'] == 'ON') {
      this.logoutbut = false
      this.dealer = true
    }
    else {
      this.logoutbut = true
    }

    this.logo = window.localStorage['logo'];
    this.text = window.localStorage['text'];

    this.testTable();

  }


  tab: any;
  exportExcel() {



    var tab_text = "<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j = 0;
    var table = $('#deviceTable').clone();
    table[0].querySelector("thead").remove();
    table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];//document.getElementById('deviceTable'); // id of table

    for (j = 0; j < this.tab.rows.length; j++) {
      tab_text = tab_text + this.tab.rows[j].innerHTML + "</tr>";
      //tab_text=tab_text+"</tr>";
    }

    tab_text = tab_text + "</table>";
    tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
    tab_text = tab_text.replace(/<img[^>]*>/gi, ""); // remove if u want images in your table
    tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));

    return (sa);
  }


  skip: number = 0;
  limit: number = 10;
  firstcall: boolean = false;
  lastcall: boolean = true;


  tabelObj: any;
  callfunction(): void {
    this.Load = true;
    this.deviceArr = $('#select').multipleSelect('getSelects', 'value');
    this.tabelObj.draw();
  }
  dtOptions: any = {}
  testTable() {
    const that = this;

    this.Load = true;
    $(document).ready(function () {
      that.tabelObj = $('#deviceTable').DataTable({
        dom: 'lBftip',
        buttons: [
          'copy',
          'print',
          'excel'
        ],
        "processing": true,
        "searching": false,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: true,
        "scrollY": '55vh',
        "scrollX": true,
        "scrollCollapse": true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        ajax: (dataTablesParameters: any, callback) => {
          that.Load = true;
          dataTablesParameters.op = {};
          dataTablesParameters.select = [];
          dataTablesParameters.find = {};
          var currDay = new Date().getDay();
          var currMonth = new Date().getMonth();
          var currYear = new Date().getFullYear();
          var selectedDay = new Date(that.date1).getDay();
          var selectedMonth = new Date(that.date1).getMonth();
          var selectedYear = new Date(that.date1).getFullYear();

          if ((currDay == selectedDay) && (currMonth == selectedMonth) && (currYear == selectedYear)) {
            var devname = "Device_Name";
            var devid = "Device_ID";
            var today_odo = "today_odo";
            var today_running = "today_running";
            var today_stopped = "today_stopped";
            var today_trips = "today_trips";
            var maxSpeed = "maxSpeed";
            var Mileage = "Mileage";
            var start_location_lat = "today_start_location.lat";
            var start_location_long = "today_start_location.long";
            var end_location_lat = "last_location.lat";
            var end_location_long = "last_location.long";
            var start_odo_manual = "start_odo_manual";
            var end_odo_manual = "end_odo_manual";

          } else {

            var devid = "imei";
            var devname = "ID.Device_Name";
            var today_odo = "today_odo";
            var today_running = "today_running";
            var today_stopped = "today_stopped";
            var today_trips = "today_trips";
            var maxSpeed = "ID.maxSpeed";
            var Mileage = "Mileage";
            var start_location_lat = "start_location.lat";
            var start_location_long = "start_location.long";
            var end_location_lat = "end_location.lat";
            var end_location_long = "end_location.long";
            var start_odo_manual = "start_odo_manual";
            var end_odo_manual = "end_odo_manual";

          }

          dataTablesParameters.columns = [
            // {data: "_id" },
            { data: devname },
            { data: devid },
            { data: today_odo },
            { data: today_running },
            { data: Mileage },
            { data: today_stopped },
            { data: today_trips },
            { data: maxSpeed },
            { data: "t_idling" },
            { data: "t_noGps" },
            { data: "t_ofr" },
            { data: start_location_lat },
            { data: start_location_long },
            { data: end_location_lat },
            { data: end_location_long },
            { data: start_odo_manual },
            { data: end_odo_manual },
            { data: null, defaultContent: '' }
          ]

          var deviceID;
          dataTablesParameters.find.user_id = that.useridd;

          if (that.deviceArr.length != 0) {

            var dev_in = { '$in': that.deviceArr };
            dataTablesParameters.find.devId = dev_in;
          }

          // if ((that.dataSelect.length!=0)&&(that.dataSelect[0].did!='all')) {
          //     dataTablesParameters.find.devId = that.dataSelect[0].did;
          // }

          if (that.date1) {
            var fdate = new Date(that.date1).toISOString()
            // dataTablesParameters.find['created_on'] = dataTablesParameters.find['created_on'] ? dataTablesParameters.find['created_on'] : {};
            dataTablesParameters.find.date = fdate
          };
          if(that.date1 && that.deviceArr.length != 0){
          var suburl = "";
          suburl += "/devices/daily_report";
          that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {
            that.reportArr = [];
            that.reportArr = resp['data'];
            if (that.reportArr.length != 0) {
              var j = 0;
              var finalArr = [];
              for (var i = 0; i < that.reportArr.length; i++) {

                that.clocation_1(that.reportArr[i], function (err, succ) {
                  if (err) {
                    console.log(err);
                    j++;
                  } else {
                    finalArr.push(succ);
                    console.log(finalArr);
                    j++;
                    if (j === that.reportArr.length) {
                      callback({ data: finalArr });
                    }
                  }
                })

                that.Load = false;
              }
            } else {
              that.Load = false;
              callback({ data: [] });

            }

            // that.Load= false;         
            // callback(resp);
          }, err => {
            that.Load = false;

          });
        }else {
              that.Load = false;
              callback({ data: [] });

            }

        },
        "rowCallback": function(row: Node, data: any | Object, index: number){ 
          $('#manual_start', row).bind('click', () => {         
            var msE = document.getElementById("openingReading"); 
            var manualStartEntry = msE['value'] ; 
            console.log('manualStartEntry',manualStartEntry);
            var updateEntry = {
              start_odo : manualStartEntry , 
              id: data._id
            };
        
          
            that.contactService.updatedailyLog(updateEntry).subscribe(res=>{
              that.data_descip = "Value Saved" ;  

              launch_toast()
              function launch_toast() {
                // console.log(divid);
                 var x = document.getElementById("toast")
                 //console.log(x);
                 x.className = "show";
                 setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1500);
             }

             that.tabelObj.ajax.reload();

            },err=>{

            })
  
          }); 
          $('#manual_end', row).bind('click', () => {          
            var mEE = document.getElementById('closingReading');
            var manualEndEntry = mEE['value'];
            console.log('manualEndEntry',manualEndEntry);
            var updateEntry = {
              end_odo:manualEndEntry,
              id : data._id
            };
         
            that.contactService.updatedailyLog(updateEntry).subscribe(res=>{
              that.data_descip = "Value Saved" ;  
              launch_toast()
              function launch_toast() {
                // console.log(divid);
                 var x = document.getElementById("toast")
                 //console.log(x);
                 x.className = "show";
                 setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1500);
             }
             that.tabelObj.ajax.reload();

            },err=>{

            })
              
          }); 
           },
        "columns": [
          {
            "data": "Device_Name",
            "defaultContent": "_id",
            "render": function (data, type, row) {

              if (row.Device_Name) {
                return row.Device_Name
              }
              if (row.ID != null) {
                return row.ID.Device_Name;
              } else {
                return "";
              }

            }
          },
          {
            "data": "Device_ID",
            "defaultContent": "_id",
            render: function (data, type, row) {
              return row.Device_ID ? row.Device_ID : row.imei;
              // if(row.Device_ID){
              //   return row.Device_ID;
              //  }else{
              //   row.imei;
              //  }

            }
          },
          {
            "data": "Mileage",
            "defaultContent": "_id",
            render: function (data, type, row) {
              var mileage = ((data == undefined) || (data == NaN)) ? "NA" : (row.today_odo / parseFloat(data)).toFixed(2);
              return mileage;
            }
          },
          {
            "data": "today_running",
            render: function (data, type, row) {
              var ign_on: any;

              if (data != undefined) {
                ign_on = that.millisecondConversion(parseInt(data));
              } else {
                ign_on = '0:0'
              }



              return ign_on;
            }
          },
          {
            "data": "today_stopped",
            render: function (data, type, row) {


              if ((data != undefined) && (data != null) && (data != NaN)) {
                var stopped = that.millisecondConversion(data);
              } else {
                var stopped = "0:0";
              }
              return stopped;
            }
          },
          {
            "data": "t_idling",
            render: function (data, type, row) {

              if ((data != undefined) && (data != null) && (data != NaN)) {
                var idleTime = that.millisecondConversion(data);
              } else {
                var idleTime = "0:0";
              }
              return idleTime;
            }
          },
          {
            "data": "t_ofr",
            render: function (data, type, row) {

              if ((data != undefined) && (data != null) && (data != NaN)) {
                var ofr = that.millisecondConversion(data);
              } else {
                var ofr = "0:0";
              }
              return ofr;
            }

          },
          {
            "data": "t_noGps",
            render: function (data, type, row) {

              if ((data != undefined) && (data != null) && (data != NaN)) {
                if ((data < 60000) && (data == undefined)) {
                  var seconds = Math.floor((data / 1000) % 60);
                  seconds = (seconds < 10) ? 0 + seconds : seconds;

                  var n_gps = "0:0:" + seconds;
                } else {
                  var n_gps_1 = that.millisecondConversion(data);
                  var n_gps = n_gps_1 + ':0'
                }
              } else {
                var n_gps = "0:0:0";
              }
              return n_gps;
            }

          },
          {
            "data": "today_trips",
            render: function (data, type, row) {
              return data;
            }
          },
          {
            "data": "maxSpeed",
            "defaultContent": "_id",
            render: function (data, type, row) {
              // return data;
              if (row.maxSpeed) {
                return row.maxSpeed
              }
              if (row.ID != null) {
                return row.ID.maxSpeed;
              } else {
                return 0;
              }
            }
          },
          {
            "data": "startAddress",
            "defaultContent": "_id",
            render: function (data, type, row) {

              return data ? data : "";

            }
          },
          {
            "data": "endAddress",
            "defaultContent": "_id",
            render: function (data, type, row) {

              return data ? data : "";
            }
          },
          {
            "data": "start_odo_manual",
            "defaultContent": "_id",
            render: function (data, type, row) {
     
              var inputField = '<div style="display:flex">'+
              '<input type="number" style="width: 60px; margin-right: 6px;" placeholder ="Opening Reading (Logbook)" id="openingReading">'+
              '<i id="manual_start" style="font-size:20px;color:green;cursor:pointer" title="Save Start ODO" class="fas fa-save"></i>'+
              '</div>'; 
              return data ? data : inputField;
              
            }
          },
          {
            "data": "end_odo_manual",
            "defaultContent": "_id",
            render: function (data, type, row) {
              var inputField_1 = '<div style="display:flex">'+
              '<input type="number" style="width: 60px; margin-right: 6px;" placeholder="Closing Reading (Logbook)" id="closingReading">'+
              '<i id="manual_end" style="font-size:20px;color:green;cursor:pointer" title="Save End ODO" class="fas fa-save"></i>'+
              '</div>'; 

              return data ? data : inputField_1;
            }
          },
          {
            "data": "_id",
            "defaultContent": "",
            render: function (data, type, row) {
              var a =  row.start_odo_manual ; 
              var b= row.end_odo_manual ; 
              var c : any;
              if((b != undefined)&&(a != undefined)){
                c = parseFloat(b) - parseFloat(a) ;
              }else{
               c = null ; 
              }

              return c;
            }
          },
          
          {
            "data": "today_odo",
            render: function (data, type, row) {
              return data.toFixed(2);
            }
          },
          {
            "data": "_id",
            "defaultContent": "",
            render: function (data, type, row) {
              var a =  row.start_odo_manual ; 
              var b= row.end_odo_manual ; 
              var d =  row.today_odo.toFixed(2) ; 
              var c : any;
              var e : any ; 
              if((b != undefined)&&(a != undefined)){
                c = parseFloat(b) - parseFloat(a) ;
                e = d - c ; 
              }else{
               c = null ; 
               e = null ; 
              }
              return e;
            }
          },
          {
            "data": "_id",
            "defaultContent": "",
            render: function (data, type, row) {

              var a =  row.start_odo_manual ; 
              var b= row.end_odo_manual ; 
              var d =  row.today_odo.toFixed(2) ; 
              var c : any;
              var e : any ;
              var f : any;  
              if((b != undefined)&&(a != undefined)){
                c = parseFloat(b) - parseFloat(a) ;
                e = d - c ; 
                f = (e/d)*100 ; 

              }else{
               c = null ; 
               e = null ; 
               f = null; 
              }
              return f;
            }
          }
        ],
        "columnDefs": [
          { className: "dt-body-left", "targets": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] },
          {
            "targets": '_all',
            "createdCell": function (td, cellData, rowData, row, col) {
              $(td).css('padding', '18px')
            }
          },
          { "width": "50px", "targets": [10,11,14,15,16]}  
        ]
      });

    });

  }


  millisecondConversion(duration) {
   
    // var minutes = Math.floor((duration / (1000 * 60)) % 60);
    // var hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

    // hours = (hours < 10) ? 0 + hours : hours;
    // minutes = (minutes < 10) ? 0 + minutes : minutes;
  
    // return hours + ":" + minutes;

    
var x = duration;
var d = moment.duration(x, 'milliseconds');
var hours = Math.floor(d.asHours());
var mins = Math.floor(d.asMinutes()) - hours * 60;
var mainMIn = (hours>=24)?0:mins;
return  hours + ":" + mainMIn;


  }


  loadropdown() {
    let that = this;
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
    document.getElementsByTagName("head")[0].appendChild(script);

    setTimeout(() => {
      that.showSelectdevice = true;
      $('#select').multipleSelect({
        width: 200,
        placeholder: 'Select device.....',
        filter: true,
      })
      // $('#select').show();

    }, 100);
  }


  getReport(event) {
    if (event == 'getExcel') {
      this.exportExcel();
    } else {
      var deviceId: any;
      var tpdata = event;
      var that = this;
      var fd = new Date(tpdata.fromDate);
      var td = new Date(tpdata.toDate);



      var x = new Date(tpdata.toDate).setHours(23, 59, 59);

      this.date1 = new Date(x).toISOString();
      var d = new Date(this.date1);
      let a = d.setHours(0, 0, 0, 0)
      this.from = new Date(a).toISOString();



      if (event.deviceArr.length == 0) {
        deviceId = [];
      } else {
        deviceId = event.deviceArr;
      }
      this.deviceArr = deviceId;



      // this.tabelObj.clear();
      // var aa = [];
      // this.tabelObj.rows.add(aa); 
      this.tabelObj.ajax.reload();
    }

  }

  clocation_1(latlngObj, cb) {
    var outerThis = this;
    var la = '';

    let latLng = {
      lat: "0",
      long: "0"
    };
    if (latlngObj.start_location) {
      latLng = {
        lat: latlngObj.start_location.lat ? latlngObj.start_location.lat : 0,
        long: latlngObj.start_location.long ? latlngObj.start_location.long : 0
      }
    }
    if (latlngObj.today_start_location) {
      latLng = {
        lat: latlngObj.today_start_location.lat ? latlngObj.today_start_location.lat : 0,
        long: latlngObj.today_start_location.long ? latlngObj.today_start_location.long : 0
      }
    }

    // if () {
    //   latLng = {
    //     lat: 0,
    //     long: 0
    //   }
    // }

    outerThis.contactService.getAddressByApi(latLng).subscribe(res => {
      if (res.message == "Address not found in databse") {
        latlngObj['startAddress'] = "NA";
        // cb(null,latlngObj);
        var latLng_1 = {
          lat: "0",
          long: "0"
        };
        if (latlngObj.last_location) {
          latLng_1 = {
            lat: latlngObj.last_location.lat ? latlngObj.last_location.lat : 0,
            long: latlngObj.last_location.long ? latlngObj.last_location.long : 0
          }

        }
        if (latlngObj.end_location) {
          latLng_1 = {
            lat: latlngObj.end_location.lat ? latlngObj.end_location.lat : 0,
            long: latlngObj.end_location.long ? latlngObj.end_location.long : 0
          }
        }


        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            latlngObj['endAddress'] = "NA";
            cb(null, latlngObj);


          } else {
            latlngObj['endAddress'] = res.address;
            cb(null, latlngObj);
          }

        })

      } else {
        latlngObj['startAddress'] = res.address;
        var latLng_1 = {
          lat: "0",
          long: "0"
        };
        if (latlngObj.last_location) {
          latLng_1 = {
            lat: latlngObj.last_location.lat ? latlngObj.last_location.lat : 0,
            long: latlngObj.last_location.long ? latlngObj.last_location.long : 0
          }

        }
        if (latlngObj.end_location) {
          latLng_1 = {
            lat: latlngObj.end_location.lat ? latlngObj.end_location.lat : 0,
            long: latlngObj.end_location.long ? latlngObj.end_location.long : 0
          }
        }


        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            latlngObj['endAddress'] = "NA";
            cb(null, latlngObj);


          } else {
            latlngObj['endAddress'] = res.address;
            cb(null, latlngObj);
          }

        })

        // cb(null,latlngObj);
      }
    })

  }





}
