import { Component, OnInit } from "@angular/core";
import { FotaService } from "./fota.service";
//import * as XLSX from "xlsx";
import * as fileSaver from "file-saver";
const EXCEL_TYPE =
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
const EXCEL_EXTENSION = ".xlsx";
declare var $: any, _: any, moment: any, XLSX: any, DataTable: any;
@Component({
  selector: "app-fota",
  templateUrl: "./fota.component.html",
  styleUrls: ["./fota.component.scss"],
})
export class FotaComponent implements OnInit {
  data: any = {
    command: "",
    imeiList: [],
    resp2: [],
    selected: {},
  };
  constructor(private fs: FotaService) {}
  tabelObj: any;
  tblData: any = [];
  date(dt, fmt) {
    return moment(dt.createdAt).format(fmt);
  }
  db_page_cal(idx: any) {
    return idx < this.db_page;
  }
  db_page: any = 0;
  db_p_table() {
    if (this.db_page > 0) this.db_page -= 1;
  }
  db_n_table() {
    this.db_page += 1;
    console.log("n", this.data.resp2);
  }
  ngOnInit() {
    let that = this;
    that.fs.bulkCommand_triggeredCommands({}).subscribe((resp1) => {
      that.db_page = 0;
      resp1 = resp1.map((d, i) => {
        d.page_index = Math.trunc(Number(i / 10));
        return d;
      });
      that.data.resp2 = [...resp1];

      // setTimeout(() => {
      //   $("#db_table").DataTable({
      //     pagingType: "full_numbers",
      //     pageLength: 10,
      //     lengthMenu: [
      //       [10, 25, 50, -1],
      //       [10, 25, 50, "All"],
      //     ],
      //   });
      // }, 200);
    });

    // this.tbl();

    $("#excelFile").change(function (e) {
      var reader = new FileReader();
      reader.onload = function (e1: any) {
        let workbook = XLSX.read(e1.target.result, { type: "binary" });
        let worksheet = workbook.Sheets[workbook.SheetNames[0]];
        let d: any = XLSX.utils.sheet_to_json(worksheet, { raw: true });
        if (d.length > 0 && _.chain(d[0]).has("IMEINO.").value()) {
          that.data.imeiList = _.chain(d)
            .map((d) => d["IMEINO."])
            .value();
        }
      };
      reader.readAsBinaryString(e.target.files[0]);
    });
  }
  btm_submit(dt) {
    let that = this;
    that.fs
      .bulkcommand_trigger({
        imeiList: dt.imeiList,
        command: dt.command,
      })
      .subscribe((dx: any) => {
        that.fs.bulkCommand_triggeredCommands({}).subscribe((resp1) => {
          that.db_page = 0;
          resp1 = resp1.map((d, i) => {
            d.page_index = Math.trunc(Number(i / 10));
            return d;
          });
          that.data.resp2 = [...resp1];
          $("#excelFile").val("");
          that.data.imeiList = [];
          that.data.command = "";
        });
      });
  }
  valid(dt: any) {
    return dt.imeiList.length > 0 && dt.command != "" ? false : true;
  }
  bulkcommand_commanddetails(dt: any) {
    let that = this;
    this.fs.bulkcommand_commanddetails({ _id: dt._id }).subscribe((resp) => {
      dt.child = resp;
      dt.flag = !(dt.flag == undefined ? false : dt.flag);
    });
  }
  // file download

  exportAsExcelFile(json: any[], excelFileName: string): void {
    const worksheet = XLSX.utils.json_to_sheet(json);
    const workbook = {
      Sheets: { data: worksheet },
      SheetNames: ["data"],
    };
    const excelBuffer: any = XLSX.write(workbook, {
      bookType: "xlsx",
      type: "array",
    });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }
  saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], { type: EXCEL_TYPE });
    fileSaver.saveAs(
      data,
      fileName + "_export_" + new Date().getTime() + EXCEL_EXTENSION
    );
  }
  down(dt: any) {
    let that = this;
    this.fs.bulkcommand_commanddetails({ _id: dt._id }).subscribe((resp) => {
      dt.child = resp;
      // that.exportAsExcelFile(dt.child, "download.xlsx");

      let data = dt.child.map((d: any) => {
        let t: any = {};
        t.IMEI = "_" + d.imei.toString();
        t.Status = d.status;

        t.Response =
          d.deviceResponse == undefined
            ? ""
            : d.deviceResponse.replace(/\n/g, " ").replace(/,/g, " ");
        return t;
      });
      // that.exportAsExcelFile(dt.child, "download");

      const csvContent = that.fs.convertJSONToCSV(data);
      that.fs.downloadCSV(csvContent, dt._id + ".csv");
    });
  }

  export(jsonData: any) {
    jsonData = jsonData.map((d: any) => {
      d.deviceResponse = d.deviceResponse == undefined ? "" : d.deviceResponse;
      return d;
    });
    const ws = XLSX.utils.json_to_sheet(jsonData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

    const blob = new Blob(
      [XLSX.write(wb, { bookType: "xlsx", type: "blob" })],
      {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      }
    );

    const downloadLink = document.createElement("a");
    downloadLink.href = URL.createObjectURL(blob);
    downloadLink.download = "json_data.xlsx";
    downloadLink.click();
  }
  test2(dt: any) {
    const table = document.getElementById(dt._id);
    const ws = XLSX.utils.table_to_sheet(table);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

    const blob = new Blob(
      [XLSX.write(wb, { bookType: "xlsx", type: "blob" })],
      {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      }
    );

    const downloadLink = document.createElement("a");
    downloadLink.href = URL.createObjectURL(blob);
    downloadLink.download = "table_data.xlsx";
    downloadLink.click();
  }
}
