import { Component, OnInit } from '@angular/core';
import { ContactService } from './../contact.service';
import { environment } from '../../environments/environment'
declare var $: any, DataTable: any, swal: any;
import * as moment from 'moment';
// declare var jspdf: any;
// import jsPDF from 'jspdf';
//  const jsPDF = require('jspdf');

import { MdDialog } from '@angular/material';

import { EditDeviceMasterComponent } from './edit-device-master/edit-device-master.component';
import { FlashMessagesService } from 'angular2-flash-messages';
import { saveAs } from 'file-saver';
import { NormalCertComponent } from './normal-cert/normal-cert.component';
import { CertOptionComponent } from './cert-option/cert-option.component';
declare var jsPDF: any;
declare var autoTable: any;
@Component({
    selector: 'app-device',
    templateUrl: './device.component.html',
    styleUrls: ['./device.component.scss']
})
export class DeviceComponent implements OnInit {
    option: any;
    Fromdate = new Date();
    todate = new Date();
    emailid: any;
    
    useridd: any;
    tabelObj: any;
    errorStatus: string;
    serviceResponse: boolean;
    identifier:String='deviceMaster';
    supAdmin: any;
    supadm: any;
    Load: boolean;
    XLurl: any;
    tempObj: any;
    isDealer: any;
    dlrID: any;
    selectedDevice: any;
    selectedDeviceWithSIM: any;
    dev_url = environment.hostUrl;
    Message: string;
    data_descip: string;
    constructor(public contactService: ContactService, public dialog: MdDialog, private _flashMessagesService: FlashMessagesService) {
        this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
        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.isDealer = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isDealer;
        console.log(JSON.parse(window.atob(window.localStorage.token.split('.')[1])));
        console.log(this.supadm, this.isDealer);


        if (this.isDealer == true) {
            this.dlrID = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._id
        }
        //    this.supAdmin = JSON.parse(window.atob(window.localStorage.superAdminToken.split('.')));
        //    console.log(this.supAdmin);
        // console.log(this.emailid);
        // console.log(this.useridd);
    }
    deletedDevices: boolean = false;
    showDeleted: boolean = false;
    delFlag: boolean = false;
    ngOnInit() {
        this.Fromdate.setHours(0, 0, 0);
        this.testTable();
        // this.getAllDevice();
    }
    callfunction(): void {
        this.tabelObj.draw();
    }

 
    testTable() {
        const that = this;
        $(document).ready(function () {
            that.tabelObj = $('#deviceTable').DataTable({
                serverSide: true,
                "processing": true,
                "searching": false,
                // "scrollX": true,
                
                lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                ajax: (dataTablesParameters: any, callback) => {
                    dataTablesParameters.op = {};
                    dataTablesParameters.select = [];
                    dataTablesParameters.find = {};
                    dataTablesParameters.columns = [
                        { data: "_id" },
                        { data: "Device_Name" },
                        { data: "user.first_name" },
                        { data: "user.last_name" },
                        { data: "user.address" },
                        { data: "expiration_date" },
                        { data: "Device_ID" },
                        { data: "contact_number" },
                        { data: "sim_number" },
                        { data: "created_on" },
                        {data : "deletedDevice"},
                        { data: "iconType" },
                        { data: "currentFuelVoltage" },
                        { data: "today_odo" },
                        { data: "total_odo" },
                        { data: "expiration_date" },
                        { data: "supAdmin" },
                        { data: "supAdmin.email" },
                        { data: "numberOfSOS" },
                        { data: "isDealer" },
                        { data: "Dealer.first_name" },
                        { data: "Dealer.last_name" },
                        { data: "Dealer.address" },
                        { data: "Dealer.phone" },
                        { data: "Email_ID" },
                        { data: "last_loc" },
                        { data: "engineNo" },
                        { data: "CID_No" },
                        { data: "status" },
                        { data: "device_model.device_type" },
                        { data: "device_model.Manufacturer" },
                        { data: "typeOfVehicle" },
                        { data: "manufacturingCompany" },
                        { data: "vehicleRegDate" },
                        { data: "vehicleManufacturingDate" },
                        { data: "lastFitnessDate" },
                        { data: "fitmentDate" },
                        { data: "ICCICD" },
                        { data: "IMSI" },
                        { data: "uniqueID" },
                        { data: "vehicleType.description" },
                        { data: "invoiceNumber" },
                        { data: "invoiceDate" },
                        { data: "companyName" },
                        { data: "companyAddress" },
                        { data: "transportOfficeCity" },
                        { data: "transportOfficeState" },
                        {data:"deviceImage"},
                        { data: "ChassisNo" },
                        {data:"last_device_time"},
                        {data:"last_ping_on"},
                        { data: null, defaultContent: '' }
                    ]

                    //  dataTablesParameters.find.supAdmin = that.useridd; last_device_time,last_ping_on
                           console.log("this.deviceObjIdthis.deviceObjId",that.deviceObjId);
                          
                        if(that.deviceObjId != undefined){
                            if(that.deviceObjId.type =='IMEI'){
                                dataTablesParameters.find['_id'] = that.deviceObjId.did;
                            }
                            if(that.deviceObjId.type =='SIM'){
                                dataTablesParameters.find['sim_number'] = that.deviceObjId.did;
                            }

                        }
                    if (that.Fromdate) {
                        var fdate = new Date(that.Fromdate).toISOString()
                        dataTablesParameters.find['created_on'] = dataTablesParameters.find['created_on'] ? dataTablesParameters.find['created_on'] : {};
                        dataTablesParameters.find['created_on']['$gte'] = fdate
                    };
                    // }
                    if (that.todate) {
                        var tdate = new Date(that.todate).toISOString()
                        dataTablesParameters.find['created_on'] = dataTablesParameters.find['created_on'] ? dataTablesParameters.find['created_on'] : {};
                        dataTablesParameters.find['created_on']['$lte'] = tdate;
                    }
                        console.log('that.showDeleted',that.showDeleted);
                    if (that.showDeleted === true) {
                        dataTablesParameters.find.deletedDevice = { $exists: true };
                        that.delFlag = true;
                        console.log("called");


                    } else {
                        dataTablesParameters.find.deletedDevice = { $exists: false };
                        that.delFlag = false;
                        console.log("called");
                    }

                    if (that.supadm == true) {
                        dataTablesParameters.find.supAdmin = that.useridd;

                    }

                    if (that.isDealer == true) {
                        dataTablesParameters.find.Dealer = that.dlrID;
                    }


                    var suburl = "";
                    suburl += "/devices/datatable";
                    // console.log(suburl);
                    // console.log(dataTablesParameters);
                    // console.log(suburl)
                    that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {
                        console.log("Response from datatable=>", resp);
                        that.colSwitch();
                        callback(resp);
                    }, err => {
                        // console.log(err);
                        // console.log(err.status);
                    });
                },
                "rowCallback": function (row: Node, data: any | Object, index: number) {

                    $('#edit', row).bind('click', () => {
                        // console.log("Edit Method",data);
                        // $('#edit').css("visibility","hidden");

                        let dialogRef = that.dialog.open(EditDeviceMasterComponent, {
                            width: '650px',
                            height: '700px',
                            data: { "deviceInfo": data }
                        });
                        data.actionId = "edit";
                        data.OwnerName = JSON.parse(JSON.stringify(data)).user.first_name + " " + JSON.parse(JSON.stringify(data)).user.last_name;

                        var fstname = (JSON.parse(JSON.stringify(data)).Dealer != undefined) ? JSON.parse(JSON.stringify(data)).Dealer.first_name : "";
                        var lsname = (JSON.parse(JSON.stringify(data)).Dealer != undefined) ? JSON.parse(JSON.stringify(data)).Dealer.last_name : "";
                        var dlraddress = (JSON.parse(JSON.stringify(data)).Dealer != undefined) ? JSON.parse(JSON.stringify(data)).Dealer.address : "";

                        data.Dealer_name = fstname + " " + lsname;
                        data.DealerAddress = dlraddress;
                        dialogRef.afterClosed().subscribe(result => {
                            // console.log(result);
                            if (result == "success") {
                                that.toast('device_edited');
                                that.callfunction();
                            }
                        })
                    });

                    $('#delete', row).bind('click', () => {
                        // console.log("delete Method", data);
                        var did = data.Device_ID;
                        var req={
                      device:data.Device_ID,
                      userId:that.useridd
                    }
                        // console.log(did);
                        that.contactService.deldev(req)
                            .subscribe(res => {
                                // console.log(res);
                          
                                that.Fromdate = new Date();
                                that.Fromdate.setHours(0, 0, 0);
                                that.todate = new Date();
                                that.todate;

                                that.callfunction();
                                that.toast('device_deleted');
                            }, err => {
                                that.toast('error_while_deleting');
                                // console.log(err);
                            })
                    });
                    $('#exportPDF', row).bind('click', () => {


                        data.actionId = "exportPdf";

                        data.OwnerName = JSON.parse(JSON.stringify(data)).user.first_name + " " + JSON.parse(JSON.stringify(data)).user.last_name;
                        //   data.Dealer_name = JSON.parse(JSON.stringify(data))
                        var fstname = (JSON.parse(JSON.stringify(data)).Dealer != undefined) ? JSON.parse(JSON.stringify(data)).Dealer.first_name : "";
                        var lsname = (JSON.parse(JSON.stringify(data)).Dealer != undefined) ? JSON.parse(JSON.stringify(data)).Dealer.last_name : "";
                        var dlraddress = (JSON.parse(JSON.stringify(data)).Dealer != undefined) ? JSON.parse(JSON.stringify(data)).Dealer.address : "";
                        data.Dealer_name = fstname + " " + lsname;
                        data.DealerAddress = dlraddress;data.deviceImage=data.deviceImage

                        let dialogRef = that.dialog.open(CertOptionComponent, {
                            data: { "deviceInfo": data }
                        });


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

                            if (result == "advance") {
                                let dialogRef_1 = that.dialog.open(EditDeviceMasterComponent, {
                                    data: { "deviceInfo": data },
                                    width: '650px',
                                    height: '700px',
                                });
                            }

                            if (result == "basic") {
                                let dialogRef_2 = that.dialog.open(NormalCertComponent, {
                                    data: { "deviceInfo": data }
                                });
                            }
                        })

                    });
                    $('#restoreDevice', row).bind('click', () => {
                        console.log('deviceRestore', data);
                        that.contactService.restoreDevice(data.Device_ID).subscribe(res => {
                      
                            that.callfunction();
                            that.toast('device_restored');
                        }, err => {
                            that.toast('error_while_restoring');
                        })
                    });
                    $('#reset_odo', row).bind('click', () => {
                        console.log(data);
                        swal({
                            title: '<strong>RESET ODO</strong>',
                            icon: 'info',
                            html: 'Please confirm to reset Vehicle ODO ?',
                            showCloseButton: true,
                            showCancelButton: true,
                            focusConfirm: false,
                            confirmButtonText: 'Reset today ODO',
                            confirmButtonAriaLabel: 'Thumbs up, great!',
                            cancelButtonText: 'Reset total ODO',
                            cancelButtonAriaLabel: 'Thumbs down'
                        }).then((result: { value: boolean; }) => {
                            if (result) {
                                if (that.supadm === true) {
                                    var reset_by = data.supAdmin;
                                } else {
                                    var reset_by = data.Dealer ? data.Dealer._id : data.supAdmin
                                }

                                let reset_payload = {
                                    device_id: data._id,
                                    odo_reset_by: reset_by,
                                    reset_identifier: true
                                }
                                console.log(reset_payload);
                                that.contactService.resetODO(reset_payload).subscribe(res => {
                                    console.log(res);
                                    that.callfunction();
                                    that.data_descip = "Today ODO has been Reset";
                                    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", ""); }, 1500);
                                    }

                                })
                            }
                        }, function (dissmiss) {

                            if (dissmiss === 'cancel') {
                                if (that.supadm === true) {
                                    var reset_by = data.supAdmin;
                                } else {
                                    var reset_by = data.Dealer ? data.Dealer._id : data.supAdmin
                                }
                                let reset_payload = {
                                    device_id: data._id,
                                    odo_reset_by: reset_by,
                                    reset_identifier: false
                                }

                                that.contactService.resetODO(reset_payload).subscribe(res => {
                                    that.callfunction()
                                    that.data_descip = "Total ODO has been Reset";
                                    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", ""); }, 1500);
                                    }

                                })

                            }
                        });
                    });
                    $('#delete_gps_data', row).bind('click', () => {
                        console.log(data);
                        swal({
                            title: '<strong>Delete History</strong>',
                            icon: 'info',
                            html: 'Please confirm to Delete History ?',
                            showCloseButton: true,
                            showCancelButton: true,
                            focusConfirm: false,
                            confirmButtonText: "Delete today's History",
                            confirmButtonAriaLabel: 'Thumbs up, great!',
                           
                        }).then((result: { value: boolean; }) => {
                            if (result) {
                                if (that.supadm === true) {
                                    var deleted_by = data.supAdmin;
                                } else {
                                    var deleted_by = data.Dealer ? data.Dealer._id : data.supAdmin
                                }

                                let reset_payload = {
                                    device_id: data.Device_ID,
                                    history_delete_by: deleted_by,
                                    delete_identifier: 'today'
                                }
                             
                                that.contactService.delete_gps_data(reset_payload).subscribe(res => {
                                    console.log(res);
                                    that.callfunction();
                                    that.data_descip = "Device History has been deleted";
                                    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", ""); }, 1500);
                                    }

                                })
                            }
                        }
                        // , function (dissmiss) {

                        //     if (dissmiss === 'cancel') {
                        //         if (that.supadm === true) {
                        //             var deleted_by = data.supAdmin;
                        //         } else {
                        //             var deleted_by = data.Dealer ? data.Dealer._id : data.supAdmin
                        //         }

                        //         let reset_payload = {
                        //             device_id: data.Device_ID,
                        //             history_delete_by: deleted_by,
                        //             delete_identifier: 'all'
                        //         }

                        //         that.contactService.delete_gps_data(reset_payload).subscribe(res => {
                        //             that.callfunction()
                        //             that.data_descip = "Device history has been deleted";
                        //             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", ""); }, 1500);
                        //             }

                        //         })

                        //     }
                        // }
                        );
                    });
                    $('#pdelete', row).bind('click', () => {
                        console.log('permanent delete clicked=>', data);

                        // var warningMsg = "Are you sure that you want to permanently delete the selected device ?" ;
                        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.contactService.deletePermanently(data.Device_ID).subscribe(res => {
                                    that.callfunction();
                                    swal(
                                        'Deleted',
                                        'Device Deleted',
                                        'success'
                                    )
                                })
                            }
                        });
                    }) ; 
                    $('#recalculateODO', row).bind('click', () => {
                       
                        // var warningMsg = "Are you sure that you want to permanently delete the selected device ?" ;
                        swal({
                            title: 'Are you sure?',
                            text: "Vahicle ODO will be recalculated",
                            type: 'warning',
                            showCancelButton: true,
                            confirmButtonColor: '#3085d6',
                            cancelButtonColor: '#d33',
                            confirmButtonText: 'Recalculate'
                        }).then((result: { value: boolean; }) => {
                            if (result) {
                                that.contactService.recalculateODO(data.Device_ID).subscribe(res => {
                                    that.callfunction();
                                    swal(
                                        'Reset',
                                        'Vehicle ODO has been reset',
                                        'success'
                                    )
                                })
                            }
                        });
                    });
                    $('#clearLogs', row).bind('click', () => {
                       
                        // var warningMsg = "Are you sure that you want to permanently delete the selected device ?" ;
                        swal({
                            title: 'Are you sure?',
                            text: "System Logs will be deleted",
                            type: 'warning',
                            showCancelButton: true,
                            confirmButtonColor: '#3085d6',
                            cancelButtonColor: '#d33',
                            confirmButtonText: 'Clear'
                        }).then((result: { value: boolean; }) => {
                            if (result) {
                                that.contactService.deleteSystemLogs(data.Device_ID).subscribe(res => {
                                    that.callfunction();
                                    swal(
                                        'Deleted',
                                        'System Logs has been deleted',
                                        'success'
                                    )
                                })
                            }
                        });
                    })
                },
                "columns": [
                    {
                        "data": "Device_Name",
                        "render": function (data, type, row) {
                            return data ? data : "";
                        }
                    },
                    {
                        "data": "Device_ID",
                        render: function (data, type, row) {
                            return data ? data : "";
                        }
                    },
                    {
                        "data": "status",
                        render: function (data, type, row) {
                            return data ? data : "";
                        }
                    },
                    {
                        "data": "user",
                        render: function (data, type, row) {
                            return data ? (data.first_name + " " + data.last_name) : "";
                        }
                    },
                    {
                        "data": "Dealer",
                        render: function (data, type, row) {
                            return data ? (data.first_name + " " + data.last_name) : "";
                        }
                    },
                    {
                        "data": "contact_number",
                        render: function (data, type, row) {
                            return data ? data : "";
                        }
                    },
                    {
                        "data": "created_on",
                        "render": function (data, type, row) {
                            var created_time = new Date(data);
                            return data ? (moment(created_time).format('dddd,ll,LTS')) : "";
                        }
                    },
                    {
                        "data": "expiration_date",
                        "render": function (data, type, row) {
                            var expired_time = new Date(data);
                            return data ? (moment(expired_time).format('dddd,ll,LTS')) : "";
                        }
                    },
                    
                    {
                        "data": "iconType",
                        "render": function (data, type, row) {
                            return data ? data : "";
                        }
                    },
                    {
                        "data": "currentFuelVoltage",
                        "render": function (data, type, row) {
                            return data ? data : "";
                        }
                    },
                    {
                        "data": "sim_number",
                        "render": function (data, type, row) {
                            return data ? data : ""
                        }
                    },
                    {
                        "data": "today_odo",
                        "render": function (data, type, row) {
                            return data ? (parseFloat(data).toFixed(2)) : 0;
                        }
                    },
                    {
                        "data": "total_odo",
                        "render": function (data, type, row) {
                            return data ? (parseFloat(data).toFixed(2)) : 0;
                        }
                    },
                    {
                        "data": "Email_ID",
                        "visible": false,
                        "render": function (data, type, row) {
                            return data ? data : "";
                        }
                    },
                    {
                        "data": null,

                        "render": function (data, type, row) {
                            return '<button id="edit" type="button" class="btn btn-primary" style="background:blue;border:0px;">Edit</button>'

                        }
                    },
                    {
                        "data": null,

                        "render": function (data, type, row) {
                            return '<button id="pdelete" type="button" class="btn btn-primary" style="background:red;border:0px;">Delete permanently</button>'

                        }
                    },


                    {
                        "data": null,

                        "render": function (data, type, row) {
                            return '<button id="restoreDevice" type="button" class="btn btn-primary" style="background:#60ab1c;border:0px;">Restore</button>'
                        }
                    },
                    {
                        "data": null,

                        "render": function (data, type, row) {
                            return '<button id="delete" type="button" class="btn btn-primary" style="background:red;border:0px;">Delete</button>'

                        }
                    },
                    {
                        "data": null,

                        "render": function (data, type, row) {
                            return '<button id="exportPDF" type="button" class="btn btn-primary"  style="background:#118a57;border:0px;">Export Pdf</button>'
                        }
                    },
                    {
                        "data": null,
                        "render": function (data, type, row) {
                            // return '<button id="reset_ODO" type="button" class="btn btn-primary"  style="background:#118a57;border:0px;">Export Pdf</button>'   
                            // '<img id="Reset odo" src="smiley.gif" alt="Reset ODO" title="Reset ODO" height="42" width="42">'
                            return '<i id="reset_odo" class="material-icons" title="Reset ODO" style="cursor:pointer"> cached </i>'
                        }
                    }
                    ,
                    {
                        "data": null,
                        "render": function (data, type, row) {  
                            return '<i id="delete_gps_data" class="material-icons" title="Delete History Data" style="cursor:pointer;color:red"> delete_outline </i>'
                        }
                    },
                    {
                        "data": null,
                        "render": function (data, type, row) {  
                            return '<i id="recalculateODO" class="material-icons" title="Recalculate Vehicle ODO" style="cursor:pointer;color:blue"> settings_backup_restore </i>'
                        }   
                    },
                    {
                        "data": null,
                        "render": function (data, type, row) {  
                            return '<i id="clearLogs" class="fas fa-warehouse" title="Clear System logs" style="cursor:pointer;color:blue">  </i>'
                        
                        }
                    },
                    {
                        "data": "last_ping_on",
                        "render": function (data, type, row) {
                            var expired_time = new Date(data);
                            return data ? (moment(expired_time).format('dddd,ll,LTS')) : "";
                        }
                    },


                ],

                // columnDefs: [

                // ],

            });
         
            that.colSwitch()

        });

    }


    // table edit function

    // editor:any;
    // editDataTable(){
    //   $(document).ready(function() {
    //     console.log("Edit function Call!!");
    //     var outerthis= this;
    //     outerthis.editor = new $.fn.DataTable.Editor({
    //         ajax: "",
    //         table: "#deviceTable",
    //         fields: [ {
    //                 label: "Device Name:",
    //                 name: "Device_Name"
    //             }, {
    //                 label: "Device ID:",
    //                 name: "Device_ID"
    //             }, {
    //                 label: "User:",
    //                 name: "user"
    //             }, {
    //                 label: "Phone:",
    //                 name: "contact_number"
    //             }, {
    //                 label: "created_on:",
    //                 name: "extn"
    //             }, {
    //                 label: "expiration_date:",
    //                 name: "start_date",
    //                 type: "datetime"
    //             }, {
    //                 label: "iconType:",
    //                 name: "iconType"
    //             }
    //         ]
    //     } );
    //   })
    // }

    // editDocumentTableActivate(){
    //   console.log("function Call!!");
    //   var outerthis= this;
    //   $('#deviceTable').on( 'click', 'tbody td:not(:first-child)', function (e) {
    //     outerthis.editor.inline( this );
    // } );
    // }


    deviceObj = [];
    // getAllDevice() {

    //     var dealer: any;
    //     // this.Load = true;
    //     if (this.supadm) {
    //         var supadmin: any = this.useridd;
    //     }
    //     if (this.isDealer) {
    //         dealer = this.dlrID;
    //     }
    //     var searchh;
    //     this.contactService.alldevices1(this.useridd, this.emailid, supadmin, dealer, searchh)
    //         .subscribe(res => {
    //             // this.Load = false;
    //             console.log("allDevices=>", res);
    //             this.deviceObj = [];
    //             var Alldevices = {
    //                 id: "all",
    //                 viewValue: "ALL Devices",
    //                 sim_Number: "ALL Devices"
    //             }
    //             this.deviceObj.push(Alldevices);

    //             for (var i = 0; i < res.devices.length; i++) {
    //                 Alldevices = {
    //                     id: res.devices[i]._id,
    //                     viewValue: res.devices[i].Device_ID ? res.devices[i].Device_ID : "",
    //                     sim_Number: res.devices[i].sim_number ? res.devices[i].sim_number : ""
    //                 }
    //                 this.deviceObj.push(Alldevices)
    //             }
    //             // console.log("deviceArray", this.deviceObj);

    //         }, err => {
    //             // this.Load = false;
    //             // console.log(err.status);
    //         })
    // }


    deviceSelect: any = [];
    simNumberSelect: any = [];
    deviceName: any;
    simnumber: any;
    filterDevices(dlr) {
        console.log("Device", dlr);

        if (dlr == '') {
            this.deviceSelect = [];
        } else {
            const filterdealerValue: any = dlr;

            this.deviceSelect = [];
            this.deviceSelect = this.deviceObj.filter(function (pp) {

                var t = pp.viewValue.toLocaleLowerCase().indexOf(filterdealerValue.toLocaleLowerCase());
                return t > -1;
            });
            console.log(this.deviceSelect);
            return this.deviceSelect;
        }

    }

    getExactValue(dev) {
        this.selectedDevice = dev;
        console.log(dev);

    }

    getSIMValue(sim) {
        console.log("SIM value=>", sim)
        this.selectedDeviceWithSIM = sim;
        console.log(sim);

    }

    filterDevicesbysimnumber(simnum) {
        if (simnum == '') {
            this.simNumberSelect = [];
        } else {
            const filtersimValue: any = simnum;
            this.simNumberSelect = [];
            this.simNumberSelect = this.deviceObj.filter(function (pptt) {
                // debugger;
                // console.log(pp);
                var t = pptt.sim_Number.toLocaleLowerCase().indexOf(filtersimValue.toLocaleLowerCase());
                return t > -1;
            });
            return this.simNumberSelect;
        }

    }

    excelExport() {
        console.log("inside excel download");
        var url = this.dev_url;
        var from = new Date(this.Fromdate);
        var to = new Date(this.todate);

        this.XLurl = url + '/devices/devReport?user=' + this.useridd + "&fromDate=" + from + "&toDate=" + to
        console.log(this.XLurl);

        // this.Load = true;
        // this.contactService.getVehicleExcelSheet(from.toISOString(),to.toISOString(),this.useridd).subscribe(res=>{
        //     this.Load = false;
        //     console.log(res);
        //     this.saveToFileSystem(res)

        // })
    }

    private saveToFileSystem(response) {
        console.log(response);
        console.log("Inside pdf");
        var blob = new Blob([response._body], { type: "application/xlsx" });

        var filename = "Vehicledata";
        // console.log(filename);
        saveAs(blob, filename);
    }

    pdfExport() {
        var doc = new jsPDF();
        var columns = [];
        var rows = [];
        // doc.autoTable(columns, rows, {
        //     margin: {top: 60},
        // }); 

        doc.fromHTML($('#content').html(), 15, 15, {
            'width': 170,

        });

        doc.text("Hello world", 1, 6);
        doc.save('Test.pdf');
    }



    colSwitch() {
        if (this.isDealer == true) {
            for (var k = 0; k < 18; k++) {
                if (this.delFlag == false) {
                    this.tabelObj.column(17).visible(true);
                    if (((k == 13) || (k == 14) || (k == 15) || (k == 16))) {
                        this.tabelObj.column(k).visible(false);
                    }
                } else {
                    this.tabelObj.column(15).visible(true);
                    this.tabelObj.column(16).visible(true);
                    if ((k == 13) || (k == 14) || (k == 17)) {
                        this.tabelObj.column(k).visible(false);
                    }
                }


            }
        }

        if (this.supadm == true) {
            console.log("Inside function");
            for (var k = 0; k <= 18; k++) {
                if (this.delFlag == true) {
                    // if(((k ==13) || (k==14))){
                    //     this.tabelObj.column( k ).visible( false );
                    //     this.tabelObj.column(k + 1).visible(true);
                    //     this.tabelObj.column(k + 2).visible(true);
                    // }

                    if (((k == 15) || (k == 16) || (k == 17))) {
                        this.tabelObj.column(k).visible(true);
                    }
                    if (((k == 18) || (k == 17))) {
                        this.tabelObj.column(k).visible(false);
                    }

                } else {
                    this.tabelObj.column(14).visible(true);
                    this.tabelObj.column(13).visible(true);
                    this.tabelObj.column(17).visible(true);
                    this.tabelObj.column(18).visible(true);

                    if ((k == 15) || (k == 16)) {
                        this.tabelObj.column(k).visible(false);
                    }
                }
            }
        }
    }

    tab:any;
exportExcel()
{

    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    var table = $('#deviceTable').clone();
    table[0].querySelector("thead").remove();
    table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];//document.getElementById('deviceTable'); // id of table

    for(j = 0 ; j < this.tab.rows.length ; j++) 
    {     
        tab_text=tab_text+this.tab.rows[j].innerHTML+"</tr>";
      
    }

    tab_text=tab_text+"</table>";
   
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}
deviceObjId:any;
getReport(event){
  
  console.log("inside function");
  if(event == 'getExcel'){
    this.exportExcel();
  }else{
    var deviceId: any;
    var tpdata = event ; 
    var that = this;
    var fd = new Date(tpdata.fromDate);
    var td  = new Date(tpdata.toDate);
    console.log('this.showDeleted',event.deletedDevice);
    if(event.deletedDevice != undefined){
        this.showDeleted = event.deletedDevice ; 
       
    }
  
    if(event.deviceId != undefined){
        this.deviceObjId = {"did" : event.deviceId[0],"type":event.type}   ;
        console.log('this.deviceObjId',this.deviceObjId);

    }
    
    this.Fromdate = fd;
    this.todate = td;
     this.tabelObj.ajax.reload();  
   
  }
 
}

toast(divid){
   
    if(divid == "device_restored"){
      this.data_descip = "Device succesfully restored";
      launch_toast();
    }else if(divid == "error_while_restoring"){
      
      this.data_descip = "Error Occured while restoring";
      launch_toast();
    }
    else if(divid == "device_deleted"){
      this.data_descip = "Device Deleted Succesfully";
      launch_toast();
    }
    else if(divid == "error_while_deleting"){
      this.data_descip = "Error Occured while deleting";
      launch_toast();
    }
    else if(divid == "device_edited"){
      this.data_descip = "Information updated successfully";
      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", ""); }, 1500);
    }
     }

}
