import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import * as moment from 'moment';
import { MessageService } from 'primeng/api';
import { StaticDataService } from 'src/app/core/common/static-data.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { FlightContractDTO, FlightDetailDto, FlightsRateDto } from 'src/app/core/models/flight-service/flight-contracts.model';
import { API } from 'src/app/core/services/api.service';

@Component({
  selector: 'app-flight-services-add',
  templateUrl: './flight-services-add.component.html',
})
export class FlightServicesAddComponent implements OnInit {


  constructor(public ApiServ: API, public Fb: FormBuilder,
    public validationService: ValidationService, public CommonVar: StaticDataService,
    public MsgService: MessageService, public router: Router) { }
  Formdata: FormGroup;
  CurrencyList;
  AirCabinClassList;
  AirPaxTypeList;
  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"]
  lovKeyDataObj = {
    AirCabinClass: [],
    AirPaxType: [],
    AirTripType: [],
    DaySelect: [],
    AirBaggageUnit: [],
    AirFareType: [],
  };
  AirportListFrom;
  AirportListTO;
  AirlineList;
  AllAircraftTypeList;


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

  ToasterMsg(msg) {
    this.MsgService.add({
      severity: "error",
      detail: msg,
    });
  }



  OnInitForm() {
    this.Formdata = this.Fb.group({
      contract_name: this.validationService.required,
      contract_description: [''],
      _trip_type: [1, Validators.required],
      from_airport: this.validationService.required,
      to_airport: this.validationService.required,
      pnr: this.validationService.required,
      currency_code: this.validationService.required,
      is_instant_confirmation: ['Instant', Validators.required],
      contracted_cabin: this.validationService.required,
      contracted_pax_types: this.validationService.required,
      validating_airline: this.validationService.required,
      is_multi_day: [false],
      outbound_date: this.validationService.required,
      return_date: [''],
      is_multi_day_range: [''],
      operation_from: [''],
      operation_to: [''],
      outbound_days: [''],
      outbound_dates: [''],

      FlightDetail: this.Fb.array([
        this.Fb.group({
          airline_code: this.validationService.required,
          flight_no: this.validationService.required,
          _aircraft_type: this.validationService.required,
          from_airport: this.validationService.required,
          to_airport: this.validationService.required,
          departure_Hour: this.validationService.required,
          departure_minutes: this.validationService.required,
          departure_terminal: this.validationService.required,
          is_next_day_arrival: [false],
          arrival_hour: [''],
          arrival_minutes: [''],
          arrival_terminal: [''],
          flying_duration_hour: [''],
          flying_duration_minutes: [''],
          is_next_day_departure: [false],
        })
      ]),

      FlightsRate: this.Fb.array([
        this.Fb.group({
          rbd: this.validationService.required,
          cabin_class: this.validationService.required,
          adt_base_fare: this.validationService.decimal,
          adt_tax: this.validationService.decimal,
          chd_base_fare: this.validationService.decimal,
          chd_tax: this.validationService.decimal,
          inf_base_fare: this.validationService.decimal,
          inf_tax: this.validationService.decimal,
          seat_allocation: this.validationService.number,
          seat_booked: [''], //
          seat_remaining: [''], //
          adt_check_bag: this.validationService.number,
          chd_check_bag: this.validationService.number,
          inf_check_bag: this.validationService.number,
          _check_bag_unit: this.validationService.required,
          adt_cabin_bag: this.validationService.number,
          chd_cabin_bag: this.validationService.number,
          inf_cabin_bag: this.validationService.number,
          _cabin_bag_unit: this.validationService.required,
          _fare_type: this.validationService.required,
          adt_fare_rule: this.validationService.required,
          chd_fare_rule: this.validationService.required,
          inf_fare_rule: this.validationService.required,
          is_meal_included: [''],
          meal_details: [''],
          inclusions: [''],
          is_instant_confirmation: [''],
          is_stop_sale: [''],
        })
      ]),
      is_active: [false]
    });
  };

  get FlightDetail() {
    return this.Formdata.get('FlightDetail') as FormArray;
  }
  get FlightsRate() {
    return this.Formdata.get('FlightsRate') as FormArray;
  }
  get FlightRateDetail() {
    return this.Formdata.get('FlightRateDetail') as FormArray;
  }

  addFlightGroupBtn(FormName) {
    let formgroup;
    FormName == 'FlightDetail' ? formgroup = this.FlightDetail : formgroup = this.FlightRateDetail;

    formgroup.push(
      this.Fb.group({
        airline_code: this.validationService.required,
        flight_no: this.validationService.required,
        _aircraft_type: this.validationService.required,
        from_airport: this.validationService.required,
        to_airport: this.validationService.required,
        departure_Hour: this.validationService.required,
        departure_minutes: this.validationService.required,
        departure_terminal: this.validationService.required,
        is_next_day_arrival: [false],
        arrival_hour: [''],
        arrival_minutes: [''],
        arrival_terminal: [''],
        flying_duration_hour: [''],
        flying_duration_minutes: [''],
        is_next_day_departure: [false],
      })
    );
  };
  addFlightsRateGroupBtn() {
    this.FlightsRate.push(this.Fb.group({
      rbd: this.validationService.required,
      cabin_class: this.validationService.required,
      adt_base_fare: this.validationService.decimal,
      adt_tax: this.validationService.decimal,
      chd_base_fare: this.validationService.decimal,
      chd_tax: this.validationService.decimal,
      inf_base_fare: this.validationService.decimal,
      inf_tax: this.validationService.decimal,
      seat_allocation: this.validationService.number,
      seat_booked: [''], //
      seat_remaining: [''], //
      adt_check_bag: this.validationService.number,
      chd_check_bag: this.validationService.number,
      inf_check_bag: this.validationService.number,
      _check_bag_unit: this.validationService.required,
      adt_cabin_bag: this.validationService.number,
      chd_cabin_bag: this.validationService.number,
      inf_cabin_bag: this.validationService.number,
      _cabin_bag_unit: this.validationService.required,
      _fare_type: this.validationService.required,
      adt_fare_rule: this.validationService.required,
      chd_fare_rule: this.validationService.required,
      inf_fare_rule: this.validationService.required,
      is_meal_included: [''],
      meal_details: [''],
      inclusions: [''],
      is_instant_confirmation: [''],
      is_stop_sale: [''],
    }))
  }
  removeFlightGroupBtn(ind, formname) {
    let formgroup;
    formname == 'FlightDetail' ? formgroup = this.FlightDetail : formgroup = this.FlightRateDetail;
    formgroup.removeAt(ind);
  };

  removeFlightsRateGroupBtn(ind) {
    this.FlightsRate.removeAt(ind);
  };
  RemoveFlightrRoundArr() {
    this.Formdata.removeControl('FlightRateDetail');
  };

  AddFLightRoundArr() {
    this.Formdata.addControl(
      'FlightRateDetail', this.Fb.array([
        this.Fb.group({
          airline_code: this.validationService.required,
          flight_no: this.validationService.required,
          _aircraft_type: this.validationService.required,
          from_airport: this.validationService.required,
          to_airport: this.validationService.required,
          departure_Hour: this.validationService.required,
          departure_minutes: this.validationService.required,
          departure_terminal: this.validationService.required,
          is_next_day_arrival: [false],
          arrival_hour: [''],
          arrival_minutes: [''],
          arrival_terminal: [''],
          flying_duration_hour: [''],
          flying_duration_minutes: [''],
          is_next_day_departure: [false],
        })
      ])
    );
  };

  trip_type(val) {
    console.log(val)
    if (val == 2) {
      this.Formdata.get('is_multi_day').setValue(false)
      this.AddFLightRoundArr()
    } else this.RemoveFlightrRoundArr()

  }

  GetCurrency() {
    this.ApiServ.Get('/Currency/GetCurrency').subscribe(obj => {
      if (obj) {
        this.CurrencyList = obj;
      }
    })
  }

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

  GetAllAircraftType() {
    this.ApiServ.Get('/MasterSearch/GetAllAircraftType').subscribe(obj => {
      if (obj) {
        this.AllAircraftTypeList = obj;
      }
    });
  }





  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 : '';
        });
      }
    });
  };



  //  validation

  nextdayarrivelcheck(check, ind, formname) {
    if (check) {
      this.AddOutboundtvalid(ind, 'arrival_hour', 'add', formname);
      this.AddOutboundtvalid(ind, 'arrival_minutes', 'add', formname);
      this.AddOutboundtvalid(ind, 'arrival_terminal', 'add', formname);
      this.AddOutboundtvalid(ind, 'flying_duration_hour', 'add', formname);
      this.AddOutboundtvalid(ind, 'flying_duration_minutes', 'add', formname);
    } else {
      this.AddOutboundtvalid(ind, 'arrival_hour', 'remove', formname);
      this.AddOutboundtvalid(ind, 'arrival_minutes', 'remove', formname);
      this.AddOutboundtvalid(ind, 'arrival_terminal', 'remove', formname);
      this.AddOutboundtvalid(ind, 'flying_duration_hour', 'remove', formname);
      this.AddOutboundtvalid(ind, 'flying_duration_minutes', 'remove', formname);
    }

  }


  MealTypeIncludedcheck(val, ind) {
    console.log(val)
    if (val == 'Yes') this.addvalidMealTypeIncluded(ind, 'meal_details', 'add')
    else this.addvalidMealTypeIncluded(ind, 'meal_details', 'remove')

  }

  AddOutboundtvalid(index, name, type, formname) {
    let formgroup;
    formname == 'FlightDetail' ? formgroup = this.FlightDetail : formgroup = this.FlightRateDetail
    if (type == 'add') {
      formgroup.controls[index].get(name).addValidators([Validators.required]);
      formgroup.controls[index].get(name).updateValueAndValidity();
    } else {
      formgroup.controls[index].get(name).clearValidators();
      formgroup.controls[index].get(name).updateValueAndValidity();
      formgroup.controls[index].get(name).markAsUntouched();
    }
  };
  addvalidMealTypeIncluded(index, name, type) {
    if (type == 'add') {
      this.FlightsRate.controls[index].get(name).addValidators([Validators.required]);
      this.FlightsRate.controls[index].get(name).updateValueAndValidity();
    } else {
      this.FlightsRate.controls[index].get(name).clearValidators();
      this.FlightsRate.controls[index].get(name).updateValueAndValidity();
      this.FlightsRate.controls[index].get(name).markAsUntouched();
    }
  };
  addvalid(name, type) {
    if (type == 'add') {
      this.Formdata.controls[name].addValidators([Validators.required]);
      this.Formdata.controls[name].updateValueAndValidity();
    } else {
      this.Formdata.controls[name].clearValidators();
      this.Formdata.controls[name].updateValueAndValidity();
      this.Formdata.controls[name].markAsUntouched();
    }
  };
  //
  multi_day_check(val) {
    console.log(val)
    if (val) {
      this.addvalid('is_multi_day_range', 'add');
      this.addvalid('operation_from', 'add');
      this.addvalid('operation_to', 'add');
    } else {
      this.addvalid('is_multi_day_range', 'remove');
      this.addvalid('operation_from', 'remove');
      this.addvalid('operation_to', 'remove');
      this.Formdata.get('is_multi_day_range').setValue('')
    }
  }
  multi_day_range(val) {
    if (val == 'Range') {
      this.addvalid('outbound_dates', 'remove');
      this.addvalid('outbound_days', 'add');
    } else {
      this.addvalid('outbound_days', 'remove');
      this.addvalid('outbound_dates', 'add');
    }
  }

  //  save 
  saveData() {
    let value = this.Formdata.getRawValue();
    let OutbondList = this.FlightDetail.getRawValue();
    let lastNumber = OutbondList.length - 1;

    console.log(value)
    if (this.Formdata.status == "INVALID") {
      this.validationService.showValidationsMsg(this.Formdata);
      return;
    }
    if (!OutbondList[lastNumber].to_airport && !value.to_airport && !value.from_airport && !OutbondList[0].from_airport) {
      this.ToasterMsg("Please enter departure and arrival city or airport")
      return;
    }
    if (OutbondList[lastNumber].to_airport != value.to_airport || OutbondList[0].from_airport != value.from_airport) {
      this.ToasterMsg("Departure must be different from arrival")
      return;
    };

    let FlightRateVal = this.FlightsRate.getRawValue();
    let date = moment(new Date).format('YYYY-MM-DD');
    let AllFlightDetailslist = [];


    /// flight details

    OutbondList.map((e, i) => {
      let fligtDetlPostData = new FlightDetailDto();
      fligtDetlPostData.airline_code = e.airline_code
      fligtDetlPostData.flight_no = e.flight_no;
      // fligtDetlPostData._aircraft_type = e._aircraft_type;
      fligtDetlPostData.from_airport = e.from_airport;
      fligtDetlPostData.to_airport = e.to_airport;
      fligtDetlPostData.departure_time = date + 'T' + e.departure_Hour + ':' + e.departure_minutes + ':00';
      fligtDetlPostData.is_next_day_departure = e.is_next_day_departure;
      fligtDetlPostData.departure_terminal = e.departure_terminal;
      fligtDetlPostData.is_next_day_arrival = e.is_next_day_arrival;
      fligtDetlPostData.arrival_time = date + 'T' + e.arrival_hour + ':' + e.arrival_minutes + ':00';
      fligtDetlPostData.arrival_terminal = e.arrival_terminal;
      fligtDetlPostData.flying_duration = date + 'T' + e.flying_duration_hour + ':' + e.flying_duration_minutes + ':00';
      fligtDetlPostData._sector_type = '1';
      fligtDetlPostData.leg_nbr = i + 1;
      console.log(fligtDetlPostData);
      AllFlightDetailslist.push(fligtDetlPostData);
    });

    if (value._trip_type == 2) {
      let returnList = this.FlightRateDetail.getRawValue();
      let last = returnList.length - 1;
      if (!returnList[last].to_airport && !value.to_airport && !value.from_airport && !returnList[0].from_airport) {
        this.ToasterMsg("Please enter departure and arrival city or airport")
        return;
      }
      if (returnList[last].to_airport != value.from_airport || returnList[0].from_airport != value.to_airport) {
        this.ToasterMsg("Departure must be different from arrival")
        return;
      };
      returnList.map((e, i) => {
        let fligtDetlPostData = new FlightDetailDto();
        fligtDetlPostData.airline_code = e.airline_code
        fligtDetlPostData.flight_no = e.flight_no;
        // fligtDetlPostData._aircraft_type = e._aircraft_type;
        fligtDetlPostData.from_airport = e.from_airport;
        fligtDetlPostData.to_airport = e.to_airport;
        fligtDetlPostData.departure_time = date + 'T' + e.departure_Hour + ':' + e.departure_minutes + ':00';
        fligtDetlPostData.is_next_day_departure = e.is_next_day_departure;
        fligtDetlPostData.departure_terminal = e.departure_terminal;
        fligtDetlPostData.is_next_day_arrival = e.is_next_day_arrival;
        fligtDetlPostData.arrival_time = date + 'T' + e.arrival_hour + ':' + e.arrival_minutes + ':00';
        fligtDetlPostData.arrival_terminal = e.arrival_terminal;
        fligtDetlPostData.flying_duration = date + 'T' + e.flying_duration_hour + ':' + e.flying_duration_minutes + ':00';
        fligtDetlPostData._sector_type = '2';
        fligtDetlPostData.leg_nbr = i + 1;
        console.log(fligtDetlPostData);
        AllFlightDetailslist.push(fligtDetlPostData);
      });
    };


    // flight Rate 
    let FlightRate = []
    FlightRateVal.map(e => {
      let Ratepostdata = new FlightsRateDto();
      Ratepostdata.rbd = e.rbd;
      Ratepostdata.cabin_class = this.checkClassType(e.cabin_class);
      Ratepostdata.adt_base_fare = e.adt_base_fare;
      Ratepostdata.adt_tax = e.adt_tax;
      Ratepostdata.chd_base_fare = e.chd_base_fare;
      Ratepostdata.chd_tax = e.chd_tax;
      Ratepostdata.inf_base_fare = e.inf_base_fare;
      Ratepostdata.inf_tax = e.inf_tax;
      Ratepostdata.seat_allocation = e.seat_allocation;
      Ratepostdata.seat_booked = 0;  // 
      Ratepostdata.seat_remaining = 0; //
      Ratepostdata.adt_check_bag = e.adt_check_bag;
      Ratepostdata.chd_check_bag = e.chd_check_bag;
      Ratepostdata.inf_check_bag = e.inf_check_bag;
      Ratepostdata._check_bag_unit = e._check_bag_unit;
      Ratepostdata.adt_cabin_bag = e.adt_cabin_bag;
      Ratepostdata.adt_fare_rule = e.adt_fare_rule;
      Ratepostdata.chd_cabin_bag = e.chd_cabin_bag;
      Ratepostdata.inf_cabin_bag = e.inf_cabin_bag;
      Ratepostdata._cabin_bag_unit = e._cabin_bag_unit;
      Ratepostdata._fare_type = e._fare_type;
      Ratepostdata.adt_fare_rule = e.adt_fare_rule;
      Ratepostdata.chd_fare_rule = e.chd_fare_rule;
      Ratepostdata.is_meal_included = e.is_meal_included == 'Yes' ? true : false;
      Ratepostdata.meal_details = e.is_meal_included == 'Yes' ? e.meal_details : '';
      Ratepostdata.inclusions = e.inclusions;
      Ratepostdata.inf_fare_rule = e.inf_fare_rule;
      Ratepostdata.pnr = value.pnr;
      FlightRate.push(Ratepostdata)

    })

    //  Post data 

    let PostData = new FlightContractDTO();
    PostData.contract_name = value.contract_name;
    PostData.contract_description = value.contract_description;
    PostData._trip_type = value._trip_type.toString();
    PostData.from_airport = value.from_airport;
    PostData.to_airport = value.to_airport;
    PostData.pnr = value.pnr;
    PostData.is_instant_confirmation = value.is_instant_confirmation == 'Instant' ? true : false;
    PostData.is_economy = false;
    PostData.is_premium_economy = false;
    PostData.is_business = false;
    PostData.is_first_class = false;

    value.contracted_cabin ? value.contracted_cabin.map(e => {
      e == 1 ? PostData.is_economy = true : '';
      e == 2 ? PostData.is_premium_economy = true : '';
      e == 3 ? PostData.is_business = true : '';
      e == 4 ? PostData.is_first_class = true : '';
    }) : ''
    PostData.is_adult = false;
    PostData.is_child = false;
    PostData.is_infant = false;
    value.contracted_pax_types ? value.contracted_pax_types.map(e => {
      e == 1 ? PostData.is_adult = true : '';
      e == 2 ? PostData.is_child = true : '';
      e == 3 ? PostData.is_infant = true : '';
    }) : ''
    PostData.is_all_pax_type = PostData.is_adult && PostData.is_child && PostData.is_infant ? true : false;
    PostData.validating_airline = value.validating_airline;
    PostData.is_multi_day = value.is_multi_day;
    PostData.outbound_date = moment(value.outbound_date).format('YYYY-MM-DD');
    PostData.return_date = value._trip_type == 2 ? value.return_date ? moment(value.return_date).format('YYYY-MM-DD') : '' : date;
    PostData.is_multi_day_range = value.is_multi_day_range == 'Range' ? true : false;
    PostData.operation_from = value.is_multi_day ? value.operation_from ? moment(value.operation_from).format('YYYY-MM-DD') : '' : date;
    PostData.operation_to = value.is_multi_day ? value.operation_to ? moment(value.operation_to).format('YYYY-MM-DD') : '' : date;
    PostData.outbound_days = value.is_multi_day && value.is_multi_day_range == 'Range' ? value.outbound_days.join(',') : '';
    let outbond_dates = []
    value.outbound_dates ? value.outbound_dates.map(e => outbond_dates.push(moment(e).format('YYYY-MM-DD'))) : ''
    PostData.outbound_dates = value.is_multi_day && value.is_multi_day_range != 'Range' ? outbond_dates ? outbond_dates.join(',') : '' : '';
    PostData.supplier_id = '';
    PostData.is_active = value.is_active;
    PostData.currency_code = value.currency_code;
    PostData.flightDetail = AllFlightDetailslist;
    PostData.flightRate = FlightRate;
    PostData.org_id = '2105311837100000021';

    console.log(PostData)
    this.ApiServ.Post('/FlightContract/SaveFlightContracts', PostData).subscribe(obj => {
      if (obj) {
        this.MsgService.add({
          severity: obj["status"] ? "success" : "error",
          detail: obj["message"],
        });
        obj["status"] ? setTimeout(() => {
          this.router.navigate(['/Services/FlightServices/Search'])
        }, 500) : '';
      }
    });

  };

  // 

  checkClassType(classType) {
    let value = ''
    if (classType == 4) {
      value = 'F'
    } else if (classType == 3) {
      value = 'J'
    } else if (classType == 2) {
      value = 'W'
    } else if (classType == 1) {
      value = 'Y'
    }
    return value
  }


  //  static dropdown


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

  ];

  Option = [
    { id: 2, name: 'Yes' },
    { id: 3, name: 'No' },
  ];


}
