import { Component, OnInit } from "@angular/core";
import { ContactService } from "../contact.service";
import { BsDatepickerConfig } from "ngx-bootstrap";
import {
  Router,
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
} from "@angular/router";
import { forkJoin } from "rxjs/observable/forkJoin";
declare var moment: any, $: any, swal: any, _: any;
@Component({
  selector: "app-finance-approval",
  templateUrl: "./finance-approval.component.html",
  styleUrls: ["./finance-approval.component.scss"],
})
export class FinanceApprovalComponent implements OnInit {
  constructor(private cs: ContactService, private router: Router) { }
  bsConfig: Partial<BsDatepickerConfig>;
  logined_user: any = {};
  clicked: boolean = false;
  //?user_id=XXXXX&status=PENDING
  search: any = {
    user_id: "",
    status: "",
    from: new Date(new Date().setHours(0, 0, 0)),
    to: new Date(),
  };
  pg_data: any = { tbl: [], userList: [], row: {}, status: {} };
  status_popup_data: any = {
    CourierName: "",
    TrackingId: "",
  }
  file_data: any;
  status_save_change(st_data: any) {
    console.log("status_save_change=>", st_data);
    let that = this;

    if (st_data.CourierName != "" && st_data.TrackingId != "") {
      that.cs.db_editOrder(st_data).subscribe((resp) => {
        that.db_user_change(that.search);
        $("#status_changed_popupl_close").click();
        // swal("Deleted!", "Your imaginary file has been deleted.", "success");
      });
    }



  }
  status_changed(dt: any) {
    //"status_changed_popup"
    debugger;
    // this.status_popup_data.form = dt;
    // $("show_status_changed_popup").click();
    // console.log("status=>", dt);
  }
  ngOnInit() {
    let that = this;
    that.bsConfig = Object.assign(
      { dateInputFormat: "DD-MM-YYYY, h:mm:ss a" },
      { containerClass: "theme-dark-blue" }
    );
    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);

    this.logined_user = JSON.parse(atob(localStorage.token.split(".")[1]));
    //this.getOederSummary("?user_id=" + this.logined_user._id).subscribe(
    this.getOederSummary("").subscribe((resp) => {
      console.log("resp=>", resp);
      that.pg_data.tbl = resp[0];
      that.pg_data.status = resp[1];
    });
    // getOederSummary
    //user_id
    //organization=
    that.cs
      .db_getDealers(
        "?organisation=" +
        that.logined_user.organisation +
        "&pageNo=1&size=9999"
      )
      .subscribe((resp) => {
        that.pg_data.userList = resp;
        setTimeout(() => {
          $("#dbselect123").multipleSelect({
            width: 300,
            placeholder: "placeholderval",
            filter: true,
            single: true,
            selectAll: false,
            // onOptgroupClick: function (view) {
            //   console.log(view);
            // },
            onClick: function (view) {
              that.search.user_id = view.value;
              // that.db_user_change(that.search);
            },
          });

          // $("#dbselect").change(() => {
          //   this.clicked = false;
          // });
        }, 100);
      });
  }

  dt_f(d, f) {
    return moment(d).format(f);
  }
  fileDownload_blob(t) {
    const pdfUrl =
      this.cs.db_getUrl("dev_url") + t.filePath.replace(/public/g, "");

    const fileName = pdfUrl.split(".").at(-1);

    fetch(pdfUrl)
      .then((response) => response.blob())
      .then((blob) => {
        const blobUrl = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = blobUrl;
        a.download = fileName;
        a.click();
      });
  }
  fileDownload(t) {
    const downloadLink: any = document.createElement("a");
    downloadLink.href =
      this.cs.db_getUrl("dev_url") + t.filePath.replace(/public/g, "");

    const fileName = downloadLink.href.split(".").at(-1);
    downloadLink.download = t.filePath.split("/").at(-1);
    downloadLink.innerText = fileName;
    downloadLink.target = "_blank";
    downloadLink.click();
  }
  fileUpload(row) {
    console.log("row=>", row);
    this.pg_data.row = row;
    $("#db_file").click();
  }
  onFileChanged(ev: any) {
    debugger;
    let that = this;
    let file = ev.target.files[0];
    const fd = new FormData();
    fd.append("photo", file, file.name);
    console.log("Binaryimage = > ", fd);
    that.cs.imageupload(fd).subscribe((res: any) => {
      console.log("resp=>", res);
      that.pg_data.row.filePath = res._body;
      that.db_editOrder(that.pg_data.row);
    });
  }
  showAdd(t) {
    if (t.shippingAddress != undefined) {
      return (
        (t.shippingAddress.city || "") +
        (t.shippingAddress.state || "") +
        (t.shippingAddress.country || "") +
        (t.shippingAddress.pincode || "")
      );
    }
    return "";
  }
  getOederSummary(srl) {
    return forkJoin([
      this.cs.getOederSummary(srl),
      this.cs.db_countByStatus({}),
    ]);
  }
  downloadExcel(data) {
    this.csvDownload(data);
  }
  changeTab(d: any) { }
  logout() {
    window.localStorage.clear();
    this.router.navigateByUrl("login");
  }

  show(dt) {
    console.log("dt=>", dt);
  }
  db_open_popup(id, obj) {
    this.pg_data.row = obj;
    $(id).click();
  }
  db_row_status_edit(obj) {
    let that = this;

    if (obj.status == "Dispatched") {
      console.log(obj);
      this.status_popup_data = obj;
      $("#show_status_changed_popup").click();
      return;
    }
    swal({
      title: "Are you sure?",
      text: "Do you want to save the changes?",
      type: "warning",
      showCancelButton: true,
      confirmButtonText: "Yes",
      cancelButtonText: "No",
    }).then(
      function () {
        let temp = JSON.parse(JSON.stringify(obj));
        if (temp.user_id != undefined) delete temp.user_id;
        else if (temp.__v != undefined) delete temp.__v;
        that.cs.db_editOrder(temp).subscribe((resp) => {
          that.db_user_change(that.search);
          // swal("Deleted!", "Your imaginary file has been deleted.", "success");
        });
      },
      function (dismiss) {
        // dismiss can be 'cancel', 'overlay', 'close', 'timer'
        if (dismiss === "cancel") {
          that.db_user_change(that.search);
          // swal("Cancelled", "Your imaginary file is safe :)", "error");
        }
      }
    );
  }
  db_editOrder(obj) {
    let that = this;
    let temp = JSON.parse(JSON.stringify(obj));
    if (temp.user_id != undefined) delete temp.user_id;
    else if (temp.__v != undefined) delete temp.__v;
    this.cs.db_editOrder(temp).subscribe((resp) => {
      that.db_user_change(that.search);
    });
  }
  db_user_change(srch) {
    let that = this;
    let t: any = {};
    for (let i in srch) {
      if (srch[i] != "") {
        t[i] = srch[i];
      }
    }
    this.getOederSummary("?" + $.param(t)).subscribe((resp) => {
      console.log("resp=>", resp);
      that.pg_data.tbl = resp[0];
      that.pg_data.status = resp[1];
    });
  }

  db_status_change(srch) {
    debugger;
    let that = this;
    let t: any = {};
    for (let i in srch) {
      if (srch[i] != "") {
        t[i] = srch[i];
      }
      if (i == "from" && t[i] != "") {
        t.from = new Date(t.from).toISOString();
      }
      if (i == "to" && t[i] != "") {
        t.to = new Date(t.to).toISOString();
      }
    }
    this.getOederSummary("?" + $.param(t)).subscribe((resp) => {
      console.log("resp=>", resp);
      that.pg_data.tbl = resp[0];
      that.pg_data.status = resp[1];
    });
  }

  convertToCSV(jsonData) {
    const separator = ",";
    const keys = Object.keys(jsonData[0]);
    const header = keys.join(separator);
    const rows = jsonData.map((obj) =>
      keys.map((key) => obj[key]).join(separator)
    );

    return [header, ...rows].join("\n");
  }
  csvDownload(jsonData: any) {
    let that = this;
    let xlsxData = jsonData.map((d) => {
      let t: any = {};
      t.Name = (d.buyer_first_name || "") + (d.buyer_last_name || "");
      t.Email = d.email;
      t.Phone = d.phone;
      t.Status = d.status;
      t.purchased_on = that.dt_f(d.purchased_on, "DD-MM-YYYY hh:mm a");
      t.Amount = d.amount || "";
      t.Address =
        d.shippingAddress != undefined
          ? (d.shippingAddress.city || "") +
          " " +
          (d.shippingAddress.state || "") +
          " " +
          (d.shippingAddress.country || "") +
          " " +
          (d.shippingAddress.pincode || "")
          : "";
      t.Payment_Status = d.payment_status || "";
      t.Payment_Ref = d.payment_reference || "";
      d.CartData.map((dx, i) => {
        // return { ...t, ...dx };
        // t[`Cart-${i + 1}/cartId`] = dx.cartId;
        t[`Cart-${i + 1}/deviceName`] = dx.deviceName;
        t[`Cart-${i + 1}/price`] = dx.price;
        t[`Cart-${i + 1}/quantity`] = dx.quantity;
      });
      return t;
    });

    // const csvData = this.convertToCSV(_.flatMap(xlsxData));
    const csvData = this.convertToCSV(xlsxData);

    const blob = new Blob([csvData], { type: "text/csv" });
    const blobUrl = URL.createObjectURL(blob);
    const downloadLink = document.createElement("a");
    downloadLink.href = blobUrl;
    downloadLink.download = "data.csv";
    downloadLink.innerText = "Download CSV";
    downloadLink.click();
    URL.revokeObjectURL(blobUrl);
  }
}
