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 { DeviceEntryComponent } from '../device-entry/device-entry.component';
import { FlashMessagesService } from 'angular2-flash-messages';
declare var $: any, DataTable: any;
@Component({
    selector: 'app-inventory-list',
    templateUrl: './inventory-list.component.html',
    styleUrls: ['./inventory-list.component.scss']
})
export class InventoryListComponent implements OnInit {
    from_date: Date;
    to_date: Date;
    bsConfig: Partial<BsDatepickerConfig>;
    tabelObj: any;
    useridd: any;
    supadm: any;
    isOperator: boolean = false;
    supAdminId: any;
    newVar:any;
    newVar1:any;
    colorTheme = 'theme-dark-blue';
    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.to_date = new Date();
        this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' }, { containerClass: this.colorTheme });
    }

    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;
        // this.isOperator =  JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isOperator;
    }
    InventoryList() {
        console.log(this.from_date);
        console.log(this.to_date);
        this.tabelObj.draw();
    }

    adddev(){
        // console.log("Inside adddiv");
        //console.log(id);   
        this.router.navigateByUrl("deviceEntry");
      }


    testTable() {
        const that = this;
        $(document).ready(function () {
            that.tabelObj = $('#deviceTable').DataTable({
                "serverSide": true,
                "processing": true,
               
                "order": [[3, "desc"]],
                "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                "fields" :[{label :"Vehicle Number",name : "Device_Name"}],
                scrollX: true,
                ajax: (dataTablesParameters: any, callback) => {
                    dataTablesParameters.op = {};
                    dataTablesParameters.select = ['Device_ID'];
                    dataTablesParameters.find = {};
                    // dataTablesParameters.search.regex = true;
                
                    if(that.supadm == true){
                        dataTablesParameters.find['superAdmin'] = that.useridd;
                    }
                
                    if(that.isOperator == true){
                        dataTablesParameters.find['operator_id'] = that.useridd;
                    }

                    if (that.from_date) {
                        dataTablesParameters.find['systemDate'] = dataTablesParameters.find['systemDate'] ? dataTablesParameters.find['systemDate'] : {};
                        dataTablesParameters.find['systemDate']['$gte'] = {
                          _eval: 'date',
                          value: new Date(that.from_date).toISOString()
                        }
                      };
                      // }
                      if (that.to_date) {
                        dataTablesParameters.find['systemDate'] = dataTablesParameters.find['systemDate'] ? dataTablesParameters.find['systemDate'] : {};
                        dataTablesParameters.find['systemDate']['$lte'] = {
                          _eval: 'date',
                          value: new Date(that.to_date).toISOString()
                        };
                      }
                  
                    dataTablesParameters.columns = [
                        {data : "_id"},
                        { data: "systemDate" },
                        { data: "Device_ID" },
                        { data: "Device_Name" },
                        { data: "chessisNumber" },
                        { data: "sim_number_1" },
                        { data: "sim_provider_1" },
                        { data: "sim_number_2" },
                        { data: "sim_provider_2" },
                        {data : "trackingSoft"},
                        { data: "approvingRTO" },
                        { data: "ownerNumber" },
                        { data: "Alternatenumber" },
                        { data: "email" },
                        { data: "status" },
                        { data: "dealerName" },
                        {data :"engine_number"},
                        {data :"device_model.device_type" },

                        { data: "operator_id.first_name" }, { data: "operator_id.last_name" }, { data: "costumer_first_name" },{data : "costumer_last_name"}
                    ]
                    // dataTablesParameters.find.user = that.useridd;

                    var suburl = "";
                    suburl += "/inventory/inventorydatatable";
                    that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {  
                        callback(resp);
                    }, err => {

                        // console.log(err.status);
                    });
                },
                "rowCallback": function(row: Node, data: any | Object, index: number){  
                    $('#edit', row).bind('click', () => {    
                        var editData = data;  
                        editData.actionId= "edit";  
                       localStorage.setItem("invantoryObject",JSON.stringify(editData));
                        that.router.navigateByUrl('deviceEntry');
              
                    });    
                  },

                "columns": [
                    {                    
                        "data": "systemDate",
                        // "searchable" : true,
                        "render": function (data, type, row) {
                            var system_date = new Date(data);
                            return data ? (moment(system_date).format('dddd,ll,LTS')) : "";

                        }
                    },
                    {
                        
                        "data": "Device_Name",
                        // "searchable" : true,
                        render: function (data, type, row) {
                            // console.log(data);
                            return data ? data : "";
                        }
                    },
                    {
                        
                        "data": "chessisNumber",
                        // "searchable" : true,
                        render: function (data, type, row) {

                            return data ? data : "";
                        }
                    },
                    {
                        
                        "data": "engine_number",
                        // "searchable" : true,          
                        render: function (data, type, row) {
                            console.log("engine_number=>",data);
                            return data ? data : "";
                        }
                    },
                    {
                        
                        "data": "device_model",
                        // "searchable" : true,
                        render: function (data, type, row) {
                            console.log("device_model=>",data);
                            return data ? data.device_type : "NA";
                        }
                    },
                    {       
                        "data": "Device_ID",
                        "searchable" : true,
                        render: function (data, type, row) {
                            console.log(data);
                            return data ? data : "";
                        }
                    },
           
                
                    {
                        
                        "data": "sim_number_1",
                        // "searchable" : true,
                        render: function (data, type, row) {

                            return data ? data : "";
                        }
                    },
                    // {
                        
                    //     "data": "sim_provider_1",
                    //     // "searchable" : true,
                    //     // "visible" :false,

                    //     "render": function (data, type, row) {
                    //         // console.log(data);
                    //         return data ? data : "";
                    //     }
                    // },
                    {
                        
                        "data": "sim_number_2",
                        // "searchable" : true,
                        "render": function (data, type, row) {
                            return data ? data : "";
                        }
                    },
                    {
                        
                        "data": "approvingRTO",
                        // "searchable" : true,
                        // "visible" :false,

                        "render": function (data, type, row) {
                            // console.log(data);
                            return data ? data : "";
                        }
                    },
                    {
                        
                        "data": "ownerNumber",
                        // "searchable" : true,
                        // "visible" :false,

                        "render": function (data, type, row) {
                            // console.log(data);
                            return data ? data : "";
                        }
                    },
                   
                    {
                        
                        "data": "Alternatenumber",
                        // "searchable" : true,
                        // "visible" :false,

                        "render": function (data, type, row) {
                            // console.log(data);
                            return data ? data : "";
                        }
                    },
                    {
                        
                        "data": "status",
                        // "searchable" : true,
                        // "visible" :false,

                        "render": function (data, type, row) {
                            // console.log(data);
                            return data ? data : "";
                        }
                    },
                        {
                        
                        "data": "dealerName",
                        "searchable" : true,
                        // "visible" :false,

                        "render": function (data, type, row) {
                            // console.log(data);
                            return data ? data : "";
                        }
                    },

                
                    {
                        
                        "data": "trackingSoft",
                        // "searchable" : true,
                        // "visible" :false,

                        "render": function (data, type, row) {
                            // console.log(data);
                            return data ? data : "";
                        }
                    },
                    {
                        
                        "data": "costumer_first_name",
                        // "searchable" : false,
                        "visible" :false,

                        "render": function (data, type, row) {
                            // console.log(data);
                            return row ? (row.costumer_first_name + "" + row.costumer_last_name) : "";;
                        }
                    },
                    {
                        
                        "data": "costumer_last_name",
                        // "searchable" : true,
                         "visible" :true,

                        "render": function (data, type, row) {
                            // console.log(data);
                            return row ? (row.costumer_first_name + " " + row.costumer_last_name) : "";
                        }
                    },                         
                    {
                        
                        "data": "email",
                        // "searchable" : true,
                        // "visible" :false,

                        "render": function (data, type, row) {
                            // console.log(data);
                            return data ? data : "";
                        }
                    },
        
                
                    {
                        
                        "data": "operator_id",
                        // "searchable" : true,
                        // "visible" :false,

                        "render": function (data, type, row) {
                            // console.log(data);

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

                    }
                } ,
                ],
                
            });

      
        });

    }

    tab:any;

    exportExcel() {
 
 
        var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
        var textRange; var j=0;
        this.tab = 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+"</tr>";
        }
    
        tab_text=tab_text+"</table>";
        tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
        tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
        tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
        // tab_text= tab_text.replace(/<th>Edit</th>/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);
    }


}
