import { Component, OnInit, Inject } from '@angular/core';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { ContactService } from '../../contact.service';
import { BsDatepickerConfig } from 'ngx-bootstrap';
declare var $

@Component({
  selector: 'app-add-vehicle-expenses',
  templateUrl: './add-vehicle-expenses.component.html',
  styleUrls: ['./add-vehicle-expenses.component.scss']
})
export class AddVehicleExpensesComponent implements OnInit {
  Load :boolean  = false;
  totalExpense:any;
  optiondefault:any;
  from_date :any;

  expenseType=[
    { "value" : "FOOD EXP.", "viewValue" : "FOOD EXP." },
    { "value" : "POLICE/TRO", "viewValue" : "POLICE/TRO" }, 
    { "value" : "PETTA", "viewValue" : "PETTA" }, 
    { "value" : "TELEPHONE", "viewValue" : "TELEPHONE" },
     { "value" : "TOLE", "viewValue" : "TOLE" }, 
    { "value" : "TRAVELLING", "viewValue" : "TRAVELLING" }, 
    { "value" : "MISCE EXP.", "viewValue" : "MISCE EXP." } ,
    { "value" : "FUEL", "viewValue" : "FUEL" } ,
    { "value" : "TYRE", "viewValue" : "TYRE" } ,
    { "value" : "WORKSHOP", "viewValue" : "WORKSHOP" } ,
    { "value" : "SPARES", "viewValue" : "SPARES" } ,
    { "value" : "ROOMRENT", "viewValue" : "ROOMRENT" } ,
    { "value" : "PERMIT", "viewValue" : "PERMIT" } ,
    { "value" : "DONATION", "viewValue" : "DONATION" } 
   ];
   paymentMethod = [
     {"value": "CASH","viewValue":"CASH"},
     {"value": "CHEQUE","viewValue":"CHEQUE"},
     {"value": "ONLINE","viewValue":"ONLINE"},
     {"value": "OTHER","viewValue":"OTHER"}
   ]
  
   prepaymentVal:any;
   expenseVal:any;
  options: any;
  devicesss: any;
  finall: any;
  emailid: any;
  useridd: any;
  custtype: any;
  superAdmin: any;
  bsConfig: Partial<BsDatepickerConfig>;
  constructor(public dialogRef: MdDialogRef<AddVehicleExpensesComponent>,@Inject(MD_DIALOG_DATA) public data: any,private contactService: ContactService,) { 
     var that = this; 
     this.from_date = new Date();
    //  var script = document.createElement("script");
    //  script.setAttribute("type", "text/javascript");
    //  script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
    //  document.getElementsByTagName("head")[0].appendChild(script);

  }



  

  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.getCurrencies();

      this.loadDropDown();
      this.contactService.getDevice(this.emailid,this.useridd).subscribe(

        data => {
          this.devicesss = data
       
          this.finall = (this.devicesss.devices);
          this.options = [];

          for(let i=0;i<this.devicesss.devices.length;i++){
  
            // if(this.devicesss.devices[i].type_of_device =="Tracker"){
              let a ={
                value : this.devicesss.devices[i].Device_Name,
                viewValue:this.devicesss.devices[i].Device_Name,
                did:this.devicesss.devices[i].Device_ID,
                id:this.devicesss.devices[i]._id,
                user:this.devicesss.devices[i].user,
                // email: this.devicesss.devices[i].Email_ID,
                // deviceType: this.devicesss.devices[i].type_of_device,      
              }
              a['selectedValue'] = this.devicesss.devices[i]._id ; 
            
              this.options.push(a);
            // }
            if(i === (this.devicesss.devices.length -1)){
              this.loadDropDown()
            }
          }

       
      

        
            // console.log("ignition option",this.options);
            let that = this;
            // setTimeout(()=>{ 
            // },100)  
        
        });

        this.getLanguage();
      

    

  }


  loadDropDown(){
    setTimeout(() => {
      $('#dbselect_add').multipleSelect({
        width: 280,
        placeholder: 'Select Vehicle',
        filter: true,
        single: true,
        selectAll: false
 
      })
  
    //  that.showLoader = false;
    }, 100);
  }
  cancel(){
    this.dialogRef.close('cancel');
  }

  saveExpense(){
    console.log('this.optiondefault',this.optiondefault);
    let did =  $('#dbselect_add').multipleSelect('getSelects','value');


   if((did.length === 0)||(this.totalExpense == undefined)||(this.prepaymentVal == undefined)||(this.expenseVal == undefined)){
     console.log("Error")
   }else{
    var dt = new Date(this.from_date) ; 
    var payload = {
      user : this.useridd,
      vehicle  : did[0],
      currency : this.optiondefault , 
      payment_mode : this.prepaymentVal,
      amount : this.totalExpense,
      type : this.expenseVal,
      date : dt.toISOString()

    }
    this.contactService.addExpenses(payload).subscribe(res=>{
     console.log('resresresresresresresres=>',res);
      let resMsg = res.message;      
       if(resMsg === "added Successfully"){
         this.dialogRef.close('success');
       }
    },err=>{
      console.log(err);
    })
   }
 
  }

  getCurrencies(){
    this.currency = [];
    // this.contactService.getCurrencies().subscribe(res=>{   
      var currencyObj = this.currencyJson;  
        console.log('currencyObj',currencyObj);
      for(var i in currencyObj){
        if(this.data.currency != undefined){
          var devicecurr = this.data.currency ; 
          if(i == devicecurr){    
            this.optiondefault = i+ '-' +  currencyObj[i];
           }

        }else{
          if(i == 'INR'){    
            this.optiondefault = i+ '-' +  currencyObj[i];
           }
        }
    
      var tempObj = {
        currencyVal : i,
        country       : i+ '-' +  currencyObj[i]
      }
        this.currency.push(tempObj);
      }
    
      console.log(this.currency);
      // this.loadropdown();
    // })
  }


  dataSelect=[];
  currency = [];
  filterStates(val) {
    console.log(val)
    // console.log(this.dummyuserData)
    if (val) {
      const filterValue: any = val;
      console.log(this.currency);
      this.dataSelect = this.currency.filter(function (d) {
              console.log("inside Search Method=>",d);
        return d.country.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase()) > -1;
      });
      return this.dataSelect;
    }
    // console.log("searched user=>",this.dataSelect);
  }

  getLanguage(){
    var that = this;
  var Var = { uid: this.useridd };
   this.contactService.getLanguages(Var).subscribe(res=>{
     var currencyfiltered = this.currency.filter(d=>{
       if(res.currency_code != undefined){
        if(d.currencyVal === res.currency_code){
          return d.country;
        }
       }else{
         if(d.currencyVal === 'INR'){
          return d.country;
         }
       }
     })
     this.optiondefault = currencyfiltered[0].country;
    },err=>{
     console.log(err);
   })
  
  }


  currencyJson = {
    "AED": "United Arab Emirates Dirham",
    "AFN": "Afghan Afghani",
    "ALL": "Albanian Lek",
    "AMD": "Armenian Dram",
    "ANG": "Netherlands Antillean Guilder",
    "AOA": "Angolan Kwanza",
    "ARS": "Argentine Peso",
    "AUD": "Australian Dollar",
    "AWG": "Aruban Florin",
    "AZN": "Azerbaijani Manat",
    "BAM": "Bosnia-Herzegovina Convertible Mark",
    "BBD": "Barbadian Dollar",
    "BDT": "Bangladeshi Taka",
    "BGN": "Bulgarian Lev",
    "BHD": "Bahraini Dinar",
    "BIF": "Burundian Franc",
    "BMD": "Bermudan Dollar",
    "BND": "Brunei Dollar",
    "BOB": "Bolivian Boliviano",
    "BRL": "Brazilian Real",
    "BSD": "Bahamian Dollar",
    "BTC": "Bitcoin",
    "BTN": "Bhutanese Ngultrum",
    "BWP": "Botswanan Pula",
    "BYN": "Belarusian Ruble",
    "BZD": "Belize Dollar",
    "CAD": "Canadian Dollar",
    "CDF": "Congolese Franc",
    "CHF": "Swiss Franc",
    "CLF": "Chilean Unit of Account (UF)",
    "CLP": "Chilean Peso",
    "CNH": "Chinese Yuan (Offshore)",
    "CNY": "Chinese Yuan",
    "COP": "Colombian Peso",
    "CRC": "Costa Rican Colón",
    "CUC": "Cuban Convertible Peso",
    "CUP": "Cuban Peso",
    "CVE": "Cape Verdean Escudo",
    "CZK": "Czech Republic Koruna",
    "DJF": "Djiboutian Franc",
    "DKK": "Danish Krone",
    "DOP": "Dominican Peso",
    "DZD": "Algerian Dinar",
    "EGP": "Egyptian Pound",
    "ERN": "Eritrean Nakfa",
    "ETB": "Ethiopian Birr",
    "EUR": "Euro",
    "FJD": "Fijian Dollar",
    "FKP": "Falkland Islands Pound",
    "GBP": "British Pound Sterling",
    "GEL": "Georgian Lari",
    "GGP": "Guernsey Pound",
    "GHS": "Ghanaian Cedi",
    "GIP": "Gibraltar Pound",
    "GMD": "Gambian Dalasi",
    "GNF": "Guinean Franc",
    "GTQ": "Guatemalan Quetzal",
    "GYD": "Guyanaese Dollar",
    "HKD": "Hong Kong Dollar",
    "HNL": "Honduran Lempira",
    "HRK": "Croatian Kuna",
    "HTG": "Haitian Gourde",
    "HUF": "Hungarian Forint",
    "IDR": "Indonesian Rupiah",
    "ILS": "Israeli New Sheqel",
    "IMP": "Manx pound",
    "INR": "Indian Rupee",
    "IQD": "Iraqi Dinar",
    "IRR": "Iranian Rial",
    "ISK": "Icelandic Króna",
    "JEP": "Jersey Pound",
    "JMD": "Jamaican Dollar",
    "JOD": "Jordanian Dinar",
    "JPY": "Japanese Yen",
    "KES": "Kenyan Shilling",
    "KGS": "Kyrgystani Som",
    "KHR": "Cambodian Riel",
    "KMF": "Comorian Franc",
    "KPW": "North Korean Won",
    "KRW": "South Korean Won",
    "KWD": "Kuwaiti Dinar",
    "KYD": "Cayman Islands Dollar",
    "KZT": "Kazakhstani Tenge",
    "LAK": "Laotian Kip",
    "LBP": "Lebanese Pound",
    "LKR": "Sri Lankan Rupee",
    "LRD": "Liberian Dollar",
    "LSL": "Lesotho Loti",
    "LYD": "Libyan Dinar",
    "MAD": "Moroccan Dirham",
    "MDL": "Moldovan Leu",
    "MGA": "Malagasy Ariary",
    "MKD": "Macedonian Denar",
    "MMK": "Myanma Kyat",
    "MNT": "Mongolian Tugrik",
    "MOP": "Macanese Pataca",
    "MRO": "Mauritanian Ouguiya (pre-2018)",
    "MRU": "Mauritanian Ouguiya",
    "MUR": "Mauritian Rupee",
    "MVR": "Maldivian Rufiyaa",
    "MWK": "Malawian Kwacha",
    "MXN": "Mexican Peso",
    "MYR": "Malaysian Ringgit",
    "MZN": "Mozambican Metical",
    "NAD": "Namibian Dollar",
    "NGN": "Nigerian Naira",
    "NIO": "Nicaraguan Córdoba",
    "NOK": "Norwegian Krone",
    "NPR": "Nepalese Rupee",
    "NZD": "New Zealand Dollar",
    "OMR": "Omani Rial",
    "PAB": "Panamanian Balboa",
    "PEN": "Peruvian Nuevo Sol",
    "PGK": "Papua New Guinean Kina",
    "PHP": "Philippine Peso",
    "PKR": "Pakistani Rupee",
    "PLN": "Polish Zloty",
    "PYG": "Paraguayan Guarani",
    "QAR": "Qatari Rial",
    "RON": "Romanian Leu",
    "RSD": "Serbian Dinar",
    "RUB": "Russian Ruble",
    "RWF": "Rwandan Franc",
    "SAR": "Saudi Riyal",
    "SBD": "Solomon Islands Dollar",
    "SCR": "Seychellois Rupee",
    "SDG": "Sudanese Pound",
    "SEK": "Swedish Krona",
    "SGD": "Singapore Dollar",
    "SHP": "Saint Helena Pound",
    "SLL": "Sierra Leonean Leone",
    "SOS": "Somali Shilling",
    "SRD": "Surinamese Dollar",
    "SSP": "South Sudanese Pound",
    "STD": "São Tomé and Príncipe Dobra (pre-2018)",
    "STN": "São Tomé and Príncipe Dobra",
    "SVC": "Salvadoran Colón",
    "SYP": "Syrian Pound",
    "SZL": "Swazi Lilangeni",
    "THB": "Thai Baht",
    "TJS": "Tajikistani Somoni",
    "TMT": "Turkmenistani Manat",
    "TND": "Tunisian Dinar",
    "TOP": "Tongan Pa'anga",
    "TRY": "Turkish Lira",
    "TTD": "Trinidad and Tobago Dollar",
    "TWD": "New Taiwan Dollar",
    "TZS": "Tanzanian Shilling",
    "UAH": "Ukrainian Hryvnia",
    "UGX": "Ugandan Shilling",
    "USD": "United States Dollar",
    "UYU": "Uruguayan Peso",
    "UZS": "Uzbekistan Som",
    "VEF": "Venezuelan Bolívar Fuerte (Old)",
    "VES": "Venezuelan Bolívar Soberano",
    "VND": "Vietnamese Dong",
    "VUV": "Vanuatu Vatu",
    "WST": "Samoan Tala",
    "XAF": "CFA Franc BEAC",
    "XAG": "Silver Ounce",
    "XAU": "Gold Ounce",
    "XCD": "East Caribbean Dollar",
    "XDR": "Special Drawing Rights",
    "XOF": "CFA Franc BCEAO",
    "XPD": "Palladium Ounce",
    "XPF": "CFP Franc",
    "XPT": "Platinum Ounce",
    "YER": "Yemeni Rial",
    "ZAR": "South African Rand",
    "ZMW": "Zambian Kwacha",
    "ZWL": "Zimbabwean Dollar"
  }

}
