import { Component, OnInit } from "@angular/core";
import { ContactService } from "./../contact.service";

declare var $: any, DataTable: any;
import * as moment from "moment";

import { MdDialog } from "@angular/material";
import { FlashMessagesService } from "angular2-flash-messages";
declare var XLSX: any, saveAs: any;
@Component({
  selector: "app-index-report",
  templateUrl: "./index-report.component.html",
  styleUrls: ["./index-report.component.scss"],
})
export class IndexingReportComponent implements OnInit {
  Fromdate = new Date();
  todate = new Date();
  reportData: any = [];
  tabelObj: any;
  emailid: any;
  useridd: any;
  option: any;
  supadm: any;
  deviceObjwithName: any = [];
  deviceSelect1: any = [];

  identifier: String = "gps_master";
  Load: boolean;
  super_admin: any;
  isDealer: any;
  dlrID: any;
  constructor(
    public contactService: ContactService,
    public dialog: MdDialog,
    private _flashMessagesService: FlashMessagesService
  ) {
    this.Fromdate.setHours(0, 0, 0);
    this.emailid = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).email;
    this.useridd = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    )._id;
    this.supadm = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).isSuperAdmin;
    this.isDealer = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).isDealer;
    if (this.isDealer == true) {
      this.dlrID = JSON.parse(
        window.atob(window.localStorage.token.split(".")[1])
      )._id;
    }
  }

  ngOnInit() {
    // this.getAllDevice();
    // this.testTable();
  }

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

  displayCol = [];
  testTable() {
    this.displayCol = [];

    //console.log("initId=>",id);
    console.log("Inside testTable");
    const that = this;
    let obj: any = { imei: "", from: "", to: "" };
    if (that.deviceArr.length != 0) {
      // console.log(that.deviceSelect[0].id);
      obj.imei = that.deviceArr[0];
    }

    if (that.Fromdate != null) {
      try {
        obj.from = new Date(that.Fromdate).toISOString();
      } catch (err) {}
    }
    if (that.todate != null) {
      try {
        // that.todate.setSeconds(0);
        // that.todate.setMilliseconds(0);
        obj.to = new Date(that.todate).toISOString();
      } catch (err) {}
    }

    // if(this.supadm){
    //   dataTablesParameters.find.supAdmin = that.useridd;
    // }

    var suburl = "";
    suburl += "/gps/indexingAIS140";
    // console.log(suburl);
    // console.log(dataTablesParameters);
    // console.log(suburl)
    //   if(id != 0)
    console.log("calling api");
    // {  "imei":"862818043677154",
    // "from":"2023-02-26 00:00:00.000Z",
    // "to":"2023-02-27 20:00:00.000Z"}
    that.contactService.post(suburl, obj).subscribe(
      (resp) => {
        // console.log('resp',resp);
        that.reportData = resp ? resp : [];
        if (that.reportData.length) {
          for (var key in that.reportData[0]) {
            this.displayCol.push(key);
          }
        }
      },
      (err) => {
        // console.log(err);
        // console.log(err.status);
        that.reportData = [];
      }
    );

    // $(document).ready(function () {
    //   that.tabelObj = $('#gpsTable').DataTable({
    //     "serverSide": true,
    //     "processing": true,
    //     "searching": false,
    //     "scrollX": true,
    //     "scrollY": "480px",
    //     "scrollCollapse": true,
    //     "responsive" :true,
    //     lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
    //     ajax: (dataTablesParameters: any, callback) => {
    //       console.log('inside ajax call');
    //       dataTablesParameters.op = {};
    //       dataTablesParameters.select = [];
    //       dataTablesParameters.find = {};

    //       // console.log(dataTablesParameters);
    //       // console.log("callback", callback);

    //       // dataTablesParameters.find = {
    //       //   _id: that.useridd
    //       // };
    //       dataTablesParameters.columns = [
    //         {data : "_id"},
    //         { data: "imei" },
    //         { data: "date" },
    //         { data: "latDecimal" },
    //         { data: "longDecimal" },
    //         { data: "insertionTime" },
    //         {data : 'syncedAt'},
    //         {data : 'integrationResponse'},
    //         { data: "speed" },
    //         {data:"ac"},
    //         {data : "currentFuel"},
    //         {data  : "raw"},
    //         { data: "ignition" },
    //         { data: "power" },
    //         {data : "fuelVoltage"},
    //         { data: "external_Battery" },
    //         { data: "powerCutAlarm" },
    //         { data: "satellites" },
    //         {data:'GPS positioned'},
    //         {data:'isFluctuation'},
    //         {data:'isPastData'},
    //       ]

    //         //  dataTablesParameters.find.supAdmin = that.useridd;

    //       if (that.deviceArr.length !=0) {
    //         // console.log(that.deviceSelect[0].id);
    //         dataTablesParameters.find.imei =that.deviceArr[0];
    //       }

    //       if (that.Fromdate) {
    //         console.log('that.Fromdate',that.Fromdate.toISOString());
    //         dataTablesParameters.find['insertionTime'] = dataTablesParameters.find['insertionTime'] ? dataTablesParameters.find['insertionTime'] : {};
    //         dataTablesParameters.find['insertionTime']['$gte'] = {
    //           _eval: 'date',
    //           value: new Date(that.Fromdate).toISOString()
    //         }
    //       };
    //       // }
    //       if (that.todate) {
    //         that.todate.setSeconds(0);
    //         that.todate.setMilliseconds(0);
    //         console.log('that.todate',that.todate.toISOString())

    //         dataTablesParameters.find['insertionTime'] = dataTablesParameters.find['insertionTime'] ? dataTablesParameters.find['insertionTime'] : {};
    //         dataTablesParameters.find['insertionTime']['$lte'] = {
    //           _eval: 'date',
    //           value: new Date(that.todate).toISOString()
    //         };
    //       }

    //       // if(this.supadm){
    //       //   dataTablesParameters.find.supAdmin = that.useridd;
    //       // }

    //       var suburl = "";
    //       suburl += "/gps/indexingAIS140";
    //       // console.log(suburl);
    //       // console.log(dataTablesParameters);
    //       // console.log(suburl)
    //   //   if(id != 0)
    //         console.log('calling api');
    //     that.contactService.post(suburl, {  "imei":"862818043677154",
    //     "from":"2023-02-26 00:00:00.000Z",
    //     "to":"2023-02-27 20:00:00.000Z"}).subscribe(resp => {
    //      // console.log('resp',resp);
    //       that.reportData = resp ? resp : [];
    //       callback(resp);
    //     }, err => {
    //       // console.log(err);
    //       // console.log(err.status);
    //       that.reportData = [];
    //       callback({data:[]})
    //     });

    //     },
    //     "rowCallback": function(row: Node, data: any | Object, index: number){
    //       $('#delete', row).bind('click', () => {
    //         // console.log("delete Method",data);
    //         var gpsId = data._id;
    //         that.contactService.deletegpsdata(gpsId)
    //           .subscribe(res=>{
    //             // console.log(res);
    //             that._flashMessagesService.show("Data Deleted", { cssClass: 'alert-warning', timeout: 2000 });
    //             that.callfunction();
    //           },err=>{
    //             that._flashMessagesService.show("Internal server error", { cssClass: 'alert-warning', timeout: 2000 });
    //             // console.log(err);
    //           })
    //       });
    //       },

    //     "columns": [
    //       {
    //         "data": "imei",
    //         "render": function (data, type, row) {
    //           return data ? data : "";
    //         }
    //       },
    //       {
    //         "data": "latDecimal",
    //         "render": function (data, type, row) {
    //           return data ? data : "";
    //         }
    //       },
    //       {
    //         "data": "longDecimal",
    //         "render": function (data, type, row) {
    //           return data ? data : "";
    //         }
    //       },
    //       {
    //         "data": "speed",
    //         "render": function (data, type, row) {
    //           return data ? data : "";
    //         }
    //       },
    //       {
    //         "data": "date",
    //         "render": function (data, type, row) {

    //           var device_time = new Date(data);
    //           return data ? (moment(device_time).format('dddd,ll,LTS')) : "";
    //         }
    //       },
    //       {
    //         "data": "insertionTime",
    //         "render": function (data, type, row) {
    //           var created_time = new Date(data);
    //           return data ? (moment(created_time).format('dddd,ll,LTS')) : "";
    //         }
    //       },
    //       {
    //         "data": "syncedAt",
    //         "render": function (data, type, row) {
    //           var insertion_time = new Date(data);
    //           return data ? (moment(insertion_time).format('dddd,ll,LTS')) : "";
    //         }
    //       },
    //       {
    //         "data": "integrationResponse",
    //         "render": function (data, type, row) {
    //           if(data)
    //           // alert(data);
    //           console.log(typeof(data));
    //           if(typeof(data) === 'object'){
    //             data = JSON.stringify(data);

    //           }
    //           return data ? data: "";
    //         }
    //       },
    //       {
    //         "data": "ignition",
    //         "render": function (data, type, row) {
    //           return data ? data : "";
    //         }
    //       },
    //       {
    //         "data": "power",
    //         "render": function (data, type, row) {
    //           return data ? data : ""
    //         }
    //       },
    //        {
    //         "data": "GPS positioned",
    //         "render": function (data, type, row) {
    //           return data ? data : ""
    //         }
    //       },
    //       {
    //         "data": "isFluctuation",
    //         "render": function (data, type, row) {
    //           return data ? data : ""
    //         }
    //       },
    //       {
    //         "data": "isPastData",
    //         "render": function (data, type, row) {
    //           return data ? data : ""
    //         }
    //       },
    //       {
    //         "data": "external_Battery",
    //         "render": function (data, type, row) {
    //           return data ? data : ""
    //         }
    //       },
    //       {
    //         "data": "fuelVoltage",
    //         "render": function (data, type, row) {
    //           return data ? (data/1000).toFixed(2) : ""
    //         }
    //       },
    //       {
    //         "data": "currentFuel",
    //         "render": function (data, type, row) {
    //           return data ? data : ""
    //         }
    //       },
    //       {
    //         "data": "raw",
    //         "render": function (data, type, row) {
    //           return data ? data : "" ;
    //         }
    //       },
    //       {
    //         "data": "ac",
    //         "render": function (data, type, row) {
    //           return data ? data : ""
    //         }
    //       },
    //       {
    //         "data": "powerCutAlarm",
    //         "render": function (data, type, row) {
    //           return data ? data : "";
    //         }
    //       },
    //       {
    //         "data": "satellites",
    //         "render": function (data, type, row) {
    //           return data ? data : "";
    //         }
    //       },
    //       {
    //         "data":null,"render":function(data,type,row){
    //         return '<i id="delete" class="fas fa-trash" style="cursor:pointer;color:red", title="Delete log"></i>'
    //     }}
    //     ],
    //     "columnDefs": [

    //       { width: '20px', targets: ['15'] }
    //     ]
    //   });
    // });
  }

  deviceObj = [];

  deviceSelect: any = [];
  deviceName: any;
  deviceName1: any;

  deviceArr = [];
  data_descip: any;

  exportTableToExcel(tableID, filename = "") {
    debugger;
    var downloadLink;
    var dataType = "application/vnd.ms-excel";
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, "%20");

    // Specify file name
    filename = filename ? filename + ".xls" : "excel_data.xls";

    // Create download link element
    window.open(
      "data:application/vnd.ms-excel," + encodeURIComponent(tableHTML)
    );
    /*     downloadLink = document.createElement("a");
    document.body.appendChild(downloadLink);
    // Create a link to the file
    downloadLink.href = "data:" + dataType + ", " + tableHTML;
    // Setting the file name
    downloadLink.download = filename;
    //triggering the function
    downloadLink.click(); */
  }

  leg_xlsx() {
    var tab_text = "<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange;
    var j = 0;
    var table = $("#gpsTable1").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;
  }
  json_to_xlsx(jsonData: any, screen: any) {
    jsonData = jsonData.map((d: any) => {
      for (let i in d) {
        d[i] = d[i] != undefined ? d[i] : "";
      }
      return d;
    });
    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.json_to_sheet(jsonData);
    XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
    XLSX.writeFile(workbook, screen + ".xlsx");
  }

  db_jsonToHtmlTable(jsonData) {
    let tableHtml = '<table border="1">';
    // Add table header
    tableHtml += "<tr>";
    for (const key in jsonData[0]) {
      if (jsonData[0].hasOwnProperty(key)) {
        tableHtml += "<th>" + key + "</th>";
      }
    }
    tableHtml += "</tr>";
    // Add table rows
    jsonData.forEach((item) => {
      tableHtml += "<tr>";
      for (const key in item) {
        if (item.hasOwnProperty(key)) {
          tableHtml += "<td>" + item[key] + "</td>";
        }
      }
      tableHtml += "</tr>";
    });
    tableHtml += "</table>";
    return tableHtml;
  }
  getReport(event) {
    this.deviceArr = [];
    console.log("inside function", event);
    if (event == "getExcel" || event == "Excel") {
      this.exportExcel();
    }
    //  else if (event == "Excel") {
    //   let xx = this.reportData.map((d) => {
    //     let t = {};
    //     return this.displayCol.reduce((a, b) => {
    //       a[b] = d[b];
    //       return a;
    //     }, {});
    //   });
    //   let tbl = this.db_jsonToHtmlTable(xx);
    //   let tbl2 =
    //     "<table> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td>Alfreds Futterkiste</td> <td>Maria Anders</td> <td>Germany</td> </tr> <tr> <td>Centro comercial Moctezuma</td> <td>Francisco Chang</td> <td>Mexico</td> </tr> <tr> <td>Ernst Handel</td> <td>Roland Mendel</td> <td>Austria</td> </tr> <tr> <td>Island Trading</td> <td>Helen Bennett</td> <td>UK</td> </tr> <tr> <td>Laughing Bacchus Winecellars</td> <td>Yoshi Tannamuri</td> <td>Canada</td> </tr> <tr> <td>Magazzini Alimentari Riuniti</td> <td>Giovanni Rovelli</td> <td>Italy</td> </tr> </table> ";
    //   window.open("data:application/vnd.ms-excel," + encodeURIComponent(tbl));

    // }
    else {
      var deviceId: any;
      var tpdata = event;
      var that = this;
      var Fromdate: any = null;
      var todate: any = null;
      try {
        let fd = new Date(tpdata.fromDate);
        Fromdate = fd.toISOString();
      } catch (err) {}
      try {
        let td = new Date(tpdata.toDate);
        todate = td.toISOString();
      } catch (err) {}

      var diff = moment(todate).diff(Fromdate, "days");
      // console.log(diff,"999999999");

      if (diff >= 31) {
        console.log("difference :" + diff);
        this.data_descip = "Report is unavailable for more than a month";
        launch_toast();
      } else {
        if (event.deviceId.length == 0) {
          deviceId = [];
        } else {
          deviceId = event.deviceId;
        }
        this.deviceArr = deviceId;
        this.Fromdate = Fromdate;
        this.todate = todate;
        this.testTable();
      }
    }

    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() {
    debugger;
    this.downloadFile(this.reportData);
  }
  downloadFile(data) {
    let arrHeader = this.displayCol;
    let csvData = this.ConvertToCSV(data, arrHeader);
    let blob = new Blob(["\ufeff" + csvData], {
      type: "text/csv;charset=utf-8;",
    });
    let dwldLink = document.createElement("a");
    let url = URL.createObjectURL(blob);
    let isSafariBrowser =
      navigator.userAgent.indexOf("Safari") != -1 &&
      navigator.userAgent.indexOf("Chrome") == -1;
    if (isSafariBrowser) {
      //if Safari open in new window to save file with random filename.
      dwldLink.setAttribute("target", "_blank");
    }
    dwldLink.setAttribute("href", url);
    dwldLink.setAttribute("download", "systemLogs.csv");
    dwldLink.style.visibility = "hidden";
    document.body.appendChild(dwldLink);
    dwldLink.click();
    document.body.removeChild(dwldLink);
    this.Load = false;
  }
  convertToDate(element, key) {
    if (element[key]) {
      var device_time = new Date(element[key]);
      return device_time ? moment(device_time).format("dddd,ll,LTS") : "";
    } else {
      return element[key];
    }
  }
  ConvertToCSV(objArray, headerList) {
    let array = typeof objArray != "object" ? JSON.parse(objArray) : objArray;
    array = JSON.parse(JSON.stringify(array));

    // console.log(array,"<===");Distance	126.94
    // Running	2:1
    // Idle	1:56
    // Stop

    let str = "Customer List \r\n";
    let row = "S.No,";
    // name,emial,phone,id,password and status no of vehicles
    let newHeaders = this.displayCol;
    for (let index in newHeaders) {
      row += newHeaders[index] + ",";
    }
    row = row.slice(0, -1);
    str += row + "\r\n";
    for (let i = 0; i < array.length; i++) {
      let line = i + 1 + "";
      if (i < array.length) {
      }
      for (let index in headerList) {
        let head = headerList[index];
        line += "," + this.strRep(array[i][head]);
      }
      str += line + "\r\n";
    }
    return str;
  }
  strRep(data) {
    if (typeof data == "string") {
      let newData = data.replace(/,/g, " ");
      return newData;
    } else if (typeof data == "undefined") {
      return "-";
    } else if (typeof data == "number") {
      return data.toString();
    } else {
      return data;
    }
  }
}
