import { Component, OnInit, ViewChild } from '@angular/core';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { ContactService } from '../contact.service';
import { Router } from '@angular/router';
import { MdDialog } from '@angular/material';
import { FlashMessagesService } from 'angular2-flash-messages';
import * as moment from 'moment';
declare var $: any, DataTable: any;

@Component({
  selector: 'app-costumer-support',
  templateUrl: './costumer-support.component.html',
  styleUrls: ['./costumer-support.component.scss']
})
export class CostumerSupportComponent 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';

  inquiryStatus = ['OPEN','IN PROGRESS', "CLOSED"];
  inquiryRole = ['ADMIN','DEALER', "ORGANISATION"];
  dtOptions:any={};
  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;
  }

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

testTable() {
  const that = this;
  $(document).ready(function () {
      that.tabelObj = $('#deviceTable').DataTable({
          "serverSide": true,
          "processing": true,
          "searching": false,
          "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 = [];
              dataTablesParameters.find = {};
          
              // if(that.supadm == true){
              //     dataTablesParameters.find['superAdmin'] = that.useridd;
              // }
          
              // if(that.isOperator == true){
                //   dataTablesParameters.find['user'] = that.useridd;
              // }
              
              dataTablesParameters.find['assigned_to'] = that.useridd;
              console.log("dataTablesParameters=>",dataTablesParameters);
              if (that.from_date) {
                  dataTablesParameters.find['posted_on'] = dataTablesParameters.find['posted_on'] ? dataTablesParameters.find['posted_on'] : {};
                  dataTablesParameters.find['posted_on']['$gte'] = {
                    _eval: 'date',
                    value: new Date(that.from_date).toISOString()
                  }
                };
                // }
                if (that.to_date) {
                  dataTablesParameters.find['posted_on'] = dataTablesParameters.find['posted_on'] ? dataTablesParameters.find['posted_on'] : {};
                  dataTablesParameters.find['posted_on']['$lte'] = {
                    _eval: 'date',
                    value: new Date(that.to_date).toISOString()
                  };
                }
            
              dataTablesParameters.columns = [
              {data : "_id"},
              {data : "superAdmin"},
              {data : "dealer"},
              {data : "message"},
              {data : "assigned_to"},
              {data : "assigned_to.first_name"},
              {data : "assigned_to.last_name"},
              {data : "support_status"},
              {data : "posted_on"},
              {data :"posted_by"},
              {data :"posted_by.first_name"},
              {data : "posted_by.last_name"},
              {data :"posted_by.phone"},
              {data : "posted_by.email"},
              {data : "role"},
              {data : "user"}
              ] 
              // dataTablesParameters.find.user = that.useridd;

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

                  // console.log(err.status);
              });
          },
          "rowCallback": function(row: Node, data: any | Object, index: number){  
            $('#roleChange', row).bind('change', function (ele) {
              var selectedRole = $($(row).children()[6]).children().val();
              console.log("selectedRole=>",selectedRole);
              console.log('ticketRoleStat=>',data);
              var role_update = {
                id: data._id,
                role : selectedRole,
                user : data.user,
              }

              var suburl = "";
              suburl += "/customer_support/updateCustomerQuery";
              that.contactService.post(suburl,role_update).subscribe(res=>{
                console.log(res);
              },err=>{
                console.log(err);
              })
            })

            $('#ticketStatChange', row).bind('change', function (ele) {
              var selectedStatus = $($(row).children()[7]).children().val();
              console.log("selectedStatus=>",selectedStatus);
           
              var role_update = {
                id: data._id,   
                ticketStatus : selectedStatus
              }
              

              


              var suburl = "";
              suburl += "/customer_support/updateCustomerQuery";
              that.contactService.post(suburl,role_update).subscribe(res=>{
                console.log(res);
              },err=>{
                console.log(err);
              })
            
            })
              // $('#edit', row).bind('click', () => {    
              //     var editData = data;  
              //     editData.actionId= "edit";  
              //    localStorage.setItem("invantoryObject",JSON.stringify(editData));
              //     that.router.navigateByUrl('deviceEntry');
        
              // });    
            },

          "columns": [
              {           
                  "data": "posted_on",
                  // "searchable" : true,
                  "render": function (data, type, row) {
                      var system_date = new Date(data);
                      return data ? (moment(system_date).format('dddd,ll,LTS')) : "";
                  }
              },
              {
                  
                  "data": "posted_by",
                  // "searchable" : true,
                  render: function (data, type, row) {
                      // console.log("whatdataishere=>",data);
                      var fName = data.first_name?data.first_name:"";
                      var lName = data.last_name?data.last_name:"";
                      return fName  + " " + lName;
                  }
              },
              {
                  
                "data": "posted_by",
                // "searchable" : true,
                render: function (data, type, row) {
                    // console.log("whatdataishere=>",data);
                   
                    return data.phone?data.phone : "";
                }
            },
            {
                  
              "data": "posted_by",
              // "searchable" : true,
              render: function (data, type, row) {
                 // console.log("whatdataishere=>",data);
                 
                  return data.email?data.email : "";
              }
          },
              {
                  
                  "data": "message",
                  // "searchable" : true,
                  render: function (data, type, row) {
                      return data ? data : "";
                  }
              },
              {       
                  "data": "assigned_to",
                  // "searching" : true,
                  render: function (data, type, row) {
                      // console.log("AssignedData=>",data);
                      var frstName = data.first_name? data.first_name : "";
                      var lstName = data.last_name ? data.last_name : "";
                      return frstName + " "+ lstName;
                  }
              },   
              {       
                "data": "role",
                // "searching" : true,
                render: function (data, type, row) {
              
                  var $select1 = $("<select id='roleChange'></select>", {
                    "id": row[0]+"start",
                    "value": data
                });
                $.each(that.inquiryRole, function(l,m){
           
                    var $option1 = $("<option></option>", {
                        "text": m,
                        "value": m
                    });
                    if(data === m){
                        $option1.attr("selected", "selected")
                    }
                    $select1.append($option1);

                });

                return $select1.prop("outerHTML");
                }
            },              
              {
                  
                  "data": "support_status",
                  // "searchable" : true,
                  render: function (data, type, row) {    
                        var $select = $("<select id='ticketStatChange'></select>", {
                          "id": row[0]+"start",
                          "value": data
                      });
                      $.each(that.inquiryStatus, function(k,v){       
                          var $option = $("<option></option>", {
                              "text": v,
                              "value": v
                          });
                          if(data === v){
                              $option.attr("selected", "selected");
                              $option.attr("disabled", "disabled")
                          }
                          $select.append($option);
                      });
                      console.log($select);
                      return $select.prop("outerHTML");
                  }
              },                                 
          //     {
          //         "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);
}


}
