import { Component, OnInit } from '@angular/core';
import { ExpenseComponentComponent } from '../device-report/trip-by-device/expense-component/expense-component.component';
import { MdDialog, MdSnackBar } from '@angular/material';
import { AddVehicleExpensesComponent } from './add-vehicle-expenses/add-vehicle-expenses.component';
import { ContactService } from '../contact.service';
import { VehicleExpenseDetailComponent } from './vehicle-expense-detail/vehicle-expense-detail.component';

@Component({
  selector: 'app-vehicle-expenses',
  templateUrl: './vehicle-expenses.component.html',
  styleUrls: ['./vehicle-expenses.component.scss']
})
export class VehicleExpensesComponent implements OnInit {
  Load : boolean = false;
  identifier : String = "vehicle_expenses";
  // this.gsmURL = "";
  expenseType  =[
    // { "type" : "FOOD EXP.", "viewValue" : "FOOD EXP.", "icon" : '../../assets/images/expenseComp/fork.png',showList : false ,"amount" : 200},
    // { "type" : "POLICE/TRO", "viewValue" : "POLICE/TRO" , "icon" : '../../assets/images/expenseComp/policeman.png',showList : true ,"amount" : 100 }, 
    // { "type" : "PETTA", "viewValue" : "PETTA","icon" : '',showList : false , "amount" : 200 }, 
    // { "type" : "TELEPHONE", "viewValue" : "TELEPHONE", "icon" : '../../assets/images/expenseComp/phone.png',showList : false , "amount" : 150},
    //  { "type" : "TOLE", "viewValue" : "TOLE" ,"icon" : '../../assets/images/expenseComp/toll-road.png',showList : false ,"amount" : 250}, 
    // { "type" : "TRAVELLING", "viewValue" : "TRAVELLING", "icon" : '../../assets/images/expenseComp/plane.png',showList : false , "amount" : 100}, 
    // { "type" : "MISCE EXP.", "viewValue" : "MISCE EXP." , "icon" : '../../assets/images/expenseComp/order.png',showList : true , "amount" : 250} ,
    // { "type" : "FUEL", "viewValue" : "FUEL" , "icon" : '../../assets/images/expenseComp/fuel.png' ,showList : false ,"amount" : 250} ,
    // { "type" : "TYRE", "viewValue" : "TYRE"  ,"icon" : '../../assets/images/expenseComp/wheel.png' ,showList : false , "amount" : 200} ,
    // { "type" : "WORKSHOP", "viewValue" : "WORKSHOP" , "icon" : '../../assets/images/expenseComp/workshop.png',showList : true ,"amount" : 200} ,
    // { "type" : "SPARES", "viewValue" : "SPARES" , "icon" : '../../assets/images/expenseComp/automotive.png',showList : false ,"amount" : 200} ,
    // { "type" : "ROOMRENT", "viewValue" : "ROOMRENT" ,"icon" : '../../assets/images/expenseComp/bed.png',showList : false , "amount" : 200} ,
    // { "type" : "PERMIT", "viewValue" : "PERMIT" , "icon" : '../../assets/images/expenseComp/permit.png',showList : false ,"amount" : 200} ,
    // { "type" : "DONATION", "viewValue" : "DONATION" , "icon" : '../../assets/images/expenseComp/cash.png',showList : false, "amount" : 200} 
  ];
  superAdmin: any;
  emailid: any;
  useridd: any;
  custtype: any;
  data_descip: string;

  constructor(public dialog: MdDialog,public snackBar: MdSnackBar,private contactService: ContactService) { }

  ngOnInit() {
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email; 
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;   
    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.Fromdate.setHours(0,0,0,0);
    this.getLanguage();
  }

  deviceArr = []; 
  Fromdate = new Date() ; 
  todate = new Date();

  getReport(event){
      var deviceId: any;
      var tpdata = event ; 
      var that = this;
      var fd = new Date(tpdata.fromDate);
      var td  = new Date(tpdata.toDate);
      
      if(event.deviceArr.length==0){
        deviceId=[];
      }else{
        deviceId= event.deviceArr;
      }
      this.deviceArr = deviceId;        
      this.Fromdate = fd;
      this.todate = td;
      this.getExpenses()
  }



  getExpenses(){
   
    if(this.deviceArr.length === 0){
      this.data_descip = "Please Select Device";
     return launch_toast()   ;
    }

    var getExpensesPayload = {
      user : this.useridd,
      fromDate:this.Fromdate.toISOString(),
      toDate : this.todate.toISOString(),
      vehicle : this.deviceArr[0]
    }
    console.log('getExpensesPayload',getExpensesPayload);
    this.expenseType = [];
    this.contactService.getExpensesbyCategory(getExpensesPayload).subscribe(res=>{
      console.log('resresresresres=>',res.expenseobj);  
      if((res.expenseobj === undefined)||(res.expenseobj.length == 0)){
        this.data_descip = 'No Record Found' ; 
        return launch_toast();
      }else{ 
        this.expenseType =  res.expenseobj ;
        var total = 0
        for(var i = 0 ; i <res.expenseobj.length;i++){
          total += res.expenseobj[i]?parseFloat(res.expenseobj[i].total):0 ;
        }
        var addTotalObj = {
          _id : 'TOTAL',
          total : total
        }
        this.expenseType.push(addTotalObj);
        console.log('this.expenseType',this.expenseType);
      }
    

    },err=>{
      this.data_descip = "Internal Server Error";
      return launch_toast()   ;
    })
    // mainUrl + "expense/expensebycateogry?user=" + this.islogin._id + "&fdate=" + new Date(this.datetimeStart).toISOString() + "&tdate=" + new Date(this.datetimeEnd).toISOString() + "&vehicle=" + this._vehId._id;

    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", ""); }, 1500);
   }
  }


  addexpense(){
    var  tripObject = {};
      console.log('tripObject=>',tripObject);
      let dialogRef = this.dialog.open(AddVehicleExpensesComponent, {
        width : "700px",
        data: tripObject
      });
    
      dialogRef.afterClosed().subscribe(result => {
        if(result == "success"){
          this.data_descip ="Expense Added";
          this.todate = new Date();
          this.getExpenses();
          
          launch_toast() ; 
     
       
        
        }
      });  

      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", ""); }, 1500);
     }
    
    
  }

  iconType:any;
  getIcon(id){

  
    if(id === "FOOD EXP."){
      this.iconType = '../../assets/images/expenseComp/fork.png';
     

    }else if(id === "POLICE/TRO"){
      this.iconType = '../../assets/images/expenseComp/policeman.png';
  

    }else if(id === "PETTA"){
      this.iconType = '../../assets/images/expenseComp/policeman.png';
    

    }else if(id=== "TELEPHONE"){
      this.iconType = '../../assets/images/expenseComp/phone.png'; 
      

    }else if(id=== "TOLE"){
      this.iconType = '../../assets/images/expenseComp/toll-road.png'; 

    }else if(id === "TRAVELLING"){
      this.iconType = '../../assets/images/expenseComp/plane.png'

    }else if(id === "MISCE EXP."){
      this.iconType = '../../assets/images/expenseComp/order.png'
    }else if(id === "FUEL"){
      this.iconType = '../../assets/images/expenseComp/fuel.png'
    }else if(id === "TYRE"){
      this.iconType = '../../assets/images/expenseComp/wheel.png'
    }else if(id === "WORKSHOP"){
      this.iconType = '../../assets/images/expenseComp/workshop.png'
    }
    else if(id === "SPARES"){
      this.iconType = '../../assets/images/expenseComp/automotive.png'
    }
    else if(id === "ROOMRENT"){
      this.iconType = '../../assets/images/expenseComp/bed.png'
    }
    else if(id === "PERMIT"){
      this.iconType = '../../assets/images/expenseComp/permit.png'
    }
    else if(id === "DONATION"){
      this.iconType = '../../assets/images/expenseComp/cash.png'
    }else if(id === "TOTAL"){
      this.iconType = '../../assets/images/expenseComp/money.png'
    }else{
      return '';
    }
    return this.iconType ;  
  }

  VehDetail(et){ 
    et.fromDate= this.Fromdate.toISOString();
    et.toDate = this.todate.toISOString();
    et.user = this.useridd ; 
    et.vehicle = this.deviceArr[0] ; 

    console.log('ExpenseTypeDetail=>',et);
    if(et._id != 'TOTAL'){
      let dialogRef = this.dialog.open(VehicleExpenseDetailComponent, {
        width : "700px",
        data: et
      });
    
      dialogRef.afterClosed().subscribe(result => {
        if(result == "success"){
          console.log("success");   
        }
      });  
    }
 


  }

  currency_code:any='INR';
  getLanguage(){
    var that = this;
  var Var = { uid: this.useridd };
   this.contactService.getLanguages(Var).subscribe(res=>{
    this.currency_code =  res.currency_code?res.currency_code:"INR";
    },err=>{
     console.log(err);
   })
  
  }


}
