import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { ResponseOptions, Response } from '@angular/http';
import { Contact } from '../contact';
import { ContactService } from '../contact.service';
import { Otp } from '../otp';
import {MdSnackBar} from '@angular/material';
// import {Md5} from 'ts-md5/dist/md5';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { DialogContentExampleDialogComponent } from '../dialog-content-example-dialog/dialog-content-example-dialog.component'
import { FlashMessagesService } from 'angular2-flash-messages';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn } from '@angular/forms';
const EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
import { AddCustComponent } from '../add-cust/add-cust.component';
import { MyaccountComponent } from '../myaccount/myaccount.component';
import { SidebarComponent } from '../sidebar/sidebar.component';
import { Observable } from 'rxjs/Rx';
import { EditCostumerComponent } from '../edit-costumer/edit-costumer.component';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/debounceTime';
// import { ReportSettingComponent } from './report-setting/report-setting.component';
import { ReportSettingComponent } from '../add/report-setting/report-setting.component'
import { environment } from '../../environments/environment';
import { ResetPasswordComponent } from '../add/reset-password/reset-password.component';
import { TranslateService } from 'ng2-translate';
import { DashboardContentComponent } from '../add/dashboard-content/dashboard-content.component';
import { PointShareComponent } from '../point-share/point-share.component';
declare var swal: any;
@Component({
  selector: 'app-technician',
  templateUrl: './technician.component.html',
  styleUrls: ['./technician.component.scss']
})
export class TechnicianComponent implements OnInit {
 modelChanged: Subject<string> = new Subject<string>();
  kycStatus=[{Name:'Approved',value:'Approved'},{Name:'Reject',value:'Reject'},{Name:'Pending',value:'Pending'}]
  dealerChk: boolean = false;
  ev: any;
  show1: boolean = false;
  show2: boolean = true;
  show3: boolean = false;
  first_name: any;
  logoutbut: boolean;
  last_name: any;
  passwordd: any;
  org_name: any;
  allUser:boolean=false;
  emaill: any;
  phone: any;
  executed: any;
  $event2: any;
  dealer: any;
  contacts: Contact[] = [];
  contact: Contact;
  login1: any;
  mess2: any;
  mess: any;
  otp: any;
  switchVal: any;
  str: boolean = false;
  password2: any;
  cust_load: any;
  errmsg: boolean =true;
  serviceResponse: string;
  errorMsg: boolean;
  showNav: boolean =false;
  url: any;
  dealer_Permission: any;
  adbtn: string;
  report() {
    this.cond = false
    this.router.navigateByUrl("device-report");

  }
  report_speed() {
    // console.log("report speed call")
    this.cond = false
    this.router.navigateByUrl("device-report/device-speed-report");
  }
  stre() {
    this.str = true;
  }
  stren() {
    this.str = false;
  }
  addcus() {
    this.router.navigateByUrl("add");
  }

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



  clear() {
    this.first_name = ' '
    this.last_name = ' '
    this.emaill = null
    this.phone = null
  }
  before: any;
  emmnerr: any;
  Load: any
  $event: any;
  openDialog() {
  
        let dialogRef = this.dialog.open(AddCustComponent, {
          width: '800px',
          'data':{role:'technitian'}
        //  height: '600px', 
    
        });
    
        dialogRef.afterClosed().subscribe(result => {
          // console.log(result);
          if (result == "succ") {
            this.tost1("succ");
            this.ngOnInit();
    
          }
        });
  }



  constructor(private contactService: ContactService, public snackBar: MdSnackBar, private router: Router, private _flashMessagesService: FlashMessagesService, public dialog: MdDialog, public translate: TranslateService) {
    this.modelChanged
      .debounceTime(1000) // wait 300ms after the last event before emitting last event
      .distinctUntilChanged() // only emit if value is different from previous value
      .subscribe(myInput => {
        this.myInput = myInput;
        // console.log('debounce')
        // this.dealerDetail();
        this.showDemoVideo()
        this.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);
  }

  data_descip: any;
  table1ch() {

    myFunction();
    function myFunction() {
      var input, filter, table, tr, td, i, td1;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("myTable");
      tr = table.getElementsByTagName("tr");
      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[1];
        td1 = tr[i].getElementsByTagName("td")[0]
        if (td) {
          if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
          }
          else if (td1.innerHTML.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
          }
          else {
            tr[i].style.display = "none";
          }
        }
      }
    }
  }

  tost1(divid) {
    if (divid == "EmM") {
      this.data_descip = this.emmnerr.split(":")[1]
      launch_toast();
    }
    else if (divid == "succ") {
      this.data_descip = "Custumer Successfully Added"
      launch_toast();
    }else if(divid == "reportPref"){
      this.data_descip = "Report Preference updated !!!"
      launch_toast();
    }else if(divid == "password_changed"){
      this.data_descip = "Password updated !!!";
      launch_toast();
    }else if(divid == "alertset"){
      this.data_descip = "Alert preference updated !!!";
      launch_toast();
    }else if(divid=="kyc"){
       this.data_descip = "KYC Status updated !!!";
      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", ""); }, 4500);
    }
  }

  valclear() {
    this._flashMessagesService.show("Cleared", { cssClass: 'alert-warning', timeout: 2000 });

  }

  click1(event) {
    this.show2 = false;
    this.show3 = true;
    if ((event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 9 || event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39) {
    }
    /* if(event.keyCode===13){
    this.otp_window();
    } */

    else
      event.preventDefault();
  }
  click2(event2) {
    this.show2 = true;
    this.show3 = false;

  }
  call(e) {
    {
      if (e.keyCode == 32) {
        e.preventDefault();
      }
    }
  }
  geo() {
    this.router.navigateByUrl("geofencing");

  }
  devicess: any;
  final: any;
  /*  getdev(){
     let foods = []
     this.contactService.getDevice(this.emailid,this.useridd).subscribe(
         
       data => {
         this.devicess = data 
   
         let swap;
         for(let g = 0;g<this.devicess.devices.length-1;g++ ){
           for(let c = 0;c<this.devicess.devices.length-g-1;c++ ){
             if(this.devicess.devices[c].Device_Name>this.devicess.devices[c+1].Device_Name){
                 swap = this.devicess.devices[c];
                 this.devicess.devices[c] = this.devicess.devices[c+1];
                 this.devicess.devices[c+1] = swap;
             }
           }
         }
   
         this.final = this.devicess.devices
         
        for(let i=0;i<this.devicess.devices.length;i++){
        
          if(this.devicess.devices[i].type_of_device =="Tracker"){
            let a ={
             value : this.devicess.devices[i].Device_Name,
             viewValue:this.devicess.devices[i].Device_Name
            }
            foods.push(a);
          }
       
        }
   
       });
   } */
  cond: Boolean = false;
  point: any = 0;
  aa() {
    // 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++;
    }


  }
  run() {

  }

  devicesss: any;
  subscription: any;
  timer: any;
  messageSuccess: any = true;
  selectedlanguage :any; 

  vewdev(id) {
    console.log(id);
    localStorage.setItem("custId", id);
    localStorage.removeItem("in1");
    this.selectedlanguage = localStorage.getItem('appLang'); 
    this.translate.setDefaultLang(this.selectedlanguage);
    this.translate.use(this.selectedlanguage);
    this.contactService.getcustToken(id).subscribe(
      data => {
        this.devicesss = data
        // console.log(this.devicesss)

        window.localStorage['Dealer_token'] = window.localStorage['token']
        window.localStorage['token'] = this.devicesss.custumer_token;
        localStorage.removeItem('devices');
        window.localStorage['DataUpdate'] = 'True';
        window.localStorage['Custumer'] = 'ON';
        localStorage.setItem('superadmin', "ON");
     
        var chkPP = localStorage.getItem('profilePic');
        if(chkPP != null){
          localStorage.removeItem('profilePic');
        }  
        // localStorage.setItem('Dealer',"OFF");
        // localStorage.setItem('superadmin',"OFF")
        console.log('this.superAdmin',this.superAdmin);
        debugger;
        if(this.superAdmin === true){
          localStorage.setItem('supAdminAcessToCust', 'true' ); 
        }
        if (window.localStorage['DataLoaded'] = 'True') {
          let dlrStatus = "true";

          localStorage.setItem("dlrchk", dlrStatus)

          this.router.navigateByUrl("const?_status=" + "OK");

          // console.log('testing', this.useridd);
        }


      });
  }



  myInput: any;
  myaccount() {

    let dialogRef = this.dialog.open(MyaccountComponent, {
      width: '680px',

      data: {}
    });

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

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

    });
  }
  ign() {
    this.router.navigateByUrl("device-report/ign-report");

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

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

  }

  route_map() {
    this.router.navigateByUrl("routeMapping");

  }
  ideal() {
    this.router.navigateByUrl("device-report/ideal-report");
  }
  soon() {
    this.router.navigateByUrl("const?_i=" + window.localStorage.token);

  }
  new() {
    this.router.navigateByUrl("new");

  }

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

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


  }

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

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

  }

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

  }

  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");
    }
  }


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


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

  }


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

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

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

  }


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


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

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

  summaryReport() {

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

  fs: any;
  ls: any;
  emailid: any;
  or: any;
  useridd: any;
  custtype: any;
  custumer: any=[];
  mb: any;
  cust: boolean = false;
  logo: any;
  text: any;
  superAdmin: Boolean = false;
  ngOnInit() {

    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
      console.log('whatishere=>',this.superAdmin);
    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;
    let test = JSON.parse(window.atob(window.localStorage.token.split('.')[1]));
    this.dealer_Permission = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).cust_add_permission;

    // console.log(test);
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.adbtn = localStorage.getItem("dlrchk");
    localStorage.setItem("dlrchk", this.custtype);
    //  this.getdev();
    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'];

 
    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', function () {
      history.pushState(null, null, document.URL);
    });

    this.logo = window.localStorage['logo'];
    this.text = window.localStorage['text'];
    this.getCustomer();
  }


  onChange(cust, ev) {
 
    let status = ev;
    // console.log(status.checked);

    let cust_status = cust;
    let cust_id = cust._id;
    let cust_activity = cust.status
    // console.log(cust_activity);


    this.cust_load = {
      "uId": cust_id,
      "loggedIn_id": this.useridd,
      "status": status.checked
    }
    // console.log(cust_id);


    console.log(this.cust_load);
    this.contactService.custStatus(this.cust_load)
      .subscribe(res => {
        let a = res;
        // console.log(a);
        // console.log("Status changed");
      })
  }

  getCustomer(){
     this.Load = true;  
    this.contactService.getTechnician(this.useridd, this.skip, this.limit,this.myInput,this.allUser).subscribe(  
      data => {
        this.Load = false;
        this.custumer=[];
        this.custumer = data;
        for(var i=0;i<this.custumer.length;i++){
          if(this.custumer[i].adminAlert == undefined){
            this.custumer[i]['adminAlert'] = false;
          }
          if(this.custumer[i].dealerAlert == undefined){
            this.custumer[i]['dealerAlert'] = false;
          }
        }
        console.log("custDetail=>", this.custumer);
      }, err => {
        // console.log("errlog");
         this.Load = false;
        this.custumer=[];
        this.firstcall = true;
        this.lastcall = false;
      });
  }


  edit_costumerDetail(cust_payload) {
    // console.log("edit component method!!!");
    console.log("cust_payload",cust_payload);
    cust_payload.ID = 'edit';
    let dialogRef = this.dialog.open(EditCostumerComponent, {
      width: '700px',
      // height: '600px',
      data: { dealer_payload: cust_payload }
    });


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

      // console.log(result);
      if (result == "success") {
        this.ngOnInit();
      }
    });
  }

  delete_costumerDetail(cust_payload){

    var  that =this;
    console.log(cust_payload);
    cust_payload.ID = 'delete';
    cust_payload['page'] = 'cust';

    let dialogRef = this.dialog.open(EditCostumerComponent, {
      width: '500px',
      height: '600px',
      data: { dealer_payload: cust_payload }
    });

    
    dialogRef.afterClosed().subscribe(result => {
      console.log(result);
      // console.log(result);
      if (result == "yes") {
        // console.log("DealerId=>",dealerDelete.dealer_id)
        var deletePayload = {
          'userId' : cust_payload._id,
          'deleteuser' : true
        }

        console.log(deletePayload);
        this.contactService.deleteCostumer(deletePayload)
          .subscribe(res=>{
            console.log(res);
            this.serviceResponse = "User Deleted"; 
            this.errorMsg =true;
            this.ngOnInit();
           var success =  setTimeout(function(){
             clearInterval(success);
              that.errorMsg = false; 
           },5000)
            
          },err=>{
            this.serviceResponse = "Please try after sometime";
            var error =  setTimeout(function(){
              clearInterval(error);
               that.errorMsg = false; 
            },5000)
          })

      }

      if (result == "no") {
        console.log(result);
      }

    });



  }

  skip: number = 1;
  limit: number = 10;
  firstcall: boolean = false;
  lastcall: boolean = true;
  next() {
    this.lastcall = false;
    this.skip += 1;
    this.ngOnInit();
    // this.sidebarData();
  }
  pre() {
    // console.log(this.skip)
    if (this.skip > 1) {
      this.skip -= 1;
      this.lastcall = false;
      this.firstcall = false;
      this.ngOnInit();
      // this.sidebarData();
    } else {
      this.lastcall = true;
      this.firstcall = false;
    }

  }

  searchFilter(text: string) {
    this.modelChanged.next(text);
    // this.myInput;
    // console.log(this.myInput);
    // this.sidebarData()

  }

  viewDocuments(docs){
    console.log("Documents=>", docs);
    var  that =this;
    docs.ID = 'viewDoc';
    console.log(docs);
    let dialogRef = this.dialog.open(EditCostumerComponent, {
      width: '900px', 
      data: { dealer_payload: docs }
    });

    
    dialogRef.afterClosed().subscribe(result => {
      if (result == "yes") {
        this.getCustomer()
      }

      if (result == "no") {
     
      }
      if(result == 'imageupdated'){
        swal(
          'Updated',
          'Documents has been Updated.',
          'success'
        ) 
          this.ngOnInit();
      }
    });
  }

  reportSetting(custObj){
    console.log("custObj=>" , custObj);
   var custId = custObj._id;
    let dialogRef = this.dialog.open(ReportSettingComponent, {
      width: '800px',
      data : custId
    //  height: '600px', 

    });

    dialogRef.afterClosed().subscribe(result => {
      // console.log(result);
      if (result == "updated") {
        this.tost1("reportPref");
        this.ngOnInit();

      }
    });

  }


  
  showMenu = environment.showLandingpageMenu;
  showDemoVideo(){
    let split1 = document.URL.split('//')[1];
    console.log(split1,document);
    let split2 = split1.split('/')[0];
    let splitForStyle = split1.split('/')[1];
    this.url =  split2;
    console.log("split2",this.url);
   
    
      for(var i = 0; i <this.showMenu.length;i++){
        if (this.url == 'www.oneqlik.in') {
          this.showNav = true;
            return;
        } else {
          this.showNav = false;
        }
      }
  
  }

  shareUserCredential(costDetails){
    console.log('costDetails',costDetails);
    var cost_id = costDetails._id;
    this.contactService.shareCostumerInfo(cost_id).subscribe(res=>{
      console.log(res);
      let message =res.message;
      let action
      this.snackBar.open(message, action, {
        duration: 4000,
      });
   
    },err=>{
      console.log(err);
    })

    
  }

  resetPassword(cust_array){
    console.log("Inside reset",cust_array);
    let dialogRef = this.dialog.open(ResetPasswordComponent, {
      width: '400px',
      data : cust_array
    //  height: '600px', 

    });

    dialogRef.afterClosed().subscribe(result => {
      // console.log(result);
      if (result == "succ") {
        this.tost1("password_changed");
        this.ngOnInit();
      }

      if (result == "close") {
        // this.tost1("succ");
        // this.ngOnInit();
      }
    });
    
  }


  custom_table(cust_arr){
    console.log(cust_arr);
    let dialogRef = this.dialog.open(DashboardContentComponent, {
      width: '500px',
      data : cust_arr
    //  height: '600px', 

    });

    dialogRef.afterClosed().subscribe(result => {
      // console.log(result);
      if (result == "updated") {
        this.tost1("Table Content Customised");
        this.ngOnInit();
      }

      if (result == "close") {
      
      }
    });

  }


  addPoints(data){
    let dialogRef = this.dialog.open(PointShareComponent, {
      width: '300px',     
      data: {"userInfo":data}                      
    });

    dialogRef.afterClosed().subscribe(result => {   
      // console.log(result);
      if(result == 'added'){

        this.data_descip =  "Point Added";
        this.ngOnInit();
        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", ""); }, 4500);
       }  
    })  
  }

  
  custPhone(dlr){
  var dphn = '';
  if(dlr.std_code != undefined){
     dphn = '+' + dlr.std_code.dialcode + ' ' + dlr.phone ; 
     return dphn ; 
  }else{
     dphn = dlr.phone ; 
    return dphn ; 
  }
}

accountStatus:boolean = true;
accountStatusOnChange(custObj, event){


    console.log(custObj,event.checked);
    var payload = {
      accountSuspended : event.checked,
      acoountId : custObj._id  ,
      suspendedBy : 'distributer' 
    }
      var that = this;
    swal("Are you sure ?", "Do you want to change account status ?").then((ans)=>{
      console.log(ans);
      that.contactService.accountSuspend(payload).subscribe(res=>{
        console.log(res);
        that.getCustomer();
        that.data_descip =  "Account Status Changed";
        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", ""); }, 4500);
       }    
      })
     
    },err=>{
      that.getCustomer();
      console.log(err);
    });
  
}


allUserFunction(ev){
  console.log('event=>',ev);
  this.allUser = ev.checked ;
   
    this.skip = 1;
    this.getCustomer(); 
}

adm_alert:boolean=false;
alertStatus(ev,cobj){
 
  var aAlert= ev.checked;
 
  var pld= {
    uid : cobj._id,
    adminAlert : aAlert
  }
  console.log(pld);
  this.contactService.setlanguage(pld).subscribe(res=>{
    console.log(res);
    this.tost1('alertset');
  })

}

dealerAlert(ev,cobj){
 
  var aAlert= ev.checked;
 
  var pld= {
    uid : cobj._id,
    dealerAlert : aAlert
  }
  console.log(pld);
  this.contactService.setlanguage(pld).subscribe(res=>{
    console.log(res);
    this.tost1('alertset');
  })

}
changeKYC(data,event){
  console.log(event);
  var req={
    user:data._id,
    status:event
  }
  this.contactService.changeKycStatus(req).subscribe(res=>{
    console.log(res);
     this.tost1('kyc');
  })
  
}



}
