import { Component, OnInit } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

declare var google: any;
declare var $:any;
declare var swal:any;
declare var html2canvas:any;
declare var pdfMake :any ; 
import * as moment from 'moment';
import { ContactService } from '../contact.service';
import { environment } from '../../environments/environment';


@Component({
  selector: 'app-billing-dashboard',
  templateUrl: './billing-dashboard.component.html',
  styleUrls: ['./billing-dashboard.component.scss']
})
export class BillingDashboardComponent implements OnInit {
  ignition_data: any =[];
  fs : any;
  ls : any;
  emailid : any;
  date1 = new Date();

  before:any;
  or : any;
  useridd :any;
  time :any;
  device_data:any;
  devicess:any;
  final:any;
  custtype:any;
  cust:boolean=false;
  Load : Boolean = false;
  date : any;
  devicesss:any;
  mb:any;
  logoutbut:boolean;
  dealer:boolean;
  text:any;
  option:any; 
  finall:any;
  Fromdate:any;
  todate:any;
  options=[];
  logo:any;
  superAdmin:Boolean = false;
  dev_url = environment.hostUrl;
  t:any;
  dataSelect:any;
  errorMsg: any;
  errorDialog: boolean=false;
  searchText:any;
tabelObj:any; 
  tableFlag: boolean=true;
  identifier : String = "billing_detail";
  stoppage_data:any;
  arrival_time:any;
  departure_time:any;
  report_to_show =[];
  Durations:any;
  address_show:any;
  start_add_lat:any;
  start_add_long:any;
  uId:any;
  vName:any;
  deviceArr = [];
  from_date: any;
  data_descip: string;

  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog) { 
    
  
  }

  ngOnInit() {
    this.t = document.getElementById("download");
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
    this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    var fd = new Date();
    this.from_date = new Date(fd.setDate(1));
    console.log(this.from_date);
    var pdate = moment(fd).endOf('month').format('YYYY-MM-DD hh:mm');
    this.todate = new Date(pdate);
    this.testTable();
  }

  tab:any;
  optionVal: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);
}

userArr:any;
billingStauts :any;
billingType :any;
getReport(event){
  console.log("inside function",event);
  if(event == 'getExcel'){
    this.exportExcel();
  }else{
    var userId: any;
    var tpdata = event ; 
    var that = this;
    var fd = new Date(event.date);
    this.from_date = new Date(fd.setDate(1));
    var pdate = moment(fd).endOf('month').format('YYYY-MM-DD hh:mm');
    this.todate = new Date(pdate);
    console.log(this.todate);  
    
    userId= event.user;
    this.billingStauts = event.status[0];
    this.billingType = event.type[0]
    this.userArr = userId[0];   
    console.log(this.billingStauts,this.billingType,this.userArr,this.from_date,this.todate); 
    this.tabelObj.ajax.reload();  
   
  }
 
}

testTable() {
  const that = this;
  console.log("inside function");
  $(document).ready(function() {
     that.tabelObj = $('#deviceTable').DataTable({
      // dom: 'Bfrtip',
      // buttons: [
      //     'copy', 'csv', 'excel', 'pdf', 'print'
      // ]  ,
          "processing": true,
          "searching": true, 
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: true,
          "scrollY":'65vh',  
          "scrollCollapse": true,
          order: [[0, 'asc']],
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
          ajax: (dataTablesParameters,callback) => {
            dataTablesParameters.op = {};
            dataTablesParameters.select = [];
            dataTablesParameters.find = {};
            that.Load = true;  

            dataTablesParameters.columns = [
              {data : '_id', "orderable": "true" },  
              {data : "user"}  ,
              { data: "user.first_name" },
              { data: "user.last_name" },
              { data: "billing_type" },
              { data: "total_Amount" },
              { data: "GST" },
              { data: "Status" },
              { data: "Rate" },
              { data: "Number_of_Devices" },
              { data: "billing_Date" },
              ]
              console.log(that.todate);
              
       
            // if (that.from_date) {
            //   dataTablesParameters.find['created_on'] = dataTablesParameters.find['created_on'] ? dataTablesParameters.find['created_on'] : {};
            //   dataTablesParameters.find['created_on']['$gte'] = {
            //     _eval: 'date',
            //     value: new Date(that.from_date).toISOString()
            //   }
            // };
        
            // if (that.todate) {
            //   dataTablesParameters.find['created_on'] = dataTablesParameters.find['created_on'] ? dataTablesParameters.find['created_on'] : {};
            //   dataTablesParameters.find['created_on']['$lte'] = {
            //     _eval: 'date',
            //     value: new Date(that.todate).toISOString()
            //   };
            // }
         
    

          if(that.userArr){
            dataTablesParameters.find.user =  that.userArr; 
          }
          if(that.billingType){
            dataTablesParameters.find.billing_type =  that.billingType;
          }
          if(that.billingStauts){
            
            dataTablesParameters.find.Status =  that.billingStauts;

          }
          console.log(dataTablesParameters);

            var suburl = "";
            suburl += "/billing/getBillingDetail";
            that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {
              that.Load = false;
              callback(resp);
  
            }, err => {
              that.Load = false;
              callback({data:[]});
              console.log(err);
           
            });
           
          
        },  
        "rowCallback": function(row: Node, data: any | Object, index: number){  
          $('#changeStatus', row).bind('click', () => {    
                  console.log(data);
                  swal("Are you sure ?", "Do you want to change payment status ?").then((ans)=>{
                    console.log(ans);
                    that.changeStatus(data);
                  },err=>{
                    console.log(err);
                  });
               
            });
          }, 
         "columns": [
              {
                  "data": "_id",
                  "visible": false,
                  "render": function(data, type, row) {
                    return data?data : '';                  
                  }
              },
              {
                "data": "user",
                render: function(data, type, row) {
                  console.log(row);  
                  var fName = row.user?row.user.first_name:'' ;
                  var lName = row.user?row.user.last_name:''             
                  return fName + ' ' + lName;        
                }
            },
              {
                  "data": "billing_Date",
                  render: function(data, type, row) {
                    var billDate = new Date(data);
                    return data ? (moment(billDate).format('LL')) : "";
                 
                  }
              },
              {
                "data": "Number_of_Devices",
                render: function(data, type, row) {
                  return data?data:'';        
                }
            },
              {
                  "data": "total_Amount",      
                  render: function(data, type, row) {
                    return data?data:0;
                
                  }
              }, 
        
              
            {
              "data": "Rate",
              "defaultContent": "_id",
              render: function(data, type, row) {        
              return data;
              }
          }   ,
          {
            "data": "Status",
            "defaultContent": "_id",
            render: function(data, type, row) {  
              var btnclr = "white";  
              if(data === 'Pending'){
                btnclr = "red";

              }  else{ 
                btnclr = "green";
              }
              return '<button type="button" id="changeStatus" title="Change Status" style="width:80%;color:white;cursor:pointer;background:'+btnclr+'" class="btn">'+data+'</button>'  
            // return data?data:'';
            }
        }   ,
        {
          "data": "billing_type",
          "defaultContent": "_id",
          render: function(data, type, row) {        
          return data?data:'';
          }
      } 
        // { data: "billing_type" },

          ],  
          // "columnDefs": [
          //   { className: "dt-body-left", "targets": [ 0,1,2,3 ] },
          //   {
          //     "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 },
       
          // ] 
      });

  });

}

changeStatus(data){
  console.log(data);
  var statusVal =(data.Status === "Pending")?'Paid': 'Pending';
  var payload = {
    docId : data._id,
    status : statusVal
  }
  console.log(payload);

  this.contactService.changeBillingStauts(payload).subscribe(res=>{
    this.data_descip =  "Payment Status Changed";
    launch_toast();
    this.tabelObj.draw();
    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", ""); }, 4500);
   }    


  },err=>{

  })

}



}
