import { Component, OnInit } from '@angular/core';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { ContactService } from '../../contact.service';
declare var google: any;
declare var jsPDF : any;
import * as moment from 'moment';
declare var $:any;

@Component({
  selector: 'app-new-route-plan-report',
  templateUrl: './new-route-plan-report.component.html',
  styleUrls: ['./new-route-plan-report.component.scss']
})
export class NewRoutePlanReportComponent implements OnInit {
  headerArray=['Haults']
  emailid;
  useridd;
  options;
  routes;
  poiArray=[];
  from_date =new Date();
   colorTheme = 'theme-dark-blue';
  to_date = new Date();
  Load:boolean=false;
  bsConfig: Partial<BsDatepickerConfig>;
  constructor(private contactService:ContactService) {
    this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' }, { containerClass: this.colorTheme });
   }

  ngOnInit() {
    var fTime = new Date();
    fTime.setHours(0,0,0,0);   
    this.from_date = new Date(fTime);
     this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
     this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
     this.getVehicleData();
     this.getRouteName();
     this.getPois();
     this.testTable();
  }

  getPois(){
     this.contactService.get('/poi/getPois?user='+this.useridd).subscribe((res:any)=>{

      var poiObj; 

    for(var i=0;i<res.length;i++){
      poiObj ={
          poiname: res[i].poi.poiname,
          id : res[i]._id,
          location:res[i].poi.location.coordinates,
          address:res[i].poi.address
        }

        this.poiArray.push(poiObj);
        if(this.poiArray.length==res.length){
          this.loadropdown();

        }
    }
    })
  }

  getVehicleData(){
    this.contactService.getDevice(this.emailid,this.useridd).subscribe(
      data => {
      var devicesss = data
        this.options = [];
        for(let i=0;i<devicesss.devices.length;i++){
            let a ={
              value : devicesss.devices[i].Device_Name,
              viewValue:devicesss.devices[i].Device_Name,
              did:devicesss.devices[i].Device_ID,
              id:devicesss.devices[i]._id,
              user:devicesss.devices[i].user,
              
            }
            a['selectedValue'] = devicesss.devices[i]._id ; 
            this.options.push(a); 
        }
          this.loadropdown();
          let that = this;
      
      });
  }

  getRouteName(){
    this.contactService.post('/routePlan/get',{user:this.useridd}).subscribe((res:any)=>{
    // this.contactService.get('/trackRoute/user/'+this.useridd).subscribe((res:any)=>{
      console.log(res);
      this.routes=res;
      this.loadropdown();
    })
  }

   loadropdown() {
    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);

    setTimeout(() => {
      $('#vehicles').multipleSelect({
        width: 200,
        placeholder: 'Select Vehicle',
        filter: true,
        single: false,
        selectAll: false
 
      })
  
   
    }, 100);

     setTimeout(() => {
      $('#poi').multipleSelect({
        width: 200,
        placeholder: 'Select poi',
        filter: true,
        single: false,
        selectAll: false
 
      })
  
   
    }, 100);

     setTimeout(() => {
      $('#routes').multipleSelect({
        width: 200,
        placeholder: 'Select route',
        filter: true,
        single: false,
        selectAll: false
 
      })
  
   
    }, 100);
  }
  reportData=[]
  routeName;
  mainArray=[]
  search(){
    this.mainArray=[]
    console.log("IN SEARCH");
    var diffInMs   = moment(this.to_date).diff(moment(this.from_date), 'days');
    console.log(diffInMs,"==DIFFRENCE");
    this.headerArray=["Haults"]
    if(diffInMs>0){
      for(var i=0;i<diffInMs;i++){
        var date=moment(this.from_date, "DD-MM-YYYY").add('days', i)
        this.headerArray.push(JSON.stringify((moment(date).format('LL'))))
      }
    }else{
      this.headerArray.push(JSON.stringify((moment(this.from_date).format('LL'))))
    }

    for(var i=0;i<this.poiArray.length;i++){
      this.mainArray.push({data:{poiname:this.poiArray[i].poiname,id:this.poiArray[i].id,date:[]}})
      for(var j=1;j<this.headerArray.length;j++){
        this.mainArray[i].data.date.push('N')

      }

    }
    // console.log(this.mainArray);
    
    
   var vehicle=$('#vehicles').multipleSelect('getSelects','value');
    var poi=$('#poi').multipleSelect('getSelects','value');
    var routes=$('#routes').multipleSelect('getSelects','value');
    for(var i=0;i<this.routes.length;i++){
      console.log(routes+"=="+this.routes[i]._id);
      
      if(routes==this.routes[i]._id){
        this.routeName=this.routes[i].name
      }
    }
    var data={
      vehicle:vehicle,
      poi:poi,
      route:routes,
      user:this.useridd,
      from:this.from_date,
      to:this.to_date
    }
    console.log(data);
    this.contactService.post('/RoutePlan/routeReport',data).subscribe((res:any)=>{

      for(var i=0;i<this.poiArray.length;i++){
        this.mainArray.push({data:{poiname:this.poiArray[i].poiname,date:[]}})
        for(var j=1;j<this.headerArray.length;j++){
          for(var k=0;k<res.length;k++){
            var arrDate=res[k].arrivalTime.split('T');
            var headerDate=this.headerArray[j].split('T');
            // console.log(moment(arrDate[0]).isSame(headerDate[0]),(arrDate[0]),"=",(headerDate[0]));
            
            if(moment(arrDate[0]).isSame(headerDate[0])){
            // res[k].arrivalTime==this.headerArray[j]){
              if(res[k].poi){
                console.log(res[k].poi._id==this.poiArray[i].id,res[k].poi._id,"==",this.poiArray[i].id);
                if(res[k].poi._id==this.poiArray[i].id){
                  if(this.mainArray[i].data.date.length<(this.headerArray.length-1)){
  
                    this.mainArray[i].data.date.push('Y')
                  }
                }else{
                  if(this.mainArray[i].data.date.length<(this.headerArray.length-1)){
  
                    this.mainArray[i].data.date.push('N')
                  }
                }

              }else{
                if(this.mainArray[i].data.date.length<(this.headerArray.length-1)){

                  this.mainArray[i].data.date.push('N')
                }
              }
            }else{
                if(this.mainArray[i].data.date.length<(this.headerArray.length-1)){

                  this.mainArray[i].data.date.push('N')
                }
            }
          }
        }
      }
      console.log(this.mainArray);
      
    })
  }

  tabelObj
  testTable(){
  const that = this;
  // console.log("inside function");
 
   $(document).ready(function() {
     that.tabelObj = $('#deviceTable').DataTable({
       "processing": false,
          "searching": true, 
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: false,
          responsive: true,
          "scrollY":'60vh',  
          "scrollCollapse": true, 
          
          // "deferLoading": 25 ,  
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            // "rowCallback": function(row: Node, data: any | Object, index: number){
          ajax: (mainData,callback) => {

             callback({ data:that.reportData});
      // that.contactService.getRenewalHistory(this.data._id).subscribe(res=>{
      //   console.log(res);
      //   that.Load = false;
      //   if(res.length!=0){
      //     callback({ data: res[0].data });

      //   }else{
      //      callback({ data: [] });
      //   }
        
      // })

   
  },
   "columns": [
              {
                  "data": "device",
                  "render": function(data, type, row) {  
                    console.log(data);
                                     
                    return data?data.Device_Name : '';                  
                  }
              },
              {
                  "data": "lat",
                  "render": function(data, type, row) {   
                    console.log(that.routeName);
                                    
                    return that.routeName?that.routeName: '';                  
                  }
              },
              {
                  "data": "poi",
                  "render": function(data, type, row) {                   
                    return data?data.poi.poiname : '';                  
                  }
              },
              {
                  "data": "arrivalTime",
                  "render": function(data, type, row) {                   
                   return data ? (moment(data).format('llll')) : "";                
                  }
              },
              {
                  "data": "departureTime",
                  "render": function(data, type, row) {                   
                   return data ? (moment(data).format('llll')) : "";                  
                  }
              },
             
   
          ],  
          // "columnDefs": [
          //   { className: "dt-body-left", "targets": [ 0,1,2,3] },  
          // { "width": "10px", "targets": 0 },
          // { "width": "40px", "targets": 1 },
          // { "width": "100px", "targets": 2 },
          // { "width": "70px", "targets": 3 },] , 
          // order: [[ 3, 'desc' ], [ 0, 'asc' ]]
      });

  });

}

 exportExcel(){
   console.log("EXCEL");
    
	    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]);
    var tab = table[0];
  
	    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, ""); 

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

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

	    return (sa);
  }

  exportPDF(){
     console.log("PDF");
    var doc = new jsPDF("p", "pt", "a2");
   var header = function(data) {
                      doc.setFontSize(15);
                      doc.setTextColor(40);
                      doc.setFontStyle('normal');
                      // doc.addImage(dataUrl, 'JPEG', data.settings.margin.left, 20, 30, 30);
                      doc.text("Sales Order", data.settings.margin.left, 50);
                    };

    doc.autoTable({html:"#deviceTable",margin:{bottom:140,left:30,right:8,top:80},theme:'grid',beforePageContent: header},);
    doc.save("RoutePlanReport");
  }

}
