import { Component, OnInit } from '@angular/core';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { ContactService } from '../../contact.service';
import { MdDialog, MdSnackBar } from '@angular/material';
import { ExpenseComponentComponent } from './expense-component/expense-component.component';
import { ExpenselistComponent } from './expenselist/expenselist.component';
declare var $:any;
declare var google : any;

@Component({
  selector: 'app-trip-by-device',
  templateUrl: './trip-by-device.component.html',
  styleUrls: ['./trip-by-device.component.scss']
})
export class TripByDeviceComponent implements OnInit {
  trip_data =[];
  from_date=new Date();
  to_date=new Date();
  bsConfig: Partial<BsDatepickerConfig>;
  colorTheme = 'theme-dark-blue';
  vehicle: any;
  deviceArr: any=[];
  superAdmin: any;
  fs: any;
  ls: any;
  emailid: any;
  or: any;
  useridd: any;
  mb: any;
  custtype: any;
  devicesss: any;
  finall: any;
  options: any=[];
  supAdmin: any;
  Dealer: any;
  tripReport: any=[];
  quomaseprate = " "
  lattitude: any;
  longitude: any;
  lattitude1: any;
  longitude1: any;
  addressLink: string;
  addressLink1: string;
  constructor(private contactService: ContactService,  public dialog: MdDialog, public snackBar: MdSnackBar) {
    this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' }, { containerClass: this.colorTheme });
    this.from_date.setHours(0,0,0,0); 
   }

  ngOnInit() {
    var that = this;

    $('#select').hide();
    console.log("loginDetails=>",JSON.parse(window.atob(window.localStorage.token.split(".")[1])));

    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.supAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;
    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]))._id;
    this.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.Dealer = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).Dealer;
    // $('.demo').fSelect();
  


    this.contactService.getDevice(this.emailid,this.useridd).subscribe(

      data => {
        this.devicesss = data
     
        this.finall = (this.devicesss.devices);

        for(let i=0;i<this.devicesss.devices.length;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
            }
            this.options.push(a);
          }

        // }
           console.log(this.options);
           let that = this;
           setTimeout(()=>{
             that.loadropdown();
           },100)  

      });
 
  }

  loadropdown() {
    let that = this;
    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(() => {

      $('#select').multipleSelect({
        width: 200,
        placeholder: 'Select device.....',
        filter: true,
      })
     // $('#select').show();
    }, 100);


  }
    Load : boolean = false;
  tripListList(){
    console.log($('#select').multipleSelect('getSelects','value'));
    this.deviceArr =  $('#select').multipleSelect('getSelects','value');
    console.log('this.deviceArr',this.deviceArr);
    // var query ={}
    // query["$and"] = [];
  
    // var query1 = {
    //   $or:[{
    //     user :this.useridd,   
    //   },{
    //     dealer :(this.custtype == true)?this.Dealer:this.useridd,
    //   },{
    //     supAdmin : (this.superAdmin==true)?this.useridd:this.supAdmin
    //   }]
    // }
    // query["$and"].push(query1);
    // if(this.deviceArr.length>0){
    //  var deviceArrQuery = {$in : this.deviceArr};
    //  query["$and"].push(deviceArrQuery);
    // }

    // if(this.from_date){
    //   var fDate = {start_time : {$gte : this.from_date.toISOString()}};
    //   query["$and"].push(fDate);
    // }
    // if(this.to_date){
    //   var tDate ={start_time :  {$lte : this.to_date.toISOString()}};
    //   query["$and"].push(tDate);
    // }


    var query = {
      
    };
    console.log('this.deviceArr=>',this.deviceArr);
    query['user'] = this.useridd;
    query['fromDate'] = this.from_date.toISOString();
    query['toDate'] = this.to_date.toISOString();
    query['device'] = this.deviceArr;
    this.Load = true;
    this.contactService.gettripByDevice(query).subscribe(res=>{
      console.log(res);
      this.Load = false;
      if(res.message == "No Trip Found"){
        let message1="No Trip Found";
        let action:any;
        this.snackBar.open(message1, action, {
          duration: 5000,
          
        });
        this.tripReport=[];
      }else{
        this.tripReport =  res;
      }
    
    },err=>{
      this.Load = false;
      let message1="Please try again";
      let action:any;
      this.snackBar.open(message1, action, {
        duration: 5000,
        
      });
      console.log(err);
    })  
  }


  


  locationAddress: any;
  getAddress(fuelval,val) {
    var outerThis = this;
    console.log(fuelval);
    if (fuelval == undefined) {
      this.lattitude = null;
      this.longitude = null;
      this.lattitude1 = null;
      this.longitude1 = null;
    } else {
      if(val == 'start'){
        this.lattitude = fuelval.start_lat;
        this.longitude = fuelval.start_long;
        var geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(this.lattitude, this.longitude);
      }
      else if(val == 'end'){
        this.lattitude1 = fuelval.end_lat;
        this.longitude1 = fuelval.end_long;
        var geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(this.lattitude1, this.longitude1);
      }else{
        this.lattitude = null;
        this.longitude = null;
        this.lattitude1 = null;
        this.longitude1 = null;
      }

    }


    this.addressLink =  'https://maps.google.com/?q=' + this.lattitude + ',' + this.longitude;
    this.addressLink1 = 'https://maps.google.com/?q=' + this.lattitude1 + ',' + this.longitude1

  }

  exportExcel(){}

  addExpense(tripObject){
    console.log('tripObject=>',tripObject);
    let dialogRef = this.dialog.open(ExpenseComponentComponent, {
      width : "700px",
      data: tripObject
      
    });
  
    dialogRef.afterClosed().subscribe(result => {
      // console.log(result);
      if(result == "success"){
        let message1="Expense Added";
        let action:any;
        this.snackBar.open(message1, action, {
          duration: 5000,          
        });        
      }  
    });  
  }
  
  expenseList(tripObject)
  {
    let dialogRef = this.dialog.open(ExpenselistComponent, {
      width : "700px",
      data: tripObject
    });
  
  }
  

}
