import { Component, OnInit } from '@angular/core';
import { MdDialog } from '@angular/material';
import { Router } from '@angular/router';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { routes } from '../../app.router';
import { ContactService } from '../../contact.service';
import { HualtListComponent } from '../hualt-list/hualt-list.component';
declare var google: any;
declare var jsPDF : any;
declare var  swal:any;
declare var $:any;
@Component({
  selector: 'app-route-list',
  templateUrl: './route-list.component.html',
  styleUrls: ['./route-list.component.scss']
})
export class RouteListComponent implements OnInit {
emailid;
  useridd;
  options;
  routes;
  
  poiArray=[];
  from_date =new Date();
   colorTheme = 'theme-dark-blue';
  to_date = new Date();
  Load:boolean=false;
  selectedPoisArray=[]
  bsConfig: Partial<BsDatepickerConfig>;
  constructor(private contactService:ContactService,private router:Router,public dialog: MdDialog,) {
    this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' }, { containerClass: this.colorTheme });
   }

  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);
    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();
     const that=this
    $('#routes').on('change', function(){
      var routes=$('#routes').multipleSelect('getSelects','value');
      console.log("jjjddjk",routes);
      that.selectedPoisArray=[]
      if(routes.length>0){
        for(var i=0;i<routes.length;i++){
          for(var j=0;j<that.routes.length;j++){
            if(routes[i]==that.routes[j]._id){
              if(!that.selectedPoisArray.includes(that.routes[j].endPoint._id))
              that.selectedPoisArray.push(that.routes[j].endPoint._id)

              if(!that.selectedPoisArray.includes(that.routes[j].startPoint._id))
              that.selectedPoisArray.push(that.routes[j].startPoint._id);

              console.log(that.selectedPoisArray);
              
            }
          }
        }
      }

      var Table = $('#deviceTable').DataTable( {
 // optional info
});

      $('#deviceTable tbody').on('click', 'tr', function () {

  let bookingData = Table.row(this).data();

  console.log(bookingData);
  
  // do your staff
 });

      that.getPois(that.selectedPoisArray);
    // var selected = $(this).find("option:selected");
    // var arrSelected = [];
    // selected.each(function(){
    //    arrSelected.push($(this).val());
    // });
})
    //  $('#routes').multipleSelect({
    //     width: 200,
    //     placeholder: 'Select route',
    //     filter: true,
    //     single: false,
    //     selectAll: false
 
    //   })
//      $(document).ready(function () {
//      $('#routes').multiselect({
//     // selectAllValue: 'multiselect-all',
//     // enableCaseInsensitiveFiltering: true,
//     // enableFiltering: true,
//     // maxHeight: '300',
//     // buttonWidth: '235',
//     onChange: function(element, checked) {
//         // var brands = $('#routes option:selected');
//         // var selected = [];
//         // $(brands).each(function(index, brand){
//         //     selected.push([$(this).val()]);
//         // });

//         console.log(element);
//     }
// });
  // })
}

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

      var poiObj; 
      this.poiArray=[]
    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;
      
      });
  }
  routeName
  getRouteName(){
    this.contactService.post('/routePlan/get',{user:this.useridd}).subscribe((res:any)=>{
      console.log(res);
      this.routes=res;
      this.loadropdown();
    })
  }
  selectRouteName(event){
    console.log(event);
    
  }

   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);
    //  this.search()
  }
  reportData=[]
  vehicle;
  poi;
  route;
  search(){

   this.vehicle=$('#vehicles').multipleSelect('getSelects','value');
    this.poi=$('#poi').multipleSelect('getSelects','value');
    this.routes=$('#routes').multipleSelect('getSelects','value');
    
    // 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/get',data).subscribe((res:any)=>{
    //   this.reportData=res;
      this.tabelObj.ajax.reload()
    // })
  }

  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){
              
              // $('#deviceTable tbody').on('click', 'tr', function () {
              //   $('#deviceTable').dataTable();
                
              //   console.log(data;
                
               

                
                
              // });
              $('#hault', row).bind('click', () => {   
             //      that.tabelObj.row.add( [ 
             //     'New Group'
             //  ] ).draw( false );
              // $( "#hault").off( "click" );
             
            //   let bookingData =  that.tabelObj.row(this).data();
            //  console.log(bookingData);
             
             let dialogRef = that.dialog.open(HualtListComponent, {
               // width: '950px',
               // height: '1160px',  
               data: data
             }); 
             dialogRef.afterClosed().subscribe(result => {   
            // console.log(result);
              if(result)
               that.tabelObj.ajax.reload();      
            
          })  
             
            
             })
              $('#delete', row).bind('click', () => {   
                var internalThat  = that;
              swal("Are you sure ?", "Do you want to delete ?").then((ans)=>{
                    console.log(ans);
                    // that.accountActivityFunc(data);
                    internalThat.contactService.post('/routePlan/delete',{id:data._id}).subscribe(res=>{
                      internalThat.search()
                    })
                  },err=>{
                    console.log(err);
                  });
              
                
              });

               $('#view', row).bind('click', () => {   
              that.router.navigate(['/addRoutePlan']);
              console.log(data);
              
                localStorage.setItem('routePlanData',JSON.stringify(data))
              
                
              });


            // console.log("kjdkfjdjfj",bookingData);
  
              // });
            },
          ajax: (mainData,callback) => {

           
    
          var data={
            vehicle:that.vehicle,
            poi:that.poi,
            route:that.routes,
            user:that.useridd,
            from:that.from_date,
            to:that.to_date
          }
          console.log(data);

           that.contactService.post('/RoutePlan/get',data).subscribe((res:any)=>{
            that.reportData=res;
            callback({ data:that.reportData});
            },err=>{
              callback({ data:[]});

            })
      // 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": "vehicle",
                  "render": function(data, type, row) {                   
                    return data?data.Device_Name : '';                  
                  }
              },
              {
                  "data": "name",
                  "render": function(data, type, row) {                   
                    return data?data: '';                  
                  }
              },
              {
                  "data": "startPoint",
                  "render": function(data, type, row) {                   
                    return data?data.poi.address : '';                  
                  }
              },
              {
                  "data": "endPoint",
                  "render": function(data, type, row) {                   
                    return data?data.poi.address : '';                   
                  }
              },
              {
                  "data": "hault",
                  
                  "render": function(data, type, row) {                   
                    return data?data.length : 0                 
                  }
                },
                {
                    "data": 'status',
                    "render": function(data, type, row) {                   
                      return data?data.status : '';                  
                    }
                },

               {
          "data":null,
          "defaultContent": "",
          "render":function(data,type,row){   
            return '<button style="background:blue;color:black"><i id="hault" title="Show hault List" style="font-size:20px;color: red" class="fas fa-info"></i></button>'    
      }
    },

               {
          "data":null,
          "defaultContent": "",
          "render":function(data,type,row){   
            return '<i id="delete" title="Delete Route Plan" style="font-size:20px;color: red" class="fas fa-trash"></i>'    
      }
    },

    {
          "data":null,
          "defaultContent": "",
          "render":function(data,type,row){   
            return '<i id="view" title="view Route Plan" style="font-size:20px;color: blue" class="fas fa-eye"></i>'    
      }
    }
             
   
          ],  
          // "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");
  }

  addRoute(){
    this.router.navigate(['/addRoutePlan'])
  }

}
