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

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.scss']
})
export class DetailComponent implements OnInit {
fs : any;

  ls : any;
  emailid : any;
  or : any;
  useridd :any;
  time :any;
  device_data:any;
  devicess:any;
  final:any;
  custtype:any;
  cust:boolean=false;
  Load : Boolean = false;
  date : any;
  devicesss:any;
  mb:any;
  logoutbut:boolean;
  dealer:boolean;
  text:any;
  option:any; 
  finall:any;
  Fromdate:any;
  todate:any;
  options=[];
  logo:any;
  before:any;
  date1:any;
  daily_report_data:any;
  superAdmin:Boolean = false;
  uId:any;
d_name:any;
d_report:any;
total_dist:any;
total_km:any;
start_add_lat:any;
start_add_long:any;
end_add_lat:any;
end_add_long:any;
device_summary=[];
address_show:any;
fromDate:any;
toDate:any;
  firstcall:boolean=true;
  lastcall:boolean=true;
  skip:number=0;
end_add_show:any;
identifier:any = 'distance_report';
mainData:any
tableData:any
  deviceArr: any[];
  reportArr: any[];
  constructor(public dialogRef: MdDialogRef<DetailComponent>,private contactService: ContactService,
    @Inject(MD_DIALOG_DATA) public data: any) {
       console.log('data=>',data,data.from_date,data.to_date);
       this.mainData=data
       console.log(this.mainData);
       
       this.fromDate=data.from_date;
       this.toDate=data.to_date
    }

  ngOnInit() {
          this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
//  setTimeout(function(){ alert("Hello"); }, 3000);
    this.testTable2(this.mainData)
  }
  tabelObj: any ;
testTable() {
  const that = this;
  console.log("inside function");

 that.Load = true;
            var from_date =this.mainData.from_date;
            var to_date = that.mainData.to_date;
            var user = that.useridd;
            var temp = {
            from_date : from_date,
            to_date : to_date,
            user : user,
            device:this.mainData._id
            }
            console.log('temp',temp);
            
        // '&user=' + "5fdb427d38956a5d79ffb09b" + '&skip='+that.skip + '&limit='+ limit+'&device='+"5fdb54cb8939f65e6cc02527";
            var suburl = "";
            var limit = 26;
            suburl += "/summary/distanceNew?from=" + temp.from_date +'&to=' + temp.to_date + 
            '&user=' + user + '&skip='+that.skip + '&limit='+ limit+'&device='+temp.device;
         that.contactService.getDetails(suburl).subscribe(resp => {   
                that.Load = false;  
                console.log("TTTTT",resp);
                this.tableData=resp;
                
         }, err => {   
              that.Load= false;    
              // callback({ data: [] });
              console.log("error",err) ;     
            });


}

testTable2(data1){
  const that = this;
  console.log("inside function");
  $(document).ready(function() {
     that.tabelObj = $('#detailsTable').DataTable({
        // dom: 'Bfrtip',
        // buttons: [
        //   'copy',
        //   'print',
        //   'excel'
        // ],       
          "processing": false,
          "searching": true, 
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: false,
          responsive: true,
          "scrollY":'60vh',  
          "scrollCollapse": true, 
          
          // "deferLoading": 25 ,  
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            "rowCallback": function(row: Node, data: any | Object, index: number){

            $('#edit', row).bind('click', () => {   
              var internalThat  = that;
              console.log('rowrowrowrow=>',row);
              console.log('datadatadatadata',data);
          
  
          
              // dialogRef.afterClosed().subscribe(result => {
              //   console.log("result",result);
              //   that.ngOnInit();
             
              //     if(result=="done"){
              //       console.log("resultdone",result)
              //       that.tost1("update");
              //       window.localStorage['DataUpdate'] = 'True';
              //       that.sidebar.sidebarData();       
              //     }
              // });              
            }); 
          
            },
          ajax: (mainData,callback) => {
           
              var deviceID;
              
              that.Load = true;
              console.log("ddddddd",data1);
              var date=data1.from_date
            var user = that.useridd;
            var temp = {
            from_date :date,
            to_date :data1.to_date,
            user : user,
            device:data1._id
            }
            console.log('temp',temp);
            
        
            var suburl = "";
            var limit = 26;
            suburl += "/summary/distanceNew?from=" + temp.from_date +'&to=' + temp.to_date + 
            '&user=' + temp.user + '&skip='+that.skip + '&limit='+ limit+'&device='+temp.device;
           
            that.contactService.getDetails(suburl).subscribe(resp => {   
                that.Load = false;  
                that.reportArr = [];
                that.reportArr= resp ; 
                //  if (that.reportArr.length != 0) {
                //   resp.forEach(element => {
                //     console.log(element);
                //     element.date=that.convertDate(element.date)
                    
                    
                //   });
                //  }
            
                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) {
                          that.Load = false;
                          callback({ data: finalArr });
                        }
                      }
                    })
    
                   
                  }
                } else {
                  that.Load = false;
                  that.firstcall=true;
                  that.lastcall=(that.skip>0)?false:true;
                  callback({ data: [] });
    
                }
            }, err => {   
              that.Load= false;    
              callback({ data: [] });
              console.log("error",err) ;     
            });
        },  
      
          "columns": [
              {
                  "data": "device",
                  "render": function(data, type, row) {                   
                    return data?data.Device_Name : '';                  
                  }
              },
               {
              "data": "date",
              render: function(data, type, row) { 
               
                // convertDate(element.date)
           
                return data ? (moment(data).format('DD-MM-YYYY')):0;
              }
          } ,
              {
                  "data": "startAddress",
                  "defaultContent": "",
                  render: function(data, type, row) {            
                  
                    var aiden = typeof(data) ;
                    if(aiden == 'object'){
                      var addressLink = '<a href="https://maps.google.com/?q='+ data.latlng.lat +','+data.latlng.long +' "  target="_blank" title="Click to get vehicle start location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>'; 
                      return addressLink;
                    }else{
                      return data?data : '--';   
                    }
                     
                    
                  }
              },
              {
                  "data": "endAddress",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    var biden = typeof data ; 
                    if(biden === 'object'){
                      var addressLink = '<a href="https://maps.google.com/?q='+ data.latlng.lat +','+data.latlng.long +' "  target="_blank" title="Click to get vehicle last location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>'; 
                      return addressLink; 
                    }else{
                      return data?data : '--';   
                    }
                 
                  }
              },        
            {
              "data": "distance",
              render: function(data, type, row) { 
           
                return data?data.toFixed(2):0;
              }
          } ,
    //      {
    //       "data":null,
    //       "defaultContent": "",
    //       "render":function(data,type,row){   
    //         return '<button class="btn btn=info btn-sm"><i id="edit" title="Edit Vehicle" style="font-size:20px;color: green" class="fas fa-info-circle"></i></button>'    
    //   }
    // }
// <i class="fas fa-info-circle"></i>
          ],  
          "columnDefs": [
            { className: "dt-body-left", "targets": [ 0,1,2,3,4] },  
          //   {
          //     "targets": '_all',
          //     "createdCell": function (td, cellData, rowData, row, col) {
          //         $(td).css('padding', '18px')
          //     }
          // } ,
          { "width": "10px", "targets": 0 },
          { "width": "40px", "targets": 1 },
          { "width": "100px", "targets": 2 },
          { "width": "70px", "targets": 3 },  
                    { "width": "10px", "targets": 4 },   
 
    //       {
    //     targets: -1, //-1 es la ultima columna y 0 la primera
    //     data: null,
    //     defaultContent: '<div class="btn-group"> <button (click)="show()">view</button></div>'
    // },
          ] 
      });

  });

}

  convertDate(inputFormat) {
          function pad(s) { return (s < 10) ? '0' + s : s; }
            var d = new Date(inputFormat)
           return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')
              }


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

    let latLng = {
      lat: "0",
      long: "0"
    };
  
      latLng = {
        lat: latlngObj.startLat ? latlngObj.startLat : 0,
        long: latlngObj.startLng ? latlngObj.startLng : 0
      }
    
  
    // if () {
    //   latLng = {
    //     lat: 0,
    //     long: 0
    //   }
    // }

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

        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            var bdata = {
              iden : 'noaddress',
              latlng : latLng_1
            }
        
            latlngObj['endAddress'] = bdata;
            cb(null, latlngObj);


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

        })

      } else {
        latlngObj['startAddress'] = res.address;
        var latLng_1 = {
          lat: "0",
          long: "0"
        };
    
          latLng_1 = {
            lat: latlngObj.endLat ? latlngObj.endLat : 0,
            long: latlngObj.endLng ? latlngObj.endLng : 0
          }
        
 


        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            var cdata = {
              iden : 'noaddress',
              latlng : latLng_1
            }
        
            latlngObj['endAddress'] = cdata;
            cb(null, latlngObj);


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

        })

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

  }

data_descip:any;
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);
    if(event.deviceArr.length==0){
      deviceId=[];
    }else{
      deviceId= event.deviceArr;
    }
    this.deviceArr = deviceId; 
    console.log('this.deviceArr',this.deviceArr);
    this.Fromdate = fd.toISOString();
    this.todate = td.toISOString();
 
      var diff = moment(this.todate).diff(this.Fromdate, 'days')
      console.log('difference :' + diff)
      if(diff>=31){
          this.data_descip = 'Report is unavailable for more than a month';
          launch_toast();

      }else{
        this.skip = 0;
        this.firstcall=false;
        this.lastcall= true;
        this.tabelObj.ajax.reload();     
      }

    
    
  }
  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", ""); }, 4500);
  }
    


}

tab:any;
  exportExcel()
	{
   console.log("Export");
   

	    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
	    var textRange; var j=0;
      var table = $('#detailsTable').clone();
    
      table[0].querySelector("thead").remove();
      table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];
    console.log(this.tab);
    
  
	    for(j = 0 ; j < this.tab.rows.length ; j++) 
	    {     
	        tab_text=tab_text+this.tab.rows[j].innerHTML+"</tr>";
	     
	    }

	    tab_text=tab_text+"</table>";
	 
	    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); 

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

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

	    return (sa);
  }

next() {
    // this.deviceData =[];
    this.lastcall=false;
    this.skip += 1; 
    // this.sidebarData();
    // this.ngOnInit();
    this.tabelObj.ajax.reload();     
  }
  pre() {
    // this.deviceData=[]
    // console.log(this.skip)
    if(this.skip>0){
      this.skip -= 1;   
      this.lastcall=false;
      // this.sidebarData();
      // this.ngOnInit();
      this.tabelObj.ajax.reload();     
    }else{
      this.lastcall=true;
      this.firstcall=false;
    }
   
  }

}
