import { Component, OnInit, ViewChild } from '@angular/core';
import { Product } from 'src/app/core/services/product';
import { ProductService } from 'src/app/core/services/product.service';
import * as FileSaver from 'file-saver';
import { MatDialog } from '@angular/material/dialog';
import { MatMenuTrigger } from '@angular/material/menu';
import { EditContractDetailsComponents } from '../flight-services-manage/edit-contract/edit-contract-details';
import { API } from 'src/app/core/services/api.service';
import { FlightContractSearhObj } from 'src/app/core/models/flight-service/flight-service-search/flight-service-search.model';
import { FormBuilder, FormGroup } from '@angular/forms';
import * as moment from 'moment';
import { MessageService } from 'primeng/api';
import { Router } from '@angular/router';
@Component({
  selector: 'app-flight-services-search',
  templateUrl: './flight-services-search.component.html',
})
export class FlightServicesSearchComponent implements OnInit {
  @ViewChild('menuTrigger') menuTrigger: MatMenuTrigger;
  lovKeyDataObj = {
    AirCabinClass: [],
    AirPaxType: [],
    AirTripType: [],
    DaySelect: [],
    AirBaggageUnit: [],
    AirFareType: [],
  };
  Formdata: FormGroup;
  CurrencyList;
  AirlineList;
  AirportListFrom;
  AirportListTO;
  AtoZ = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
  FlightAllDetails;
  constructor(
    private productService: ProductService,
    public dialog: MatDialog,
    public ApiServ: API,
    public fb: FormBuilder,
    public MsgService: MessageService,
    public router: Router
  ) { }

  ngOnInit(): void {
    this.OnInitForm();
    this.GetLOVKeys('AirCabinClass,AirPaxType,AirTripType,DaySelect,AirBaggageUnit,AirFareType');
    this.GetCurrency();

  }

  OnInitForm() {
    this.Formdata = this.fb.group({
      contract_name: [''],
      supplier_name: [''],
      _trip_type: [''],
      airline_code: [''],
      flight_no: [''],
      from_airport: [''],
      to_airport: [''],
      is_multi_day: [false],
      pnr: [''],
      currency_code: [''],
      fare_type: [''],
      Cabin_Class: [],
      is_instant_confirmation: [''],
      rbd: [''],
      ret_days: [''],
      dep_days: [''],
      departure_date: [''],
      return_date: [''],
    });
  }



  GetFlightDetails() {
    let value = this.Formdata.getRawValue();
    let Postdata = new FlightContractSearhObj();
    Postdata.contract_name = value.contract_name;
    Postdata.supplier_name = value.supplier_name;
    Postdata._trip_type = value._trip_type.toString();
    Postdata.airline_code = value.airline_code;
    Postdata.flight_no = value.flight_no;
    Postdata.from_airport = value.from_airport;
    Postdata.to_airport = value.to_airport;
    Postdata.dep_from_date = value.departure_date[0] ? moment(value.departure_date[0]).format('YYYY-MM-DD') : '';
    Postdata.dep_to_date = value.departure_date[1] ? moment(value.departure_date[1]).format('YYYY-MM-DD') : '';
    Postdata.ret_from_date = value.return_date[0] ? moment(value.return_date[0]).format('YYYY-MM-DD') : '';
    Postdata.ret_to_date = value.return_date[1] ? moment(value.return_date[1]).format('YYYY-MM-DD') : '';
    Postdata.is_multi_day = value.is_multi_day;
    Postdata.pnr = value.pnr;
    Postdata.rbd = value.rbd;
    Postdata.ret_days = value.ret_days ? value.ret_days.join(',') : '';
    Postdata.dep_days = value.dep_days ? value.dep_days.join(',') : '';
    Postdata.currency_code = value.currency_code;
    Postdata.fare_type = value.fare_type ? value.fare_type : 0;
    Postdata.is_instant_confirmation = value.is_instant_confirmation == 'Instant' && value.is_instant_confirmation ? true : false;
    value.Cabin_Class == 1 ? Postdata.is_economy = true : Postdata.is_economy = false;
    value.Cabin_Class == 2 ? Postdata.is_premium_economy = true : Postdata.is_premium_economy = false;
    value.Cabin_Class == 3 ? Postdata.is_business = true : Postdata.is_business = false;
    value.Cabin_Class == 4 ? Postdata.is_first_class = true : Postdata.is_first_class = false;
    this.ApiServ.Post('/FlightContract/GetAllFlightContractView', Postdata).subscribe(obj => {
      if (obj) {
        this.FlightAllDetails = obj.responseObject;
      }
    });
  }

  GetLOVKeys(lov_key_names) {
    let lov_key_names_arr = lov_key_names.split(',');
    let lov_obj = {
      "lov_types": [],
      "lov_lang": "en"
    };
    lov_key_names_arr.forEach(key_name => {
      lov_obj.lov_types.push({ "lov_type": key_name });
    });
    this.ApiServ.Post('/LovMaster/GetLov', lov_obj).subscribe(lov_data => {
      if (lov_data && lov_data.status) {
        lov_key_names_arr.forEach(key_name => {
          let arr = lov_data.responseObject.filter(el => el.lov_type == key_name);
          arr.length > 0 ? this.lovKeyDataObj[key_name] = arr[0].keys : '';
        });
      }
    });
  };

  updateStatus(id, val) {
    let obj = {
      Id: id,
      Status: val ? false : true,
      UpdatedBy: ''
    }
    this.ApiServ.Post('/FlightContract/UpdateStatus', obj).subscribe(obj => {
      if (obj) {
        this.GetFlightDetails();
        this.MsgService.add({
          severity: obj["status"] ? "success" : "error",
          detail: obj["message"],
        });
      }
    });
  }
  GetAllAirline(val) {
    if (val.value) {
      this.ApiServ.Get('/MasterSearch/GetAllAirline/en/' + val.value).subscribe(obj => {
        if (obj) {
          this.AirlineList = obj;
        }
      });
    }
  }
  GetCurrency() {
    this.ApiServ.Get('/Currency/GetCurrency').subscribe(obj => {
      if (obj) {
        this.CurrencyList = obj;
      }
    })
  }
  // static dropdown

  Confirmation_Type = [
    { id: 0, name: 'Instant' },
    { id: 1, name: 'Manual' },
  ];

  ResetVal() {
    let val = this.Formdata.getRawValue()
    Object.keys(val).forEach(e => {
      if (e == 'is_multi_day') this.Formdata.get(e).setValue(false)
      else this.Formdata.get(e).setValue('');

    })
  }


  getAirportDetails(val, check) {
    if (val.value.length >= 3) {
      this.ApiServ.Get('/MasterSearch/GetAllMasterSearch/en/' + val.value).subscribe(obj => {
        if (obj) {
          if (check) this.AirportListFrom = obj
          if (!check) this.AirportListTO = obj
        }
      });
    }
  }

  editRateInventry(contract_id) {
    let obj = { id: contract_id };
    this.router.navigate(['/Services/FlightServices/Manage/EditRateAndInventory'], { queryParams: obj });
  };
  EditFlightDetails(contract_id) {
    let obj = { id: contract_id };
    this.router.navigate(['/Services/FlightServices/Manage/EditFlight'], { queryParams: obj });
  }






















  displayModal: boolean;
  showModalDialog() {
    this.displayModal = true;
  }
  openDialog(Id) {
    const dialogRef = this.dialog.open(EditContractDetailsComponents, {
      width: '35rem',
      restoreFocus: false,
      data: {
        contractId: Id,
      }
    });

    // Manually restore focus to the menu trigger since the element that
    // opens the dialog won't be in the DOM any more when the dialog closes.
    dialogRef.afterClosed().subscribe(() => this.menuTrigger.focus());
  }




























  cities = [
    { id: 1, name: 'Vilnius' },
    { id: 2, name: 'Kaunas' },
    { id: 3, name: 'Pavilnys', disabled: true },
    { id: 4, name: 'Pabradė' },
    { id: 5, name: 'Klaipėda' },
  ];
  selectedCity = this.cities[0].name;



  rangeDates: Date[];

  minDate: Date;

  maxDate: Date;

  es: any;

  invalidDates: Array<Date>;
  // table
  cols!: any[];

  productDialog!: boolean;

  products!: Product[];

  product!: Product;

  selectedProducts!: Product[];

  submitted!: boolean;

  openNew() {
    this.product = {};
    this.submitted = false;
    this.productDialog = true;
  }

  findIndexById(id: string): number {
    let index = -1;
    for (let i = 0; i < this.products.length; i++) {
      if (this.products[i].id === id) {
        index = i;
        break;
      }
    }
    return index;
  }
  createId(): string {
    let id = '';
    var chars =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (var i = 0; i < 5; i++) {
      id += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return id;
  }
  exportExcel() {
    import('xlsx').then((xlsx) => {
      console.log(xlsx);
      const worksheet = xlsx.utils.json_to_sheet(this.products);
      const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
      const excelBuffer: any = xlsx.write(workbook, {
        bookType: 'xlsx',
        type: 'array',
      });
      this.saveAsExcelFile(excelBuffer, 'products');
    });
  }

  saveAsExcelFile(buffer: any, fileName: string): void {
    import('file-saver').then((abc) => {
      let EXCEL_TYPE =
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
      let EXCEL_EXTENSION = '.xlsx';
      const data: Blob = new Blob([buffer], {
        type: EXCEL_TYPE,
      });
      console.log(FileSaver);
      FileSaver.saveAs(
        data,
        fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION
      );
    });
  }
}
