import { Component, OnInit } from '@angular/core';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { ContactService } from '../contact.service';
declare var $: any;
declare var swal: any
import * as moment from 'moment';
import { ReportService } from '../report/report.service';
import { Router } from '@angular/router';
@Component({
  selector: 'app-job-card',
  templateUrl: './job-card.component.html',
  styleUrls: ['./job-card.component.scss']
})
export class JobCardComponent implements OnInit {
fromDate=new Date();
  toDate=new Date();
  tabelObj: any;
  userId;
  jobCards=[]
   bsConfig: Partial<BsDatepickerConfig>;
  colorTheme = 'theme-dark-blue';
  Load: boolean;
  constructor(private contactService:ContactService,private reportService:ReportService,private router:Router) {
    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.testTable()
  }

   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', () => {   
            localStorage.setItem('Carddata',JSON.stringify(data))
            that.router.navigate(['/JobCardAdd'])
              that.reportService.openEditJobCard(data);
          })
         },
        ajax: (dataTablesParameters, callback) => {
          console.log('temptemptemptemptemp', dataTablesParameters);
           that.Load = true;
          var suburl = "";
         that.contactService.get("/jobCard/get?id="+that.userId+"&from="+new Date(that.fromDate).toISOString()+"&to="+new Date(that.toDate).toISOString()).subscribe((res:any)=>{
        console.log(res);
        that.jobCards=res;
        for(var i=0;i<res.length;i++){
          if(!res[i].JobCompletedOn){
            res[i].JobCompletedOn='N/A'
          }
          if(!res[i].SIM){
            res[i].SIM='N/A'
          }
           if(!res[i].IMEI){
            res[i].IMEI='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": "JobType",
           
            "render": function (data, row) {  
              // console.log(row);
                         
              return data?data:'N/A';   
            }
          },
          {
            "data": "CustomerName",
           
            "render": function (data, row) {             
              return data?data:'N/A';   
            }
          },
          {
            "data": "Mobile",
           
            "render": function (data, row) {             
              return data?data:'N/A';   
            }
          },
          {
            "data": "Address",
           
            "render": function (data, row) {             
              return data?data:'N/A';   
            }
          },
            {
            "data": "Location",
            "render": function (data, type, row) {       
             
              return "";   
            }
          },
            {
            "data": "Description",
            "render": function (data, type, row) {       
              return data?data:'N/A';   
            }
          },
           {
            "data": "NoOfInstallation",
            "render": function (data, type, row) {       
              return data?data:'N/A';   
            }
          },
          {
            "data": "SIM",
            "render": function (data, type, row) {       
              return data?data:'N/A';   
            }
          },
          {
            "data": "IMEI",
            "render": function (data, type, row) {       
              return data?data:'N/A';   
            }
          },
          {
            "data": "Amount",
            "render": function (data, type, row) {  
              return data?data:'N/A';   
            }
          },
          {
            "data": "PaymentStatus",
            "render": function (data, type, row) { 
              var solutionRemarks=  data?data:'N/A';     
              return solutionRemarks
            }
          },
          {
            "data": "CreatedDate",
            "render": function (data, type, row) { 
              var solutionRemarks=  data?(moment(data).format('LL')):'N/A';     
              return solutionRemarks
            }
          },
          {
            "data": "JobDate",
            "render": function (data, type, row) { 
             var solutionRemarks=  data?(moment(data).format('LL')):'N/A';     
              return solutionRemarks
            }
          },
          {
            "data": "JobCompletedOn",
            "render": function (data, type, row) { 
              var solutionRemarks=  data!='N/A'?(moment(data).format('LL')):'N/A';     
              return solutionRemarks
            }
          },
          {
            "data": "Status",
            "render": function (data, type, row) { 
              return data?data:'N/A'
            }
          },
           {
            "data": "Remarks",
            "render": function (data, type, row) { 
              return data?data:'N/A'
            }
          },
          {
            "data": "Technician",
            "render": function (data, type, row) { 
              return data?data.first_name+' '+data.last_name:'N/A'
            }
          },
           {
            "data": 'Status',
            "render": function (data, type, row) { 
                var button
              if(data=='complete' || data=='Complete') {
                button= `<button disabled class="btn btn=info btn-sm"><i  title="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="Edit Job Card" style="font-size:20px;color: green" class="fas fa-edit"></i></button>`;
              }
              // var button=`<button class="btn btn=info btn-sm"><i id="edit" title="Edit Job Card" 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();
  }

}
