import { Component, OnInit, Output, EventEmitter, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { ContactService } from '../contact.service';
import {Contact} from '../contact';
import * as moment from 'moment-timezone';
import { FlashMessagesService } from 'angular2-flash-messages';
import { MdDialog } from '@angular/material';
import { NotificationSettingComponent } from '../notification-setting/notification-setting.component';
import { TranslateService } from 'ng2-translate';
import { AllMenusComponent } from '../all-menus/all-menus.component';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { AddPlanComponent } from './add-plan/add-plan.component';

declare var swal: any;
declare var $:any;

@Component({
  selector: 'app-account-detail',
  templateUrl: './account-detail.component.html',
  styleUrls: ['./account-detail.component.scss']
})
export class AccountDetailComponent implements OnInit {
  @ViewChild(AllMenusComponent ) languageChangeDetection: AllMenusComponent ; 
  data_descip: string;
  phone_number:'numer';
  final_counter: number;
  text3: string;
  driverManagement:boolean=false;
  paymentGateway:boolean=false
  // relay_timer:boolean=false;
 announcement:any;
 renewalCharges;
 show:boolean=false;
 service2
  service1
  support1
  support2;
  support3
  bsConfig: Partial<BsDatepickerConfig>;
  api_key:any;
  available_languages = [{
      view : "English",
      id : "en"
  },{
      view : "Spanish",
      id : "sp"
  },{
    view : "Persian",
    id : "fa"
},{
  view : "Arabic",
  id : "ar"
},{
  view : "Portuguese",
  id : "pr"
},
{
  view : "Albanian",
  id : "newLan2"
},
{
  view : "French",
  id : "fr"
},
{
  view : "Indonesian",
  id : "bhasa_web"
}];
  fuelunitArr = ['PERCENTAGE', 'LITRE'];
  workingHoursArray=[{name:'Digital input1',id:1},{name:'Digital input2',id:2}];
  workingHours=1;
  fuelunit = 'LITRE';
  selectedlanguage='en';
  GET_notif:any;
  GET_announcememt:any;
  showAnnouncementMenu:boolean=false;
  symbol3: string;
  timezone:any = 'Asia/Kolkata';
  final_counter2: number;
  text2: string;
  symbol2: string;
  timezoneArray=[];
  phone_verfi: boolean;
  text: string;
  final_counter1: number;
  tripGenerationVal:any;
  tripGenerationArr=[{'view': 'Automatic','value':'auto'},{'view' :'Manual', 'value':'manual'}]
  symbol: string;
  email_verfi: boolean;
  logo: any;
  logoutbut: boolean;
  dealer: boolean;
  cust: boolean;
  custtype: any;
  mb: any;
  useridd: any;
  or: any;
fs :any;
ls:any;
cond:Boolean = false;
point : any = 0;
before:any;
emailid:any;
mobile:any;
contacts: Contact[]=[];
contact: Contact;
  Notification: any[];
  data: any = {
    ign: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    poi: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    power: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    fuel: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    geo: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    overspeed: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    AC: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    route: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    maxstop: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    sos: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    sms: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
     vibration: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
     lowBattery: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    accAlarm: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    toll: {
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    harshBreak:{
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    harshAcceleration:{
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    over_stopped:{
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    over_idle:{
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },
    theft:{
      sms_status: false, email_status: false,
      notif_status: false,
      priority: 1, emails:[], phones:[]
    },

  };
  dataOriginal: any;
  fData: any = {
  
  };
  Load: boolean;
  notifType: any;
  isAddEmail: boolean =false;
  emailList: any;
  isAddPhone: boolean = false;
  phonelist: any;
  shownotifdiv: boolean=true;
  allocatedPoints: any;
  colorTheme = 'theme-dark-blue';
  optiondefault: any;
  labelSetting:boolean=true

  constructor(private router: Router,private contactService: ContactService,public translate: TranslateService,private _flashMessagesService: FlashMessagesService,public dialog: MdDialog) {
    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);
    this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' }, { containerClass: this.colorTheme });
   }
  superAdmin:Boolean = false;
  from_date= new Date();
  to_date = new Date();

  ngOnInit() {
   
    var timeZones = moment.tz.names();
    console.log('timeZones',timeZones);

    var fTime = new Date().setHours(0,0,0,0);
    this.from_date = new Date(fTime);

    var td  = new Date().setHours(23,59,59,999);
    this.to_date = new Date(td);
   
   
    this.timezoneArray=[];
    for (var i in timeZones) {
      this.timezoneArray.push({ viewValue: "(GMT" + moment.tz(timeZones[i]).format('Z') + ")" + timeZones[i], value: timeZones[i] });
    }
    

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



    this.logo=window.localStorage['logo'];
   
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    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.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.mobile = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn; 
    this.email_verfi = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).email_verfi; 
    this.phone_verfi = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phone_verfi; 
    this.GET_notif = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).GET_notif; 
    this.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    this.fuelunit = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).fuel_unit
    //console.log(this.mobile) email_verfi phone_verfi
    // console.log(JSON.parse(window.atob(window.localStorage.token.split('.')[1])))\
    var supadm =  localStorage.getItem('superadmin');
    console.log("superadmin=>",supadm);
    if((supadm == 'ON')||(supadm == 'OFF')||(this.custtype)||(this.superAdmin)){
     
      this.shownotifdiv = false;
    }
    console.log("shownotifVeh=>",this.shownotifdiv);
   
    this.getAlert();

    if(this.custtype == true){
      this.cust = true;
    }  
    if(this.mb.charAt(0)=="n"){
      this.mb = ' '
    }


    if( window.localStorage['Custumer'] == 'ON'){
      this.logoutbut = false
      this.dealer = true
   }
   else{
       this.logoutbut = true
   }
        
   this.logo=window.localStorage['logo'];
   this.text=window.localStorage['text'];

   this.getCurrencies();
   this.getLanguage();

   this.getToken();
   this.getApiKey();
   this.getTransectionDetail();
   if(this.superAdmin)
   this.getRechargePlans()
   

}


myaccount(){

  
  this.cond = false
  this.router.navigateByUrl("accountSettings");



// let dialogRef = this.dialog.open(MyaccountComponent, {
//   width: '903px',
//   data: {}
// });

// dialogRef.afterClosed().subscribe(result => {

//   if(result == "succ"){
//     console.log("Updated")
//   }

// });


}
tost1(divid){
  if(divid == "nofsls"){
    this.data_descip = "Please Enter Mandatory Fields";
    launch_toast();
  }
 else if(divid == "succ"){
  this.data_descip = "Succesfully Updated";
  launch_toast();
 }
 else if(divid == "currset"){
  this.data_descip = "Currency Updated";
  launch_toast();
 } else if(divid == "alertset"){
  this.data_descip = "Alert preference set";
  launch_toast();
 }
    function launch_toast() {
     // console.log(divid);
      var x = document.getElementById("toast_1")
      //console.log(x);
      x.className = "show";
      setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1500);
  }
   }

   
editAccount(){
  if(this.fs == "" || this.ls == "" || this.fs == " " || this.ls == " " ){
      this.tost1("nofsls")
  }
  else{
    var tzone = $('#dbselect').multipleSelect('getSelects','value'); 
    console.log('tzone=>',tzone[0]);
    const newContact ={
      fname: this.fs,
      lname: this.ls,
      org: this.or,
      noti: this.GET_notif,
      uid:this.useridd,
      show_announcement:this.GET_announcememt,
      label_setting:this.labelSetting?this.labelSetting:false,
      digital_input:this.workingHours,
      driverManagement:this.driverManagement,
      paymentGateway:this.paymentGateway
      // relay_timer:this.relay_timer
        }
        if(this.renewalCharges!=undefined){
          newContact['renewal_charges']=this.renewalCharges
        }
        if(tzone != undefined){
          newContact['timezone'] = tzone[0];
        }
        
        if(this.fuelunit != undefined){
          newContact['fuel_unit'] = this.fuelunit;
        } 

        if(this.support1 != undefined){
    newContact['support1'] = this.support1;
}
 if(this.support2 != undefined){
    newContact['support2'] = this.support2;
}
 if(this.support3 != undefined){
    newContact['support3'] = this.support3;
}
 if(this.service1 != undefined){
    newContact['service1'] = this.service1
}
 if(this.service2 != undefined){
    newContact['service2'] = this.service2
}




        console.log(newContact);
        this.contactService.updateuid(newContact) .subscribe(contact => {
          this.contacts.push(contact);
          this.tost1("succ");
          window.localStorage['token'] = contact.token ; 
          this.getToken();
          this.ngOnInit();
        } , (err: any) => { 
        
        if(err.status ==   500) {

         }
        else{
       
  
        }
        } 
      ); 
  }

}

mydealer(){
  window.localStorage['token'] =  window.localStorage['Dealer_token'];
  localStorage.removeItem('devices');
  window.localStorage['DataUpdate'] = 'True';
  if(window.localStorage['DataLoaded'] = 'True'){
    window.localStorage['Custumer'] = 'OFF'
    this.router.navigateByUrl("add")
   // this.router.navigateByUrl("const?_status="+"OK");
  }
}

verify_email(){
  if(this.email_verfi == true){
    this.symbol = '\u2714';
    this.text = "Email Verified"
    this.final_counter1 = 0;
    return true
  }
  else{
    this.symbol =  'X'
    this.text = "Email Not Verified"
    this.final_counter1 = 1;
    return true
  }
}

verify_phone(){
  if(this.phone_verfi == true){
    this.symbol2 = '\u2714';
    this.text2 = "Mobile Verified"
    this.final_counter2 = 0;
    return true
  }
  else{
    this.symbol2 =  'X'
    this.text2 = "Mobile Not Verified"
    this.final_counter2 =1;
    return true
  }
}

notifications(){
  this.cond = false
  this.router.navigateByUrl("notifications");
}




deal(){
  if(this.custtype == true){
    this.symbol3 = '\u2714';
    this.text3 = "Dealer"
    this.final_counter = 0;
    return true
  }
  else{
    this.symbol3 =  'X'
    this.text3 = "Not a Dealer"
    this.final_counter =1;
    return true
  }
}




  a(){
    // console.log(this.point);
     if(this.point == 0){
      this.cond = true;
      this.point ++;
     }
   else if(this.point % 2 == 0){
    this.cond = true;
    this.point ++;
   }
   else{
     this.cond = false
     this.point ++;
   }
  
    
  }
  report(){
    this.cond = false
    this.router.navigateByUrl("device-report");
  
  }

  vehicleRoute(){
    this.router.navigateByUrl("vehicleRoute");

  }

  dealerInfo(){
    this.cond = false
    this.router.navigateByUrl("dealerInfo");
  }
  route_map(){
    this.router.navigateByUrl("routeMapping");

  }

  
  Ddetail(){
    this.router.navigateByUrl("driverdetail");
  }
  DModel(){
    this.router.navigateByUrl("deviceModel");
  }
  VType(){
    this.router.navigateByUrl("VehicleType");
  }
  

  
  
  report_speed(){
    // console.log("report speed call")
    this.cond = false
    this.router.navigateByUrl("device-report/device-speed-report");
  }

  driverPerformance(){
    this.cond = false
    this.router.navigateByUrl("device-report/Driver-performance");
  }

  geo(){
    this.router.navigateByUrl("geofencing");
    
  }
  ideal(){
    this.router.navigateByUrl("device-report/ideal-report");
  }
run(){

}
openNav() {
  /*  document.getElementById("myNav").style.width = "100%";
*/
   this.router.navigateByUrl("location");
  
}

logout(){
  window.localStorage.clear();
  this.router.navigateByUrl("login");
}
devi(){
  this.router.navigateByUrl("dashboard");

}
soon(){
  this.router.navigateByUrl("const");
  
}

summaryReport(){

  this.cond = false
  this.router.navigateByUrl("device-report/summary-report");
}

geofancingReport(){
  this.cond = false
  this.router.navigateByUrl("device-report/geofancing");
}

overspeed(){
  this.cond = false
  this.router.navigateByUrl("device-report/overspeed");

} 
routeViolation(){
  this.cond = false
  this.router.navigateByUrl("device-report/routeViolation");

}

stoppage_report(){
  this.cond = false
  this.router.navigateByUrl("device-report/stoppage_report");

}
ignition_report(){
  this.cond = false
  this.router.navigateByUrl("device-report/ignition_report");


}

alert_report(){
  this.cond = false
  this.router.navigateByUrl("device-report/alert_report");


}
trip_report(){
  this.cond = false
  this.router.navigateByUrl("device-report/trip_report");

}

group(){
  this.cond = false
  this.router.navigateByUrl("group_view");
}


distance_report(){
  this.cond = false
  this.router.navigateByUrl("device-report/distance_report");
}

new(){
  this.router.navigateByUrl("new");
  
}
addcus(){
  this.router.navigateByUrl("add");
}
selectedFile: File;
imageURL:any;
onFileChanged(event) {
  
  this.selectedFile = <File>event.target.files[0];
}

onUpload() {

 const fd = new FormData();
 fd.append('photo',this.selectedFile,this.selectedFile.name)
  console.log("Binaryimage = > ",fd );
  this.contactService.imageupload(fd)
    .subscribe(res=>{
      console.log(res);
      if(res){
        var pld = {
          _id : this.useridd,
          imageDoc : [res['_body']]
        }

        this.contactService.updateImage(pld).subscribe(res=>{
          console.log(res);
          var chkPP = localStorage.getItem('profilePic');
          if(chkPP != null){
            localStorage.removeItem('profilePic');
          }   
          this.data_descip = "Image Succesfully Shared";
          launch_toast();
        })

      }   
  console.log(res);
    },err=>{
      console.log(err);
    })

    function launch_toast() {
      // console.log(divid);
       var x = document.getElementById("toast_1")
       //console.log(x);
       x.className = "show";
       setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1500);
   }

}

// https://www.oneqlik.in/users/uploadImage
getAlert() {
  this.Load = true;
  this.contactService.getcustToken(this.useridd).subscribe(resp => {
    console.log(resp);
    this.Load = false;
    console.log(resp);
    if (resp['cust'].alert != undefined){
      console.log("aasas", resp['cust'].alert);
          var dummy=resp['cust'].alert;
      // this.data = resp['cust'].alert;
    

    for(var mData in this.data){
      for(var pData in dummy){
        if(mData === pData){
          console.log(dummy[mData]);
          this.data[mData]=dummy[mData];
        }else{
          this.data[pData]= dummy[pData];
        }
      }
   
    }

      console.log("kkkk", this.data);
      this.dataOriginal = JSON.parse(JSON.stringify(this.data));
    }
  }, err => {
    this.Load = false;
    console.log("err", err);
  })

}

tab(key1, key2) {
  if (key1 && key2)
    this.data[key1][key2] = !this.data[key1][key2];

  if (JSON.stringify(this.data) === JSON.stringify(this.dataOriginal))
    return;

  this.fData.contactid = this.useridd;
  this.fData.alert = this.data;
  this.Load = true;
  this.contactService.editDealer(this.fData).subscribe(resp => {
    this.Load = false;
    this._flashMessagesService.show("Setting Updated", { cssClass: 'alert-success', timeout: 2000 });
    // toastr.success("Setting Updated");
   // this.router.navigateByUrl("/account")
    this.dataOriginal = JSON.parse(JSON.stringify(this.data));
  }, err => {
    this.Load = false;
    this._flashMessagesService.show("Server error , Try after sometime !!!", { cssClass: 'alert-denger', timeout: 2000 });
    console.log("err", err);
  })
}

tab1(key1, key2, value) {
  if (key1 && key2)
    if (!value)
      this.data[key1][key2] = !this.data[key1][key2];
    else
      this.data[key1][key2] = value;
  if (JSON.stringify(this.data) === JSON.stringify(this.dataOriginal))
    return;

  this.fData.contactid = this.useridd;
  this.fData.alert = this.data;
  this.Load = true;
  this.contactService.editDealer(this.fData).subscribe(resp => {
 //   toastr.success("Setting Updated");
 this.Load = false;
 this._flashMessagesService.show("Setting Updated", { cssClass: 'alert-success', timeout: 2000 });
   // this.router.navigateByUrl("/account")
    this.dataOriginal = JSON.parse(JSON.stringify(this.data));
  }, err => {
    this.Load = false;
    this._flashMessagesService.show("Server error , Try after sometime !!!", { cssClass: 'alert-denger', timeout: 2000 });
    console.log("err", err);
  })
}


onClickAddEmail(noti){
  console.log(this.data);
  console.log(noti);
  this.notifType=noti;
  this.isAddEmail=true;
  var data = {
    "buttonClick" : 'email',
    "notifType" : this.notifType,
    "compData" : this.data
  }
  //this.emailList=this.data[noti].emails;
 // console.log("in Email",this.emailList);
  let dialogRef = this.dialog.open(NotificationSettingComponent, {
    data: {"notifData":data}   
  });

  dialogRef.afterClosed().subscribe(result => {
    // console.log(result);
    if (result == "close") {
    
    }
  });
// this.modelService.getModal('myModal').open();
}
onClickAddPhone(noti){
  console.log(this.data);
  this.notifType=noti;
  this.isAddPhone=true;
  var data = {
    buttonClick : 'phone',
    "notifType" : this.notifType,
    "compData" :this.data
  }
 // this.phonelist=this.data[noti].phones;
//console.log("in Email",this.phonelist)
// this.modelService.getModal('myModal').open();
let dialogRef = this.dialog.open(NotificationSettingComponent, {
  data: {"notifData":data}         
});
dialogRef.afterClosed().subscribe(result => {
  // console.log(result);
  if (result == "close") {
   
  }
});

}


setPriority(notiType, priority) {
  console.log(priority);
  console.log(this.data);
  switch (notiType) {
    case 'ign':
      this.data.ign.priority = priority;
      return;
    case 'geo':
      this.data.geo.priority = priority;
      return;
    case 'poi':
      this.data.poi.priority = priority;
      return;
    case 'route':
      this.data.route.priority = priority;
      return;
    case 'overspeed':
      this.data.overspeed.priority = priority;
      return;
    case 'maxstop':
      this.data.maxstop.priority = priority;
      return;
    case 'fuel':
      this.data.fuel.priority = priority;
      return;
    case 'AC':
      this.data.AC.priority = priority;
      return;
    case 'power':
      this.data.power.priority = priority;
      return;
    case 'sos':
      this.data.sos.priority = priority;
      return;
    default:
      return;
  };


}


changelanguage(){
  console.log("inside function");
  var payload = {
    uid: this.useridd,
    lang: this.selectedlanguage
  }
  this.contactService.setlanguage(payload).subscribe(res=>{
    console.log(res);
    // this.translate.use(this.selectedlanguage);
    if(res.message == 'language updated sucessfully'){
      console.log("language saved");
      localStorage.setItem('appLang',this.selectedlanguage);
      this.languageChangeDetection.getLanguage()
      // this.getLanguage()
    }
    // this.translate.setDefaultLang('es');
  },err=>{
    this.selectedlanguage = 'en' ; 
  })

}

getLanguage(){
  var that = this;
var Var = { uid: this.useridd };
 this.contactService.getLanguages(Var).subscribe(res=>{
   this.selectedlanguage = res.language_code ;
   console.log("fdkjjdfj",res);
   
   if(res.isSuperAdmin)
   {
     this.showAnnouncementMenu=true
   }else{
     this.showAnnouncementMenu=false
   }
   this.support1=res.support1?res.support1:undefined
   this.support2=res.support2?res.support2:undefined
   this.support3=res.support3?res.support3:undefined
   this.service1=res.service1?res.service1:undefined
    this.service2=res.service2?res.service2:undefined
   this.announcement=res.announcement?res.announcement:undefined
   this.GET_announcememt=res.show_announcement?res.show_announcement:false;
   
   console.log(res.isSuperAdmin,this.showAnnouncementMenu,this.announcement,this.GET_announcememt);
   
   this.translate.setDefaultLang(this.selectedlanguage);
 
   this.translate.use(this.selectedlanguage);
   var currencyfiltered = this.currency.filter(d=>{
     if(res.currency_code != undefined){
      if(d.currencyVal === res.currency_code){
        return d.country;
      }
     }else{
       if(d.currencyVal === 'INR'){
        return d.country;
       }
     }
   })
   this.optiondefault = currencyfiltered[0].country;
 

  },err=>{
   console.log(err);
 })

}

getToken(){
 
  this.contactService.getUserObj(this.useridd).subscribe(res=>{
    this.timezone = res.timezone; 
    this.support1=res.support1?res.support1:undefined
   this.support2=res.support2?res.support2:undefined
   this.support3=res.support3?res.support3:undefined
   this.service1=res.service1?res.service1:undefined
    this.service2=res.service2?res.service2:undefined;
    this.driverManagement=res.driverManagement?res.driverManagement:false;
    this.paymentGateway=res.paymentgateway?res.paymentgateway:false;
    if(res.digital_input){
      this.workingHours=res.digital_input
    }
    if(res.renewal_charges){
      this.renewalCharges=res.renewal_charges
    }
    if(res.tripGeneration != undefined){
      this.tripGenerationVal = res.tripGeneration ;
    }
    // if(res.relay_timer!=undefined){
    //   this.relay_timer=res.relay_timer
    // }
    if(res.label_setting!=undefined){
        this.labelSetting=res.label_setting
    }
    console.log("LABLE SETTING", this.labelSetting);
    
    setTimeout(() => {
      $('#dbselect').multipleSelect({
        width: 300,
        placeholder: 'Select Timezone',
        filter: true,
        single: true,
        selectAll: false
      })   
    }, 100);

  })
  
}




getTransectionDetail(){
  console.log("Inside Transection Detail Page");
  this.allocatedPoints =[];
  if(this.from_date){
    var fd = this.from_date.toISOString();
  }
  if(this.to_date){
    var td = this.to_date.toISOString()
  }

  this.contactService.getPointDetails(this.useridd,fd,td).subscribe(res=>{
    console.log('allocatedPoint',res);
    this.allocatedPoints = res; 
    this.show=true;
  })
}


tripGenerationFunc(ev){
  console.log(ev);
  var payload = {
    uid: this.useridd,
    tripGeneration: ev.value
  }
  this.contactService.setlanguage(payload).subscribe(res=>{
    console.log('res=>',res);
    this.getToken()

  this.data_descip = "Setting Saved";
  launch_toast();
  })


  
  function launch_toast() {
    // console.log(divid);
     var x = document.getElementById("toast")
     //console.log(x);
     x.className = "show";
     setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1500);
 }

}
btnTag:boolean = false;
btnKey=  'Save'
getApiKey(){
  this.contactService.getgoogleApi(this.useridd).subscribe(res=>{
      if(res.message != "api key not found"){
        this.api_key = res.api_key; 
        this.btnTag = true;
        this.btnKey=  'Change';

      }else{
      
        console.log('this.api_key',this.api_key);
      }
  })
}

saveApi(){
  if(this.btnKey === 'Change'){
    this.btnTag = false;
    this.btnKey = 'Save';
    return;
  }

  if(this.btnKey === 'Save'){
      var pld= {
        u_id: this.useridd,
        api_key: this.api_key
      }
    this.contactService.setgoogleApi(pld).subscribe(res=>{
          console.log(res);
          this.data_descip = "Google API Key Saved";
          launch_toast();
 
  })
 
  }

  function launch_toast() {
    // console.log(divid);
     var x = document.getElementById("toast_1")
     //console.log(x);
     x.className = "show";
     setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1500);
 }
}

createAnnouncement(){
  console.log("In announcement");
   var payload = {
    uid: this.useridd,
    announcement: this.announcement
  }
  this.contactService.setlanguage(payload).subscribe(res=>{
    console.log(res);
    // this.translate.use(this.selectedlanguage);
    if(res.message == 'announcement updated sucessfully'){
      console.log("announcement saved");
       this.tost1("succ");
      this.getLanguage()
    }
    // this.translate.setDefaultLang('es');
  })
  
}

currency=[];
getCurrencies(){
  this.currency = [];
  // this.contactService.getCurrencies().subscribe(res=>{   
    var currencyObj = this.currencyJson;  
    for(var i in currencyObj){
      if(this.data.currency != undefined){
        var devicecurr = this.data.currency ; 
        if(i == devicecurr){    
          this.optiondefault = i+ '-' +  currencyObj[i];
         }

      }else{
        // if(i == 'INR'){    
        //   this.optiondefault = i+ '-' +  currencyObj[i];
        //  }
      }
  
    var tempObj = {
      currencyVal : i,
      country       : i+ '-' +  currencyObj[i]
    }
      this.currency.push(tempObj);
    }
  
    console.log(this.currency);
    // this.loadropdown();
  // })
}

dataSelect=[];

filterStates(val) {
  console.log(val)
  // console.log(this.dummyuserData)
  if (val) {
    const filterValue: any = val;
    console.log(this.currency);
    this.dataSelect = this.currency.filter(function (d) {
      return d.country.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase()) > -1;
    });
   
    return this.dataSelect;
  }
  
}

currencySet(){
  console.log(this.dataSelect);
  var pld= {
    uid : this.useridd,
    currency_code : (this.dataSelect.length !=0)? this.dataSelect[0].currencyVal : this.optiondefault.split('-')[0]
  }
  console.log(pld);
  this.contactService.setlanguage(pld).subscribe(res=>{
    console.log(res);
    this.tost1('currset');
  })
}
rechargePlans
getRechargePlans(){
  this.contactService.get('/RechargePlan/get?SupAdmin='+this.useridd).subscribe(res=>{
    console.log(res);
    this.rechargePlans=res;
    
  })
}

addNewPlan(){
  
let dialogRef = this.dialog.open(AddPlanComponent, {
  width: '600px',
  height:'400px',
  data: null
});

dialogRef.afterClosed().subscribe(result => {

  if(result == "succ"){
   this.getRechargePlans()
  }

});
}

deletePlan(id){
  this.contactService.get('/RechargePlan/delete?id='+id).subscribe(res=>{
    console.log(res);
    this.getRechargePlans()
    
  })
}
editPlan(item){
 let dialogRef = this.dialog.open(AddPlanComponent, {
  width: '600px',
  height:'400px',
  data: item
});

dialogRef.afterClosed().subscribe(result => {

  if(result == "succ"){
   this.getRechargePlans()
  }

}); 
}



currencyJson = {
  "AED": "United Arab Emirates Dirham",
  "AFN": "Afghan Afghani",
  "ALL": "Albanian Lek",
  "AMD": "Armenian Dram",
  "ANG": "Netherlands Antillean Guilder",
  "AOA": "Angolan Kwanza",
  "ARS": "Argentine Peso",
  "AUD": "Australian Dollar",
  "AWG": "Aruban Florin",
  "AZN": "Azerbaijani Manat",
  "BAM": "Bosnia-Herzegovina Convertible Mark",
  "BBD": "Barbadian Dollar",
  "BDT": "Bangladeshi Taka",
  "BGN": "Bulgarian Lev",
  "BHD": "Bahraini Dinar",
  "BIF": "Burundian Franc",
  "BMD": "Bermudan Dollar",
  "BND": "Brunei Dollar",
  "BOB": "Bolivian Boliviano",
  "BRL": "Brazilian Real",
  "BSD": "Bahamian Dollar",
  "BTC": "Bitcoin",
  "BTN": "Bhutanese Ngultrum",
  "BWP": "Botswanan Pula",
  "BYN": "Belarusian Ruble",
  "BZD": "Belize Dollar",
  "CAD": "Canadian Dollar",
  "CDF": "Congolese Franc",
  "CHF": "Swiss Franc",
  "CLF": "Chilean Unit of Account (UF)",
  "CLP": "Chilean Peso",
  "CNH": "Chinese Yuan (Offshore)",
  "CNY": "Chinese Yuan",
  "COP": "Colombian Peso",
  "CRC": "Costa Rican Colón",
  "CUC": "Cuban Convertible Peso",
  "CUP": "Cuban Peso",
  "CVE": "Cape Verdean Escudo",
  "CZK": "Czech Republic Koruna",
  "DJF": "Djiboutian Franc",
  "DKK": "Danish Krone",
  "DOP": "Dominican Peso",
  "DZD": "Algerian Dinar",
  "EGP": "Egyptian Pound",
  "ERN": "Eritrean Nakfa",
  "ETB": "Ethiopian Birr",
  "EUR": "Euro",
  "FJD": "Fijian Dollar",
  "FKP": "Falkland Islands Pound",
  "GBP": "British Pound Sterling",
  "GEL": "Georgian Lari",
  "GGP": "Guernsey Pound",
  "GHS": "Ghanaian Cedi",
  "GIP": "Gibraltar Pound",
  "GMD": "Gambian Dalasi",
  "GNF": "Guinean Franc",
  "GTQ": "Guatemalan Quetzal",
  "GYD": "Guyanaese Dollar",
  "HKD": "Hong Kong Dollar",
  "HNL": "Honduran Lempira",
  "HRK": "Croatian Kuna",
  "HTG": "Haitian Gourde",
  "HUF": "Hungarian Forint",
  "IDR": "Indonesian Rupiah",
  "ILS": "Israeli New Sheqel",
  "IMP": "Manx pound",
  "INR": "Indian Rupee",
  "IQD": "Iraqi Dinar",
  "IRR": "Iranian Rial",
  "ISK": "Icelandic Króna",
  "JEP": "Jersey Pound",
  "JMD": "Jamaican Dollar",
  "JOD": "Jordanian Dinar",
  "JPY": "Japanese Yen",
  "KES": "Kenyan Shilling",
  "KGS": "Kyrgystani Som",
  "KHR": "Cambodian Riel",
  "KMF": "Comorian Franc",
  "KPW": "North Korean Won",
  "KRW": "South Korean Won",
  "KWD": "Kuwaiti Dinar",
  "KYD": "Cayman Islands Dollar",
  "KZT": "Kazakhstani Tenge",
  "LAK": "Laotian Kip",
  "LBP": "Lebanese Pound",
  "LKR": "Sri Lankan Rupee",
  "LRD": "Liberian Dollar",
  "LSL": "Lesotho Loti",
  "LYD": "Libyan Dinar",
  "MAD": "Moroccan Dirham",
  "MDL": "Moldovan Leu",
  "MGA": "Malagasy Ariary",
  "MKD": "Macedonian Denar",
  "MMK": "Myanma Kyat",
  "MNT": "Mongolian Tugrik",
  "MOP": "Macanese Pataca",
  "MRO": "Mauritanian Ouguiya (pre-2018)",
  "MRU": "Mauritanian Ouguiya",
  "MUR": "Mauritian Rupee",
  "MVR": "Maldivian Rufiyaa",
  "MWK": "Malawian Kwacha",
  "MXN": "Mexican Peso",
  "MYR": "Malaysian Ringgit",
  "MZN": "Mozambican Metical",
  "NAD": "Namibian Dollar",
  "NGN": "Nigerian Naira",
  "NIO": "Nicaraguan Córdoba",
  "NOK": "Norwegian Krone",
  "NPR": "Nepalese Rupee",
  "NZD": "New Zealand Dollar",
  "OMR": "Omani Rial",
  "PAB": "Panamanian Balboa",
  "PEN": "Peruvian Nuevo Sol",
  "PGK": "Papua New Guinean Kina",
  "PHP": "Philippine Peso",
  "PKR": "Pakistani Rupee",
  "PLN": "Polish Zloty",
  "PYG": "Paraguayan Guarani",
  "QAR": "Qatari Rial",
  "RON": "Romanian Leu",
  "RSD": "Serbian Dinar",
  "RUB": "Russian Ruble",
  "RWF": "Rwandan Franc",
  "SAR": "Saudi Riyal",
  "SBD": "Solomon Islands Dollar",
  "SCR": "Seychellois Rupee",
  "SDG": "Sudanese Pound",
  "SEK": "Swedish Krona",
  "SGD": "Singapore Dollar",
  "SHP": "Saint Helena Pound",
  "SLL": "Sierra Leonean Leone",
  "SOS": "Somali Shilling",
  "SRD": "Surinamese Dollar",
  "SSP": "South Sudanese Pound",
  "STD": "São Tomé and Príncipe Dobra (pre-2018)",
  "STN": "São Tomé and Príncipe Dobra",
  "SVC": "Salvadoran Colón",
  "SYP": "Syrian Pound",
  "SZL": "Swazi Lilangeni",
  "THB": "Thai Baht",
  "TJS": "Tajikistani Somoni",
  "TMT": "Turkmenistani Manat",
  "TND": "Tunisian Dinar",
  "TOP": "Tongan Pa'anga",
  "TRY": "Turkish Lira",
  "TTD": "Trinidad and Tobago Dollar",
  "TWD": "New Taiwan Dollar",
  "TZS": "Tanzanian Shilling",
  "UAH": "Ukrainian Hryvnia",
  "UGX": "Ugandan Shilling",
  "USD": "United States Dollar",
  "UYU": "Uruguayan Peso",
  "UZS": "Uzbekistan Som",
  "VEF": "Venezuelan Bolívar Fuerte (Old)",
  "VES": "Venezuelan Bolívar Soberano",
  "VND": "Vietnamese Dong",
  "VUV": "Vanuatu Vatu",
  "WST": "Samoan Tala",
  "XAF": "CFA Franc BEAC",
  "XAG": "Silver Ounce",
  "XAU": "Gold Ounce",
  "XCD": "East Caribbean Dollar",
  "XDR": "Special Drawing Rights",
  "XOF": "CFA Franc BCEAO",
  "XPD": "Palladium Ounce",
  "XPF": "CFP Franc",
  "XPT": "Platinum Ounce",
  "YER": "Yemeni Rial",
  "ZAR": "South African Rand",
  "ZMW": "Zambian Kwacha",
  "ZWL": "Zimbabwean Dollar"
}
}
