import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../contact.service';
import { Http, Headers, RequestOptions, ResponseContentType } from '@angular/http';
import { saveAs } from 'file-saver';
import { environment } from '../../../environments/environment';
import { MdSnackBar } from '@angular/material';
declare var $: any;
declare var google: any;
import * as moment from 'moment';





const now = new Date();
@Component({
  selector: 'app-day-wise-report',
  templateUrl: './day-wise-report.component.html',
  styleUrls: ['./day-wise-report.component.scss']
})
export class DayWiseReportComponent implements OnInit {
  dateStr: any;
  Fromdate = new Date();
  todate = new Date();
  useridd: any;
  fDate: any;
  tDate: any;
  dev_url = environment.hostUrl;
  // dateString=['Today Report','Yesterday Report','Weekly Report','Monthly Report'];
  fromDate: any;
  toDate: any;
  Load: boolean;
  tabelObj: any;
  custtype: any;
  superAdmin: any;
  data_descip: string;
  reportArr :any= [];
  constructor(private contactService: ContactService, private http: Http, public snackBar: MdSnackBar, ) {

    // 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);

  }

  ngOnInit() {

    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    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.tDate = new Date();
    var fd = new Date();
    fd.setHours(0, 0, 0, 0);
    this.fDate = fd;
    // this.getDevices();
    this.testTable()

  }

  deviceArr = [];
  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 + "</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);
  }
  emailid: any;
  devicesss: any;
  options: any;
  finall: any;

  //   getDevices(){
  //     console.log("Inside getDevice function");
  //     this.contactService.getDevice(this.emailid,this.useridd).subscribe(

  //       data => {
  //         this.devicesss = data;
  //         console.log('this.devicesss',this.devicesss);  
  //         this.finall = (this.devicesss.devices);
  //         this.options = [];

  //         for(let i=0;i<this.devicesss.devices.length;i++){
  //           console.log('this.devicesss.devices',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,      
  //             }  

  //               a['selectedValue'] = this.devicesss.devices[i].Device_ID ; 


  //             // }
  //             this.options.push(a);
  //           // }

  //           if(i === (this.devicesss.devices.length -1)){
  //             setTimeout(() => {
  //               $('#dbselect').multipleSelect({
  //                 width: 200,
  //                 placeholder: 'Select Vehicle.....',
  //                 filter: true,
  //               })
  //             }, 100);

  //           }
  //         }
  //   })

  // }



  testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function () {
      that.tabelObj = $('#deviceTable').DataTable({
        // dom: 'Bfrtip',
        // buttons: [ 'copy', 'csv', 'ex  cel', 'pdf', 'print' ],
        "autoWidth": true,
        'deferRender':true,
        "processing": true,
        "searching": true,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: false,
        "scrollX": true,
        "scrollY": '65vh',
        "scrollCollapse": true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        ajax: (dataTablesParameters, callback) => {
          console.log('temptemptemptemptemp', dataTablesParameters);
          var deviceID;
          that.Load = true;


          var from_date = that.Fromdate;
          var to_date = that.todate;
          var user = that.useridd;
          var temp = {
            from_date: from_date,
            to_date: to_date,
            user: user
          }
          var suburl = "";
          // https://www.oneqlik.in/summary/getDayWiseReport?user=5e37c4a218ff144091101d3e&to=2020-02-27T18:29:59.115Z&from=2020-02-26T18:30:00.115Z&device=865205038055231   
          suburl += "/summary/getDayWiseReport?from=" + temp.from_date.toISOString() + '&to=' + temp.to_date.toISOString() + '&user=' + temp.user;
          if (that.deviceArr.length != 0) {
            suburl += '&device=' + that.deviceArr;
          }else{
            that.Load = false
            callback({ data: [] });
      
          }

          if ((temp.from_date != undefined) && (temp.to_date != undefined) && that.deviceArr.length != 0) {
            //  console.log('resp=>',temp.from_date,temp.to_date); 
            that.contactService.get(suburl).subscribe(resp => {
              // console.log(ignReport.length);  
               // that.Load = false;
              that.reportArr = [];
              that.reportArr= resp ; 
              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;
                        var x = [];
                        finalArr.sort(function(a,b){
                          // Turn your strings into dates, and then subtract them
                          // to get a value that is either negative, positive, or zero.
                          var aDate:any = new Date(a.Date);
                          var bDate:any = new Date(b.Date);  
                          return bDate - aDate;
                        });
                
                        
                        callback({ data: finalArr });
                      }
                    }
                  })
  
                 
                }
              } else {
                that.Load = false;
                callback({ data: [] });
  
              }
            }, err => {
              that.Load = false;
              var errCode = err.status;
              if(errCode == 500){
                callback({ data: [] });
              }

            
            });

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

        },

        "columns": [
          {
            "data": "_id",
            // "orderable":true,
            "defaultContent": "",
            "visible" :false, 
            "render": function (data, type, row) {             
              return  "";   
            }
          },
          {
            "data": "Date",
            "render": function (data, type, row) {       
              var reportDate = new Date(data);
              return data ? (moment(reportDate).format('LL')) : "";   
            }
          },
          {
            "data": "VRN",
            render: function (data, type, row) {
              return data ? data : '';
            }
          },
          {
            "data": "Distance(Kms)",
            render: function (data, type, row) {
            
              return data ? parseFloat(data).toFixed(2) : 0.0;

            }
          },
          {
            "data": "Moving Time",
            "defaultContent": "",
            render: function (data, type, row) {
            
              var hhmm;
              if(data){
                data = Math.abs(data); // Change to positive
                var decimal = data - Math.floor(data);
                console.log(decimal);
                var minValue = (decimal *60).toFixed(2);
                console.log('minValue',minValue);
                var hrValue= data.toString().split(".")[0] ; 

                hhmm = hrValue + ':' + parseInt(minValue);
              }else{
                hhmm  =0+':'+0;

              }
            return hhmm;
            }
          },
          {
            "data": "Stoppage Time",
            "defaultContent": "_id",
            render: function (data, type, row) {
              // return data ? parseFloat(data).toFixed(2) : 0.0;
              var hhmm;
              if(data){
                data = Math.abs(data); // Change to positive
                var decimal = data - Math.floor(data);
                // console.log(decimal);
                var minValue = (decimal *60).toFixed(2);
                // console.log('minValue',minValue);
                var hrValue= data.toString().split(".")[0] ; 

                hhmm = hrValue + ':' + parseInt(minValue);
              }else{
                hhmm  =0+':'+0;

              }
            return hhmm;
            }
          },
          {
            "data": "Idle Time",
            "defaultContent": "_id",
            render: function (data, type, row) {
              // return data ? parseFloat(data).toFixed(2) : 0.0;
              var hhmm;
              if(data){
                data = Math.abs(data); // Change to positive
                var decimal = data - Math.floor(data);
                console.log(decimal);
                var minValue = (decimal *60).toFixed(2);
                console.log('minValue',minValue);
                var hrValue= data.toString().split(".")[0] ; 

                hhmm = hrValue + ':' + parseInt(minValue);
              }else{
                hhmm  =0+':'+0;

              }
            return hhmm;
            }
          },
          {
            "data": "startAddress",
            "defaultContent": "_id",
            render: function (data, type, row) {
              return data ? data : '';
            }
          },
          {
            "data": "endAddress",
            "defaultContent": "_id",
            render: function (data, type, row) {
              return data ? data : '';
            }
          }
        ],
        "columnDefs": [
          { className: "dt-body-left", "targets": [0, 1, 2, 3,4,5,6,7] },
          {
            "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 },

        ]
      });

    });

  }





  identifier: any = 'dayWiseReport';
  getReport(event) {
    console.log("inside function");
    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;


      this.Fromdate = fd;
      this.todate = td;
      this.tabelObj.ajax.reload();
      // this.tabelObj.draw();  
      // this.tabelObj.draw();
      // if(this.ajaxCount != 0){

      // }
      // this.ajaxCount = 1 ; 
    }

  }

  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);
      }
    })

  }


}