import { Component, OnInit } from '@angular/core';
import { ContactService } from '../contact.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { MyaccountComponent } from '../myaccount/myaccount.component';
import { MdDialog } from '@angular/material';
import { AddDealerComponent } from '../add-dealer/add-dealer.component';
import { DeviceEditComponent } from '../dashboard/device-edit/device-edit.component';
import { EditDealerComponent } from '../edit-dealer/edit-dealer.component';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/debounceTime';
import { EditCostumerComponent } from '../edit-costumer/edit-costumer.component';
import { environment } from '../../environments/environment';
import { DealerPermissionComponent } from './dealer-permission/dealer-permission.component';
import { PointShareComponent } from '../point-share/point-share.component';
declare var swal: any;
declare var ol : any;
declare var PerfectScrollbar:any;

declare var html2canvas:any;
declare var pdfMake : any;
// import {Fill, Stroke, Circle, Style} from 'ol/style';
declare var Feature, Overlay,View,Point,TileJSON,VectorSource,Icon,Style : any ; 

// import 'ol/ol.css';
// import Feature from 'ol/Feature';
// import Map from 'ol/Map';
// import Overlay from 'ol/Overlay';
// import View from 'ol/View';
// import Point from 'ol/geom/Point';
// import {Tile as TileLayer,Vector as VectorLayer} from 'ol/layer';
// import TileJSON from 'ol/source/TileJSON';
// import VectorSource from 'ol/source/Vector';
// // import {Icon, Style} from 'ol/style';
// import LineString from 'ol/geom/LineString';
// import {fromLonLat} from 'ol/proj';
// import OSM from 'ol/source/OSM';
// import {Circle as CircleStyle, Fill, Icon, Stroke, Style} from 'ol/style';

@Component({
  selector: 'app-dealers-info',
  templateUrl: './dealers-info.component.html',
  styleUrls: ['./dealers-info.component.scss']
})
export class DealersInfoComponent implements OnInit {
  dealer_load: { "uId": any; "loggedIn_id": any; "status": any; };
  show1: boolean = false;
  show2: boolean = true;
  show3: boolean = false;
  first_name: any;
  last_name: any;
  passwordd: any;
  org_name: any;
  emaill: any;
  phone: any;
  executed: any;
  $event2: any;
  dealer: any;
  firstcall: boolean = false;
  lastcall: boolean = true;
  // contacts: Contact[]=[];
  // contact: Contact;
  login1: any;
  cond: Boolean = false;
  mess2: any;
  mess: any;
  otp: any;
  str: boolean = false;
  password2: any;
  cust_load: any;
  fs: any;
  ls: any;
  emailid: any;
  or: any;
  useridd: any;
  custtype: any;
  custumer: any;
  mb: any;
  cust: boolean = false;
  logo: any;
  text: any;
  myInput: any;
  superAdmin: Boolean = false;
  before: any;
  dealers_info = [];
  modelChanged: Subject<string> = new Subject<string>();
  errorMsg: boolean;
  serviceResponse: string;
  Load: boolean;
  url: any;
  showNav: boolean=false;
  constructor(private contactService: ContactService, private router: Router, private _flashMessagesService: FlashMessagesService, public dialog: MdDialog) {
    
    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;
       this.dealerDetail();
      });


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

  ngOnInit() {
    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.mb = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    let test = JSON.parse(window.atob(window.localStorage.token.split('.')[1]));
    this.showDemoVideo();
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;

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

    this.dealerDetail();
    // this.testOpenLayerMap();

    $(document).ready(function () {
      $('.js-pscroll').each(function(){
        var ps = new PerfectScrollbar(this);
  
        $(window).on('resize', function(){
          ps.update();
        })
  
        $(this).on('ps-x-reach-start', function(){
          $(this).parent().find('.table100-firstcol').removeClass('shadow-table100-firstcol');
        });
  
        $(this).on('ps-scroll-x', function(){
          $(this).parent().find('.table100-firstcol').addClass('shadow-table100-firstcol');
        });
  
      });
    })
  }


  stre() {
    this.str = true;
  }
  stren() {
    this.str = false;
  }

 

  clear() {
    this.first_name = ' '
    this.last_name = ' '
    this.emaill = null
    this.phone = null
  }

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


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



  onChange(dealer, ev) {

    // console.log(ev.checked);
    let dealer_status = ev.checked;
    let dealer_id = dealer._id;
    // let dealer_activity = dealer.status; 


    this.dealer_load = {
      "uId": dealer_id,
      "loggedIn_id": this.useridd,
      "status": dealer_status
    }
    // console.log(dealer_id);
    // console.log(this.dealer_load);
    this.contactService.custStatus(this.dealer_load)
      .subscribe(res => {
        let a = res;
      }, err => {
      })
  }


  dealerDetail() {
    this.Load = true;
   console.log("Inside function",this.myInput);
    this.contactService.dealer_Info1(this.useridd, this.skip, this.limit,this.myInput,null)
      .subscribe(res => {
        // console.log(res);
        this.Load = false ;
        this.dealers_info = res;
        console.log('this.dealers_info',this.dealers_info);
        // console.log("SuccessLog");
      }, err => {
        this.Load = false;
        this.dealers_info=[];
        this.firstcall = true;
        this.lastcall = false;
      })

  }


  addDealer() {   
          let dialogRef = this.dialog.open(AddDealerComponent, {
            width: '800px',
          });
      
          dialogRef.afterClosed().subscribe(result => {     
            if (result == "succ") {     
              this.ngOnInit();   
            }
          });
  }



  edit_DealerDetail(dealerEdit) {
    // console.log(dealerEdit);
      console.log(dealerEdit);
      dealerEdit.ID = 'edit'; 
      console.log(dealerEdit);
    let dialogRef = this.dialog.open(EditDealerComponent, {
      width: '500px',
      height: '600px',
      data: { dealer_payload: dealerEdit }
    });


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

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

      }
    });

  }

  delete_DealerDetail(dealerDelete){
    var  that =this;
    console.log(dealerDelete);
    dealerDelete.ID = 'delete';

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

    
    dialogRef.afterClosed().subscribe(result => {
      console.log(result);
      // console.log(result);
      if (result == "yes") {
        console.log("DealerId=>",dealerDelete._id)
        var deletePayload = {
          'userId' : dealerDelete._id,
          'deleteuser' : true
        }
        this.contactService.deleteCostumer(deletePayload)
          .subscribe(res=>{
            console.log(res);
            this.serviceResponse = "User Deleted"; 
            this.errorMsg =true;
            this.dealerDetail();
           var success =  setTimeout(function(){
             clearInterval(success);
              that.errorMsg = false; 
           },5000)
            
          },err=>{
            this.serviceResponse = "Please try after somrtime";
            var error =  setTimeout(function(){
              clearInterval(error);
               that.errorMsg = false; 
            },5000)
          })

      }

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

    });



    
  }
  dealerToken: any;
  // dealer switch function
  dealerSwitch(dlr) {
    // console.log(dlr);
    localStorage.setItem("DealerObj=>", dlr._id);
    localStorage.removeItem("in1");
    this.contactService.getcustToken(dlr._id).subscribe(
      data => {
        this.dealerToken = data
        var superAdminToken = localStorage.getItem('token');
        localStorage.setItem('superAdminToken', superAdminToken);
        localStorage.setItem('token', this.dealerToken.custumer_token);

        var chkPP = localStorage.getItem('profilePic');
        if(chkPP != null){
          localStorage.removeItem('profilePic');
        }  
        localStorage.removeItem('devices');
        window.localStorage['DataUpdate'] = 'True';
        window.localStorage['Dealer'] = 'ON';
        localStorage.setItem('superadmin', "ON");


        if (window.localStorage['DataLoaded'] = 'True') {
          this.router.navigateByUrl("const?_status=" + "OK");
        }
      });
  }

  skip: number = 1;
  limit: number = 10;

  next() {
    this.lastcall = false;
    this.skip += 1;
    // this.sidebarData();
    this.dealerDetail();
  }
  pre() {
    // console.log(this.skip)
    if (this.skip > 1) {
      this.skip -= 1;
      this.lastcall = false;
      this.firstcall = false;
      // this.sidebarData();
      this.dealerDetail();
    } else {
      this.lastcall = true;
      this.firstcall = false;
    }

  }


  searchFilter(text: string) {
    this.modelChanged.next(text);
  }

  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") {

      }

      if (result == "no") {
     
      }

      if(result == 'imageupdated'){
        swal(
          'Updated',
          'Documents has been Updated.',
          'success'
        ) 
        this.dealerDetail()

      }
    });

    
  }

  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;
        }
      }
  
  }
  data_descip :any;

  user_permission(dealer){
    console.log("user Account");

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

    });

    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);
    }
    dialogRef.afterClosed().subscribe(result => {
      // console.log(result);
      if (result == "succ") {
        // this.tost1("password_changed");
        this.data_descip = "Dealer Permission set !!!";
        launch_toast();     
        this.ngOnInit();

      }

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


  // testOpenLayerMap 
  osMap : any;

  // testOpenLayerMap() {
  //   this.contactService.getlatLong().subscribe(res => {
  //     console.log(res);
  //     let lat = parseFloat(res.lat);
  //     let lng = parseFloat(res.lon);
  //     console.log({ "lattitude": lat, "longitude": lng });
  //     this.simpleReverseGeocoding(85.130690, 25.611220);
  //     var that = this; 

  //     var map = new ol.Map({
  //       layers: [
  //         new ol.layer.Tile({
  //           source: new ol.source.OSM()
  //         })
  //       ],
  //       target: 'testOpenLayerMap',
  //       view: new ol.View({
  //         center: ol.proj.fromLonLat([lng, lat]),
  //         zoom: 15
  //       })
  //     });
  //   })
   




  // }

  // simpleReverseGeocoding(lon, lat) {
  //   fetch('http://nominatim.openstreetmap.org/reverse?format=json&lon=' + lon + '&lat=' + lat).then(function(response) {
  //     return response.json();
  //   }).then(function(json) {
  //     var testAddress = json.display_name;
  //     console.log('testAddress=>',testAddress);
  //   })
  // }


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


  availablePoint(dObj){
    // console.log('dObj=>',dObj);

    var avlpoint = dObj.point_Allocated  - (dObj.point_Shared_Other + dObj.total_vehicle)
    return avlpoint ; 

  }
  // exportPdf(){


  //   html2canvas(document.getElementById('deviceTable'), {
  //      onrendered: function (canvas) {
  //         var data = canvas.toDataURL();
  //         console.log(data);
  //         var docDefinition = {
  //             content: [{
  //                 image: data,
  //                 width: 1000
  //             }]
  //         };
  //         pdfMake.createPdf(docDefinition).download("Table.pdf");
  //     }
  // });
  
  
  // }

  exportPdf(){
    var customers  = [];
     var data_heading = ['Name','Email','Phone','User ID','Password',];
     customers.push(data_heading);
    
     for(var k =0;k<this.dealers_info.length;k++){
       var colData = [(this.dealers_info[k].first_name + " "+ this.dealers_info[k].last_name),this.dealers_info[k].email,this.dealers_info[k].phone,this.dealers_info[k].user_id?this.dealers_info[k].user_id:'--',this.dealers_info[k].pass?this.dealers_info[k].pass:'--']
       customers.push(colData);
     }
      // var json = '[["Customer Id","Name","Country"],[1,"John Hammond","United States"],[2,"Mudassar Khan","India"],[3,"Suzanne Mathews","France"],[4,"Robert Schidner","Russia"]]';
    console.log(customers);
      //Convert JSON string to JSON object.
      // var customers = eval(json);
      //Convert JSON to HTML Table.
      var table = document.createElement("TABLE") as HTMLTableElement;
      table.border = "1";
      table.id = "tblCustomers";

      //Get the count of columns.
      var columnCount = customers[0].length;

      //Add the header row.
     
      var row = table.insertRow(-1);
      debugger;
      for (var i = 0; i < columnCount; i++) {
          var headerCell = document.createElement("TH");
          headerCell.innerHTML = customers[0][i]
          console.log();
          row.appendChild(headerCell);
        
      }

   
      //Add the data rows.
        for (var i = 1; i < customers.length; i++) {
          row = table.insertRow(-1);
          for (var j = 0; j < columnCount; j++) {
              var cell = row.insertCell(-1);
              cell.innerHTML = customers[i][j];
          }
      }
     

      //Append the Table to the HTML DIV.
      var dvTable = document.getElementById("dvTable");
      dvTable.innerHTML = "";
      dvTable.appendChild(table);

      console.log(table);
      //Convert Table to PDF.
    
      html2canvas(document.getElementById('dvTable'), {
        scale: 2,
        dpi: 144,   
        onrendered: function (canvas) {
              var data = canvas.toDataURL();
              var docDefinition = {
                  content: [{
                      image: data,
                      width: 900
                  }]
              };
              pdfMake.createPdf(docDefinition).download("JSON.pdf");

              //Remove the Table.
              dvTable.innerHTML = "";
          }
      });
  
  }

  dealerPhone(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(dealerObj,event){
  var that = this ; 
  console.log(dealerObj,event.checked);
  var payload = {
    accountSuspended : event.checked,
    acoountId : dealerObj._id  ,
    suspendedBy : 'distributer' 
  }

  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.dealerDetail();
      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.dealerDetail();
    console.log(err);
  });

 
}

}

