import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../../contact.service';
import { Http, Headers, RequestOptions, ResponseContentType } from '@angular/http';
import { saveAs } from 'file-saver';
import { environment } from '../../../../environments/environment';
import { MdSnackBar } from '@angular/material';
declare var jsPDF : any;
declare var $: any;
const PDF_EXTENSION = ".pdf";
declare var google: any;
import * as moment from 'moment';
import { ReportService } from '../../report.service';
import * as _ from 'lodash';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
const now = new Date();
@Component({
  selector: 'app-day-wise-report',
  templateUrl: './day-wise-report.component.html',
  styleUrls: ['./day-wise-report.component.scss']
})
export class DayWiseReportComponent implements OnInit {
  dateStr: any;
  Fromdate = new Date();
  todate = new Date();
  useridd: any;
  fDate: any;
  tDate: any;
  dev_url = environment.hostUrl;
  // dateString=['Today Report','Yesterday Report','Weekly Report','Monthly Report'];
  fromDate: any;
  toDate: any;
  Load: boolean;
  tabelObj: any;
  custtype: any;
  superAdmin: any;
  data_descip: string;
  reportArr :any= [];
  vehicleData=[];
  dayWiseData=[];
  idleData=[];
  ignitionData=[]
  finalArr=[]
  private finalise = new Subject<void>();
  constructor(private contactService: ContactService, private http: Http, public snackBar: MdSnackBar,private _service:ReportService ) {
 this._service.invokeEventForDayWiseReport.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
        if(value){
         this.getReport(value); 
       }
       console.log(value);
       
      })
    // 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);

  }
 ngOnDestroy(){
    this.finalise.next(void 0);
  }
  ngOnInit() {
    this.vehicleData=JSON.parse(localStorage.getItem('vehicaleData'))
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.tDate = new Date();
    var fd = new Date();
    fd.setHours(0, 0, 0, 0);
    this.fDate = fd;
   
    this.testTable()

  }

  deviceArr = [];
  tab: any;

  exportExcel() {

    var tab_text = "<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j = 0;
    var table = $('#deviceTable').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);
  }
  emailid: any;
  devicesss: any;
  options: any;
  finall: any;

  //   getDevices(){
  //     console.log("Inside getDevice function");
  //     this.contactService.getDevice(this.emailid,this.useridd).subscribe(

  //       data => {
  //         this.devicesss = data;
  //         console.log('this.devicesss',this.devicesss);  
  //         this.finall = (this.devicesss.devices);
  //         this.options = [];

  //         for(let i=0;i<this.devicesss.devices.length;i++){
  //           console.log('this.devicesss.devices',i);

  //           // if(this.devicesss.devices[i].type_of_device =="Tracker"){
  //             let a ={
  //               value : this.devicesss.devices[i].Device_Name,
  //               viewValue:this.devicesss.devices[i].Device_Name,
  //               did:this.devicesss.devices[i].Device_ID,
  //               id:this.devicesss.devices[i]._id,
  //               user:this.devicesss.devices[i].user,
  //               // email: this.devicesss.devices[i].Email_ID,
  //               // deviceType: this.devicesss.devices[i].type_of_device,      
  //             }  

  //               a['selectedValue'] = this.devicesss.devices[i].Device_ID ; 


  //             // }
  //             this.options.push(a);
  //           // }

  //           if(i === (this.devicesss.devices.length -1)){
  //             setTimeout(() => {
  //               $('#dbselect').multipleSelect({
  //                 width: 200,
  //                 placeholder: 'Select Vehicle.....',
  //                 filter: true,
  //               })
  //             }, 100);

  //           }
  //         }
  //   })

  // }



  testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function () {
      that.tabelObj = $('#deviceTable').DataTable({
        // dom: 'Bfrtip',
        // buttons: [ 'copy', 'csv', 'ex  cel', 'pdf', 'print' ],
        "autoWidth": true,
        'deferRender':true,
        "processing": 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"]],
         
        ajax: (dataTablesParameters, callback) => {
          console.log('temptemptemptemptemp', dataTablesParameters);
          var deviceID;
          that.Load = true;


          var from_date = new Date(that.Fromdate).toISOString();
          var to_date = new Date(that.todate).toISOString();
          var user = that.useridd;
          var temp = {
            from_date: from_date,
            to_date: to_date,
            user: user
          }
          var suburl = "";
          // https://www.oneqlik.in/summary/getDayWiseReport?user=5e37c4a218ff144091101d3e&to=2020-02-27T18:29:59.115Z&from=2020-02-26T18:30:00.115Z&device=865205038055231   
          suburl += "/summary/getDayWiseReport?from=" + temp.from_date + '&to=' + temp.to_date + '&user=' + temp.user;
          if (that.deviceArr.length != 0) {
            suburl += '&device=' + that.deviceArr;
          }else{
            that.Load = false
            callback({ data: [] });
      
          }

          if ((temp.from_date != undefined) && (temp.to_date != undefined) && that.deviceArr.length != 0) {
            //  console.log('resp=>',temp.from_date,temp.to_date); 
            that.contactService.get(suburl).subscribe((resp:any) => {
              // console.log(ignReport.length);  
               // that.Load = false;
              that.reportArr = [];
              that.reportArr= resp ; 
              if (that.reportArr.length != 0) {
                console.log(that.reportArr);
                var j = 0;
                that.finalArr = [];
                for (var i = 0; i < that.reportArr.length; i++) {

                  // if(that.reportArr[i].distanceVariation){
                  //     console.log("IN");
                      
                  //     if(that.reportArr[i].distanceVariation[0]=="+"){
                  //       that.reportArr[i]['Distance(Kms)']=that.reportArr[i]['Distance(Kms)']+(that.reportArr[i]['Distance(Kms)']/100)*Number(that.reportArr[i].distanceVariation.substring(1))
                  //      console.log("IN",(that.reportArr[i]['Distance(Kms)']/100)*Number(that.reportArr[i].distanceVariation.substring(1)));
                  //     }else{

                  //       that.reportArr[i]['Distance(Kms)']=that.reportArr[i]['Distance(Kms)']-(that.reportArr[i]['Distance(Kms)']/100)*Number(that.reportArr[i].distanceVariation.substring(1))
                  //     console.log("IN-",that.reportArr[i]['Distance(Kms)']);
                  //     }
                  //   }

                  console.log(that.reportArr[i]['Idle Time'],that.reportArr[i]['Moving Time'],that.reportArr[i]['Stoppage Time'],that.reportArr[i]['Idle Time']);
                  
                  if((that.reportArr[i]['Idle Time']+that.reportArr[i]['Stoppage Time']+that.reportArr[i]['Moving Time'])<24){
                    that.reportArr[i].outOfReach=(24-(that.reportArr[i]['Idle Time']+that.reportArr[i]['Stoppage Time']+that.reportArr[i]['Moving Time'])).toFixed(2)
                  }else{
                    that.reportArr[i].outOfReach=0.0

                  }
  
                  that.clocation_1(that.reportArr[i], function (err, succ) {
                    if (err) {
                      console.log(err);
                      j++;
                    } else {
                      if(!(that.finalArr.includes(succ))){
                        console.log(that.finalArr.includes(succ));
                        for(var k=0;k<that.finalArr.length;k++){
                          if(succ.Device_ID!=that.finalArr[k].Device_ID && succ.Date!=that.finalArr[k].Date){
                            if(!(that.finalArr.includes(succ))){
                              that.finalArr.push(succ);
                            }
                          }
                        }
                      }else{
                        console.log(that.finalArr.includes(succ));
                      }
                      that.finalArr.push(succ);
                      console.log(that.finalArr);
                      j++;
                      if (j === that.reportArr.length) {
                        that.Load = false;
                        var x = [];
                        that.finalArr.sort(function(a,b){
                          // Turn your strings into dates, and then subtract them
                          // to get a value that is either negative, positive, or zero.
                          var aDate:any = new Date(a.Date);
                          var bDate:any = new Date(b.Date);  
                          return bDate - aDate;
                        });
                       
                     var filtered=_.uniqWith(that.finalArr, _.isEqual);
                      
                        console.log(filtered)

                        callback({ data: filtered });
                      }
                    }
                  })
                }
                console.log("HDH",that.reportArr)
              } else {
                that.Load = false;
                callback({ data: [] });
  
              }
            }, err => {
              that.Load = false;
              var errCode = err.status;
              if(errCode == 500){
                callback({ data: [] });
              }

            
            });

          } else {
            let ta = [];
            that.Load = false;
            callback({ data: ta });
          }

        },

        "columns": [
          {
            "data": "_id",
            // "orderable":true,
            "defaultContent": "",
            "visible" :false, 
            "render": function (data, type, row) {             
              return  "";   
            }
          },
          {
            "data": "Date",
            "render": function (data, type, row) {       
              var reportDate = new Date(data);
            //  return data?data:''
              return data ? (moment(reportDate).format('DD-MM-YYYY')) : "";   
            }
          },
          {
            "data": "VRN",
            render: function (data, type, row) {
              return data ? data : '';
            }
          },
          {
            "data": "Distance(Kms)",
            render: function (data, type, row) {
            
              return data ? parseFloat(data).toFixed(2) : 0.0;

            }
          },
          {
            "data": "Moving Time",
            "defaultContent": "",
            render: function (data, type, row) {
            
              var hhmm;
              if(data){
                data = Math.abs(data); // Change to positive
                var decimal = data - Math.floor(data);
                console.log(decimal);
                var minValue = (decimal *60).toFixed(2);
                
                var hrValue= data.toString().split(".")[0] ; 

                hhmm = hrValue + ':' + parseInt(minValue);
              }else{
                hhmm  =0+':'+0;

              }
            return hhmm;
            }
          },
          {
            "data": "Stoppage Time",
            "defaultContent": "_id",
            render: function (data, type, row) {
              // return data ? parseFloat(data).toFixed(2) : 0.0;
              var hhmm;
              if(data){
                data = Math.abs(data); // Change to positive
                var decimal = data - Math.floor(data);
                // console.log(decimal);
                var minValue = (decimal *60).toFixed(2);
                // console.log('minValue',minValue);
                var hrValue= data.toString().split(".")[0] ; 

                hhmm = hrValue + ':' + parseInt(minValue);
              }else{
                hhmm  =0+':'+0;

              }
            return hhmm;
            }
          },
          {
            "data": "Idle Time",
            "defaultContent": "_id",
            render: function (data, type, row) {
              // return data ? parseFloat(data).toFixed(2) : 0.0;
              var hhmm;
              if(data){
                data = Math.abs(data); // Change to positive
                var decimal = data - Math.floor(data);
                console.log(decimal);
                var minValue = (decimal *60).toFixed(2);
                console.log('minValue',minValue);
                var hrValue= data.toString().split(".")[0] ; 

                hhmm = hrValue + ':' + parseInt(minValue);
              }else{
                hhmm  =0+':'+0;

              }
            return hhmm;
            }
          },
          
          {
            "data": "Mileage",
            "defaultContent": "_id",
            render: function (data, type, row) {
              // return data ? parseFloat(data).toFixed(2) : 0.0;
             
              if(data){
                if(row['Distance(Kms)']){
                  var mileage=parseFloat(row['Distance(Kms)']) /parseFloat(data)
                  return mileage.toFixed(2)
                }else{
                    return ''
                }
               
              }else{
                
                return ''
              }
            // return hhmm;
            }
          },
          {
            "data": "startAddress",
            "defaultContent": "_id",
            render: function (data, type, row) {
              return data ? data : '';
            }
          },
          {
            "data": "endAddress",
            "defaultContent": "_id",
            render: function (data, type, row) {
              return data ? data : '';
            }
          },
         
        ],
        "columnDefs": [
          { className: "dt-body-left", "targets": [0, 1, 2, 3,4,5,6,7] },
          {
            "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 },
          { "width": "70px", "targets": 3 },
          { "width": "70px", "targets": 4 },

        ]
      });

    });

  }




deviceARR=[]
  identifier: any = 'dayWiseReport';
  getReport(event) {
    console.log("inside function");
    if (event == 'getExcel') {
      this.exportExcel();
    } else if(event=='getPdf')
  {
    this.expotToPdf();
  }else{
      var deviceId: any;
      var tpdata = event;
      var that = this;
      var fd = new Date(tpdata.fromDate);
      var td = new Date(tpdata.toDate);

      if (event.deviceArr.length == 0) {
        deviceId = [];
      } else {
       for(var i=0;i<event.deviceArr.length;i++){
         for(var j=0;j<this.vehicleData.length;j++){
           if(event.deviceArr[i]==this.vehicleData[j].Device_ID){
             this.deviceARR.push(this.vehicleData[j]._id)
           }
         }
       }
        deviceId = event.deviceArr;
      }

      this.Fromdate = fd;
      this.todate = td;
      this.deviceArr = deviceId;
      //  this.getIgnitionReport()
    // this.getDevices();
    // this.getIdleReport()

      this.tabelObj.ajax.reload();
      // this.tabelObj.draw();  
      // this.tabelObj.draw();
      // if(this.ajaxCount != 0){

      // }
      // this.ajaxCount = 1 ; 
    }

  }

  clocation_1(latlngObj, cb) {
    var outerThis = this;
    var la = '';

    let latLng = {
      lat: "0",
      long: "0"
    };
    if (latlngObj.start_location) {
      latLng = {
        lat: latlngObj.start_location.lat ? latlngObj.start_location.lat : 0,
        long: latlngObj.start_location.long ? latlngObj.start_location.long : 0
      }
    }
    if (latlngObj.today_start_location) {
      latLng = {
        lat: latlngObj.today_start_location.lat ? latlngObj.today_start_location.lat : 0,
        long: latlngObj.today_start_location.long ? latlngObj.today_start_location.long : 0
      }
    }

    // if () {
    //   latLng = {
    //     lat: 0,
    //     long: 0
    //   }
    // }

    outerThis.contactService.getAddressByApi(latLng).subscribe(res => {
      if (res.message == "Address not found in databse") {
        latlngObj['startAddress'] = "NA";
        // cb(null,latlngObj);
        var latLng_1 = {
          lat: "0",
          long: "0"
        };
        if (latlngObj.last_location) {
          latLng_1 = {
            lat: latlngObj.last_location.lat ? latlngObj.last_location.lat : 0,
            long: latlngObj.last_location.long ? latlngObj.last_location.long : 0
          }

        }
        if (latlngObj.end_location) {
          latLng_1 = {
            lat: latlngObj.end_location.lat ? latlngObj.end_location.lat : 0,
            long: latlngObj.end_location.long ? latlngObj.end_location.long : 0
          }
        }


        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            latlngObj['endAddress'] = "NA";
            cb(null, latlngObj);


          } else {
            latlngObj['endAddress'] = res.address;
            cb(null, latlngObj);
          }

        })

      } else {
        latlngObj['startAddress'] = res.address;
        var latLng_1 = {
          lat: "0",
          long: "0"
        };
        if (latlngObj.last_location) {
          latLng_1 = {
            lat: latlngObj.last_location.lat ? latlngObj.last_location.lat : 0,
            long: latlngObj.last_location.long ? latlngObj.last_location.long : 0
          }

        }
        if (latlngObj.end_location) {
          latLng_1 = {
            lat: latlngObj.end_location.lat ? latlngObj.end_location.lat : 0,
            long: latlngObj.end_location.long ? latlngObj.end_location.long : 0
          }
        }


        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            latlngObj['endAddress'] = "NA";
            cb(null, latlngObj);


          } else {
            latlngObj['endAddress'] = res.address;
            cb(null, latlngObj);
          }

        })

        // cb(null,latlngObj);
      }
    })

  }

  expotToPdf(){
    console.log(this.finalArr);

    this.downloadPdf()
    
  }
// downloadPdf() {
//     let fileName =
//       "Daywise Report" +
//       new Date().getTime() +
//       PDF_EXTENSION;
//     var pdfsize = "a2";

//     var doc = new jsPDF("p", "pt", pdfsize);
//     var f_date = moment(this.Fromdate).format('lll'); 
//   var t_date =moment(this.todate).format('lll');
//   var date_combine = f_date + ' to ' + t_date;
//   // doc.setFontSize(30);
//   doc.setFontSize(15);
//   doc.text('Daywise Report ', 20, 30);
//   // doc.text(date_combine, 250, 60);
//     doc.setFontStyle("arial");

//       var header = function(data) {
//     doc.setFontSize(15);
//     doc.setTextColor(40);
//     doc.setFontStyle('normal');
//     //doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50);
//     // doc.text("Testing Report", data.settings.margin.left, 50);
//   };

//   var options = {
//     beforePageContent: header,
//     margin: {
//       top: 120
//     },
//     startY: doc.autoTableEndPosY() + 20
//   };

//     doc.autoTable({
//       head: this.headRows(),
//       // margin: { top: 80 },
//       body: this.bodyRows(this.finalArr.length, this.finalArr),
//       options
      
//     });
//     doc.save(fileName);
//   }

startAddress;

endAddress;
f_date
t_date
downloadPdf() {
  var outerThis=this
    let fileName =
      "Daywise Report" +
      new Date()+
      PDF_EXTENSION;
    var pdfsize = "a2";
    var totalPagesExp = "{total_pages_count_string}";
 outerThis.startAddress= outerThis.finalArr[0].address;
 outerThis.endAddress= outerThis.finalArr[outerThis.finalArr.length-1].address
    var doc = new jsPDF("p", "pt", pdfsize);
    outerThis.f_date = moment(this.Fromdate).format('lll'); 
  outerThis.t_date =moment(this.todate).format('lll');
  // var date_combine = f_date + ' to ' + t_date;
  // doc.setFontSize(30);
   var pageHeight = doc.internal.pageSize.height || doc.internal.pageSize.getHeight();
var pageWidth = doc.internal.pageSize.width || doc.internal.pageSize.getWidth();
  doc.setFontSize(15);
  // doc.text(60, 20, 'Travel Path Report (Date='+date_combine+') Device Name='+this.device_name,);
  
  doc.text("Daywise Report", 500, 30);
    doc.setFontStyle("arial");

      var header = function(data) {
    doc.setFontSize(30);
    doc.setTextColor(40);
    doc.setFontStyle('arial');
  
  };

  var options = {
    beforePageContent: header,
    margin: {
      top: 120
    },
    
    startY: doc.autoTableEndPosY() + 20
  };
 var logo=localStorage.getItem('logo1');
 outerThis.toDataURL(logo, function (dataUrl) {
                
    doc.autoTable({
      head: outerThis.headRows(),
      // margin: { top: 80 },
      //  startY: doc.autoTable.previous.finalY + 200,
      body: outerThis.bodyRows(outerThis.finalArr.length, outerThis.finalArr),
      options,
       styles: {overflow: 'linebreak'},
      // tableLineColor: [0, 0, 0], //choose RGB
        // tableLineWidth: 0.5, //table border width
        // bodyStyles: {
        //     margin: 40,
        //     fontSize: 10,
        //     lineWidth: 0.2,
        //     lineColor: [0, 0, 0]
        // },
      theme:'grid',
      didDrawPage: function (data) {
        // Header
        doc.setFontSize(20);
        doc.setTextColor(40);
        doc.setFontStyle('arial');
        // logo=localStorage.getItem('logo1');
          if(logo)
              doc.addImage(dataUrl, 'JPEG', pageWidth-100, 6, 75, 75);
              doc.autoTable({html:"#headerTable",margin:{bottom:140,left:20,right:8,top:40},theme:'plain'});

        // Footer
        var str = "Page " + doc.internal.getNumberOfPages()
        // Total page number plugin only available in jspdf v1.0+
        if (typeof doc.putTotalPages === 'function') {
            str = str + " of " + totalPagesExp;
        }
        doc.setFontSize(10);

        // jsPDF 1.4+ uses getWidth, <1.4 uses .width
        var pageSize = doc.internal.pageSize;
        var pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();
        doc.text(str, data.settings.margin.left, pageHeight - 10);
    },
    
      margin: {top: 85},
     
    });
    if (typeof doc.putTotalPages === 'function') {
      doc.putTotalPages(totalPagesExp);
    }
    doc.save(fileName);
  })
  }

   toDataURL(url, callback) {
   
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            var reader = new FileReader();
            reader.onloadend = function () {
                callback(reader.result);
            }
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.send();
    }

  headRows() {

    return [
  // displayedColumns=['vehicleName','IMEI','totalDistance','fuel','ignOn','ignOff','idleTime','outOfReach','noGps','trips','maxSpeed','startLocation','endLocation','details'];

      {
        Date:'Date',
        VRN:'Vehicle Name',
        'Distance(Kms)':'Distance (Kms)',
        'Moving Time':'Moving Time (HH:MM)',
        'Stoppage Time':'Stoppage Time (HH:MM)',
        'Idle Time':'Idle Time (HH:MM)',
        startAddress:'Start Location',
        endAddress:'End Location',
      }
    ];
  }

  
  bodyRows(rowCount, pdfBody) {
    console.log(rowCount, pdfBody);

    rowCount = rowCount || 10;
    let body = [];
    for (var j = 0; j < rowCount; j++) {
      body.push({

       Date:pdfBody[j].Date,
        VRN:pdfBody[j].VRN,
        'Distance(Kms)':(pdfBody[j]['Distance(Kms)']).toFixed(2),
        'Moving Time':this.conversion(pdfBody[j]['Moving Time']),
        'Stoppage Time':this.conversion(pdfBody[j]['Moving Time']),
        "Idle Time":this.conversion(pdfBody[j]['Idle Time']),
        startAddress:pdfBody[j].startAddress,
        endAddress:pdfBody[j].endAddress,

      });
    }
    return body;
  }

  conversion(data){
    var hhmm;
              if(data){
                data = Math.abs(data); // Change to positive
                var decimal = data - Math.floor(data);
                // console.log(decimal);
                var minValue = (decimal *60).toFixed(2);
                // console.log('minValue',minValue);
                var hrValue= data.toString().split(".")[0] ; 

                hhmm = hrValue + ':' + parseInt(minValue);
              }else{
                hhmm  =0+':'+0;

              }
            return hhmm;
            

  }
// getUniqueListBy(arr, key) {
//   var data=[...new Map(arr.map(item => [item[key], item])).values()]
//     return data
// }

}