import { Component, OnInit } from '@angular/core';
declare var $:any;
import * as moment from 'moment';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { ContactService } from '../contact.service';
import { MdDialog, MdSnackBar } from '@angular/material';

import { AddReminderComponent } from './add-reminder/add-reminder.component';


declare var swal: any;
@Component({
  selector: 'app-vehicle-reminder',
  templateUrl: './vehicle-reminder.component.html',
  styleUrls: ['./vehicle-reminder.component.scss']
})
export class VehicleReminderComponent implements OnInit {
  Load:boolean=false;
  options: any=[];
  devicesss: any;
  superAdmin: any;
  supAdmin: any;
  fs: any;
  minIdleTime:any= 5;
  ls: any;
  emailid: any;
  or: any;
  useridd: any;
  mb: any;
  custtype: any;
  Dealer: any;
  finall: any;
  from_date=new Date(); 
  to_date=new Date();
  colorTheme = 'theme-dark-blue';
  reminder:any;
  reminderType :any=[
{ viewValue:"Service", value:"Service", },
{ viewValue:"Oil Change", value:"Oil Change", },
{ viewValue:"Tyres", value:"Tyres", },
{ viewValue:"Maintenance", value:"Maintenance", },
{ viewValue:"Auto Repair", value:"Auto Repair", },
{ viewValue:"Body Work", value:"Body Work" },
{ viewValue:"Diagnostics", value:"Diagnostics" },
{ viewValue:"Tune Up", value:"Tune Up" },
{ viewValue:"Brake Job", value:"Brake Job" },
{ viewValue:"Oil & Oil Filter Change", value:"Oil & Oil Filter Change" },
{ viewValue:"Tire Care", value:"Tire Care" },
{ viewValue:"Towing", value:"Towing" },
{ viewValue:"Wheel balance & Alignment", value:"Wheel balance & Alignment" },
{ viewValue:"Fleet", value:"Fleet" },
{ viewValue:"Auto Tracking", value:"Auto Tracking" },
{ viewValue:"A/C Repair", value:"A/C Repair" },
{ viewValue:"Others", value:"Others", }
]

  bsConfig: Partial<BsDatepickerConfig>;
  constructor(private contactService: ContactService,  public dialog: MdDialog, public snackBar: MdSnackBar) { 
    this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' }, { containerClass: this.colorTheme });
    this.from_date.setHours(0,0,0,0); 
    this.from_date.setMonth(this.from_date.getMonth()-1);
  // $('#select').hide();
    console.log("loginDetails=>",JSON.parse(window.atob(window.localStorage.token.split(".")[1])));
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.supAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;
    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;
    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.Dealer = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).Dealer;
  }

  ngOnInit() {
    this.getDevices();
    this.testTable();
  }

  
  getDevices(){
    
    this.contactService.getDevice(this.emailid,this.useridd).subscribe(

      data => {
        this.devicesss = data
     
        this.finall = (this.devicesss.devices);

        for(let i=0;i<this.devicesss.devices.length;i++){

          // if(this.devicesss.devices[i].type_of_device =="Tracker"){

            let a ={
              value : this.devicesss.devices[i].Device_Name,
              viewValue:this.devicesss.devices[i].Device_Name,
              did:this.devicesss.devices[i].Device_ID,
              id:this.devicesss.devices[i]._id,
              user:this.devicesss.devices[i].user,
              // email: this.devicesss.devices[i].Email_ID,
              // deviceType: this.devicesss.devices[i].type_of_device
            }
            this.options.push(a);
          // }

        }
           console.log(this.options);
           let that = this;
           setTimeout(()=>{
          
             that.loadropdown();
          
           },100)  

      }); 
    
    }

    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(() => {
  
        $('#select').multipleSelect({
          width: 200,
          placeholder: 'Select device.....',
          filter: true,
          // single: true,
          // selectAll: false
      
        })
       // $('#select').show();
       that.callfunction();
      }, 100);
  
  
    }

    tabelObj: any;  
    dtOptions:any={};
    repCount = 0 ;
    vCount = 0;
    deviceArr:any=[];
    callfunction(): void {
      this.Load = true;
      this.deviceArr =  $('#select').multipleSelect('getSelects','value');
      this.tabelObj.draw();
    }


    testTable() {
      const that = this;
      console.log("inside function");
      this.Load = true;
      $(document).ready(function() {
          that.tabelObj = $('#deviceTable').DataTable({
            dom: 'lBftip',
            buttons: [
              'copy',
              'print',
              'excel'
            ],       
              "processing": true,
              "searching": false,
              pagingType: 'full_numbers',
              pageLength: 25,
              serverSide: true,
              lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
              ajax: (dataTablesParameters: any, callback) => {
                
                  dataTablesParameters.op = {};
                  dataTablesParameters.select = [];
                  dataTablesParameters.find = {};
  
                  dataTablesParameters.find['$and'] = [];
                  var userFilter = {};
                  userFilter['$or'] =[ {user : that.useridd}, {created_by :that.useridd} ]
                  dataTablesParameters.find['$and'].push(userFilter);
    
                  // dataTablesParameters.find['$or'] = [currUser,admin]  

                  dataTablesParameters.columns = [
                
                {data:"_id"},
                {data:'user.first_name'},
                {data:'user.last_name'},
                {data:'device.Device_Name'},
                {data:'reminder_date'},    
                {data:'notification_type.SMS'},
                {data:'notification_type.EMAIL'},
                {data:'notification_type.PUSH_NOTIFICATION'},
                {data : 'reminder_type'},
                {data : 'prior_reminder'},
                {data:'note'},
                {data:'vehicleName'},
                 {data:'odo'},
                {data:'status'},
                  ]            
                 
                 if(that.repCount != 0){
                  var reminder_date={};
              
                  console.log(that.repCount);
                  // dataTablesParameters.find.user = that.useridd;
                  if(that.deviceArr.length != 0){
                    console.log('that.deviceArr',that.deviceArr);
                    var dev_in = {device : {'$in': that.deviceArr}};
                      //  dataTablesParameters.find.device = dev_in;
                      dataTablesParameters.find['$and'].push(dev_in);
                      }
                       if (that.from_date) {
                        var fdate = new Date(that.from_date).toISOString()                      
                         reminder_date['$gte']=fdate  
                      

                    };
                    if (that.to_date) {
                      var tdate = new Date(that.to_date).toISOString()        
                       reminder_date['$lte'] =  tdate     ;
                      
                  };
                  var r_d ={};
                  r_d['reminder_date'] = reminder_date ; 
                  dataTablesParameters.find['$and'].push(r_d);
                  if(that.reminder != undefined){
                    console.log(that.reminder);
                    var r_t = {};
                    r_t['reminder_type'] = that.reminder ;
                    dataTablesParameters.find['$and'].push(r_t);               
                  }
                  // dataTablesParameters.find.user = that.useridd ;       

                  
                 console.log('dataTablesParameters.find=>',dataTablesParameters.find);

                  // that.minIdleTime =      
                  var suburl = "";
                  suburl += "/reminder/reminderdatatable";
                  that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {     
                      console.log("Response from datatable=>",resp);     
                      that.Load= false;         
                      callback(resp);
                  }, err => {                
                    that.Load= false;    
                    let message1="Server Error, Please try again ";
                    let action:any;
                    that.snackBar.open(message1, action, {
                      duration: 5000,
                      
                    });  
                    console.log("error",err) ;     
                  });
                  // }else{
                  //   that.Load= false;    
                  //   let message1="Please Select Device";
                  //   let action:any;
                  //   that.snackBar.open(message1, action, {
                  //     duration: 5000,
                      
                  //   });  
                  //   return;
                  // }
                 }else{
                  that.repCount =  that.repCount + 1 ; 
                  that.Load= false;    
                 }
                                            
           
              },  
              "rowCallback": function(row: Node, data: any | Object, index: number){ 
              //  var ddoption =  $('body .dropdown-toggle').dropdown();     
              //  console.log('ddoption',ddoption);

               $('#edit', row).bind('click', (e) => {      
                  // var name = document.getElementById('cars');
                  // console.log('name',name['value']);    
                  // var selectedVal = name ; 
                  data['identifier'] = 'edit' ; 
                  console.log('data',data);
                   
                  let dialogRef = that.dialog.open(AddReminderComponent, {
                    width:"700px",
                    data: data
                  });
                  
                  dialogRef.afterClosed().subscribe(result => {
                    if(result == "Reminder updated"){
                      that.to_date = new Date();
                      that.callfunction();
                      console.log("Updated");
                      // console.log("Updated");
                    }  
                  });
              
                }); 
                $('#delete', row).bind('click', (e) => {  
                  console.log('delete');
                  swal({
                    title: 'Are you sure?',
                    text: "You won't be able to revert this!",
                    type: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, delete it!'
                  }).then((result: { value: boolean; }) => {
                    if (result) {
                      that.Load =true;
                      var pld = {rid : data._id};
                      that.contactService.deleteReminder(pld)
                      .subscribe(
                        data => {  
                          that.Load= false;                 
                          swal(
                            'Deleted',
                            'Reminder Deleted',
                            'success'
                          )   
                          
                          that.callfunction();
                      
                        },err=>{
                          that.Load  = false;
                          swal(
                            'Error',
                            'Internal Server Error, Please try after sometime !!!',
                            'success'
                          )
                        })    
                    }
                  })

              
               
              
                }); 
                
              },

              "columns": [
                  {
                      "data": "device.Device_Name",
                      "visible" :true,
                      "render": function(data, type, row) {
                    
                       return data?data:'NA';
                          
                      }
                  },
                  {
                      "data": "reminder_date",
                      "visible" :true,
                      render: function(data, type, row) {
                          
                          return moment(data).format('llll');           
                      }
                  },
                  {
                      "data": "notification_type",
                      "visible" :true,
                      render: function(data, type, row) {
                        console.log('data',data);
                  
                     
                     
                        if(data != undefined){
                          var sms:any='';
                          var email:any='';
                          var push:any='';
                          console.log("data.SMS,data.EMAIL,data.PUSH_NOTIFICATION=>",data.SMS,data.EMAIL,data.PUSH_NOTIFICATION);
                   
                          if(data.SMS == true){
                            sms = '<img src="../../assets/image/sms.png" title="SMS" alt="sms" style="width:30px;height:23px;margin-right:5px">';
                          }
                        
                          if(data.EMAIL == true){
                            email = '<img src="../../assets/image/email.png" title="Email" alt="email" style="width:20px;height:20px;margin-right:5px">';
                          }
  
                          if(data.PUSH_NOTIFICATION == true){
                            push = '<img src="../../assets/image/pushN.png" title="Push Notification" alt="Push Notification" style="width:30px;height:24px;margin-right:5px">';
                          }
                        }
                        var combinedStr = sms + email +  push ;
   
                                        
                          return (combinedStr != NaN)?combinedStr : '<p></p>';
                      }
                  }, 
                  {
                    "data": "reminder_type",
                    "visible" : true,
                    render: function(data, type, row) {  
                      
                        return data?data:"NA";
                    }
                },    
                  
                  {
                    "data": "prior_reminder",
                    "visible" :true,
                    render: function(data, type, row) {             
                        return data?data:0;
                    }
                },
                {
                    "data": "odo",
                    "visible" :true,
                    render: function(data, type, row) {             
                        return data?data:0;
                    }
                },         
                { 
                  "data": "note",
                  "visible" :true,
                  render: function(data, type, row) {
                return data?data:''
                  }
              }, 
              { 
                "data": "status",
                "visible" :true,
                render: function(data, type, row) {
                 return data?data:''
                }
            }, 
              { 
                "data": "_id",
                "visible" :true,
                render: function(data, type, row) {

                //   var option_status = '<div class="dropdown" >' + 
                //   '<button class="btn btn-sm btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Status </button>'+
                //   '<div class="dropdown-menu" aria-labelledby="dropdownMenuButton" id = "reminder_s">' + 
                //     '<a class="dropdown-item" style="cursor : pointer" value="Pending" >Pending</a>' + 
                //     '<a class="dropdown-item" style="cursor : pointer" value="Completed" >Completed' + 
                //     '<a class="dropdown-item" style="cursor : pointer" value="In Progress" >In Progress'+
                //   '</div>' + 
                // '</div>';

                  // var curr_status = 'pending'; 
                  var option_edit ="<i class='material-icons' style='cursor : pointer' title='Update Reminder' id='edit'> edit </i>";
                  // var option_status = '<select id="cars">' +
                  //   '<option value="pending" selected ='+curr_status === "pending"+'>Pending</option>' +
                  //   '<option value="in_Progress" selected ='+ curr_status === "in_Progress" +'>In Progress</option>' +
                  //   '<option value="completed" selected = "curr_status === completed">Completed</option>' +
                  //   '</select>'
                return option_edit ; 
                }
            },    
            { 
              "data": "_id",
              "visible" :true,
              render: function(data, type, row) {

            
                var option_delete ="<i class='material-icons' style='cursor : pointer' title='Update Reminder' id='delete'> delete </i>";
               
              return option_delete ; 
              }
          },                    
              ],   
          });
    
      });
    
    }

  reminderComponent(){
    
    let dialogRef = this.dialog.open(AddReminderComponent, {
      width:"800px",
      data: {identifier : 'add'}
    });
    
    dialogRef.afterClosed().subscribe(result => {
    
      if(result == "reminder Saved"){
        this.to_date = new Date();
        this.callfunction();
        console.log("Updated")
      }
    
    });
    }
    

}
