import { ChangeDetectorRef, Component, OnInit, ViewChild } from "@angular/core";
import { Contact } from "../../contact";

import { MdSnackBar } from "@angular/material";
// import {Md5} from 'ts-md5/dist/md5';
import {
  Router,
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
} from "@angular/router";
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from "@angular/material";

import { Subject } from "rxjs/Subject";
import "rxjs/add/operator/debounceTime";
import { ContactService } from "../../contact.service";
import { FlashMessagesService } from "angular2-flash-messages";
import { DeviceDocComponent } from "../device-doc/device-doc.component";
import { ReportService } from "../../report/report.service";
import { NormalCertComponent } from "../../device/normal-cert/normal-cert.component";
import { CertOptionComponent } from "../../device/cert-option/cert-option.component";
import { EditDeviceMasterComponent } from "../../device/edit-device-master/edit-device-master.component";
declare var swal: any, _: any;
import * as moment from "moment";
import { environment } from "../../../environments/environment";
import { RenewalDocumentsComponent } from "../../renewal-documents/renewal-documents.component";

@Component({
  selector: "app-device-kyc",
  templateUrl: "./device-kyc.component.html",
  styleUrls: ["./device-kyc.component.scss"],
})
export class DeviceKYCComponent implements OnInit {
  modelChanged: Subject<string> = new Subject<string>();
  status;
  pageLengthArr = [10, 25, 50, 100, 200, 500, "All"];
  state;
  sort: any = "created_on";
  dbexp:any={};
  renewal_details:any={}
  kycStatus = [
    { Name: "Approved", value: "Approved" },
    { Name: "Reject", value: "Reject" },
    { Name: "Pending", value: "Pending" },
  ];
  dealerChk: boolean = false;
  ev: any;
  show1: boolean = false;
  show2: boolean = true;
  show3: boolean = false;
  first_name: any;
  logoutbut: boolean;
  last_name: any;
  passwordd: any;
  org_name: any;
  allUser: boolean = false;
  emaill: any;
  phone: any;
  executed: any;
  $event2: any;
  dealer: any;
  contacts: Contact[] = [];
  contact: Contact;
  login1: any;
  mess2: any;
  mess: any;
  otp: any;
  switchVal: any;
  str: boolean = false;
  password2: any;
  cust_load: any;
  errmsg: boolean = true;
  serviceResponse: string;
  errorMsg: boolean;
  showNav: boolean = false;
  url: any;
  dealer_Permission: any;
  adbtn: string;
  myInput: string;

  before: any;
  emmnerr: any;
  Load: any;
  isTag: boolean = false;
  $event: any;
  Indianstate = [
    "Andhra Pradesh",
    "Arunachal Pradesh",
    "Assam",
    "Bihar",
    "Chhattisgarh",
    "Goa",
    "Gujarat",
    "Haryana",
    "Himachal Pradesh",
    "Jammu and Kashmir",
    "Jharkhand",
    "Karnataka",
    "Kerala",
    "Madhya Pradesh",
    "Maharashtra",
    "Manipur",
    "Meghalaya",
    "Mizoram",
    "Nagaland",
    "Odisha",
    "Punjab",
    "Rajasthan",
    "Sikkim",
    "Tamil Nadu",
    "Telangana",
    "Tripura",
    "Uttarakhand",
    "Uttar Pradesh",
    "West Bengal",
    "Andaman and Nicobar Islands",
    "Chandigarh",
    "Dadra and Nagar Haveli",
    "Daman and Diu",
    "Delhi",
    "Lakshadweep",
    "Puducherry",
  ];
  organisation: any;
  allCustomerData: any=[];
  constructor(
    private contactService: ContactService,
    public snackBar: MdSnackBar,
    private router: Router,
    private _flashMessagesService: FlashMessagesService,
    public dialog: MdDialog,
    private reportService: ReportService,
    private cdr: ChangeDetectorRef
  ) {
    this.reportService.deviceExcel.subscribe((value) => {
      if (value) {
        this.downloadExcel();
      }
    });
    this.modelChanged
      .debounceTime(1000) // wait 300ms after the last event before emitting last event
      .distinctUntilChanged() // only emit if value is different from previous value
      .subscribe((myInput) => {
        this.myInput = myInput;
        console.log("myInput");
        // this.dealerDetail();

        this.ngOnInit();
      });

    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);
  }

  data_descip: any;
  table1ch() {
    myFunction();
    function myFunction() {
      var input, filter, table, tr, td, i, td1;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("myTable");
      tr = table.getElementsByTagName("tr");
      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[1];
        td1 = tr[i].getElementsByTagName("td")[0];
        if (td) {
          if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
          } else if (td1.innerHTML.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
          } else {
            tr[i].style.display = "none";
          }
        }
      }
    }
  }
  searchFilter(text: string) {
    this.modelChanged.next(text);
    // this.myInput;
    // console.log(this.myInput);
    // this.sidebarData()
  }
  tost1(divid) {
    if (divid == "EmM") {
      this.data_descip = this.emmnerr.split(":")[1];
      launch_toast();
    } else if (divid == "succ") {
      this.data_descip = "Custumer Successfully Added";
      launch_toast();
    } else if (divid == "reportPref") {
      this.data_descip = "Report Preference updated !!!";
      launch_toast();
    } else if (divid == "password_changed") {
      this.data_descip = "Password updated !!!";
      launch_toast();
    } else if (divid == "alertset") {
      this.data_descip = "Alert preference updated !!!";
      launch_toast();
    } else if (divid == "kyc") {
      this.data_descip = "KYC Status updated !!!";
      launch_toast();
    }
    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);
    }
  }

  changeStatus(ev) {
    console.log(ev);
    this.getCustomer();
  }
  changesort(ev) {
    this.getCustomer();
  }

  valclear() {
    this._flashMessagesService.show("Cleared", {
      cssClass: "alert-warning",
      timeout: 2000,
    });
  }

  click1(event) {
    this.show2 = false;
    this.show3 = true;
    if (
      (event.keyCode >= 48 && event.keyCode <= 57) ||
      event.keyCode == 9 ||
      event.keyCode == 8 ||
      event.keyCode == 46 ||
      event.keyCode == 37 ||
      event.keyCode == 39
    ) {
    } else event.preventDefault();
    /* if(event.keyCode===13){
    this.otp_window();
    } */
  }
  click2(event2) {
    this.show2 = true;
    this.show3 = false;
  }
  call(e) {
    {
      if (e.keyCode == 32) {
        e.preventDefault();
      }
    }
  }
  geo() {
    this.router.navigateByUrl("geofencing");
  }
  devicess: any;
  final: any;

  cond: Boolean = false;
  point: any = 0;
  aa() {
    // console.log(this.point);
    if (this.point == 0) {
      this.cond = true;
      this.point++;
    } else if (this.point % 2 == 0) {
      this.cond = true;
      this.point++;
    } else {
      this.cond = false;
      this.point++;
    }
  }
  run() {}

  devicesss: any;
  subscription: any;
  timer: any;
  messageSuccess: any = true;
  selectedlanguage: any;

  fs: any;
  ls: any;
  emailid: any;
  or: any;
  useridd: any;
  custtype: any;
  custumer: any = [];
  mb: any;
  cust: boolean = false;
  logo: any;
  text: any;
  superAdmin: Boolean = false;
  customer_role:Boolean= false;
stateflag:Boolean=false;
userState:any='';
  ngOnInit() {
    this.superAdmin = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).isSuperAdmin;
  

    console.log("whatishere=>", this.superAdmin);
    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])
    ).supAdmin;
    this.mb = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).phn;
    let test = JSON.parse(window.atob(window.localStorage.token.split(".")[1]));
    this.dealer_Permission = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).cust_add_permission;
    this.organisation = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).organisation;
    // console.log(test);
    let userRole = JSON.parse(
      atob(window.localStorage.token.split(".")[1])
    ).customer_role;
    this.isTag = userRole == "tag" ? true : false;

    this.custtype = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).isDealer;
    this.adbtn = localStorage.getItem("dlrchk");
    localStorage.setItem("dlrchk", this.custtype);
    //  this.getdev();
    if (this.custtype == true) {
      this.cust = true;
    }
    if (this.mb.charAt(0) == "n") {
      this.mb = " ";
    }
    if (window.localStorage["Custumer"] == "ON") {
      this.logoutbut = false;
      this.dealer = true;
    } else {
      this.logoutbut = true;
    }

    this.logo = window.localStorage["logo"];
    this.text = window.localStorage["text"];

    history.pushState(null, null, document.URL);
    window.addEventListener("popstate", function () {
      history.pushState(null, null, document.URL);
    });

    this.logo = window.localStorage["logo"];
    this.text = window.localStorage["text"];
    // this.getSupAdmin();
   let id=JSON.parse(
    atob(window.localStorage.token.split(".")[1])
  )._id;
    this.contactService
    .get("/users/shareProfileImage?uid=" + id)
    .subscribe((res: any) => {
      this.userState=res.state ? res.state :'';
      console.log('Updated userState:', this.userState);
      if(userRole== 'tag' || userRole == 'kycApproval'){
        debugger
        this.customer_role=true;
        this.cdr.detectChanges();
        if(this.userState !== 'all'){
          this.state=this.userState;
          this.getCustomer();
          this.getDeviceCount();
        }
        else{
          this.stateflag=true
          this.getSupAdmin();
          
        }
      }
   
    });
    
  }

  getSupAdmin() {
    if (this.useridd == undefined) {
      this.getCustomer();
      this.getDeviceCount();
    } else if (this.useridd != undefined) {
      this.contactService
        .get("/users/shareProfileImage?uid=" + this.useridd)
        .subscribe((res: any) => {
          this.emailid = res.email;
          this.getCustomer();
          this.getDeviceCount();
        });
    }
  }

  callDataTable() {
    debugger
    this.skip = 0;
    // that.limit = len;
    this.getCustomer();
  }
  editDevice(data) {
    localStorage.setItem("deviceData", JSON.stringify(data));
    localStorage.setItem("KycApprovalRedirect", "true");
    if (location.href.match(/nipponsecura.in/g) != null) {
      this.router.navigate(["/db_editDevice"]);
    } else if (location.href.match(/nipponsecura.in/g) == null) {
      this.router.navigate(["/editDevice"]);
    }
    //this.router.navigate(["/editDevice"]);
    // this.router.navigate(["/db_editDevice"]);
  }
  get_with_address(qr: any) {
    let that = this;
    return new Promise((a, b) => {
      this.contactService.get(qr).subscribe((resp: any) => {
        if (resp == undefined) {
          resp = [];
 
        }
        if (resp.length == 0) {
          a(resp);
     
        } else {
          let all_points = _.chain(resp)
            .map((d) => {
              if (d.last_location == undefined) {
                d.last_location = { lat: 0, long: 0 };
              }
              return d;
              //last_location: {lat: 22.632629, long: 88.300888}
            })
            .map("last_location")
            .filter(Boolean)
            .value();

          that.contactService
            .getAddressByApiBulk(all_points)
            .subscribe((latLongAddress) => {
              let arr_resp = (Array.isArray(resp) ? resp : [resp || []]).map(
                (d: any, i) => {
                  d.lastAddress = latLongAddress[i].address;
                  return d;
                }
              );
              a(arr_resp);
            });
        }
      });
    });
  }
  isLoading: boolean = false; 
  db_getData(arr, num, cb) {
    let that = this;
    let qr = this.db_get_qr(num);
    // if(num>=10){
    //   cb(_.flatten(arr));
    //   return
    // }
    this.get_with_address(qr).then((resp: any) => {
      if (resp.length == 0) {
        console.log("done", resp);
        cb(_.flatten(arr));
     
      } else {
        arr.push(resp);
        num = num + 1;
        that.db_getData(arr, num, cb);
      }
    },(error:any)=>{
      cb(_.flatten(arr));
      console.log("err",error)
    });
    //  this.contactService.get(qr).subscribe((resp) => {
    //   if (resp.length == 0) {
    //     cb(_.flatten(arr));
    //     // $("#loader").hide();
    //   } else {
    //     let all_points = _.chain(resp)
    //       .map((d) => {
    //         if (d.last_location == undefined) {
    //           d.last_location = { lat: 0, long: 0 };
    //         }
    //         return d;
    //         //last_location: {lat: 22.632629, long: 88.300888}
    //       })
    //       .map("last_location")
    //       .filter(Boolean)
    //       .value();

    //     that.contactService
    //       .getAddressByApiBulk(all_points)
    //       .subscribe((latLongAddress) => {
    //         let arr_resp = resp.map((d, i) => {
    //           d.lastAddress = latLongAddress[i].address;
    //           return d;
    //         });
    //         arr.push(arr_resp);
    //         num = num + 1;
    //         that.db_getData(arr, num, cb);
    //       });
    //   }
    // }); 
  }

  db_get_qr(skip) {
    var url =
      "/devices/getAllVehi?id=" +
      this.organisation +
      "&skip=" +
      skip +
      "&limit=500";
    if (this.myInput) {
      url = url + "&search=" + this.myInput;
      console.log(this.myInput, url);
    }
    if (this.status) {
      url = url + "&status=" + this.status;
    }

    if (this.state) {
      url = url + "&state=" + this.state;
    }
    return url;
  }
  getCustomer() {
    let that = this;
    this.Load = true;
    var url =
      "/devices/getAllVehi?id=" +
      this.organisation +
      "&skip=" +
      this.skip +
      "&limit=" +
      this.limit;
    if (this.myInput) {
      url = url + "&search=" + this.myInput;
      console.log(this.myInput, url);
    }
    if (this.status) {
      url = url + "&status=" + this.status;
    }
    // else{
    //    url="/devices/getAllVehi?id="+this.organisation+"&skip="+this.skip+'&limit='+this.limit

    //  }
    if (this.state) {
      url = url + "&state=" + this.state;
    }
    var group, statuss, dateObj, DealerID, status1;
    //  this.contactService.getAllVehi()
    let l: any = this.limit;
    if (l == "All") {
      $("#loader").show();
      // $("#loading").css({ visibility: "visible" });
      this.nextButton = false;
      this.previewButton = false;
      this.db_getData([], 0, (data) => {
        // console.log("alldata=>", data);
        this.Load = false;
        //  this.custumer = data;
        
        this.allCustomerData=data;
         $("#loader").hide();
        // this.downloadExcelForAll(data);
        // $("#loading").css({ visibility: "hidden" });
        

      });
    } else {
      this.get_with_address(url + "&sortBy=" + this.sort).then((resp: any) => {
        this.Load = false;
        this.custumer = [];
        if (resp.length == 0) {
          this.nextButton = true;
          this.previewButton = false;
        } else {
          that.custumer = resp;
        }
      });
    }
  }

  skip: number = 0;
  limit: number = 25;
  nextButton: boolean = false;
  previewButton: boolean = true;
  next() {
    this.previewButton = false;
    this.skip += 1;
    this.ngOnInit();
    // this.sidebarData();
  }
  pre() {
    console.log(this.skip);
    if (this.skip > 0) {
      this.skip -= 1;
      this.previewButton = false;
      this.nextButton = false;
      this.ngOnInit();
      // this.sidebarData();
    } else {
      this.previewButton = true;
      this.nextButton = false;
    }
  }

  custPhone(dlr) {
    var dphn = "";
    if (dlr.std_code != undefined) {
      dphn = "+" + dlr.std_code.dialcode + " " + dlr.phone;
      return dphn;
    } else {
      dphn = dlr.phone;
      return dphn;
    }
  }

  allUserFunction(ev) {
    console.log("event=>", ev);
    this.allUser = ev.checked;

    this.skip = 1;
    this.getCustomer();
  }

  changeKYC(data, event) {
    console.log(event);
    var req = {
      user: data._id,
      status: event,
    };
    this.contactService.changeKycStatus(req).subscribe((res) => {
      console.log(res);
      this.tost1("kyc");
    });
  }

  tab: any;

  downloadExcel() {
 
    this.Load = true;
    // this.contactService.get('/users/getCustomer?uid='+this.useridd).subscribe(
    //   (data:any) => {
    //     this.Load = false;
    //    var custumer=[];
    //     custumer = data;
let l: any = this.limit;
    if( l == "All"){
     this.downloadExcelForAll(this.allCustomerData)
    }
    else{
      for (var i = 0; i < this.custumer.length; i++) {
        if (this.custumer[i].user == undefined || this.custumer[i].user == null) {
          this.custumer[i].user = {};
        }
        this.custumer[i].state_certifcate_date = "";
        this.custumer[i].custodian_name =
          this.custumer[i].customerType == "Firm"
            ? this.custumer[i].user.last_name || ""
            : "";
        i;
  
        this.custumer[i].device_Type_csv =
          this.custumer[i].device_model &&
          this.custumer[i].device_model.device_type
            ? this.custumer[i].device_model.device_type
            : "";
        if (
          this.custumer[i].user != undefined &&
          this.custumer[i].user.city != undefined
        ) {
          this.custumer[i].user_city = this.custumer[i].user.city;
        } else {
          this.custumer[i].user_city = "-";
        }
        if (
          this.custumer[i].user != undefined &&
          this.custumer[i].user.state != undefined
        ) {
          this.custumer[i].user_state = this.custumer[i].user.state;
        } else {
          this.custumer[i].user_state = "-";
        }
        if (this.custumer[i].imageDoc.length > 0) {
          debugger
          if (this.custumer[i].customerType == "Firm") {
            this.custumer[i].DocName = this.custumer[i].imageDoc[1].drop_type;
            this.custumer[i].DocName2 = this.custumer[i].imageDoc[0].drop_type;
          } else if (this.custumer[i].customerType == "Individual") {
            this.custumer[i].DocName = this.custumer[i].imageDoc[1].doctype_type;
            this.custumer[i].DocName2 = this.custumer[i].imageDoc[0].doctype_type;
          }
           
  
          
          this.custumer[i].adharNumber2 =this.custumer[i].imageDoc[0].phone || "";
          this.custumer[i].adharNumber = this.custumer[i].imageDoc[1].phone || "";
        }
  
        // if (this.custumer[i].imageDoc && this.custumer[i].imageDoc.length) {
        //   let findData = this.custumer[i].imageDoc.find(
        //     (dImageDoc) => dImageDoc.doctype == "Adhar card1 *"
        //   );
        //   if (findData) {
        //     this.custumer[i].DocName = "Aadhar Card";
        //     this.custumer[i].adharNumber = findData.phone
        //       ? findData.phone.replaceAll("-", "")
        //       : "-";
        //   }
        // }
        let lastName =
          this.custumer[i].user && this.custumer[i].user.last_name
            ? this.custumer[i].user.last_name
            : "";
      
        this.custumer[i].Dphone = "-";
        this.custumer[i].kycApprovalDateOnly = moment(
          this.custumer[i].kycApprovalDate
        ).format("DD/MM/YYYY");
        this.custumer[i].fuelType = this.custumer[i].fuelType || "-";
        this.custumer[i].stateServer = "-";
        this.custumer[i].email =
          this.custumer[i].user && this.custumer[i].user.email
            ? this.custumer[i].user.email
            : "";
        this.custumer[i].Dealer_full_name =
          (this.custumer[i] &&
          this.custumer[i].Dealer &&
          this.custumer[i].Dealer.first_name
            ? this.custumer[i].Dealer.first_name
            : "") +
          " " +
          (this.custumer[i] &&
          this.custumer[i].Dealer &&
          this.custumer[i].Dealer.last_name
            ? this.custumer[i].Dealer.last_name
            : "");
        //this.custumer[i].Dealer_full_name = (this.custumer[i].Dealer.first_name ? this.custumer[i].Dealer.first_name : '') + ' ' +(this.custumer[i].Dealer.last_name ? this.custumer[i].Dealer.last_name : '');
        // this.custumer[i].email=this.custumer[i].user.email?this.custumer[i].user.email:''
        this.custumer[i].user_id =
          this.custumer[i].user && this.custumer[i].user.user_id
            ? this.custumer[i].user.user_id
            : "";
        this.custumer[i].pin =
          this.custumer[i].user && this.custumer[i].user.pin
            ? this.custumer[i].user.pin
            : "";
        this.custumer[i].phone =
          this.custumer[i].user && this.custumer[i].user.phone
            ? this.custumer[i].user.phone
            : "";
        this.custumer[i].address =
          this.custumer[i].user && this.custumer[i].user.address
            ? this.custumer[i].user.address
            : "";
        this.custumer[i].fullName =
          this.custumer[i].user && this.custumer[i].user.first_name
            ? this.custumer[i].user.first_name
            : "";
  
        if (i == this.custumer.length - 1) {
          this.downloadFile(this.custumer);
        }
      }
    }
  
    //   console.log("custDetail=>", custumer);
    // }, err => {
    // console.log("errlog");
    this.Load = false;
    // custumer=[];
    // this.nextButton = true;
    // this.previewButton = false;
    // });

    //  for(var i=0;i<this.custumer.length;i++){
    //   // this.custumer[i].user.fullName=this.custumer[i].first_name?this.custumer[i].first_name:''+" "+this.custumer[i].last_name?this.custumer[i].last_name:'';
    //  }
  }
  downloadExcelForAll(customer) {

    this.Load = true;
    this.isLoading=true;
    // $("#loader").show();
    for (var i = 0; i < customer.length; i++) {
      if (customer[i].user == undefined || customer[i].user == null) {
        customer[i].user = {};
      }
      customer[i].state_certifcate_date = "";
      customer[i].custodian_name =
        customer[i].customerType == "Firm"
          ? customer[i].user.last_name || ""
          : "";
      i;

      customer[i].device_Type_csv =
        customer[i].device_model &&
        customer[i].device_model.device_type
          ? customer[i].device_model.device_type
          : "";
      if (
        customer[i].user != undefined &&
        customer[i].user.city != undefined
      ) {
        customer[i].user_city = customer[i].user.city;
      } else {
        customer[i].user_city = "-";
      }
      if (
        customer[i].user != undefined &&
        customer[i].user.state != undefined
      ) {
        customer[i].user_state = customer[i].user.state;
      } else {
        customer[i].user_state = "-";
      }
      if (customer[i].imageDoc && customer[i].imageDoc.length > 0) {
             if(customer[i].Device_ID==866477067513450){

             }
      
        // Initialize variables with defaults
        let doc1 = customer[i].imageDoc[1] || {}; // Second element or empty object
        let doc0 = customer[i].imageDoc[0] || {}; // First element or empty object
      
        if (customer[i].customerType === "Firm") {

          customer[i].DocName = doc1.drop_type || '-';
          customer[i].DocName2 = doc0.drop_type || '-';
        } else if (customer[i].customerType === "Individual") {
          if (!doc1.doctype_type ) {
            console.log("customer=>", customer[i]);
          }
          customer[i].DocName = doc1.doctype_type || '-';
          customer[i].DocName2 = doc0.doctype_type || '-';
        }
       else
        if(customer[i].customerType === "NotSpecified"){
             customer[i].DocName = doc1.doctype || '-';
             customer[i].DocName2 = doc0.doctype || '-'
        }
      
        customer[i].adharNumber2 = doc0.phone || "";
        customer[i].adharNumber = doc1.phone || "";
      }  
      

      // if (customer[i].imageDoc && customer[i].imageDoc.length) {
      //   let findData = customer[i].imageDoc.find(
      //     (dImageDoc) => dImageDoc.doctype == "Adhar card1 *"
      //   );
      //   if (findData) {
      //     customer[i].DocName = "Aadhar Card";
      //     customer[i].adharNumber = findData.phone
      //       ? findData.phone.replaceAll("-", "")
      //       : "-";
      //   }
      // }
      let lastName =
        customer[i].user && customer[i].user.last_name
          ? customer[i].user.last_name
          : "";
      console.log(lastName);
      customer[i].Dphone = "-";
      customer[i].kycApprovalDateOnly = moment(
        customer[i].kycApprovalDate
      ).format("DD/MM/YYYY");
      customer[i].fuelType = customer[i].fuelType || "-";
      customer[i].stateServer = "-";
      customer[i].email =
        customer[i].user && customer[i].user.email
          ? customer[i].user.email
          : "";
      customer[i].Dealer_full_name =
        (customer[i] &&
        customer[i].Dealer &&
        customer[i].Dealer.first_name
          ? customer[i].Dealer.first_name
          : "") +
        " " +
        (customer[i] &&
        customer[i].Dealer &&
        customer[i].Dealer.last_name
          ? customer[i].Dealer.last_name
          : "");
      //customer[i].Dealer_full_name = (customer[i].Dealer.first_name ? customer[i].Dealer.first_name : '') + ' ' +(customer[i].Dealer.last_name ? customer[i].Dealer.last_name : '');
      // customer[i].email=customer[i].user.email?customer[i].user.email:''
      customer[i].user_id =
        customer[i].user && customer[i].user.user_id
          ? customer[i].user.user_id
          : "";
      customer[i].pin =
        customer[i].user && customer[i].user.pin
          ? customer[i].user.pin
          : "";
      customer[i].phone =
        customer[i].user && customer[i].user.phone
          ? customer[i].user.phone
          : "";
      customer[i].address =
        customer[i].user && customer[i].user.address
          ? customer[i].user.address
          : "";
      customer[i].fullName =
        customer[i].user && customer[i].user.first_name
          ? customer[i].user.first_name
          : "";

      if (i == customer.length - 1) {
        this.downloadFile(customer);
      }
    }
      // console.log("custDetail=>", customer);
    // }, err => {
    // console.log("errlog");
    this.Load = false;  
    this.isLoading=false;
    // $("#loader").hide();
    this.allCustomerData=[]
    // custumer=[];
    // this.nextButton = true;
    // this.previewButton = false;
    // });

    //  for(var i=0;i<customer.length;i++){
    //   // customer[i].user.fullName=customer[i].first_name?customer[i].first_name:''+" "+customer[i].last_name?customer[i].last_name:'';
    //  }
  }
  
  downloadFile(data) {
  
    let newHeaders = [
      "IMEI NO.",
      "KYC Approve Date",
      "DEVICE ID",
      "Device Model",
      "ICCID NO.",
      "SIM 1",
      "SIM 2",
      "Profile",
      "Plan",
      "Dealership- Distributor Name",
      "D. Mobile",
      "Customer Type", // new customerType
      "ID Proof Document",
      "ID NO",
      "Customer Name",
      "Custodian Name", //new
      "Concern Person Name",
      "Mobile No",
      "MAKE BY",
      "Model",
      "Chassis No",
      "Engine No",
      "Fuel Type",
      "Vehicle No.",
      "Mfd Year", //  mfdyear
      "Vehicle Category", // vehicleCategory
      "CITY",
      "State",
      "PIN",
      "RTO STATE",
      "RTO NAME",
      "STATE SERVER",
      "State certificate Generation Date",
      "Address Proof Document",
      "Address ProofDocument No.",
      "ADDRESS",
      "Status"
      
    ];
    let arrHeader = [
      "Device_ID", //"IMEI NO."
      "kycApprovalDateOnly", // "KYC Approve Date",
      "vahanID", //"DEVICE ID",
      "device_Type_csv", //  "Device Model",
      "IccidNo", // "ICCID NO.",
      "m2mprovider",
      "sim_number", // "SIM 1",
      "sim_number2", //   "SIM 2",
      "sim_provider", // "Profile",
      "License", // "Plan",
      "Dealer_full_name", //  "Dealership- Distributor Name",
      "CID_No", //    "D. Mobile",
      "customerType", //"Customer Type"
      "DocName2",
      "adharNumber2",
      "fullName",
      "custodian_name",
      //"ConcernPersonName",
      "phone",
      "manufacturingCompany",
      "Model",
      "ChassisNo",
      "engineNo",
      "fuelType",
      "Device_Name",
      "manufacturingYear",
      "vehicleCategory",
      "user_city",
      "user_state",
      "pin",
      "transportOfficeState",
      "rto",
      "stateServer",
      "state_certifcate_date",
      "DocName",
      "adharNumber",
      "address",
      "kycStatus"    
];
    let arrHeaderOld = [
      "fullName",
      "email",
      "phone",
      "user_id",
      "kycStatus",
      "Device_Name",
      "Device_ID",
      "esim_validity",
      "remark",
      "RtoState",
      "RtoCity",
    ];
    let csvData = this.ConvertToCSV(data, arrHeader);
    console.log('csvData=>',csvData)
    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", "Customer List.csv");
    dwldLink.style.visibility = "hidden";
    document.body.appendChild(dwldLink);
    dwldLink.click();
    document.body.removeChild(dwldLink);
    this.Load = false;
  }
  ConvertToCSV(objArray, headerList) {
  
    let array = typeof objArray != "object" ? JSON.parse(objArray) : objArray;
    // console.log(array,"<===");Distance	126.94
    // Running	2:1
    // Idle	1:56
    // Stop


    let str = "Customer List \r\n";
    let row = "S.No,";

    let newHeaders = [
      "IMEI NO.",
      "KYC Approve Date",
      "DEVICE ID",
      "Device Model",
      "ICCID NO.",
      "M2M provider",
      "SIM 1",
      "SIM 2",
      "Profile",
      "Plan",
      "Dealership- Distributor Name",
      "D. Mobile",
      "Customer Type", // new customerType
      "ID Proof Document",
      "ID NO",
      "Customer Name",
      "Custodian Name", //new
      //"Concern Person Name",
      "Mobile No",
      "MAKE BY",
      "Model",
      "Chassis No",
      "Engine No",
      "Fuel Type",
      "Vehicle No.",
      "Mfd Year", //  mfdyear
      "Vehicle Category", // vehicleCategory
      "City",
      "State",
      "PIN",
      "RTO STATE",
      "RTO NAME",
      "STATE SERVER",
      "State certificate Generation Date",
      "Address Proof Document",
      "Address ProofDocument No.",
      "ADDRESS",
      "KYC Status"
    ];
    let newHeadersOld = [
      "Name",
      "Email",
      "Phone",
      "User id",
      "KYC Status",
      "Device Name",
      "IMEI",
      "E Sim Validity",
      "Remark",
      "RTO State",
      "RTO City",
    ];

    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;
  //   }
  // }

  strRep(data) {
    if (typeof data == "string") {
      // Escape quotes by doubling them
      let newData = data.replace(/"/g, '""'); 
  
      // Replace commas with space (optional, based on your previous code)
      newData = newData.replace(/,/g, " "); 
  
      // If the data contains commas, newlines, or quotes, wrap it in double quotes
      if (newData.indexOf(",") !== -1 || newData.indexOf("\n") !== -1 || newData.indexOf("\r") !== -1 || newData.indexOf("\"") !== -1) {
        newData = `"${newData}"`; 
      }
  
      return newData;
    } else if (typeof data == "undefined" || data === null) {
      return "-"; // Handle undefined or null
    } else if (typeof data == "number") {
      return data.toString(); // Convert number to string
    } else {
      return data; // Return the value as is if it's not string, undefined, or number
    }
  }
  
  viewDocuments(docs) {
    console.log("Documents=>", docs);
    var that = this;
    docs.ID = "viewDoc";
    console.log(docs);
    let dialogRef = this.dialog.open(DeviceDocComponent, {
      width: "900px",
      // height:'900px',
      data: { dealer_payload: docs, isTag: this.isTag ? this.isTag : false },
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result == "yes") {
        this.getCustomer();
        this.getDeviceCount();
      }

      if (result == "no") {
      }
      if (result == "imageupdated") {
        swal("Updated", "Documents has been Updated.", "success");
        this.ngOnInit();
      }
    });
  }

  renewDoc(docs) {
    console.log("Documents=>", docs);
    var that = this;
    // docs.ID = "viewDoc";
    console.log(docs);
    let dialogRef = this.dialog.open(RenewalDocumentsComponent, {
      width: "450px",
      // height:'900px',
      data: { dealer_payload: docs, isTag: this.isTag ? this.isTag : false },
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result == "yes") {
        this.getCustomer();
        this.getDeviceCount();
      }

      // if (result == "no") {
      // }
      // if (result == "imageupdated") {
      //   swal("Updated", "Documents has been Updated.", "success");
      //   this.ngOnInit();
      // }
    });
  }
  inventoryCount = [
    { _id: "Pending", TotalDev: 0 },
    { _id: "Approved", TotalDev: 0 },
    { _id: "Reject", TotalDev: 0 },
  ];
  getDeviceCount() {
    this.contactService
      .get("/devices/getStatusCount?id=" + this.organisation)
      .subscribe((res: any) => {
        for (var i = 0; i < res.length; i++) {
          for (var j = 0; j < this.inventoryCount.length; j++) {
            if (res[i]._id == null) {
              this.inventoryCount[0].TotalDev = res[i].TotalDev;
            }
            if (this.inventoryCount[j]._id == res[i]._id) {
              this.inventoryCount[j].TotalDev = res[i].TotalDev;
            }
          }
        }
        // this.inventoryCount=res;
      });
  }
  hasPdfFile(url) {
    return url && url.indexOf(".pdf") != -1;
  }
  // exportCertificate(data) {
  //   data.actionId = "exportPdf";

  //   data.OwnerName =
  //     JSON.parse(JSON.stringify(data)).user.first_name +
  //     " " +
  //     JSON.parse(JSON.stringify(data)).user.last_name;
  //   //   data.Dealer_name = JSON.parse(JSON.stringify(data))
  //   var fstname =
  //     JSON.parse(JSON.stringify(data)).Dealer != undefined
  //       ? JSON.parse(JSON.stringify(data)).Dealer.first_name
  //       : "";
  //   var lsname =
  //     JSON.parse(JSON.stringify(data)).Dealer != undefined
  //       ? JSON.parse(JSON.stringify(data)).Dealer.last_name
  //       : "";
  //   var dlraddress =
  //     JSON.parse(JSON.stringify(data)).Dealer != undefined
  //       ? JSON.parse(JSON.stringify(data)).Dealer.address
  //       : "";
  //   data.Dealer_name = fstname + " " + lsname;
  //   data.DealerAddress = dlraddress;
  //   data.deviceImage = data.deviceImage;

  //   let dialogRef = this.dialog.open(CertOptionComponent, {
  //     data: { deviceInfo: data },
  //   });

  //   dialogRef.afterClosed().subscribe((result) => {
  //     // console.log(result);

  //     if (result == "advance") {
  //       let dialogRef_1 = this.dialog.open(EditDeviceMasterComponent, {
  //         data: { deviceInfo: data },
  //         width: "650px",
  //         height: "700px",
  //       });
  //     }

  //     if (result == "basic") {
  //       let dialogRef_2 = this.dialog.open(NormalCertComponent, {
  //         data: { deviceInfo: data },
  //       });
  //     }
  //   });
  // }
  exportCertificate(data){
let url=`https://nipponsecura.in/devices/getInstallationPdf?_id=${data.id}`
return url
  }
  getAddress(data) {
    data.lastAddress = "";
    if (data.last_location) {
      var latlng_1 = data.last_location;

      this.contactService.getAddressByApi(latlng_1).subscribe((res) => {
        if (res.message == "Address not found in databse") {
          data.lastAddress = "NA";
        } else {
          data.lastAddress = res.address;
        }
      });
    }
  }
  editModalDeviceExpiryDate(data){
    debugger
    $("#db_exampleModal").click();
    this.dbexp = data;

    this.dbexp.db_expiration_date = new Date(data.expiration_date)
      .toISOString()
      .substring(0, 10);
      this.dbexp.db_esim_validity = new Date(data.esim_validity)
      .toISOString()
      .substring(0, 10);

  }

  ifuploadArr: Boolean = false;
  selectedFile: any = {};
  statePic;
  rcCopy;
  imageuploadObject = [
    { doctype: "RC Copy", image: "", phone: "", docdate: "" },
  ]
  onUpload(imgIndex) {
    console.log(imgIndex);
    console.log(this.imageuploadObject);
    const fd = new FormData();
    if (!(this.selectedFile[imgIndex] && this.selectedFile[imgIndex].name)) {
      swal(
        "Upload Error",
        "Please select document type before upload !!!",
        "error"
      );
    } else {
      fd.append(
        "photo",
        this.selectedFile[imgIndex],
        this.selectedFile[imgIndex].name
      );
      console.log("imgURL=>", fd);
      this.Load = true;
      this.contactService.imageupload(fd).subscribe(
        (res) => {
          this.Load = false;
          this.ifuploadArr = true;
          //   this.uploadStatus = 'Uploaded';
          console.log(res);
          var resImage = "";
          resImage = res["_body"];
          console.log(res["_body"]);
          if (imgIndex == "rc_copy") {
            this.rcCopy = resImage;
          }
          
       
          // this.imageuploadObject[imgIndex].image = resImage;
          //  console.log(this.imageuploadObject);
          // console.log(res);
        },
        (err) => {
          this.Load = false;
          this._flashMessagesService.show("Internal server error , try again", {
            cssClass: "alert-success",
            timeout: 2000,
          });
        }
      );
    }
  }
  onFileChanged(event1, type) {
    debugger
    this.selectedFile[type] = <File>event1.target.files[0];
    var fileToUpload = event1.target.files.item(0);
    if (type == "rc_copy") {
      let reader = new FileReader();
      reader.onload = (event: any) => {
        this.statePic = event.target.result;
        reader.readAsDataURL(fileToUpload);
      };
    } 

    this.onUpload('rc_copy')
  }
  vehicle_registration_date:any='';
  esim_renewal_extenstion:any='2 years';
  esim_renewal_dt:any=''
  esim_renewal_selected_dt:any=''

  validateFromDate(): void {
    const currentDate = moment().startOf('day'); // Get the current date without time
    const fromDate = moment(this.esim_renewal_selected_dt, 'YYYY-MM-DD').startOf('day');
    

    // Validate from date
    if (this.esim_renewal_selected_dt && fromDate.isBefore(currentDate)) {
     
      swal("Error", "Expiry date should not be less than the current date", "error");
      this.esim_renewal_selected_dt = '';
      return;
    }  
  }
  simValidChange(dbexp) {

    if(this.esim_renewal_extenstion == "-1" && this.esim_renewal_selected_dt =='' ){
      swal("Error", "Please select renewal date", "error");
      return
    }
    else if(this.esim_renewal_extenstion === '1 year'){
      this.esim_renewal_dt = moment().add(1, 'years').toISOString();
    }
    else if (this.esim_renewal_extenstion === '2 years') {
      this.esim_renewal_dt = moment().add(2, 'years').toISOString();
    }
    else if (this.esim_renewal_extenstion === '3 years'){
      this.esim_renewal_dt = moment().add(3, 'years').toISOString();
    }
    else if(this.esim_renewal_extenstion == "-1" ){
     this.esim_renewal_dt=new Date(this.esim_renewal_selected_dt).toISOString()
    }
if(this.esim_renewal_dt != ''){
   this.renewal_details["esim_renewal_extenstion"]=this.esim_renewal_dt;
        this.renewal_details["vts_renewal_extenstion"]=this.esim_renewal_dt;
}
debugger

    if(this.vehicle_registration_date){
        this.renewal_details["vehicle_registration_dt"]=new Date(this.vehicle_registration_date).toISOString()
      }
      console.log("dbexp=>", dbexp);  
      this.contactService
        .db_ajax_token(environment.hostUrl + "/devices/renewDevicesBulk", [
          {
            imei: dbexp.Device_ID,
            esim_expiry:this.esim_renewal_dt,
            vehicle_expiry:this.esim_renewal_dt,
            renew_by:dbexp._id,
            renewal_details:this.renewal_details,
          },
        ])
        .subscribe((resp) => {
          console.log("done");
          this.esim_renewal_dt='';
          this.esim_renewal_extenstion='2 years';
          this.esim_renewal_selected_dt='';
          this.vehicle_registration_date=''


          swal("Updated", "Updated Successfully", "success");
          $("#simValidChange_close").click();
          this.getCustomer();
          this.getDeviceCount();
        });
    }
}
