import { Component, OnInit } from '@angular/core';
import { MdSnackBar } from '@angular/material';
declare var jsPDF: any;
declare var $: any;
const PDF_EXTENSION = ".pdf";
import * as moment from 'moment';
import { ContactService } from '../../../contact.service';
import { ReportService } from '../../report.service';
@Component({
  selector: 'app-new-travel-path-report',
  templateUrl: './new-travel-path-report.component.html',
  styleUrls: ['./new-travel-path-report.component.scss']
})
export class NewTravelPathReportComponent implements OnInit {
  tabelObj: any;
  pathDuration = [
    { label: "1 Minutes", interval: "1" },
    { label: "5 Minutes", interval: "5" },
    { label: "10 Minutes", interval: "10" },
    // {label  :"45 Minutes",interval : "45"},
    // {label  :"60 Minutes",interval : "60"}

  ];
  Load: boolean;
  Fromdate: any;
  noteForpdf
  todate: any;
  useridd: any;
  pathReport = []
  travelPat_duration = { label: "10 Minutes", interval: "10" };
  skip: any;
  finalArr = []
  reportArr: any[];
  reportArr1: any[]
  firstcall: boolean;
  lastcall: boolean;
  date: any;
  device_id: any
  device_name: any;
  supAdmin: any;
  logo1: string;
  constructor(private contactService: ContactService, private _service: ReportService, public snackBar: MdSnackBar) {

    this.supAdmin = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).supAdmin;
    this._service.invokeEventFortravelPathReportt.subscribe(value => {
      if (value) {
        this.getReport(value);
      }
    });
  }

  ngOnInit() {
    var user = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isSuperAdmin ? JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id : this.supAdmin
    this.contactService.get('/users/shareProfileImage?uid=' + user).subscribe((res: any) => {
      // console.log(res);

      if (res.imageDoc.length != 0) {
        var str = res.imageDoc[0]
        var splitStr = str.split('/');
        var concatStr = '';
        for (var i = 1; i < splitStr.length; i++) {
          if (i > 0) {
            var tt = splitStr[i];
            concatStr += '/' + tt;
          }
        }
        this.logo1 = 'https://www.oneqlik.in' + concatStr


      }

    })
    this.testTable()
  }


  testTable() {
    const that = this;
    $(document).ready(function () {
      that.tabelObj = $('#travelPath').DataTable({

        "processing": false,
        "searching": true,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: false,
        order: [[0, 'desc']],
        responsive: true,
        "scrollY": '60vh',
        "scrollCollapse": true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "rowCallback": function (row: Node, data: any | Object, index: number) {


        },
        ajax: (dataTablesParameters, callback) => {

          if (that.device_id && that.Fromdate && that.todate) {
            that.Load = true;
            var payload = {
              "to": new Date(that.todate).toISOString(),
              "from": new Date(that.Fromdate).toISOString(),
              "device": that.device_id,
              "interval": that.travelPat_duration.interval
            }
            var suburl = "";
            var limit = 26;
            suburl += "/user_trip/StoppageLogs?date=" + that.date + "&device=" + that.device_id
            // if(that.deviceArr.length != 0){  
            //   suburl +='&device='+that.deviceArr;
            // }
            that.contactService.getTravel_path_report(payload).subscribe((resp: any) => {
              clearTimeout(this.clear_interval);

              that.reportArr = resp;
              that.reportArr = resp.filter(function (el) {
                return el != null;
              });


              let last = { speed: '' };
              let result = [];

              for (let i = 0; i < that.reportArr.length; i++) {

                let char = that.reportArr[i];
                if (char.speed !== last.speed) {
                  var cum_distance = parseFloat(that.reportArr[i].odo) - parseFloat(that.reportArr[0].odo);
                  char.cum_distance = Math.abs(parseFloat(cum_distance.toFixed(2)))

                  if (i == 0) {
                    char.avgSpeed = 0.00;
                  } else {
                    var avgSpeed = parseFloat(that.reportArr[i].odo) - parseFloat(that.reportArr[i - 1].odo);
                    char.avgSpeed = Math.abs(parseFloat((avgSpeed / 0.166).toFixed(2)));
                  }

                  if (i == 0) {
                    char.distanceFromPrevious = 0.00;
                  } else {
                    var distanceFromPrevious = parseFloat(that.reportArr[i].odo) - parseFloat(that.reportArr[i - 1].odo);
                    char.distanceFromPrevious = Math.abs(parseFloat(distanceFromPrevious.toFixed(2)));
                  }
                  // char.avgSpeed = that.getavgSpeed(i)
                  // char.distanceFromPrevious = that.get_distance(i)
                  result.push(char);
                  last = char;
                }
              }

              that.reportArr1 = result


              if (that.reportArr1.length != 0) {
                var j = 0;
                for (let i = 0; i < resp.length; i++) {
                  if (resp[i] != null) {
                    resp[i].Device_name = that.device_name;
                    that.pathReport.push(resp[i]);
                  } else {
                  }
                }

                that.finalArr = [];
                for (var i = 0; i < that.reportArr1.length; i++) {
                  that.clocation_1(that.reportArr1[i], function (err, succ) {
                    if (err) {
                      console.log(err);
                      j++;
                    } else {
                      // console.log(succ);
                      succ['index'] = j
                      that.finalArr.push(succ);
                      // console.log(that.finalArr,j);
                      j++;
                      if (j === that.reportArr1.length) {
                        that.Load = false;
                        that.finalArr.sort(function (a: any, b: any) {
                          return new Date(a.date).valueOf() - new Date(b.date).valueOf();
                        });
                        callback({ data: that.finalArr });
                      }
                    }
                  })


                }
                if (that.pathReport.length == 0) {
                  that.Load = false;
                }
              } 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);
            });
          } else {
            that.Load = false;
            callback({ data: [] });
          }
        }, "aaSorting": [],
        "columns": [
          {
            "data": "device",
            "render": function (data, type, row) {
              return that.device_name;
            }
          },
          {
            "data": "imei",
            "render": function (data, type, row) {

              return that.device_id;
            }
          },
          {
            "data": "date",
            "render": function (data, type, row) {

              return moment(data).format('lll');
            }
          },
          {
            "data": "odo",
            "render": function (data, type, row) {

              return data ? data.toFixed(2) : 0;
            }
            // return end_time;
          },

          {
            "data": "distanceFromPrevious",
            "render": function (data, type, row) {
              // var res = that.get_distance(row.index)
              return data;
            }
            // return end_time;
          },

          {
            "data": "speed",
            "render": function (data, type, row) {

              return data;
            }
            // return row.event_time;
          },
          {
            "data": "avgSpeed",
            "render": function (data, type, row) {
              // var res = that.getavgSpeed(row.index)
              return data;
            }
          },
          {
            "data": "external_Battery",
            "render": function (data, type, row) {

              return data ? data : '0';
            }

          },
          {
            "data": "temp",
            "render": function (data, type, row) {
              return data ? (parseFloat(data) / 10).toFixed(2) : '0';
            }

          },
          {
            "data": "cum_distance",
            "render": function (data, type, row) {
              // var res=that.getcummulative_distance(row,row.index)
              return data;
            }
          },
          {
            "data": "address",
            "render": function (data, type, row) {
              var str = (row.latDecimal ? row.latDecimal : 0) + ' , ' + (row.longDecimal ? row.longDecimal : 0)

              return str;
            }

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

              return data;
            }

          }
          // },

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


          //       {
          //     targets: -1, //-1 es la ultima columna y 0 la primera
          //     data: null,
          //     defaultContent: '<div class="btn-group"> <button (click)="show()">view</button></div>'
          // },
        ]
      });
      // that.tabelObj.sort

    });

  }

  getReport(value) {
    if (value == 'getExcel') {
      this.exportExcel();
    } else if (value == 'getPdf') {
      this.downloadPdf();
    } else {

      this.Fromdate = value.fromDate;
      this.todate = value.toDate;
      this.device_id = value.deviceArr[0].id[0]
      this.device_name = value.deviceArr[0].name
      var that = this;
      if ((this.Fromdate == undefined) || (this.todate == undefined)) {
        let message1 = "Please Select Date";
        let action: any;
        this.snackBar.open(message1, action, {
          duration: 5000,

        });
        // this._flashMessagesService.show("Please Select Date", { cssClass: 'alert-danger', timeout: 3000 });

        return;
      }

      if (this.Fromdate.getTime() > this.todate.getTime()) {
        let message1 = "From Date cannot be greater than to date...";
        let action: any;
        this.snackBar.open(message1, action, {
          duration: 5000,

        });
        // this._flashMessagesService.show("Please Select Date", { cssClass: 'alert-danger', timeout: 3000 });

        return;
      }
      var diff = (this.todate.getTime() - this.Fromdate.getTime()) / 3600000;
      var now = this.todate;
      var then = this.Fromdate;
      var difference = this.todate.getTime() - this.Fromdate.getTime();
      var hour = (difference / (60 * 60 * 1000));
      var diff_hr = Math.round(hour);

      if (diff_hr > (24 * 15)) {
        let message1 = "Date difference should not be greater then 15 Days";
        let action: any;
        this.snackBar.open(message1, action, {
          duration: 5000,
        });
        return;
      }

      if ((value.deviceArr.length == 0) || (value.deviceArr[0] == undefined)) {
        let message1 = "Please Select Device";
        let action: any;
        this.snackBar.open(message1, action, {
          duration: 5000,

        });
        // this._flashMessagesService.show("Please Select Device", { cssClass: 'alert-danger', timeout: 3000 });toISOString();
        return;
      }
      this.skip = 0;
      this.firstcall = false;
      this.lastcall = true;
      this.tabelObj.ajax.reload();

    }
  }

  tab: any;
  exportExcel() {
    var tab_text = "<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j = 0;
    var table = $('#travelPath').clone();

    table[0].querySelector("thead").remove();
    table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];

    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);
  }
  clocation_1(latlngObj, cb) {
    if (latlngObj == null) {
      cb(null, latlngObj);
    }
    var outerThis = this;
    var la = '';

    let latLng = {
      lat: "0",
      long: "0"
    };

    latLng = {
      lat: latlngObj.latDecimal ? latlngObj.latDecimal : 0,
      long: latlngObj.longDecimal ? latlngObj.longDecimal : 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['address'] = adata;
        // cb(null,latlngObj);
        var latLng_1 = {
          lat: "0",
          long: "0"
        };

        latLng_1 = {
          lat: latlngObj.latDecimal ? latlngObj.latDecimal : 0,
          long: latlngObj.longDecimal ? latlngObj.longDecimal : 0
        }


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

            latlngObj['address'] = bdata;
            cb(null, latlngObj);


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

        })

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

        latLng_1 = {
          lat: latlngObj.latDecimal ? latlngObj.latDecimal : 0,
          long: latlngObj.longDecimal ? latlngObj.longDecimal : 0
        }




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

            latlngObj['address'] = cdata;
            cb(null, latlngObj);


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

        })

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

  }

  export_pdf() {
    // jsPDF(orientation, unit, format

    this.noteForpdf = '';
    var f_date = moment(this.Fromdate).format('lll');
    var t_date = moment(this.todate).format('lll');
    var date_combine = f_date + '-' + t_date;
    let doc = new jsPDF();
    doc.setFontSize(100);
    doc.text('Travel Path Report', 350, 30);
    doc.text(date_combine, 250, 60);


    // doc.addHTML(document.getElementById("exportPdf"), function() {
    //   var tpr ="";
    //    doc.save("obrz.pdf");
    // });

    var specialElementHandlers = {
      '#editor': function (element: any, renderer: any) {
        return true;
      }
    };

    doc.autoTable({
      theme: 'striped',
      html: '#deviceTable',
      margin: { top: 100 },
      styles: {
        cellWidth: 50
      },
      willDrawCell: data => {
        // }
        if ((data.row.index === 0) || (data.cell.text[0] === "Device")) {
          // data.row.cells[0].styles.halign = 'center';
          data.row.cells[1].styles.halign = 'center';
          data.row.cells[2].styles.halign = 'center';
          data.row.cells[3].styles.halign = 'center';
          data.row.cells[4].styles.halign = 'center';
          data.row.cells[5].styles.halign = 'center';
          data.row.cells[6].styles.halign = 'center';
          // data.row.cells[0].styles.fillColor =  [224,224,224];
          // doc.setLineHeightFactor()
        }
        // data.row.cells[0].styles.halign = 'center';
        data.row.cells[1].styles.halign = 'center';
        data.row.cells[2].styles.halign = 'center';
        data.row.cells[3].styles.halign = 'center';
        data.row.cells[4].styles.halign = 'center';
        data.row.cells[5].styles.halign = 'center';
        data.row.cells[6].styles.halign = 'center';



      }

    });
    // var pdfNameStr = travel_path_report
    // doc.setFontSize(15);
    doc.save('travel_path_report.pdf');



  }

  startAddress;

  endAddress;
  f_date
  t_date
  downloadPdf() {
    var outerThis = this
    let fileName =
      "Travel Path Report" +
      new Date().getTime() +
      PDF_EXTENSION;
    var pdfsize = "a2";
    var totalPagesExp = "{total_pages_count_string}";
    outerThis.startAddress = outerThis.finalArr[0].address;
    outerThis.endAddress = outerThis.finalArr[outerThis.finalArr.length - 1].address
    var doc = new jsPDF("p", "pt", pdfsize);
    outerThis.f_date = moment(this.Fromdate).format('lll');
    outerThis.t_date = moment(this.todate).format('lll');
    // var date_combine = f_date + ' to ' + t_date;
    // doc.setFontSize(30);
    var pageHeight = doc.internal.pageSize.height || doc.internal.pageSize.getHeight();
    var pageWidth = doc.internal.pageSize.width || doc.internal.pageSize.getWidth();
    doc.setFontSize(15);
    // doc.text(60, 20, 'Travel Path Report (Date='+date_combine+') Device Name='+this.device_name,);

    doc.text("Travel Path Report", 500, 30);
    doc.setFontStyle("arial");

    var header = function (data) {
      doc.setFontSize(30);
      doc.setTextColor(40);
      doc.setFontStyle('arial');

    };

    var options = {
      beforePageContent: header,
      margin: {
        top: 120
      },

      startY: doc.autoTableEndPosY() + 20
    };

    outerThis.toDataURL(outerThis.logo1, function (dataUrl) {

      doc.autoTable({
        head: outerThis.headRows(),
        // margin: { top: 80 },
        //  startY: doc.autoTable.previous.finalY + 200,
        body: outerThis.bodyRows(outerThis.finalArr.length, outerThis.finalArr),
        options,
        styles: { overflow: 'linebreak' },
        // tableLineColor: [0, 0, 0], //choose RGB
        // tableLineWidth: 0.5, //table border width
        // bodyStyles: {
        //     margin: 40,
        //     fontSize: 10,
        //     lineWidth: 0.2,
        //     lineColor: [0, 0, 0]
        // },
        theme: 'grid',
        didDrawPage: function (data) {
          // Header
          doc.setFontSize(20);
          doc.setTextColor(40);
          doc.setFontStyle('arial');
          if (outerThis.logo1)
            doc.addImage(dataUrl, 'JPEG', pageWidth - 100, 6, 75, 75);
          doc.autoTable({ html: "#headerTable", margin: { bottom: 140, left: 20, right: 8, top: 20 }, theme: 'plain' });

          // Footer
          var str = "Page " + doc.internal.getNumberOfPages()
          // Total page number plugin only available in jspdf v1.0+
          if (typeof doc.putTotalPages === 'function') {
            str = str + " of " + totalPagesExp;
          }
          doc.setFontSize(10);

          // jsPDF 1.4+ uses getWidth, <1.4 uses .width
          var pageSize = doc.internal.pageSize;
          var pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();
          doc.text(str, data.settings.margin.left, pageHeight - 10);
        },
        // didParseCell: function (table) {

        //       if (table.section === 'head') {
        //         table.cell.styles.textColor = '#FFFFFF';
        //         table.cell.styles.fillColor = 'red';
        //       }
        //       if(table.section === 'body' && table.cell.raw < 0){
        //     table.cell.styles.textColor = "red";
        // }
        //    },
        //  createdCell: function (cell, data) {
        //       cell.styles.fillColor = '#ffffff';
        //   },
        margin: { top: 85 },
        // styles: { fillColor: "#C0C0C0" },
      });
      if (typeof doc.putTotalPages === 'function') {
        doc.putTotalPages(totalPagesExp);
      }
      doc.save(fileName);
    })
  }
  headRows() {

    return [
      // displayedColumns=['vehicleName','IMEI','totalDistance','fuel','ignOn','ignOff','idleTime','outOfReach','noGps','trips','maxSpeed','startLocation','endLocation','details'];

      {
        deviceName: 'device Name',
        imei: 'IMEI',
        date: 'Date',
        odo: 'ODO',
        distanceFromPrevious: 'Distance',
        speed: 'Speed',
        avgSpeed: 'AVG Speed',
        externalBattery: 'Ext Battery',
        temperature: 'Temperature',
        cumDistance: 'Cum Distance',
        location: 'Location',
        address: 'Address',
      }
    ];
  }
  toDataURL(url, callback) {

    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
      var reader = new FileReader();
      reader.onloadend = function () {
        callback(reader.result);
      }
      reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
  }
  bodyRows(rowCount, pdfBody) {

    rowCount = rowCount || 10;
    let body = [];
    for (var j = 0; j < rowCount; j++) {
      body.push({

        deviceName: pdfBody[j].Device_name,
        imei: pdfBody[j].imei,
        date: moment(pdfBody[j].date).format('lll'),
        odo: pdfBody[j].odo ? (pdfBody[j].odo).toFixed(2) : 0,
        distanceFromPrevious: this.get_distance(pdfBody[j].index),
        speed: pdfBody[j].speed,
        avgSpeed: this.getavgSpeed(pdfBody[j].index),
        externalBattery: pdfBody[j].external_Battery ? pdfBody[j].external_Battery : '0',
        temperature: pdfBody[j].temp ? (parseFloat(pdfBody[j].temp) / 10).toFixed(2) : '0',
        cumDistance: this.getcummulative_distance(pdfBody[j], pdfBody[j].index),
        location: (pdfBody[j].latDecimal ? pdfBody[j].latDecimal : 0) + ' , ' + (pdfBody[j].longDecimal ? pdfBody[j].longDecimal : 0),
        address: pdfBody[j].address,

      });
    }
    return body;
  }

  getcummulative_distance(gps_report, index) {

    if (index == 0) {
      return 0.00;
    } else {
      var cum_distance = parseFloat(this.reportArr1[index].odo) - parseFloat(this.reportArr1[0].odo);
      return Math.abs(parseFloat(cum_distance.toFixed(2)));
    }

  }

  getavgSpeed(index_1) {
    if (index_1 == 0) {
      return 0.00;
    } else {
      var cum_distance = parseFloat(this.reportArr1[index_1].odo) - parseFloat(this.reportArr1[index_1 - 1].odo);
      return Math.abs(parseFloat((cum_distance / 0.166).toFixed(2)));
    }
  }

  get_distance(index_1) {
    if (index_1 == 0) {
      return 0.00;
    } else {
      var cum_distance = parseFloat(this.reportArr1[index_1].odo) - parseFloat(this.reportArr1[index_1 - 1].odo);
      // console.log(cum_distance);
      return Math.abs(parseFloat(cum_distance.toFixed(2)));
    }

  }

}
