import { Component, OnInit } from '@angular/core';
import { ContactService } from '../contact.service';
import * as moment from 'moment';
import { Router } from '@angular/router';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { MdDialog } from '@angular/material';

import { FlashMessagesService } from 'angular2-flash-messages';
import { AddDistributersComponent } from '../add-distributers/add-distributers.component';
import { Subject } from 'rxjs/Subject';
import { PointShareComponent } from '../point-share/point-share.component';
import { environment } from '../../environments/environment';
declare var $: any, DataTable: any;
declare var  swal:any;

@Component({
  selector: 'app-distributers-list',
  templateUrl: './distributers-list.component.html',
  styleUrls: ['./distributers-list.component.scss']
})
export class DistributersListComponent implements OnInit {
  dev_url = environment.hostUrl;
  from_date: Date;
  to_date: Date;
  bsConfig: Partial<BsDatepickerConfig>;
  tabelObj: any;
  useridd: any;
  myInput:any;
  supadm: any;
  modelChanged: Subject<string> = new Subject<string>();
  
  isOperator: boolean = false;
  supAdminId: any;
  newVar:any;
  newVar1:any;
  colorTheme = 'theme-dark-blue';
  tttpppcccc: any='';
  data_descip: string;

  constructor(public contactService: ContactService, private router: Router,public dialog: MdDialog,private _flashMessagesService: FlashMessagesService) { 
 
    // this.from_date = new Date();
    // this.from_date.setHours(0,0,0,0);
    // this.from_date.setMonth(this.from_date.getMonth() -1);
    // if(this.from_date.getMonth() == 1){
    //   this.from_date.setMonth(12);
    //   this.from_date.setFullYear(this.from_date.getUTCFullYear()-1);
    // }

    // this.to_date = new Date();

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

    this.modelChanged
    .debounceTime(2000) // 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('this.myInput in constructor = > ',this.myInput);
      this.tabelObj.draw();


    });
  }

  ngOnInit() {

    this.testTable();
        this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
        this.supadm = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
        this.isOperator = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isOperator;
        this.supAdminId = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;

     
  }

  testTable() {
    console.log("Inside function");
    const that = this;
   
    $(document).ready(function () {
      that.tabelObj = $('#userTable').DataTable({
        "ordering": true,
        'serverSide': true,
        "processing": true, 
        "searching": false,
        scrollX: true,
        order: [[0, 'desc']],
        ajax: (dataTablesParameters: any, callback) => {

          dataTablesParameters.op = {};
          dataTablesParameters.select = [];
          dataTablesParameters.find = {};
          console.log('dataTablesParameters',dataTablesParameters);
        
          // console.log(dataTablesParameters);
          // console.log("callback", callback);

          // dataTablesParameters.find = {
          //   _id: that.useridd         
          // };
          dataTablesParameters.columns = [    
            {data : '_id', "orderable": "true" },    
            { data: "first_name" },
            { data: "email" },
            { data: "phone" },
            { data: "user_id" },
            { data: "pushNotification" },
            { data: "organisation_name" },
            {data : "point_Allocated"},
            {data : "point_Shared_Other"},
            {data : "std_code"},
            { data: "welcome_msg" },
            { data: "created_on" },
            {data:'expire_date'},
            {data : "accountSuspended"},
            {data : 'pass'},
            {data : 'billing_id.billing_contact'},
            {data : 'billing_id.billing_rate'},
            {data : 'billing_id.BillingType'},
            {data : 'billing_id.std_code'},
            {data : 'billing_id.email'},
            { data: "Dealer.first_name" },
            { data: "Dealer.last_name" },
            { data: "last_name" },   
            { data: "address"},
            {data : "status" },
            {data : "kyc_verification_mail" },
            {data : "inventoryManagement" },
            {data : "bussinessType" },
            {data:'devicePermission.Add'},
            {data:'devicePermission.Edit'},
            {data:'devicePermission.Delete'},
            {data:'userPermission.Add'},
            {data:'userPermission.Edit'},
            {data:'userPermission.Delete'},
            // {data:'userPermission'},
            {data : "Plan" },
            {data:'support1'},
            {data:'support2'},
            {data:'support3'},
             {data:'service1'},
              {data:'service2'},
              {data:'SpeedLimit'},
               {data:'outOfReach'},
              ]
    //           support1:{type:String},
    // support2:{type:String},
    // support3:{type:String},
    // service1:{type:String},
    // service2:{type:String},
              // this.userSelect._id
              // dataTablesParameters.find.supAdmin = that.useridd;
                
          // if ((that.userSelect)&&(that.userSelect.length!=0)&&(that.userSelect[0].user_type!="All")) {
          //   dataTablesParameters.find._id = that.userSelect[0]._id;
          // }

          // if ((that.userSelect1)&&(that.userSelect1.length!=0)&&(that.userSelect1[0].user_type!="All")) {
          //   dataTablesParameters.find._id = that.userSelect1[0]._id;
          // }


          if (that.from_date) {
            dataTablesParameters.find['created_on'] = dataTablesParameters.find['created_on'] ? dataTablesParameters.find['created_on'] : {};
            dataTablesParameters.find['created_on']['$gte'] = {
              _eval: 'date',
              value: new Date(that.from_date).toISOString()
            }
          };
          // }
          if (that.to_date) {
            dataTablesParameters.find['created_on'] = dataTablesParameters.find['created_on'] ? dataTablesParameters.find['created_on'] : {};
            dataTablesParameters.find['created_on']['$lte'] = {
              _eval: 'date',
              value: new Date(that.to_date).toISOString()
            };
          }

          if((that.myInput != undefined) &&(that.myInput != '')){
            console.log('that.myInput',that.myInput);
            dataTablesParameters.find['$or']  = [{'phone' : {"$regex" : that.myInput, $options : 'i'}},{first_name : {"$regex" : that.myInput, $options : 'i'}},{email : {"$regex" : that.myInput, $options : 'i'}}];
          }

          // if(this.supadm){
          //   dataTablesParameters.find.supAdmin = that.useridd;
          // }
          dataTablesParameters.find.organisation = that.useridd ; 
          dataTablesParameters.sort = {_id :-1}
          
          var suburl = "";
          suburl += "/users/datatable";
          // console.log(suburl);
          // console.log(dataTablesParameters);
          // console.log(suburl)
          that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {

            callback(resp);

          }, err => {
            // console.log(err);
            // console.log(err.status);
          });
        },
        "rowCallback": function(row: Node, data: any | Object, index: number){  
          $('#accountActivity', row).bind('click', () => {    
                  console.log(data);
                  swal("Are you sure ?", "Do you want to change account status ?").then((ans)=>{
                    console.log(ans);
                    that.accountActivityFunc(data);
                  },err=>{
                    console.log(err);
                  });
               
            });

            // $('#openNewTab', row).bind('click', () => {    
            //       that.router.navigate([]).then(result => { 
            //         console.log(data,row);
            //       that.contactService.getcustToken(data['_id']).subscribe(res=>{
            //         console.log(res.cust);
            //         console.log(res.cust.custumer_token);
            //         // window.addEventListener('storage', (e) => {
            //              localStorage.setItem('token',res.custumer_token) ;
            //       //  });
                 
            //         // window.localStorage['token'] = ;
            //         window.open(that.dev_url+"/const?_status="+"OK", '_blank'); });   
            //         console.log('new window');
            //       })      
            // });
                  
          $('#edit', row).bind('click', () => {    
          // console.log("Edit Method",data);
          data.edit = true;
          let dialogRef = that.dialog.open(AddDistributersComponent, {
            width: '800px',
      
            data: {"userInfo":data}                      
          });

          dialogRef.afterClosed().subscribe(result => {   
            // console.log(result);
          
               that.Distributers();      
            
          })  

          });

          $('#pointShare', row).bind('click', () => {    
            // console.log("Edit Method",data);
            data.edit = true;
            let dialogRef = that.dialog.open(PointShareComponent, {
              width: '300px',     
              data: {"userInfo":data}                      
            });
  
            dialogRef.afterClosed().subscribe(result => {   
              // console.log(result);
              if(result == 'added'){
                this.data_descip =  "Point Added";
                that.Distributers();    
                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);
               }    
            })  
            });
          },
        "columns": [
          {
            "data": "_id",
            "visible": false,
            "render": function (data, type, row) {
              return data;
            }
          },
          {
            "data": "first_name",
            "render": function (data, type, row) {
              return data ? (data + " " + row.last_name) : "";
            }
          },
          // {
          //   "data": "Dealer",
          //   render: function (data, type, row) {
          //     return data ? (data.first_name + " " + data.last_name) : ""
          //   }
          // },
          // {
          //  "data": "isDealer",
          //   render: function (data, type, row) {
          //   return data?data:'false' ;
          //   }
          // },
          {
            "data": "created_on",
            "render": function (data, type, row) {
              // return new Date(data).getTime();
              var created_time = new Date(data);

              return data ? (moment(created_time).format('LL')) : "";
            }
          },
          {
            "data": "email",
            render: function (data, type, row) {
              return data ? data : ""
            }
          },
          {
            "data": "phone",
         
            "render": function (data, type, row) {
              console.log('row=>',row);
              var phoneShow = '';
              if(row.std_code != undefined){
                phoneShow ='+' + row.std_code.dialcode + '-' + data ; 
              }else{
                phoneShow = data ; 
              }
              return phoneShow;
            }
          },
          {
            "data": "pass",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "address",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "organisation_name",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "point_Allocated",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          }, 
          // {
          //   "data" : "_id",
          //   "render" : function(data, type,row){
         
          //     let promiseName = new Promise(function(resolve, reject) {
          //       var distPoint = '0';
          //       that.contactService.getAvialblePoints(row._id,distPoint).subscribe(res=>{
                
          //         var pointCount =res.available_points?res.available_points: 0 ; 
              
          //         resolve(pointCount);
          //       },err=>{
          //         reject("Error");
          //       })        
          //       });
          //     promiseName.then(pResult =>{
          //       console.log(pResult);
          //      that.tttpppcccc = pResult  ;
              
          //     });
          //     return that.tttpppcccc;
           
          //   }
          // },
          { 
            "data": "point_Shared_Other",
            "render": function (data, type, row) {
              // console.log('typeof(data)',typeof(data));
              return data ? data : "";
            }
          }, 
            
          {

            "data": "status", 
            "render": function (data, type, row) {
              // console.log(data);
              if(data == true){
                var distStatus = 'Active'
              }
              if(data == false){
                var distStatus = 'Inactive'
              }
            
              return distStatus;
            }
          },

          // {

          //   "data": "pushNotification",
          //   "render": function (data, type, row) {
          //     var tokenCount = data ?  data.length :0;
          //     return tokenCount;
          //   }
          // },
          {
            "data":null,"render":function(data,type,row){
            // return '<button id="edit" type="button" md-raised-button class="btn btn-primary">Edit</button>';
            return '<i id="edit" type="button" class="far fa-edit" md-tooltip="Edit" style="cursor: pointer;"></i>'
          }
          },
          {
            "data":null,"render":function(data,type,row){
         
            return '<i id="pointShare" style="cursor:pointer" class="fas fa-coins"></i>'
          }
          }  ,
          {
            "data":"accountSuspended","render":function(data,type,row){
              console.log(data);
            var btnClr = '';
            if(data === false){
              btnClr = 'green';
            }else{
              var btnClr = 'red';
            }
            var accountAction =   '<i id="accountActivity" style="color:'+btnClr+'" class="fas fa-power-off"></i>';
            return accountAction;
          }
          }
          // ,
          // {
          //   "data":"_id",
          //   "render":function(data,type,row){
          //   return '<i id="openNewTab" class="fas fa-toggle-off"></i>';
           
          // }
          // }

        ],
        columnDefs: [
          {      
              "className": "dt-body-left",
               "targets": [ 0,1,2,3,4,5,6,7] , 
           
              
          },
     
        ]

      });
     
    });

  }


  Distributers() {
    console.log(this.from_date);
    console.log(this.to_date);
    this.tabelObj.draw();

}

adddev(){
  var that = this;
  let dialogRef = this.dialog.open(AddDistributersComponent, {
    width: '1000px',
    // height: '1000px', 

  });

  dialogRef.afterClosed().subscribe(result => {
    // console.log(result);
    if (result == "success") {
   
      that.Distributers();     

    }
  });
}

searchFilter(text: string) {
  console.log('texttext',text);
  this.modelChanged.next(text);
 

}

accountActivityFunc(distObj){
  console.log(distObj);
  var activity = !distObj.accountSuspended;
  console.log('activity',activity);
  var payload = {
    accountSuspended : activity,
    acoountId : distObj._id  ,
    suspendedBy : 'org' 
  }

  this.contactService.accountSuspend(payload).subscribe(res=>{
    console.log(res);
    this.data_descip =  "Account Status Changed";
    launch_toast();
    this.tabelObj.draw();
    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);
   }    


  })
}

ngOnDestroy(): void {
    console.log("Destroying loop"); // ngOnDestroy is not triggering
    // this.tabelObj.un
  }
 
}
