import { Component, OnInit } from '@angular/core';

declare var $: any, DataTable: any, google: any;

import * as moment from 'moment'
import { MdDialog } from '@angular/material';
import { FlashMessagesService } from 'angular2-flash-messages';
import { ContactService } from '../../../contact.service';
import { FuelObjectcomponentComponent } from '../../../fuel-objectcomponent/fuel-objectcomponent.component';
declare var $: any;
@Component({
  selector: 'app-device-fuel-report',
  templateUrl: './device-fuel-report.component.html',
  styleUrls: ['./device-fuel-report.component.scss']
})
export class DeviceFuelReportComponent implements OnInit {
  option: any;
  Fromdate = new Date();
  todate = new Date();
  emailid: any;
  useridd: any;
  identifier: any = 'fuel_consumption_report';
  tabelObj: any ;
  errorStatus: string;
  filterRtype: any;
  // reportType = ['Time','Daily','Trip']
  serviceResponse: boolean;
  devicesss: any;
  finall: any;
  fuelDataArr: any[];
  eventT: any;
  rowcolor: string;
  xlbutton: boolean = false;
  Load: boolean;
  address_show: string;
  lattitude: any;
  longitude: any;
  lattitude1: any;
  longitude1: any;
  addressLink: any;
  addressLink1: string;
  tempVehName: any;
  constructor(public contactService: ContactService, public dialog: MdDialog, private _flashMessagesService: FlashMessagesService) {

    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
   
  }

  ngOnInit() {
    this.Fromdate.setHours(0, 0, 0);
    this.testTable();
    // this.getAllDevice();
  }

  callfunction(): void {
    this.tabelObj.draw();
  }


  deviceObj = [];
  // getAllDevice() {
  //   this.deviceObj = [];
  //   this.contactService.getDevice(this.emailid, this.useridd).subscribe(
  //     data => {
  //       this.devicesss = data
  //       this.finall = (this.devicesss.devices);
  //       for (let i = 0; i < this.devicesss.devices.length; i++) {

  //         if (this.devicesss.devices[i].type_of_device == "Tracker") {

  //           let a = {
  //             value: this.devicesss.devices[i].Device_Name,
  //             viewValue: this.devicesss.devices[i].Device_Name,
  //             did: this.devicesss.devices[i].Device_ID,
  //             id: this.devicesss.devices[i]._id,
  //             user: this.devicesss.devices[i].user,
  //             email: this.devicesss.devices[i].Email_ID,
  //             deviceType: this.devicesss.devices[i].type_of_device
  //           }
  //           this.deviceObj.push(a);
  //         }

  //       }
  //       // console.log(this.deviceObj);


  //     });
  // }


  deviceSelect: any = [];
  deviceName: any;
  // filterDevices(dlr) {
  //     // console.log("deviceData=>", dlr);
  //     if (dlr) {
  //         // console.log(dlr);
  //         const filterdealerValue: any = dlr;
  //         this.deviceSelect = [];
  //         this.deviceSelect = this.deviceObj.filter(function(pp) {        
  //             // console.log(pp);
  //             var t = pp.viewValue.toLocaleLowerCase().indexOf(filterdealerValue.toLocaleLowerCase());
  //             return t > -1;
  //         });
  //         return this.deviceSelect;
  //     }

  // }


  testTable() {
    const that = this;
   
    $(document).ready(function () {
      that.tabelObj = $('#deviceTable').DataTable({
        // dom: 'Bfrtip',
        // buttons: [
        //     'copy', 'csv', 'excel', 'pdf', 'print'
        // ]  ,
        "processing": true,
        "searching": true,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: false,
        "scrollX": true,
        "scrollY": '63vh',
        "scrollCollapse": true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        ajax: (dataTablesParameters, callback) => {
          that.fuelDataArr = [];
          if ((that.filterRtype == 'Daily') || (that.filterRtype == 'Trip')) {
            if (that.deviceArr.length == 0) {
              that._flashMessagesService.show("Please Select Device ... ", { cssClass: 'alert-warning', timeout: 3000 });
              return;
            }
          }

          if (that.Fromdate == undefined) {
            that._flashMessagesService.show("Please Select Fromdate  ", { cssClass: 'alert-warning', timeout: 3000 });
            return;
          }
          if (that.todate == undefined) {
            that._flashMessagesService.show("Please Select Todate  ", { cssClass: 'alert-warning', timeout: 3000 });
            return;
          }

          if (that.deviceArr.length<0 ||that.deviceArr.length==0) {
            console.log("INDD");
            
            that._flashMessagesService.show("Please Select Device  ", { cssClass: 'alert-warning', timeout: 3000 });
            return;
          }

          var payloadObj = {
            from: that.Fromdate.toISOString(),
            to: that.todate.toISOString(),
            user: that.useridd
          }

          if (that.filterRtype == 'Daily') {
            payloadObj['daywise'] = true;
            payloadObj['imei'] = that.deviceArr[0].did;
            payloadObj['vehicle'] = that.deviceArr[0].id;
          }
          if (that.filterRtype == 'Trip') {
            payloadObj['trip'] = true;
            payloadObj['imei'] = that.deviceArr[0].did;
            payloadObj['vehicle'] = that.deviceArr[0].id;
          }

          if (that.filterRtype == 'Time') {
            if (that.deviceArr.length != 0) {
              payloadObj['imei'] = that.deviceArr[0].did;
              payloadObj['vehicle'] = that.deviceArr[0].id;
              delete payloadObj.user;
            }
          }
          console.log(that.deviceArr,payloadObj);

          that.Load = true;

          that.contactService.devicefuelreport(payloadObj)
            .subscribe(res => {
              that.fuelDataArr = [];
              that.Load = false;         
             that.fuelDataArr = res;
              if ((that.fuelDataArr.length != 0) && (that.deviceArr.length != 0)) {
                for (var i = 0; i < that.fuelDataArr.length; i++) {
                  that.fuelDataArr[i]['tempVehName'] = that.deviceArr[0].viewValue;
                }
              }
              // console.log('that.fuelDataArr',that.fuelDataArr);
              callback({ data: that.fuelDataArr });

            }, err => {
              that.Load = false;
              that._flashMessagesService.show("Internal Server error , Please try after sometime !!!", { cssClass: 'alert-warning', timeout: 2000 });
              // console.log(err);
            })
        },
        "rowCallback": function(row: Node, data:any | Object, index: number){  
          $('#in', row).bind('click', () => {      
                 
            data.event = 'in';   
            console.log('data',data.in_event_count);
            if(data.in_event_count != 0){
              let dialogRef_1 = that.dialog.open(FuelObjectcomponentComponent, { 
                width: '950px',
                data: data
              });     
            }
                
          });

          $('#out', row).bind('click', () => {  
            data.event = 'out';   
         
            if(data.out_event_count != 0){
              let dialogRef_1 = that.dialog.open(FuelObjectcomponentComponent, {
                width: '950px',
                data: data
              });   
            }         
           
          }); 
        
        },  

        "columns": [
          {
            "data": "vehicle_name",
            "defaultContent": "_id",
            "render": function (data, type, row) {
              // console.log(row);
              // var vname = ((data != undefined) && (data) && (data.trim().length != 0)) ? data : row.tempVehName;
              var vname = (data!=undefined)?data:row.tempVehName ; 
                return vname;
            }
          },
          {
            "data": "start_time",
            render: function (data, type, row) {
              var st = new Date(data);
              return data ? (moment(st).format('llll')) : "";

            }
          },
          {
            "data": "end_time",
            render: function (data, type, row) {
              var et = new Date(data);
              return data ? (moment(et).format('llll')) : "";
            }
          },
          {
            "data": "fuel_consumed",
            render: function (data, type, row) {
              var fc = data ? data.toFixed(2) : "0";
              return fc;
            }
          },
          {
            "data": "distance",
            render: function (data, type, row) {
              var dis = (data != "NaN") ? data.toFixed(2) : "0"
              return dis;
            }
          },
          {
            "data": "in_event_count",
            render: function (data, type, row) {
              let in_event_count =  "<i id='in' style='cursor:pointer'>"+data+"</i>" ; 
              return in_event_count;
            }
          },
          {
            "data": "out_event_count",
            render: function (data, type, row) {
              // <i id="deviceSetting" style="font-size:20px" title="Share device" class="fas fa-cog"></i>
              let out_event_element = "<i id='out' style='cursor:pointer'>"+data+"</i>" ; 
              return out_event_element;
             
            }
          },
          {
            "data": "start_location",
            render: function (data, type, row) {
              let lat = (data != undefined)?data.lat: null;
              let long = (data != undefined)?data.lng : null;
              var addressLink = '<a href="https://maps.google.com/?q='+ lat +','+long +' "  target="_blank" title="Click to get vehicle start location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>';               
                return addressLink;                
            }
          },
          {
            "data": "end_location",
            render: function (data, type, row) {
              let lat = (data != undefined)?data.lat: null;
              let long = (data != undefined)?data.long : null;
              var addressLink = '<a href="https://maps.google.com/?q='+ lat +','+long +' "  target="_blank" title="Click to get vehicle last location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>';                
                return addressLink;             
            }
          },

        ],
        "columnDefs": [
          { className: "dt-body-left", "targets": [0, 1, 2, 3,4,5,6,7,8] },
          {
            "targets": '_all',
            "createdCell": function (td, cellData, rowData, row, col) {
              $(td).css('padding', '18px')
            }
          },
       
          { "width": "13%", "targets": 1 },
          { "width": "13%", "targets": 2 },
      

        ]
      });

    });

  }


  // devicefuelreport(){ 
  //     console.log("this.filterDevices=>",this.filterRtype);
  //     // pe = ['time','daily','trip']
  //     if((this.filterRtype == 'Daily')||(this.filterRtype == 'Trip')){
  //       if(this.deviceSele ct.length == 0){
  //         this._flashMessagesService.show("Please Select Device ... ", { cssClass: 'alert-warning', timeout: 3000 });
  //         return;
  //       }

  //     }

  //     if(this.Fromdate == undefined){
  //       this._flashMessagesService.show("Please Select Fromdate  ", { cssClass: 'alert-warning', timeout: 3000 });
  //       return;
  //     }
  //     if(this.todate == undefined){
  //       this._flashMessagesService.show("Please Select Todate  ", { cssClass: 'alert-warning', timeout: 3000 });
  //       return;
  //     }

  //     var payloadObj = {
  //       from : this.Fromdate.toISOString(),
  //       to : this.todate.toISOString(),
  //       user : this.useridd    
  //     }

  //     if(this.filterRtype == 'Daily'){
  //       payloadObj['daywise'] = true;
  //       payloadObj['imei'] = this.deviceSelect[0].did;
  //       payloadObj['vehicle'] = this.deviceSelect[0].id;
  //     }
  //     if(this.filterRtype == 'Trip'){
  //       payloadObj['trip'] = true;
  //       payloadObj['imei'] = this.deviceSelect[0].did;
  //       payloadObj['vehicle'] = this.deviceSelect[0].id;
  //     }

  //     if(this.filterRtype == 'Time'){
  //       if(this.deviceSelect.length != 0){
  //         payloadObj['imei'] = this.deviceSelect[0].did;
  //         payloadObj['vehicle'] = this.deviceSelect[0].id;
  //         delete payloadObj.user;
  //       }
  //     }
  //     console.log(payloadObj);

  //     this.Load = true;
  //     // this.todate.toISOString(),this.Fromdate.toISOString(),this.deviceSelect[0].did

  //     this.contactService.devicefuelreport(payloadObj)
  //         .subscribe(res=>{
  //          this.Load =false;
  //          this.xlbutton =false;
  //          console.log("fuelconsumptionReport=>",res);
  //          this.fuelDataArr = res;
  //          if((this.fuelDataArr.length != 0)&&(this.deviceSelect.length != 0) ){
  //            this.tempVehName = this.deviceSelect[0].viewValue ; 
  //          }  
  //         },err=>{
  //           this.Load = false;   
  //             this._flashMessagesService.show("Internal Server error , Please try after sometime !!!", { cssClass: 'alert-warning', timeout: 2000 });
  //             // console.log(err);
  //         })
  // }

  secondsToHms(d) {
    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    var hDisplay = h > 0 ? h + (h == 1 ? " hr, " : " hrs, ") : "";
    var mDisplay = m > 0 ? m + (m == 1 ? " min, " : " mins, ") : "";
    var sDisplay = s > 0 ? s + (s == 1 ? " sec" : " sec") : "";
    return hDisplay + mDisplay + sDisplay;
  }

  colorChangefunc(fuelval) {
    //   console.log(fuelval)
  }

  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>";
      // console.log('tab_text',JSON.parse(tab_text));
      //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);
  }


  locationAddress: any;
  getAddress(fuelval, val) {
    var outerThis = this;
    console.log(fuelval);
    if (fuelval == undefined) {
      this.lattitude = null;
      this.longitude = null;
      this.lattitude1 = null;
      this.longitude1 = null;
    } else {
      if (val == 'start') {
        this.lattitude = fuelval.start_location.lat;
        this.longitude = fuelval.start_location.lng;
        var geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(this.lattitude, this.longitude);
      }
      else if (val == 'end') {
        this.lattitude1 = fuelval.end_location.lat;
        this.longitude1 = fuelval.end_location.lng;
        var geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(this.lattitude1, this.longitude1);
      } else {
        this.lattitude = null;
        this.longitude = null;
        this.lattitude1 = null;
        this.longitude1 = null;
      }


    }


    this.addressLink = 'https://maps.google.com/?q=' + this.lattitude + ',' + this.longitude;
    this.addressLink1 = 'https://maps.google.com/?q=' + this.lattitude1 + ',' + this.longitude1

  }

  // showinoutReport(fuelObj, ev) {
  //   if ((fuelObj.in_event_count == 0) && (ev == 'in')) {
  //     return
  //   }
  //   if ((fuelObj.out_event_count == 0) && (ev == 'out')) {
  //     return
  //   }
  //   fuelObj.event = ev;
  //   let dialogRef_1 = this.dialog.open(FuelObjectcomponentComponent, {
  //     // height:'500px',
  //     width: '950px',
  //     data: fuelObj
  //   });
  // }
  deviceArr: any = []
  getReport(event) {
    this.deviceArr = [];
    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);

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

      this.Fromdate = fd;
      this.todate = td;
      this.filterRtype = tpdata.filter_type;


      this.tabelObj.ajax.reload();    

    }

  }


}
