import { Component, OnInit, TemplateRef } from '@angular/core';
import { FlashMessagesService } from 'angular2-flash-messages';
import { BsDatepickerConfig, BsModalRef, BsModalService } from 'ngx-bootstrap';
import { ContactService } from '../contact.service';
declare var XLSX:any;
declare var swal: any;
// import * as XLSX from 'xlsx';
declare var $: any;
@Component({
  selector: 'app-device-inventory',
  templateUrl: './device-inventory.component.html',
  styleUrls: ['./device-inventory.component.scss']
})
export class DeviceInventoryComponent implements OnInit {
uploadJSON: any;
 bsConfig: Partial<BsDatepickerConfig>;
  tollList;
  allUser:boolean=false;
  from_date=new Date();
  to_date=new Date();
  masterSelected:boolean;
  failedFiles=[];
  selectedAll:boolean=false
  failedUploadFiles:any;
  showErrorupload: boolean =false;
  faileduploadDevices=[];
  showErrorupload_1: boolean =false;
  Load: boolean;
  useridd: any;
  selectedArr=[]
  inventory=[]
  checkedList=[];
 skip: number = 1;
  limit: number = 100;
  dealers_info: any;
  dealerData: any;
  dealerObj: any;
  dealerSelect: any[];
  installerData:any[];
  distributerData:any[];
  distributerSelect:any[]
  installerSelect:any[];
  distributer_info;
  distributerObj
  Obj
  installerObj
  dateId: any;
  inventoryCount=[];
  installer_info: any;
  transaction=[]
  myInput: any;
 
  array=[{IMEI:'877',Vendor_Name:'test',Purchase_date:'2021-12-20T18:30:00.000Z','Bill date':'2021-12-20T18:30:00.000Z','Bill no':'2212',State:'Maharastra',
       'eSIM validaity':'One Year/Two Year','Device model no':'3232','Serial no':'5443','Iccid no':'4223','Mob-1':'983993022','Mob-2':'983993022','vahanID':"45433"}]
  constructor(private contactService:ContactService,private _flashMessagesService: FlashMessagesService) {
    this.masterSelected = false;
   }

  ngOnInit() {
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.getInventory();
    this.dealerDetail();
    this.getInventoryCount();
    this.distributerDetail()
     let that = this;
    //  this.testTable()

     
     $("#excelFile").change(function(e){
      let _e:any = e;
      that.failedFiles=[]
      console.log("Inside function");
        var reader = new FileReader();
        console.log(reader);
        reader.onload = function(e) {
         
          let _E:any = e;
          var data = _E.target.result;
       
        
        let workbook = XLSX.read(data, {type: 'binary' });
      
         let first_sheet_name = workbook.SheetNames[0];
      
       let worksheet = workbook.Sheets[first_sheet_name];
       let d:any = XLSX.utils.sheet_to_json(worksheet,{raw:true});
         
       that.uploadJSON=d.map(function(d){  
        return d;
          
        });
        console.log("file=>",that.uploadJSON);

        console.log("Failed",that.failedFiles);
        
        that.faileduploadDevices=that.uploadJSON;
        that.showErrorupload_1=true
        };
           reader.readAsBinaryString(_e.target.files[0]); 
      
      });
      this.getInstallerData()
  }

  uploadExcel(){
    this.failedUploadFiles = [];
    this.uploadJSON.forEach(element => {
      element=JSON.stringify(element)
    });

    // for(var i=0;i<this.uploadJSON.length;i++){
    //   this.uploadJSON
    // }
    
    console.log("Device Json Payload",this.uploadJSON);
    var data={
      data:this.uploadJSON,
      user:this.useridd
    }
    console.log(data);
    
    this.contactService.addMultipleInventory(data).subscribe(res=>{
      console.log(res);
      this.getInventory()
       var msg = "Records Added Successfully"
     this._flashMessagesService.show(msg, { cssClass: 'alert-success', timeout: 3000 });
    })
  
 }
show1:boolean=true
 uploadExcelAndUpdate(){
this.failedUploadFiles = [];
    this.uploadJSON.forEach(element => {
      element=JSON.stringify(element)
    });

    console.log("Device Json Payload",this.uploadJSON);
    var data={
      data:this.uploadJSON,
      user:this.useridd
    }
    console.log(data);
    
    this.contactService.post('/Device_inventory/addOrUpdateMultiPle',data).subscribe(res=>{
      console.log(res);
      this.show1=false;
      this.getInventory()
      swal({
        // position: 'top-end',
        // icon: 'success',
        title: 'Records updated Successfully',
        showConfirmButton: false,
        timer: 1500
      })


    //    var msg = "Records updated Successfully"
    //  this._flashMessagesService.show(msg, { cssClass: 'alert-success', timeout: 3000 });
    })
  }


 

 getInventory(){
   var dateObj={}
   var url="/Device_inventory/getInventory?user="+this.useridd
  if((this.dateId == 'to_date')||(this.to_date != undefined)){
     dateObj['to_date'] = this.to_date.toISOString();
  }
  if((this.dateId == 'from_date')||(this.from_date != undefined)){
     dateObj['from_date'] = this.from_date.toISOString();
  }

  //  if(dateObj != undefined){
  //   url="/Device_inventory/getInventory?from="+this.from_date+'&to='+this.to_date
  // }
   this.contactService.get(url).subscribe((res:any)=>{
     console.log(res);
     for(let i=0;i<res.length;i++){
       res[i].isSelected=false
      }
      this.inventory=res;
    this.showErrorupload=true;
     this.getCheckedItemList();
   })
 }
 checkValue(data,index){
   if(index){
     this.selectedArr.push(data)
   }else{
     if(this.selectedAll){
        this.selectedAll=false;
        
     }else{
       const i=this.selectedArr.indexOf(data);
       if (i > -1) {
       this.selectedArr.splice(i,1)
       }
     }
   }
   console.log(this.selectedArr,index);
   
 }

 selectAll(event){
    this.selectedArr=[]
   this.selectedAll=event;
   if(this.selectedAll){
     this.selectedArr=this.inventory;
   }else{
     this.selectedArr=[]
   }
   console.log(this.selectedArr);
   
 }
 checkUncheckAll() {
    for (var i = 0; i < this.inventory.length; i++) {
      this.inventory[i].isSelected = this.masterSelected;
    }
    this.getCheckedItemList();
  }

  // Check All Checkbox Checked
  isAllSelected() {
    this.masterSelected = this.inventory.every(function(item:any) {
        return item.isSelected == true;
      })
    this.getCheckedItemList();
  }

  getCheckedItemList(){
    this.checkedList = [];
    for (var i = 0; i < this.inventory.length; i++) {
      if(this.inventory[i].isSelected)
      this.checkedList.push(this.inventory[i]);
    }
    // this.checkedList = JSON.stringify(this.checkedList);
    console.log(this.checkedList);
    
  }

  getInstallerData(){
    this.Load = true;
     this.contactService.getTechnician(this.useridd, this.skip, this.limit,this.myInput,this.allUser).subscribe((res)=>{
       this.Load = false ;
        this.installer_info = res;
        for(let i=0;i<this.installer_info.length;i++){
          this.installer_info[i].fullName=this.installer_info[i].first_name+' '+this.installer_info[i].last_name;
        }
      },err=>{
        this.Load=false;
        this.installer_info=[];
      })
  }

 
  dealerDetail() {
    this.Load = true;
   console.log("Inside function");
  //  this.contactService.dealer_Info1(this.useridd,1,10000,2,null)
 this.contactService.getDealersDetails(this.useridd)    
   .subscribe(res => {
        // console.log(res);
        this.Load = false ;
        this.dealers_info = res;
        for(let i=0;i<this.dealers_info.length;i++){
          this.dealers_info[i].fullName=this.dealers_info[i].first_name+' '+this.dealers_info[i].last_name;
        }
        console.log('this.dealers_info',this.dealers_info);
      }, err => {
        this.Load = false;
        this.dealers_info=[];
        // this.firstcall = true;
        // this.lastcall = false;
      })

  }

  distributerDetail() {
    this.Load = true;
   console.log("Inside function");
  //  this.contactService.dealer_Info1(this.useridd,1,10000,2,null)
 this.contactService.getDistributerList(this.useridd)    
   .subscribe(res => {
        // console.log(res);
        this.Load = false ;
        this.distributer_info = res;
        for(let i=0;i<this.distributer_info.length;i++){
          this.distributer_info[i].fullName=this.distributer_info[i].first_name+' '+this.distributer_info[i].last_name;
        }
        console.log('this.distributer_info',this.distributer_info);
      }, err => {
        this.Load = false;
        this.distributer_info=[];
        // this.firstcall = true;
        // this.lastcall = false;
      })

  }
  filtergrpStatess(val) {

  console.log(val)
  // console.log(this.options)
 
  if (val) {
// this.userDetail=undefined
    const filtergrpValue:any = val;

    this.dealerSelect=[];
     this.dealerSelect = this.dealers_info.filter(function(g){
      var c = (g.first_name).toLocaleLowerCase().indexOf(filtergrpValue.toLocaleLowerCase());
    // console.log("TESTINg",c)
      return c > -1;    
    });
    if(this.dealerData){
      for(let i=0;i<this.dealers_info.length;i++){
        if(this.dealers_info[i].fullName==this.dealerData){
          this.dealerObj=this.dealers_info[i]._id
          console.log(this.dealers_info[i]);
        }
      }
    }
      console.log( this.dealerObj);
      return this.dealerSelect;
  }

}

filtergrpStatess1(val) {

  console.log(val)
  // console.log(this.options)
 
  if (val) {
// this.userDetail=undefined
    const filtergrpValue:any = val;

    this.installerSelect=[];
     this.installerSelect = this.installer_info.filter(function(g){
      var c = (g.first_name).toLocaleLowerCase().indexOf(filtergrpValue.toLocaleLowerCase());
    // console.log("TESTINg",c)
      return c > -1;    
    });
    if(this.installerData){
      for(let i=0;i<this.installer_info.length;i++){
        if(this.installer_info[i].fullName==this.installerData){
          this.installerObj=this.installer_info[i]._id
          console.log(this.installer_info[i]);
        }
      }
    }
      console.log( this.installerObj);
      return this.installerSelect;
  }

}

 filtergrpStatess2(val) {

  console.log(val)
  // console.log(this.options)
 
  if (val) {
// this.userDetail=undefined
    const filtergrpValue:any = val;

    this.distributerSelect=[];
     this.distributerSelect = this.distributer_info.filter(function(g){
      var c = (g.first_name).toLocaleLowerCase().indexOf(filtergrpValue.toLocaleLowerCase());
    // console.log("TESTINg",c)
      return c > -1;    
    });
    // console.log(this.distributerData);
    
    if(this.distributerData){
      for(let i=0;i<this.distributer_info.length;i++){
        if(this.distributer_info[i].fullName==this.distributerData){
          this.distributerObj=this.distributer_info[i]._id
          console.log(this.distributer_info[i]);
        }
      }
    }
      console.log( this.distributerObj);
      return this.distributerSelect;
  }

}
transfer(){
  var data={
      data:this.checkedList.length>0?this.checkedList:this.uploadJSON,
      dealer:this.dealerObj,
      user:this.useridd
    }

  this.contactService.transferInventory(data).subscribe((res:any)=>{
    console.log(res);
    this.getInventory()
    
  })
}

transfer1(){
  var data={
      data:this.checkedList.length>0?this.checkedList:this.uploadJSON,
      dealer:this.installerObj,
      user:this.useridd
    }

  this.contactService.transferInventory(data).subscribe((res:any)=>{
    console.log(res);
    this.getInventory()
    
  })
}

transfer2(){
  var data={
      data:this.checkedList.length>0?this.checkedList:this.uploadJSON,
      dealer:this.distributerObj,
      user:this.useridd
    }

  this.contactService.transferInventory(data).subscribe((res:any)=>{
    console.log(res);
    this.getInventory()
    
  })
}


changeDate(id){
  this.dateId=id
 this.getInventory()

}
getInventoryCount(){
  this.contactService.getInventoryCount(this.useridd).subscribe((res:any)=>{
    this.inventoryCount=res;
   
  })
}
applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    console.log(filterValue);
    
    // this.inventory.filter = filterValue.trim().toLowerCase();
  }

selectTab(id){
  console.log(id);
  
  if(id=='sent'){
    this.contactService.get('/DeviceInventoryTransaction/getByStatus?id=sent&user='+this.useridd).subscribe((res:any)=>{
      this.transaction=res;
    })

  }else{
     this.contactService.get('/DeviceInventoryTransaction/getByStatus?id=receive&user='+this.useridd).subscribe((res:any)=>{
      this.transaction=res;
    })
  }

}
show:Boolean=false;
addmultiple(){
  this.show=!this.show;
  this.testTable()
  // this.tabelObj.ajax.reload();
}

tab:any;

exportExcels() {
  
    this.downloadFile(this.array);
  }

  downloadFile(data, filename = 'Distance Report') {

    let arrHeader = ["IMEI","Device model no","Purchase_date","Serial no","Iccid no","Mob-1","Mob-2", "Vendor_Name", "Bill date", "Bill no","State","eSIM validaity"];
    let csvData = this.ConvertToCSV(data, arrHeader);
    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", "Sample.csv");
    dwldLink.style.visibility = "hidden";
    document.body.appendChild(dwldLink);
    dwldLink.click();
    document.body.removeChild(dwldLink);
  }
  ConvertToCSV(objArray, headerList) {
    let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

    let str = ""
    let row = 'S.No,';


    let newHeaders =["IMEI","Device model no","Purchase_date","Serial no","Iccid no","Mob-1","Mob-2", "Vendor_Name", "Bill date", "Bill no","State","eSIM validaity"];

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


exportExcel()
{

    var tab_text="<table><tr>";
    var textRange; var j=0;
    var table = $('#sample').clone();
    table[0].querySelector("thead").remove();
    table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];//document.getElementById('deviceTable'); // id of table

    for(j = 0 ; j < this.tab.rows.length ; j++) 
    {     
        tab_text=tab_text+this.tab.rows[j].innerHTML+"</tr>";
      
    }

    tab_text=tab_text+"</table>";
   
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}

// exportExcel(){

//     var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
//     var textRange; var j=0;
//     var table = $('#sample').clone();
//     table[0].querySelector("thead").remove();
//     table[0].prepend($(".dataTable thead").clone()[0]);
//     var tab:any = table[0];//document.getElementById('deviceTable'); // id of table

//     for(j = 0 ; j <  tab.rows.length ; j++) 
//     {     
//         tab_text=tab_text+ tab.rows[j].innerHTML+"</tr>";
      
//     }

//     tab_text=tab_text+"</table>";
   
//     tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

//     var ua = window.navigator.userAgent;
//     var msie = ua.indexOf("MSIE "); 

//     var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

//     return (sa);
// }

tabelObj
testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function () {
      that.tabelObj = $('#sample').DataTable({
      
        "autoWidth": true,
        'deferRender':true,
        "processing": true,
        stateSave: true,
        "bDestroy": true,
        "searching": true,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: false,
        "scrollX": true,
        "scrollY": '65vh',
        "scrollCollapse": true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "createdRow": function(row: Node, data: any | Object, index: number){
       
        
        },
        ajax: (dataTablesParameters, callback) => {
         
        callback({data:that.array})

        },
//  array=[{IMEI:'877',Vendor_Name:'test',Purchase_date:'2021-12-20','Bill date':'2021-12-20','Bill no':'2212',State:'Maharastra',
//        'eSIM validaity':'One Year/Two Year','Device model no':'3232','Serial no':'5443','Iccid no':'4223','Mob-1':'983993022','Mob-2':'983993022'}]
        "columns": [
          {
            "data": "IMEI",
            "render": function (data, row) { 
             return data?data:'N/A';  
            }
          },
          {
            "data": "Device model no",
           
            "render": function (data, row) {             
              return data;   
            }
          },
           {
            "data": "Purchase_date",
           
            "render": function (data, row) {             
              return data;   
            }
          },
           {
            "data": "Serial no",
           
            "render": function (data, row) {             
              return data;   
            }
          },
          {
            "data": "Iccid no",
           
            "render": function (data, row) {             
              return data;   
            }
          },
           {
            "data": "Mob-1",
           
            "render": function (data, row) {             
              return data;   
            }
          },
          {
            "data": "Mob-2",
           
            "render": function (data, row) {             
              return data;   
            }
          },
           {
            "data": "Vendor_Name",
            "render": function (data, row) {  
              return data?data:'N/A';   
            }
          },
         
           {
            "data": "Bill date",
           
            "render": function (data, row) {             
              return data;   
            }
          },
           {
            "data": "Bill no",
           
            "render": function (data, row) {             
              return data;   
            }
          },
            {
            "data": "State",
           
            "render": function (data, row) {             
              return data;   
            }
          },
            {
            "data": "eSIM validaity",
           
            "render": function (data, row) {             
              return data;   
            }
          },
          
           
         
         
          
        ],
        // "columnDefs": [
        //   { className: "dt-body-left", "targets": [0,1,2] },
        //   {
        //     "targets": '_all',
        //     "createdCell": function (td, cellData, rowData, row, col) {
        //       $(td).css('padding', '18px')
        //     }
        //   },
        //   { "width": "10px", "targets": 0 },
        //   { "width": "40px", "targets": 1 },
        //   { "width": "100px", "targets": 2 },

        // ], order: [[ 0, 'desc' ], [ 0, 'asc' ]]
      });
 
    });

  }

  uploadedFile(e){
    console.log(e);
    var that=this
     let _e:any = e;
      that.failedFiles=[]
      console.log("Inside function");
        var reader = new FileReader();
        console.log(reader);
        reader.onload = function(e) {
         
          let _E:any = e;
          var data = _E.target.result;
       
        
        let workbook = XLSX.read(data, {type: 'binary' });
      
         let first_sheet_name = workbook.SheetNames[0];
      
       let worksheet = workbook.Sheets[first_sheet_name];
       let d:any = XLSX.utils.sheet_to_json(worksheet,{raw:true});
         
       that.uploadJSON=d.map(function(d){  
        return d;
          
        });
        console.log("file=>",that.uploadJSON);

        console.log("Failed",that.failedFiles);
        
        that.faileduploadDevices=that.uploadJSON;
        that.showErrorupload_1=true
        };
           reader.readAsBinaryString(_e.target.files[0]); 
    
  }
  change(){
    this.uploadJSON=[];
    this.failedFiles=[];
    this.dealerObj=undefined
  }

}
