import { Component, OnInit } from "@angular/core";
import { ContactService } from "../../contact.service";
import { of } from "rxjs/observable/of";
import {
  Router,
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
} from "@angular/router";
declare var $: any, _: any, moment: any;
declare var swal: any;
@Component({
  selector: "app-newissuelist",
  templateUrl: "./newissuelist.component.html",
  styleUrls: ["./newissuelist.component.scss"],
})
export class NewissuelistComponent implements OnInit {
  constructor(private cs: ContactService, private router: Router) {}
  db_all: any = false;
  popup2: any = {
    assigned_to: "",
    status: "Pending",
  };
  search: any = {};
  inventory: any = [];
  tabelObj: any;
  issueForm: any = {
    status: "Pending",
  };
  issueForm2: any = {
    reported_by: {
      phone: "",
      customerName: "",
      email: "",
    },
    vehicle_id: "",
    label: "",
    priority: "",
    status: "",
    due_date: "",
    description: "",
  };
  ngOnInit() {
    this.allDev();
    this.setAssignto();
    this.loadropdown("#inventory");
    this.loadropdown("#inventory2");
    this.testTable(this.search);
    this.getIssuesCountbyStatus();
  }
  phoneChange(issueForm: any) {
    let that = this;
    let token = JSON.parse(atob(localStorage.token.split(".")[1]));
    fetch(
      "https://www.oneqlik.in/users/searchUserByPhone?user=" +
        token._id +
        "&phone=" +
        issueForm.phone
    )
      .then((r) => r.json())
      .then((resp) => {
        if (
          resp.data.length > 0 &&
          resp.data[0].first_name != undefined &&
          resp.data[0].last_name != undefined
        ) {
          that.issueForm.customerName =
            resp.data[0].first_name + " " + resp.data[0].last_name;
          that.issueForm.email = resp.data[0].email;
          that.issueForm.reported_by = resp.data[0]._id;
        }
      });
  }
  selectAll(value, ev, data) {
    console.log(value, ev, data);
    if (ev.target.checked == true) {
      data = data.map((d) => {
        d.flag = true;
        return d;
      });
    } else if (ev.target.checked == false) {
      data = data.map((d) => {
        d.flag = false;
        return d;
      });
    }
  }
  singleSelect(row, data) {
    let dt = _.filter(data, (d: any) => {
      return d.flag == row.flag;
    });
    if (row.flag == false) {
      this.db_all = false;
    } else if (dt.length == data.length) {
      this.db_all = row.flag;
    }
  }

  save(data: any) {
    let that = this;
    let token = JSON.parse(atob(localStorage.token.split(".")[1]));
    let qr: any = JSON.parse(JSON.stringify(data));
    qr.vehicle_id = $("#inventory")
      .multipleSelect("getSelects", "value")[0]
      .split(":")[1]
      .replace(/'/g, "")
      .replace(/ /g, "");

    if (qr.phone == undefined || qr.phone == "") {
      swal("Enter Phone Number.");
      return;
    }
    if (qr.vehicle_id == undefined || qr.vehicle_id == "") {
      swal("Enter Vehicle ID Number.");
      return;
    }
    if (qr.label == undefined || qr.label == "") {
      swal("Select Type.");
      return;
    }
    if (qr.priority == undefined || qr.priority == "") {
      swal("Select Priority.");
      return;
    }
    if (qr.status == undefined || qr.status == "") {
      swal("Select Status.");
      return;
    }
    if (qr.due_date == undefined || qr.due_date == "") {
      swal("Select Due Date.");
      return;
    }
    qr.due_date = new Date(data.due_date).toISOString();

    qr.report_date = new Date().toISOString();
    // qr.reported_by = token._id;
    qr.assigned_to = token._id;
    // qr.vehicle_id = $("#inventory")
    //   .multipleSelect("getSelects", "value")[0]
    //   .split(":")[1]
    //   .replace(/'/g, "")
    //   .replace(/ /g, "");

    this.cs
      .db_post("https://www.oneqlik.in/Issue/addIssue", qr)
      .subscribe((resp) => {
        console.log(resp);
        this.testTable(this.search);
        // that.tabelObj.ajax.reload();
        $("#db_close").click();

        that.issueForm = {
          status: "pending",
        };
      });
  }
  _getIssuesCountbyStatus: any = {};
  getIssuesCountbyStatus() {
    let that = this;
    let token = JSON.parse(atob(localStorage.token.split(".")[1]));
    this.cs
      .db_ajax("https://www.oneqlik.in/Issue/getIssuesCountbyStatus", {
        assigned_to: token._id,
      })
      .subscribe((resp) => {
        console.log("getIssuesCountbyStatus=>", resp);
        this._getIssuesCountbyStatus = resp;
      });
  }

  allDev() {
    let that = this;
    let token = JSON.parse(atob(localStorage.token.split(".")[1]));
    fetch(
      "https://www.oneqlik.in/Device_inventory/getInventoryDropdown?user=" +
        token._id
    )
      .then((r) => r.json())
      .then((resp) => {
        console.log("getInventoryDropdown=>", resp);
        that.inventory = resp;
      });
  }
  loadropdown(id) {
    let that = this;

    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.componentIdentifier === 'notification_master')

    setTimeout(() => {
      $(id).multipleSelect({
        width: 394,
        placeholder: "Select IMEI",
        filter: true,
        single: true,
        selectAll: false,
      });
    }, 100);
  }
  popupOpen() {
    console.log("popupOpen");
    this.loadropdown("#inventory");
    $(document).on("change", "#inventory", function () {
      var value = $("#inventory").val();
      console.log(value);
    });
  }
  //https://www.oneqlik.in/Issue/getIssues?reported_by=61dbc06f1bafaf325c49a9a8
  add() {}
  testTableArr: any = [];
  testTable(srch: any) {
    const that = this;
    let qr = $.param(srch);
    let token = JSON.parse(atob(localStorage.token.split(".")[1]));
    fetch(
      "https://www.oneqlik.in/Issue/getIssues?assigned_to=" +
        token._id +
        "&" +
        qr
    )
      .then((r) => r.json())
      .then((resp) => {
        that.testTableArr = resp;
        that.getIssuesCountbyStatus();
      });
  }
  dt(i: any) {
    return moment(new Date(i.due_date)).format("DD-MM-YYYY");
  }
  db_popup_open() {
    $("#exampleModal_btn").click();

    $(".ms-parent").css("width", "369px");
  }
  statusChange(data) {
    $("#open_statusUpdate").click();
  }
  __statusUpdate(pp2, temp_statusUpdate) {
    console.log("temp_statusUpdate=>", temp_statusUpdate);
    let that = this;
    let qrArr = temp_statusUpdate
      .filter((d) => d.flag == true)
      .map((d: any) => {
        return { _id: d._id, status: pp2.status };
      });
    this.cs
      .db_ajax("https://www.oneqlik.in/Issue/setStatusMultiple", qrArr)
      .subscribe((resp) => {
        $("#close__statusUpdate").click();
        this.db_all = false;
        swal({
          position: "top-end",
          icon: "success",
          title: "Updated Status Successfully",
          showConfirmButton: false,
          timer: 1000,
        });
        that.testTable(this.search);
      });
    console.log("pp2=>", pp2);
  }
  change(srch: any) {
    console.log(srch);
  }
  convertJSONtoCSV(data: any) {
    let data2 = data.map((dtdt: any) => {
      let t: any = {};
      t["Name"] =
        dtdt.reported_by.first_name + " " + dtdt.reported_by.last_name;
      t["Phone"] = dtdt.reported_by.phone;
      t["Email"] = dtdt.reported_by.email;
      t["Priority"] = dtdt.priority;
      t["Technician"] =
        dtdt.assigned_to.first_name + " " + dtdt.assigned_to.last_name;
      t["Status"] = dtdt.status;
      t["Type"] = dtdt.label;
      t["Due"] = this.dt(dtdt);
      t["IMEI"] = dtdt.vehicle_id;
      t["Description"] = dtdt.description;
      return t;
    });
    const csvData = this.convertJSONToCSVString(data2);

    // Create Blob
    const blob = new Blob([csvData], { type: "text/csv" });

    // Create download link
    const link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = "data.csv";

    // Append link to body and trigger download
    document.body.appendChild(link);
    link.click();

    // Clean up
    document.body.removeChild(link);
  }

  convertJSONToCSVString(jsonData) {
    const csvRows = [];

    // Extract header row
    const headers = Object.keys(jsonData[0]);
    csvRows.push(headers.join(","));

    // Extract data rows
    for (const row of jsonData) {
      const values = headers.map((header) => {
        const escaped = ("" + row[header]).replace(/"/g, '\\"');
        return `"${escaped}"`;
      });
      csvRows.push(values.join(","));
    }

    return csvRows.join("\n");
  }
  check_double(_testTableArr: any) {
    let flag: any = false;
    if (_.filter(_testTableArr, { flag: true }).length > 0) {
      flag = true;
    }
    return flag;
  }
  logout() {
    window.localStorage.clear();
    this.router.navigateByUrl("login");
  }
  assigntoList: any = [];
  assignto(dt: any) {
    debugger;
    let that = this;
    //that.assigntoList = [];
    let token = JSON.parse(atob(localStorage.token.split(".")[1]));
    // fetch(
    //   "https://www.oneqlik.in/users/getTechnician?uid=" +
    //     token.organisation +
    //     "&pageNo=1&size=9999999"
    // )
    //   .then((r) => r.json())
    //   .then((resp) => {
    //     that.assigntoList = resp;
    //     that.popup2 = dt;
    //     that.popup2.assigned_to = dt.assigned_to._id;
    //   });
    that.popup2 = dt;
    that.popup2.assigned_to = dt.assigned_to._id;
    $("#assigntopopup_id").click();
  }
  setAssignto() {
    let that = this;
    let token = JSON.parse(atob(localStorage.token.split(".")[1]));
    fetch(
      "https://www.oneqlik.in/users/getTechnician?uid=" +
        token.organisation +
        "&pageNo=1&size=9999999"
    )
      .then((r) => r.json())
      .then((resp) => {
        that.assigntoList = resp;
      });
  }
  assigntopopup_save(data) {
    let that = this;
    this.cs
      .db_ajax("https://www.oneqlik.in/Issue/updateIssue", {
        _id: data._id,
        assigned_to: data.assigned_to,
        status: data.status,
      })
      .subscribe((resp) => {
        this.db_all = false;
        $("#assigntopopup_close").click();
        swal({
          position: "top-end",
          icon: "success",
          title: "Updated Status Successfully",
          showConfirmButton: false,
          timer: 1000,
        });
        that.testTable(this.search);
      });
  }
  rowEdit(dt: any) {
    let that = this;
    // that.assigntoList = [];
    $(".ms-parent").css("width", "369px");
    let token = JSON.parse(atob(localStorage.token.split(".")[1]));
    /*     fetch(
      "https://www.oneqlik.in/users/getTechnician?uid=" +
        token.organisation +
        "&pageNo=1&size=9999999"
    )
      .then((r) => r.json())
      .then((resp) => {
        that.assigntoList = resp;
      }); */
    this.issueForm2 = JSON.parse(JSON.stringify(dt));
    this.issueForm2.reported_by.customerName =
      (this.issueForm2.reported_by.first_name || "") +
      " " +
      (this.issueForm2.reported_by.last_name || "");

    this.issueForm2.due_date = moment(
      new Date(this.issueForm2.due_date)
    ).format("YYYY-MM-DD");
    this.loadropdown("#inventory2");
    // $(document).on("change", "#inventory2", function () {
    //   var value = $("#inventory2").val();
    //   console.log(value);
    // });
    $("#inventory2").multipleSelect("setSelects", [this.issueForm2.vehicle_id]);

    this.issueForm = dt;
    $("#editpopup_id").click();
  }
  f_editpopup_save(data: any) {
    let that = this;
    let vehicle_id = $("#inventory2").multipleSelect("getSelects", "value")[0];
    this.cs
      .db_ajax(
        "https://www.oneqlik.in/Issue/updateIssue",

        {
          _id: data._id,
          vehicle_id: vehicle_id,
          report_date: new Date().toISOString(),
          due_date: new Date(data.due_date).toISOString(),
          // summary: "device issue",
          description: data.description,
          label: data.label,
          reported_by: data.reported_by._id,
          priority: data.priority,
          assigned_to: data.assigned_to,
          status: data.status,
        }
      )

      .subscribe((resp) => {
        this.db_all = false;
        $("#close__statusUpdate2").click();
        swal({
          position: "top-end",
          icon: "success",
          title: "Updated Successfully",
          showConfirmButton: false,
          timer: 1000,
        });
        that.testTable(this.search);
      });
  }
}
