import { Component, OnInit } from '@angular/core';
import { ContactService } from '../contact.service';
import { Router } from '@angular/router';


declare var $:any;

@Component({
  selector: 'app-message-utility',
  templateUrl: './message-utility.component.html',
  styleUrls: ['./message-utility.component.scss']
})
export class MessageUtilityComponent implements OnInit {
  msgContent:any;
  msgTitle:any;
  options=[];
  tabelObj: any;
  useridd: any;
  superAdmin: any;
  custtype: any;
  orgChek: any;
  supAdminDropDown = false;
  dealeDropDown: boolean =false;
  tableList: any =[{
    "_id": "",
    "first_name": "",
    "last_name": "",
    "phone": ""  
  }];
  distributers:any=[];
  dealers:any=[];
  customers:any=[];
  DealersData: any;
  disDataFIlter: any=[];
  dealDataFIlter: any=[];
  notificationType='1';
  data_descip: string;
  selectedRole="dealer"
distributerValue
dealerValue
  constructor(private contactService: ContactService,private router: Router) {
  //   $("#distSelect").change(function() {
  //     console.log("inside function");
  //   var di =  $("#distSelect").val($(this).val());
  //   console.log(di);
     
  //  });
  //  $("#dealerSelect").change(function() { 
  //    console.log("inside function");
  //  var dea =  $("#dealerSelect").val($(this).val());
  //  console.log(dea);
  //  });
  //  $("#custSelect").change(function() {
  //    console.log("inside function");
  //   var cus =  $("#custSelect").val($(this).val());
  //   console.log(cus);
  //  });

   }

   selectedItems=[];

  ngOnInit() {
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.orgChek = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isOrganisation;
    this.testTable();
    if(this.orgChek === true){
      this.supAdminDropDown = true; 
      this.dealeDropDown = true; 
      this.getDistributer_1('supAdmin',this.useridd);
    }


    if((this.orgChek === false)&&(this.superAdmin === true)){
      this.dealeDropDown = true;
      this.getDistributer_1('supAdmin',this.useridd);
    }
    if(this.custtype ===true){
      this.getDistributer_1('Dealer',this.useridd);
    }
    // this.loadropdown();


 var that = this;

   $('body').on('change', '#mass_select_all', function() {
    var rows, checked;
   var ttttt =  document.getElementById('mass_select_all');
   that.selectedItems=[];
   if(ttttt['checked'] === true){
        that.selectedItems = that.tableArr; 
        
   }
   if(ttttt['checked'] === false){
    that.selectedItems = [];

  }


  
   console.log("ttttt['checked']",that.selectedItems);

    $('#checkbox-value').text($('#checkbox1').val());
    rows = $('#deviceTable').find('tbody tr');
    checked = $(this).prop('checked');
    $.each(rows, function() { 
       var checkbox = $($(this).find('td').eq(0)).find('input').prop('checked', checked); 
       var chkdObj =  that.tabelObj.row( this.closest('tr') ).data() ;     
    });
   
  
  
  });

  }

  // 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(() => {
  //       $('#distSelect').multipleSelect({
  //         width: 200,
  //         placeholder: "Search Distributer",
  //         filter: true,
  //         single: true,
  //         selectAll: false
  //       }) 
  //     }, 100);
    
  //     setTimeout(() => {
  //       $('#dealerSelect').multipleSelect({
  //         width: 200,
  //         placeholder: "Search Dealer",
  //         filter: true,
  //         single: true,
  //         selectAll: false
         
  //       }) 
  //     }, 100);
    
  //     setTimeout(() => {
  //       $('#custSelect').multipleSelect({
  //         width: 200,
  //         placeholder: "Search Customer",
  //         filter: true,
  //         single: true,
  //         selectAll: false
        
  //       })   
  //     }, 100);
  // }


  testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function() {   
      that.tabelObj=    $('#deviceTable').DataTable({
            "processing": true,
            "searching": true, 
            // pagingType: 'full_numbers',
            "serverSide": false,
           "paging": false,
            "lengthChange": false,
            "scrollY":'50vh',  
            "scrollCollapse": true, 
            // "dataSrc" :that.tableArr,
            "columnDefs": [ {
              "targets": [0],
              "orderable": false,
        } ],
        ajax: (dataTablesParameters: any, callback) => {
          console.log("ASSD",that.tableArr)
          callback({data : that.tableArr})

        }
    ,
          "rowCallback": function(row: Node, data: any | Object, index: number){   
        
            // console.log(index)
            let idSlct = data._id ;
            $('#'+idSlct, row).off('click').on('click', () => {  
              let id = data._id;
              let a = document.getElementById(id);   
              // console.log(a);
                  if(a['checked'] === true){
                  
                      that.selectedItems.push(data);
                  } 
               
                  if(a['checked'] === false){
                   var b = that.selectedItems.filter(e => e._id === data._id);
                    b.forEach(f => that.selectedItems.splice(that.selectedItems.findIndex(e => e._id === f._id),1));
                  }   
                  // console.log('that.selectedItems=>',that.selectedItems);
              
               })
          },
           
          "columns": [
            {
              "data": "_id",
              "visible" :true,
              "render": function (data, type, row) {     
           
             
                return '<input type="checkbox"  id='+ data + ' class="editor-active">';
              }
            },
    
            {
              "data": "last_name",
              "visible" :true,
              "render": function (data, type, row) {        
                var fn =row.first_name?row.first_name:'';
                var ln=data?data:''; 
                return fn + ' ' + ln;
              }
            },
            {
              "data": "phone",
              "visible" :true,
              "render": function (data, type, row) {             
                return data? data: '';
              }
            },
          ]    
                      
        });

  
    });
  
  }


  // getDistributer(id){
  //   this.tableList =[];
  //   this.contactService.getDistributer(this.useridd,id).subscribe(res=>{
  //     console.log(res);  
  //       this.distributers = res; 
  //     if(id=== 'supAdmin'){
  //       this.dealers =res ; 
  //     }
  //     if(id === 'Dealer'){
  //       this.customers = res ; 
  //     }
  //       //  this.loadropdown(); 
  //        if(this.tabelObj!=undefined){
  //         this.tabelObj.clear();
  //        }
  //        this.tabelObj.rows.add(this.distributers); 
  //        this.tabelObj.draw();   
       
  //   },err=>{
  //     console.log(err);
  //   })
  // }

    tableArr = [];
  getDistributer_1(id,loginId){
    // 'org','supAdmin','Dealer'
    this.DealersData = [];
    this.tableArr = [];
    var i:any; 
    if(id === 'org'){
          // fetch all distributer
          console.log(id);
          
          var pLoad ={"draw": 1,"columns": [{"data": "_id"},{"data": "first_name"},{ "data": "last_name"},{"data": "email"},{"data": "phone"}],"order": [{
                "column": 0,"dir": "desc"}],"start": 0,"length": 100000,"search": {"value": "","regex": false},"op": {},"select": [],"find": {"organisation": loginId}}
          this.contactService.post('/users/datatable', pLoad).subscribe(resp => {    
            this.distributers = resp['data'];
            // this.tableArr= resp['data'];
            console.log(this.distributers);  
            var loadinguser1 = {
              user_type: "All",
              _id: "All User"
            }
            for(var i=0;i<this.distributers.length;i++){
              loadinguser1 = {
                user_type:  this.distributers[i].first_name + " " + this.distributers[i].last_name,
                _id: this.distributers[i]._id
              }
              this.disDataFIlter.push(loadinguser1);
            }         
             this.tableArr = this.distributers;
             this.reLoadTable()
         
          })
          
        // this.contactService.getDistributer(loginId,id).subscribe(res=>{
        //   this.distributers = res; 
      

        //   this.tableArr = this.distributers;
        // })
    }
    if(id === 'supAdmin'){
              // fetch all Dealer
               console.log(id);
      this.contactService.dealer_Info1(loginId,1,10000,i,null).subscribe(res=>{
          this.DealersData  = res ; 
          console.log('this.DealersData',this.DealersData);
          this.tableArr = this.DealersData  ; 
          var loadinguser = {
            user_type: "All",
            _id: "All User"
          }
          for(var j=0;j<this.DealersData.length;j++){
            loadinguser = {
              user_type:  this.DealersData[j].first_name + " " + this.DealersData[j].last_name,
              _id: this.DealersData[j]._id
            }
            this.dealDataFIlter.push(loadinguser);
          }
          console.log(this.dealDataFIlter);
       
          this.reLoadTable();
      })

      // this.contactService.getTableData(loginId).subscribe(res=>{
      //   this.tableArr = res;
      //   this.reLoadTable(); 
      // })

    }
    if(id === 'Dealer'){
       console.log(id);
        // fetch all Customer
        this.contactService.getCustumer(loginId,1, 10000,i,false).subscribe(  
          data => {
            this.tableArr = data;  

            this.reLoadTable()    
          }, err => {
      
          });

    }

      

  }

  reLoadTable(){
    console.log(this.tableArr);
    if(this.tabelObj!=undefined){
      this.tabelObj.clear();
     }
     console.log(this.tabelObj); 
    this.tabelObj.rows.add(this.tableArr); 
    this.tabelObj.draw(); 

  }

  changedUser(this,ev){
      console.log(this);
      console.log(ev);
  }


  // filterStates(distributerValue){
  //   console.log({"inside function" : distributerValue});
  // }

  onChange(role,id){
    console.log(role,id);
    if(role === 'supAdmin'){
      console.log(id);
        this.getDistributer_1(role,id[0]._id);
    }
    if(role === 'Dealer'){
      console.log(id);
        this.getDistributer_1(role,id[0]._id);
    }

  //  this.getDistributer_1(role,id);


  }

  distributerSelect = [];
  filterStates(usr1) {
    // console.log("userObj=>",usr);
    if(usr1.length == 0){
      this.distributerSelect =[];
    }
    
    if (usr1) {
      console.log("user=>",usr1);
      const filterdealerValue:any = usr1;
      this.distributerSelect=[];
       this.distributerSelect = this.disDataFIlter.filter(function(ppp){
       
        var t = ppp.user_type.indexOf(filterdealerValue);
      //  this.option = this.options[i];
      console.log("India1");
        return t > -1;    
      });
        console.log(this.distributerSelect);
        if(this.distributerSelect.length === 1){
          this.onChange('supAdmin',this.distributerSelect);

        }
        return this.distributerSelect;
    }
  
  }

  DealerSelect=[];
  filterStatesdelaer(usr1){

      // console.log("userObj=>",usr);
      if(usr1.length == 0){
        this.DealerSelect =[];
      }
      
      if (usr1) {
        console.log("user=>",usr1);
        const filterdealerValue:any = usr1;
        this.DealerSelect=[];
         this.DealerSelect = this.dealDataFIlter.filter(function(ppp){
          var t = ppp.user_type.indexOf(filterdealerValue);
        //  this.option = this.options[i];
          return t > -1;    
        });
          // console.log("selectedUser=>",this.DealerSelect)
          if(this.DealerSelect.length === 1){
            this.onChange('Dealer',this.DealerSelect);
  
          }
          return this.DealerSelect;
      }

  }

  changeValue(ev){
    console.log(ev);
    this.notificationType = ev.value;
  }
  changeRole(event){
    console.log(event);
    this.selectedRole=event.value;
    if(this.selectedRole=="dealer"){
      this.SetDealer();
      
    }else if(this.selectedRole=="directCustomer"){
        this.CustomerData();

    }else if(this.selectedRole=="dealersCustomer"){
      this.tableArr=[];
      this.dealerValue=null
       this.reLoadTable();
        this.data_descip = 'Please Select Dealer';
      this.launch_toast()
    }else{
       this.distributerValue=null
       this.tableArr=[];
       this.reLoadTable();
      // this.data_descip = 'Please Select Distributer';
      // this.launch_toast()
      this.Distributer()
    }
  }

  messageSend(){
    if((this.selectedItems.length === 0)||(this.notificationType === undefined)||(this.msgContent == undefined)||(this.msgTitle == undefined)){
      this.data_descip = 'Please Select all Mendatory Fields';
      this.launch_toast()
      return;
    }
    var phoneObject = [];
    for(var i = 0 ;i <this.selectedItems.length;i++){
      var pObj = {
        phone : this.selectedItems[i].phone
      }
      phoneObject.push(pObj)

    }
    var payLoad = {
      numberArr : phoneObject,
      messageTitle : this.msgTitle,
      msgContent:this.msgContent,
      notificationType:(this.notificationType =='2')?'SMS':'NOTIFICATION'
    }
      console.log(payLoad);
      this.contactService.sendMessages(payLoad).subscribe(res=>{
        console.log(res);
        this.data_descip = 'Messages Sent Successfully';
        var x = document.getElementById("toast")
        //console.log(x);
        x.className = "show";
        setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3500);
      })

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

  }
launch_toast() {
        // console.log(divid);
         var x = document.getElementById("toast")
         //console.log(x);
         x.className = "show";
         setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3500);
     }
  SetDealer(){
    this.dealDataFIlter=[]
    this.contactService.dealer_Info1(this.useridd,1,10000,null,null).subscribe(res=>{
          this.DealersData  = res ; 
          console.log('this.DealersData',this.DealersData);
          this.tableArr = this.DealersData  ; 
          var loadinguser = {
            user_type: "All",
            _id: "All User"
          }
          for(var j=0;j<this.DealersData.length;j++){
            loadinguser = {
              user_type:  this.DealersData[j].first_name + " " + this.DealersData[j].last_name,
              _id: this.DealersData[j]._id
            }
            this.dealDataFIlter.push(loadinguser);
          }
          console.log(this.dealDataFIlter);
       
          this.reLoadTable();
      })
  }

  CustomerData(){
     this.contactService.getCustumer(this.useridd,1, 10000,null,false).subscribe(  
          data => {
            this.tableArr = data;  

            this.reLoadTable()  
  })
}

Distributer(){
  var pLoad ={"draw": 1,"columns": [{"data": "_id"},{"data": "first_name"},{ "data": "last_name"},{"data": "email"},{"data": "phone"}],"order": [{
                "column": 0,"dir": "desc"}],"start": 0,"length": 100000,"search": {"value": "","regex": false},"op": {},"select": [],"find": {"organisation": this.useridd}}
          this.contactService.post('/users/datatable', pLoad).subscribe(resp => {    
            this.distributers = resp['data'];
            // this.tableArr= resp['data'];
            console.log(this.distributers);  
            var loadinguser1 = {
              user_type: "All",
              _id: "All User"
            }
            for(var i=0;i<this.distributers.length;i++){
              loadinguser1 = {
                user_type:  this.distributers[i].first_name + " " + this.distributers[i].last_name,
                _id: this.distributers[i]._id
              }
              this.disDataFIlter.push(loadinguser1);
            }         
             this.tableArr = this.distributers;
             this.reLoadTable()
         
          })
          
}
 
}
