import { Component, OnInit, TemplateRef } from '@angular/core';
import { BsDatepickerConfig, BsModalRef, BsModalService } from 'ngx-bootstrap';
import { ContactService } from '../contact.service';
declare var $: any;
declare var swal: any
import * as moment from 'moment';
@Component({
  selector: 'app-issue-list',
  templateUrl: './issue-list.component.html',
  styleUrls: ['./issue-list.component.scss']
})
export class IssueListComponent implements OnInit {
  issues=[];
  modalRef: BsModalRef;
  bsConfig: Partial<BsDatepickerConfig>;
  fromDate=new Date();
  toDate=new Date();
  tabelObj: any;
  userId
  colorTheme = 'theme-dark-blue';
  Load: boolean;
  constructor(private contactService:ContactService,private modalService: BsModalService) {
    this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' }, { containerClass: this.colorTheme });
   }

  ngOnInit() {
    var fTime = new Date();
    fTime.setHours(0,0,0,0);   
    this.fromDate = new Date(fTime);

      var today = new Date();
      var startDate = new Date(today.getFullYear(), today.getMonth(), 1);
      this.fromDate=startDate
    this.userId= JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    // this.getIssues()
    this.testTable()
  }

  getIssues(){
   
    
    this.contactService.get("/customer_support/getIssues?user="+this.userId+"&from="+this.fromDate+"&to="+this.toDate).subscribe((res:any)=>{
      console.log(res);
      this.issues=res;
    })
  }


   testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function () {
      that.tabelObj = $('#deviceTable').DataTable({
        // dom: 'Bfrtip',
        // buttons: [ 'copy', 'csv', 'ex  cel', 'pdf', 'print' ],
        "autoWidth": true,
        'deferRender':true,
        "processing": true,
        "searching": true,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: false,
        "scrollX": true,
        "scrollY": '65vh',
        "scrollCollapse": true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
         "rowCallback": function(row: Node, data: any | Object, index: number){
          $('#edit', row).bind('click', () => {   
             
              console.log(data);

              var body={}
              if(data.support_status=='OPEN'){
                body={
                  title: "Update Status",
                  // text: "Please Enter Solution Remark:",
                  // input: 'text',
                  showCancelButton: true ,
                  confirmButtonColor: 'green',
                   confirmButtonText:'IN PROGRESS'
                }
              }else{
                 body={
                  title: "Update Status",
                  text: "Please Enter Solution Remark:",
                  input: 'text',
                  showCancelButton: true ,
                  confirmButtonColor: 'green',
                 
                }
              }
              // var req={
              //   id:data._id,
              //   ticketStatus:'RESOLVED'
              // }
              // that.contactService.post('/customer_support/updateCustomerQuery',req).subscribe(res=>{
              //   console.log(res);
              //   that.tabelObj.ajax.reload()
              // })
               swal(body
                //  {
                //   // title: 'Are you sure?',
                //   title: "Update Status",
                //   text: "Please Enter Solution Remark:",
                //   input: 'text',
                //   showCancelButton: true ,
                //   confirmButtonColor: 'green',
                // }
                ).then((result) =>{                      
                  if(result){
                    console.log(result);
                    var req={
                id:data._id,
                solutionRemarks:data.support_status=='OPEN'?undefined:result,
                ticketStatus:data.support_status=='OPEN'?'IN PROGRESS':'CLOSE'
              }
              that.contactService.post('/customer_support/updateCustomerQuery',req).subscribe(res=>{
                console.log(res);
                that.tabelObj.ajax.reload()
              })
               
                    }else{
                       console.log(result);
                    }
                      
                  })               
                     
            });
         },
        ajax: (dataTablesParameters, callback) => {
          console.log('temptemptemptemptemp', dataTablesParameters);
           that.Load = true;
          var suburl = "";
         that.contactService.get("/customer_support/getIssues?user="+that.userId+"&from="+that.fromDate+"&to="+that.toDate).subscribe((res:any)=>{
        console.log(res);
        that.issues=res;
        for(var i=0;i<res.length;i++){
          if(!res[i].ticketId){
            res[i].ticketId='N/A'
          }
          if(!res[i].solutionRemarks){
            res[i].solutionRemarks='N/A'
          }
          if(!res[i].closedDate){
            res[i].closedDate='N/A'
          }
          // console.log(res);
          
        }
        
         that.Load = false
        callback({ data: res });
         })

        },

        "columns": [
           {
            "data": "ticketId",
           
            "render": function (data, row) {  
              // console.log(row);
                         
              return data?data:'N/A';   
            }
          },
          {
            "data": "posted_by",
           
            "render": function (data, row) {             
              return data.first_name+" "+data.last_name;   
            }
          },
          {
            "data": "posted_by",
           
            "render": function (data, row) {             
              return data.email;   
            }
          },
          {
            "data": "posted_by",
           
            "render": function (data, row) {             
              return data.phone;   
            }
          },
            {
            "data": "posted_on",
            "render": function (data, type, row) {       
              var reportDate = new Date(data);
              return data ? (moment(reportDate).format('LL')) : "";   
            }
          },
            {
            "data": "assigned_to",
            "render": function (data, type, row) {       
              return data.first_name+" "+data.last_name;   
            }
          },
           {
            "data": "message",
            "render": function (data, type, row) {       
              return data;   
            }
          },
          {
            "data": "support_status",
            "render": function (data, type, row) {  
              return data=='CLOSE' || data=='CLOSED'?'CLOSED':data=='IN PROGRESS'?data:'OPEN';   
            }
          },
          {
            "data": "solutionRemarks",
            "render": function (data, type, row) { 
              var solutionRemarks=  data?data:'N/A';     
              return solutionRemarks
            }
          },
          {
            "data": "closedDate",
            "render": function (data, type, row) { 
              var closedDate= data!='N/A'? moment(data).format('llll'):'N/A';
                  
              return closedDate
            }
          },
           {
            "data": "support_status",
            "render": function (data, type, row) {    
              var button 
              if(row.support_status=='CLOSE') {
                button= `<button disabled class="btn btn=info btn-sm"><i  title="Query Closed" style="font-size:20px;color: green" class="fas fa-check"></i></button>`;
              } else{
                button=`<button class="btn btn=info btn-sm"><i id="edit" title="Resolve Query" style="font-size:20px;color: green" class="fas fa-edit"></i></button>`;
              }
              return button 
            }
          },
          
        ],
        "columnDefs": [
          { className: "dt-body-left", "targets": [0,1,2,3,4,5,6,7,8,9,10] },
          {
            "targets": '_all',
            "createdCell": function (td, cellData, rowData, row, col) {
              $(td).css('padding', '18px')
            }
          },
          { "width": "10px", "targets": 0 },
          { "width": "40px", "targets": 1 },
          { "width": "100px", "targets": 2 },
          { "width": "70px", "targets": 3 },
          { "width": "70px", "targets": 4 },
           { "width": "70px", "targets": 5 },
           { "width": "70px", "targets": 6 },
           { "width": "70px", "targets": 7 },
           { "width": "70px", "targets": 8 },
           { "width": "70px", "targets": 9 },
           { "width": "70px", "targets": 10 },

        ], order: [[ 4, 'desc' ], [ 0, 'asc' ]]
      });

    });

  }
  changeDate(){
    console.log("chabjhdsb",this.toDate,this.fromDate);
    
    this.tabelObj.ajax.reload();
  }

  openModal(template: TemplateRef<any>,data) {
    this.modalRef = this.modalService.show(template,{'backdrop':'static',class:'modal-lg modal-dialog-centered'});
    
  }

  

}
