import { Component, OnInit } from "@angular/core";
import { MdDialog, MdSnackBar } from "@angular/material";
import { Router, ActivatedRoute } from "@angular/router";
import { ContactService } from "../../contact.service";
import { OrderDetailsComponent } from "../order-details/order-details.component";

declare var moment: any, _: any, $: any;
@Component({
  selector: "app-order-summary",
  templateUrl: "./order-summary.component.html",
  styleUrls: ["./order-summary.component.scss"],
})
export class OrderSummaryComponent implements OnInit {
  Fromdate: any;
  todate: any;
  superAdmin: any;
  fs: any;
  ls: any;
  emailid: any;
  or: any;
  mb: any;
  useridd: any;
  custtype: any;
  deviceArr: any;

  constructor(
    public dialog: MdDialog,
    public snackBar: MdSnackBar,
    private contactService: ContactService,
    private router: Router,
    private route: ActivatedRoute
  ) {}
  identifier: any = "order_summary";
  Load: boolean = false;
  ngOnInit() {
    this.superAdmin = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).isSuperAdmin;

    this.fs = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).fn;
    this.ls = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).ln;
    this.emailid = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).email;
    this.or = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    )._orgName;
    this.useridd = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    )._id;
    this.mb = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).phn;
    this.custtype = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).isDealer;
    this.testTable();
  }

  refTable() {
    this.tabelObj.destroy();
    this.testTable();
    //this.tabelObj.draw();
  }
  getReport(ev) {
    console.log(ev);
  }

  // db st

  db_pop_selected_row_val(dt) {
    if (dt.product != "" && dt.selected.qt > 0) return false;
    else {
      return true;
    }
  }
  db_show_pp() {
    let that = this;
    that.tbl_product = [];
    that.db_address = {
      city: "",
      state: "",
      country: "",
      pincode: "",
      payment_status: "PAID",
      payment_reference: "",
      description: "",
    };
    that.db_pop = {
      product: "",
      selected: {
        price: 0,
        qt: 1,
      },
    };

    that.contactService.getProducts().subscribe((resp) => {
      that.product_list = resp;
      $("#show_exampleModal").click();
    });
  }
  db_remove(t, arr) {
    this.tbl_product = arr.reduce((a, b) => {
      if (b._id != t._id) a.push(b);
      return a;
    }, []);
  }
  db_edit(t, db_pop, arr) {
    let _t: any = JSON.parse(JSON.stringify(t));
    this.db_pop = {
      product: _t._id,
      selected: _t,
    };
    this.tbl_product = arr.reduce((a, b) => {
      if (b._id != _t._id) a.push(b);
      return a;
    }, []);
  }
  db_popup_submit(tbl_product: any, db_address: any) {
    let that = this;
    let user: any = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    );
    let gtotal = that.showttl(tbl_product) * 1.18;
    let obj: any = {
      user_id: user._id,
      first_name: user.fn,
      last_name: user.ln,
      email: user.email,
      phone: user.phn,
      amount: gtotal,
      payment_status: db_address.payment_status,
      purchased_on: new Date().toISOString(),
      CartData: _.chain(tbl_product)
        .map((dx: any) => {
          return {
            quantity: dx.qt,
            price: dx.price,
            _id: dx._id,
            product_id: dx.product_id,
            deviceName: dx.Product_name,
          };
        })
        .value(),
      shippingAddress: "",
      city: db_address.city,
      state: db_address.state,
      country: db_address.country,
      pin_code: db_address.pincode,
      description: db_address.description,
    };
    if (db_address.payment_status == "PAID") {
      obj.payment_reference = db_address.payment_reference;
    }
    this.contactService.sendReceipt(obj).subscribe((resp) => {
      $("#examplemodal_close").click();
      setTimeout(() => {
        that.refTable();
      }, 500);
    });
  }
  showttl(tbl) {
    return tbl.length > 0
      ? _.chain(tbl)
          .map((d) => {
            d.ttl = d.price * d.qt;
            return d;
          })
          .map("ttl")
          .sum()
          .value()
      : 0;
  }
  add_product_list(db_pop, tbl) {
    let dx: any = JSON.parse(JSON.stringify(db_pop));
    tbl.push(dx.selected);
    // this.db_pop = {
    //   selected: {
    //     price: 0,
    //   },
    // };

    this.db_pop = {
      product: "",
      selected: {
        price: 0,
        qt: 1,
      },
    };
  }
  db_popup_submit_val(tbl_product, db_address) {
    if (
      tbl_product.length > 0 &&
      db_address.payment_status == "PAID" &&
      db_address.payment_reference != ""
    ) {
      return false;
    } else if (
      tbl_product.length > 0 &&
      db_address.payment_status == "UNPAID"
    ) {
      db_address.payment_reference = "";
      return false;
    } else {
      return true;
    }
  }
  db_select_product(db_pop, product_list) {
    let selected = _.filter(product_list, { _id: db_pop.product });
    let old_qt: any = JSON.parse(JSON.stringify(db_pop));
    db_pop.selected = selected.length > 0 ? selected[0] : {};
    db_pop.selected.qt = old_qt.selected.qt;
    console.log("db_select_product=>", db_pop);
  }

  tabelObj: any;
  db_address: any = {
    city: "",
    state: "",
    country: "",
    pincode: "",
  };
  product_list: any = [];
  db_pop: any = {
    product: "",
    selected: {
      price: 0,
      qt: 1,
    },
  };
  tbl_product: any = [];
  // db nd
  fileDownload_blob(t) {
    const pdfUrl =
      this.contactService.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();
      });
  }
  markaspaid_202: any = {};
  db_markaspaid(value) {
    let that = this;
    console.log(value);
    console.log(this.markaspaid_202);
    this.markaspaid_202.payment_status = "PAID";
    this.markaspaid_202.payment_reference = value;
    this.contactService.db_editOrder(this.markaspaid_202).subscribe((resp) => {
      console.log("db_markaspaid resp=>", resp);
      that.markaspaid_202 = {};
      //that.tabelObj.draw();
      that.refTable();
      $("#l360").click();
    });
  }
  testTable() {
    const that = this;
    console.log("inside function");
    let user: any = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    );
    that.tabelObj = $("#deviceTable").DataTable({
      // dom: 'Bfrtip',
      // buttons: [
      //     'copy', 'csv', 'excel', 'pdf', 'print'
      // ]  ,
      processing: true,
      searching: true,
      pagingType: "full_numbers",
      pageLength: 25,
      serverSide: false,
      scrollY: "65vh",
      scrollCollapse: true,
      lengthMenu: [
        [10, 25, 50, -1],
        [10, 25, 50, "All"],
      ],
      ajax: (dataTablesParameters, callback) => {
        that.contactService.getOederSummary("?user_id=" + user._id).subscribe(
          (resp) => {
            that.Load = false;
            callback({ data: resp });

          },
          (err) => {
            that.Load = false;
            callback({ data: [] });
            console.log("error", err);
          }
        );
      },
      rowCallback: function (row: Node, data: any | Object, index: number) {
        $("#orderDetail", row).bind("click", () => {
          // console.log('ExpenseTypeDetail=>',et);
          console.log("orderDetail",data);

          let dialogRef = that.dialog.open(OrderDetailsComponent, {
            width: "900px",
            data: data
          });

          dialogRef.afterClosed().subscribe((result) => {
            if (result == "success") {
              console.log("success");
            }
          });
        });
        $("#db_fileDownload", row).bind("click", () => {
          that.fileDownload_blob(data);
        });
        $("#markaspaid", row).bind("click", () => {
          console.log("paid ==>", row, data, index);
          that.markaspaid_202 = data;
          $("#show_l314_markaspaid").click();
        });

        /*           $("#db_add_details", row).bind("click", () => {
            that.tbl_product = [];
            that.db_address = {};
            that.db_pop = {
              selected: {
                price: 0,
              },
            };

            that.contactService.getProducts().subscribe((resp) => {
              that.product_list = resp;
              $("#show_exampleModal").click();
            });
          }); */
      },

      columns: [
        {
          data: "order_id",
          render: function (data, type, row) {
            return data || "";
          },
        },

        {
          data: "buyer_first_name",
          visible: true,
          render: function (data, type, row) {
            var fn = data ? data : "";
            var ln = row.buyer_last_name ? row.buyer_last_name : "";
            return `<span class="text-nowrap"> ${fn} ${ln} </span><br>${row.phone}`;
          },
        },
        //   {
        //     "data": "buyer_last_name",
        //     "visible" : true,
        //     render: function(data, type, row) {
        //       return row.buyer_first_name?row.buyer_first_name:''+ " "+ data.buyer_last_name?data.buyer_last_name:data.buyer_last_name;
        //     }
        // },
        // {
        //   data: "phone",
        //   render: function (data, type, row) {
        //     return data ? data : "";
        //   },
        // },
        {
          data: "email",
          render: function (data, type, row) {
            return data ? data : "";
          },
        },
        {
          data: "purchased_on",
          render: function (data, type, row) {
            return `<span class="text-nowrap">${
              data ? moment(data).format("llll") : "--"
            }</span>`;
          },
        },
        {
          data: "amount",
          render: function (data, type, row) {
            if (data != undefined) {
              data = Number(data).toFixed(2);
            } else {
              data = "";
            }
            return `<span class="text-right">${data}</span>`;
          },
        },
        {
          data: "shippingAddress",
          defaultContent: "_id",
          render: function (data, type, row) {
            if (data == undefined) {
              return "";
            } else
              return (
                (data.city || "") +
                " " +
                (data.state || "") +
                " " +
                (data.country || "") +
                " " +
                (data.pincode || "")
              );
          },
        },
        {
          data: "status",
          defaultContent: "_id",
          render: function (data, type, row) {
            let temp = data ? data : "Processed";
            return `<span class="text-left">${temp} </span>`;
          },
        },
        {
          data: "CartData",
          defaultContent: "_id",
          render: function (data, type, row) {
            return '<i id="orderDetail" title="Order Detail" style="font-size:20px" class="fas fa-info w-100 text-center"></i>';
          },
        },
        {
          data: "filePath",
          defaultContent: "_id",
          render: function (data, type, row) {
            if (row.filePath != undefined)
              return '<u id="db_fileDownload" style="cursor: pointer" title="Download">  Download Invoice</u>';
            else return "";
          },
        },
        {
          data: "payment_status",
          // defaultContent: "_id",
          render: function (data, type, row) {
            if ("UNPAID" == row.payment_status) {
              return `${row.payment_status} <br> <u id="markaspaid">Mark as Paid</u>`;
            } else if ("PAID" == row.payment_status)
              return row.payment_status || "";
          },
        },
        {
          data: "payment_reference",
          // defaultContent: "_id",
          render: function (data, type, row) {
            return row.payment_reference || "";
          },
        },
        {
          data: "CourierName",
          // defaultContent: "_id",
          render: function (data, type, row) {
            return row.CourierName || "";
          },
        },
        {
          data: "TrackingId",
          // defaultContent: "_id",
          render: function (data, type, row) {
            return data || "";
          },
        },
        /* {
            data: "filePath",
            defaultContent: "_id",
            render: function (data, type, row) {
              if (row.filePath != undefined)
                return '<u id="db_fileDownload" style="cursor: pointer" title="Download">  Download Invoice</u>';
              else return "";
            },
          },
          {
            data: "filePath",
            defaultContent: "_id",
            render: function (data, type, row) {
              if (row.filePath != undefined)
                return '<u id="db_fileDownload" style="cursor: pointer" title="Download">  Download Invoice</u>';
              else return "";
            },
          }, */
        /* 
          <span>
              <u
                style="cursor: pointer"
                *ngIf="t.filePath != undefined"
                (click)="fileDownload_blob(t)"
              >
                Download invoice
              </u>
              <!-- <u *ngIf="t.filePath != undefined" (click)="fileDownload(t)">
                download invoice
              </u> -->
            </span>
             */
        // {
        //   defaultContent: "_id",
        //   render: function (data, type, row) {
        //     return '<i id="db_add_details" class="fas fa-plus-circle text-center text-success" title="Add Details" style="font-size:20px" ></i>';
        //   },
        // },
      ],
      columnDefs: [
        { className: "dt-body-left", targets: [0, 1, 2, 3] },
        { className: "dt-body-center", targets: [6] },
      ],
    });
  }
}
