import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { MessageService } from 'primeng/api';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { StaticDataService } from 'src/app/core/common/static-data.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { FlightContractReq, FlightContracts, FlightRateArray } from 'src/app/core/models/flight-service/flight-contracts.model';
import { API } from 'src/app/core/services/api.service';
import { FlightContractService } from 'src/app/core/services/flight-contract.service.ts/flight-contract.service';
import { BreakpointsService } from 'src/app/core/services/breakpoints.services';

@Component({
  selector: 'app-flight-inventory-add',
  templateUrl: './flight-inventory-add.component.html',
})
export class FlightInventoryAddComponent implements OnInit {
  allAirpotList = {
    fromAirList: [],
    toAirList: [],
    origin1AirList: [],
    origin2AirList: [],
    destination1AirList: [],
    destination2AirList: [],
  };
  allAirCraftList: any;
  allAirLineList: any;
  IsMobile;
  ReturnDateMinDate = new Date();
  allDaysSelected: boolean;

  constructor(
    public ApiServ: API,
    public Fb: FormBuilder,
    private activateRoute: ActivatedRoute,
    public validationService: ValidationService,
    public _staticService: StaticDataService,
    public MsgService: MessageService,
    public router: Router,
    public _flightContractService: FlightContractService,
    public _commonService: CommonFunctionService,
    public brkpointsrv: BreakpointsService
  ) {
    // console.log(brkpointsrv.IsMobile.getValue())
  }
  Formdata: FormGroup;
  CurrencyList;
  AirCabinClassList;
  AirPaxTypeList;
  lovKeyDataObj = {
    AirCabinClass: [],
    AirPaxType: [],
    AirTripType: [],
    DaySelect: [],
    AirBaggageUnit: [],
    AirFareType: [],
  };
  AirportListFrom;
  AirportListTO;
  AirlineList;
  AllAircraftTypeList;
  minDate;
  // static dropdown value

  MultiDayType = [
    { value: 'RANGE', displayName: 'Range' },
    { value: 'SPECIFICDATES', displayName: 'Specific Dates' },
  ];
  
  RefundType = [
    { value: 'Refundale', displayName: 'Refundale' },
    { value: 'Non-Refundale', displayName: 'Non-Refundale' },
  ];

  staticCurrency = [
    { value: 'INR', displayName: 'Indian Rupees' },
    { value: 'USD', displayName: 'US Dollar' },
  ];
  tripType = [
    { value: 'ONEWAY', displayName: 'One Way' },
    { value: 'ROUNDTRIP', displayName: 'Round Trip' },
  ];

  FareFamilyList = [];
  ngOnInit(): void {
    this.OnInitForm();
    this._commonService.GetCurrencyList('ALL');
    this.GetFlightContract()
    for (let index = 1; index <= 3; index++) {
      this.FareFamilyList.push(index)
    };
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth();
    const day = date.getDate();
    this.minDate = new Date(year, month, day);
    this.IsMobile = this.brkpointsrv.IsMobile.getValue();
  }

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

  OnInitForm() {
    this.Formdata = this.Fb.group({
      contract_name: this.validationService.required,
      contract_description: [''],
      trip_type: this.validationService.required,
      origin: this.validationService.required,
      destination: this.validationService.required,
      pnr: [''],// pass value on flight rate 
      currency_code: this.validationService.required,
      is_instant_confirmation: ['INSTANT', Validators.required],// pass value on flight rate 
      contracted_cabin_class: this.validationService.required,
      contracted_pax_type: this.validationService.required,
      validating_airline: this.validationService.required,
      // is_multi_day: [false],
      is_nearby_airports: [false],
      outbound: 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: [''],
          is_next_day_arrival: [false],
          arrival_hour: this.validationService.required,
          arrival_minutes: this.validationService.required,
          arrival_terminal: [''],
          flying_duration_hour: this.validationService.required,
          flying_duration_minutes: this.validationService.required,
          is_next_day_departure: [false],
        })
      ]),
      inbound: this.Fb.array([]),
      FlightsRate: this.Fb.array([
        this.Fb.group({
          rbd: this.validationService.required,
          fare_family_group_id: this.validationService.required,
          fare_family_name: this.validationService.required,
          cabin_class: this.validationService.required,
          adt_base_fare: this.validationService.decimal,
          adt_tax: this.validationService.decimal,
          // chd_base_fare: [],
          // chd_tax: [],
          // inf_base_fare: [],
          // inf_tax: [],

          // fare_type_applicability: ['BOTH', Validators.required],
          // round_trip_discount_type: [''],
          // adult_round_trip_discount: [null],

          seat_allocation: this.validationService.number,
          // is_allocation_update_due_cancel: this.validationService.required,
          // seat_booked: [],
          // seat_remaining: [],
          is_checked_bag_included: [false],
          is_apply_discount_with_same_vc_only: [false],
          adt_check_bag: [{ value: '', disabled: true }],
          // chd_check_bag: [],
          // inf_check_bag: [],
          _check_bag_unit: [{ value: '', disabled: true }],
          adt_cabin_bag: this.validationService.required,
          _cabin_bag_unit: this.validationService.required,
          refund_type: this.validationService.required,
          adt_fare_rule: this.validationService.required,
          // chd_fare_rule: [],
          // inf_fare_rule: [],
          is_meal_included: this.validationService.required,
          meal_details: [{ value: '', disabled: true }],
          inclusions: [],
        })
      ]),
      is_active: [false]
    });
    if(this._commonService.clientId == '2109111018200000021') {
      this.Formdata.get('trip_type').setValue('ONEWAY');
      this.UpdateTripType();
    }
    this.Formdata.get('contracted_pax_type').setValue(['A']);
    this.UpdateMultiDayOperation();
  };

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

  addFlightGroupBtn(check) {
    let formgroup = check ? this.inbound : this.outbound
    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: [''],
        is_next_day_arrival: [false],
        arrival_hour: this.validationService.required,
        arrival_minutes: this.validationService.required,
        arrival_terminal: [''],
        flying_duration_hour: this.validationService.required,
        flying_duration_minutes: this.validationService.required,
        is_next_day_departure: [false],
      })
    );
  };
  addFlightsRateGroupBtn() {
    this.FlightsRate.push(
      this.Fb.group({
        rbd: this.validationService.required,
        fare_family_group_id: this.validationService.required,
        fare_family_name: this.validationService.required,
        cabin_class: this.validationService.required,
        adt_base_fare: this.validationService.decimal,
        adt_tax: this.validationService.decimal,
        seat_allocation: this.validationService.number,
        is_checked_bag_included: [false],
        is_apply_discount_with_same_vc_only: [false],
        adt_check_bag: [{ value: '', disabled: true }],
        _check_bag_unit: [{ value: '', disabled: true }],
        adt_cabin_bag: this.validationService.required,
        _cabin_bag_unit: this.validationService.required,
        refund_type: this.validationService.required,
        adt_fare_rule: this.validationService.required,
        is_meal_included: this.validationService.required,
        meal_details: [],
        inclusions: [],
      })
    );
    this.AddUpdatePaxWiseControls();
    this.UpdateFlightsRateFormGroup();
  };
  AddUpdatePaxWiseControls() {
    let val = this.Formdata.get('contracted_pax_type').value;
    let grp = this.FlightsRate.controls[this.FlightsRate.controls.length - 1];
    if (val?.includes('C')) this.UpdatePaxWiseControls(grp, 'chd', true);
    if (val?.includes('I')) this.UpdatePaxWiseControls(grp, 'inf', true);
  };

  UpdateAllPaxWiseControls() {
    let val = this.Formdata.get('contracted_pax_type').value;
    this.FlightsRate.controls.forEach(e => {
      val.includes('C') ? this.UpdatePaxWiseControls(e, 'chd', true) : this.UpdatePaxWiseControls(e, 'chd', false);
      val.includes('I') ? this.UpdatePaxWiseControls(e, 'inf', true) : this.UpdatePaxWiseControls(e, 'inf', false);
    });
  };
  UpdatePaxWiseControls(group, name, check) {
    let grp = group as FormGroup;
    let discountName = name == 'chd' ? 'child' : 'infant';
    let trip_type = this.Formdata.controls['trip_type'].value;
    if (check) {
      grp.addControl(name + '_base_fare', this.validationService.decimal);
      grp.addControl(name + '_tax', this.validationService.decimal);
      grp.addControl(name + '_check_bag', this.Fb.control({ value: null, disabled: true }));
      grp.addControl(name + '_cabin_bag', this.validationService.required);
      grp.addControl(name + '_fare_rule', this.validationService.required);
      trip_type == 'ONEWAY' ? grp.addControl(discountName + '_round_trip_discount', this.Fb.control(null)) : '';
    } else {
      grp.removeControl(name + '_base_fare');
      grp.removeControl(name + '_tax');
      grp.removeControl(name + '_check_bag');
      grp.removeControl(name + '_cabin_bag');
      grp.removeControl(name + '_fare_rule');
      grp.removeControl(discountName + '_round_trip_discount');
    }
    this.UpdateBag(grp)
  };

  removeFlightGroupBtn(ind, check) {
    let formgroup = check ? this.inbound : this.outbound
    formgroup.removeAt(ind);
  };

  removeFlightsRateGroupBtn(ind) {
    this.FlightsRate.removeAt(ind);
  };
  RemoveFlightrRoundArr() {
    this.Formdata.removeControl('FlightRateDetail');
  };
  plusDate = new Date()
  changeFormDate() {
    let max = new Date(this.Formdata.get('operation_to').value);
    this.plusDate = new Date(this.Formdata.get('operation_from').value);
    if (this.plusDate > max) {
      this.Formdata.get('operation_to').setValue(null);
    }
  };
  UpdateBag(grp) {
    let group = grp as FormGroup;
    let controls = [
      'adt_check_bag',
      'chd_check_bag',
      'inf_check_bag',
      '_check_bag_unit',
      // 'adt_cabin_bag',
      // 'chd_cabin_bag',
      // 'inf_cabin_bag',
      // '_cabin_bag_unit',
    ];
    if (group.get('is_checked_bag_included').value) controls.forEach(e => this.UpdateControlsValidation(group, e, 'add'));
    else controls.forEach(e => this.UpdateControlsValidation(group, e, 'remove'));
    if (group.get('is_checked_bag_included').value) controls.forEach(e => group.get(e)?.enable());
    else {
      controls.forEach(e => {
        group.get(e)?.disable();
        group.get(e)?.setValue('');
      });
    }
  };
  UpdateMealTypeIncluded(grp) {
    let group = grp as FormGroup;
    if (group.get('is_meal_included').value == 'Yes') {
      this.UpdateControlsValidation(group, 'meal_details', 'add');
      group.get('meal_details').enable()
    }
    else {
      group.get('meal_details').disable();
      group.get('meal_details').setValue('');
      this.UpdateControlsValidation(group, 'meal_details', 'remove');
    }
  };

  UpdateControlsValidation(group, name, type) {
    if (type == 'add') {
      group.get(name)?.addValidators([Validators.required]);
      group.get(name)?.updateValueAndValidity();
    } else {
      group.get(name)?.clearValidators();
      group.get(name)?.updateValueAndValidity();
      group.get(name)?.markAsUntouched();
    };
  };

  UpdateNearByAirport() {
    let val = this.Formdata.get('is_nearby_airports').value;
    if (val) {
      this.Formdata.addControl('nearby_from_airports', this.Fb.control([]));
      this.Formdata.addControl('nearby_to_airports', this.Fb.control([]));
    } else {
      this.Formdata.removeControl('nearby_from_airports');
      this.Formdata.removeControl('nearby_to_airports');
    }
  };
  // UpdateNextDayArrivelcheck(grp) {
  // let group = grp as FormGroup;
  // let controls = [
  //   'arrival_hour',
  //   'arrival_minutes',
  //   'arrival_terminal',
  //   'flying_duration_hour',
  //   'flying_duration_minutes',
  // ];
  // if (group.get('is_next_day_arrival').value) controls.forEach(e => this.UpdateControlsValidation(group, e, 'add'));
  // else controls.forEach(e => this.UpdateControlsValidation(group, e, 'remove'));
  // };

  //  Save 
  saveData() {
    let value = this.Formdata.getRawValue();
    if (this.Formdata.status == "INVALID") {
      this.validationService.showValidationsMsg(this.Formdata);
      setTimeout(() => {
        this.validationService.scrollToError();
      }, 50);
      return;
    }
    if (value?.trip_type == 'ONEWAY' && value?.origin == value?.destination) {
      this.ToasterMsg('origin airports and destination airports cannot be same in one way');
      return
    }
    // Out Bond
    let FlightoutboundList = this.outbound.getRawValue();
    let outboundlastNumber = FlightoutboundList.length - 1;
    if (!FlightoutboundList[outboundlastNumber].to_airport && !value.origin && !value.destination && !FlightoutboundList[0].from_airport) {
      this.ToasterMsg("(Outbound) Please enter departure and arrival city or airport")
      return;
    }
    if (JSON.stringify(FlightoutboundList[outboundlastNumber].to_airport) != JSON.stringify(value.destination) || JSON.stringify(FlightoutboundList[0].from_airport) != JSON.stringify(value.origin)) {
      this.ToasterMsg("(Outbound) Departure must be different from arrival")
      return;
    };
    let Duplicate = false;
    FlightoutboundList.forEach((e, index) => {
      const duplicateIndex = FlightoutboundList.findIndex((item, i) => {
        return i !== index && item.from_airport === e.from_airport && item.to_airport === e.to_airport;
      });
      if (duplicateIndex !== -1) {
        Duplicate = true;
      }
    });
    if (Duplicate) {
      this.ToasterMsg('(Outbound) Duplicate flight details found for the same origin and destination airports.');
      return
    }
    // 

    // In bound
    let FlightinboundList = this.inbound.getRawValue();
    if (value?.trip_type == 'ROUNDTRIP') {
      let inboundlastNumber = FlightinboundList.length - 1;
      if (!FlightinboundList[inboundlastNumber].to_airport && !value.origin && !value.destination && !FlightinboundList[0].from_airport) {
        this.ToasterMsg("(Inbound) Please enter departure and arrival city or airport")
        return;
      }
      if (JSON.stringify(FlightinboundList[inboundlastNumber].to_airport) != JSON.stringify(value.origin) || JSON.stringify(FlightinboundList[0].from_airport) != JSON.stringify(value.destination)) {
        this.ToasterMsg("(Inbound) Departure must be different from arrival")
        return;
      };
      Duplicate = false;
      FlightinboundList.forEach((e, index) => {
        const duplicateIndex = FlightinboundList.findIndex((item, i) => {
          return i !== index && item.from_airport === e.from_airport && item.to_airport === e.to_airport;
        });
        if (duplicateIndex !== -1) {
          Duplicate = true;
        }
      });
      if (Duplicate) {
        this.ToasterMsg('(Inbound) Duplicate flight details found for the same origin and destination airports.');
        return
      }
    }
    let FlightRateVal = this.FlightsRate.getRawValue();
    let AllFlightDetailslist = [];
    /// flight details
    FlightoutboundList.forEach((e, i) => {
      let obj = {
        airline_code: e.airline_code,
        flight_no: e.flight_no,
        aircraft_type_id: e._aircraft_type,
        from_airport: e.from_airport ? e.from_airport : "",
        to_airport: e.to_airport ? e.to_airport : "",
        departure_time: e.departure_Hour + ':' + e.departure_minutes + ':00',
        is_next_day_departure: e.is_next_day_departure,
        departure_terminal: e.departure_terminal,
        is_next_day_arrival: e.is_next_day_arrival,
        arrival_time: e.arrival_hour + ':' + e.arrival_minutes + ':00',
        arrival_terminal: e.arrival_terminal,
        flying_duration: e.flying_duration_hour + ':' + e.flying_duration_minutes + ':00',
        leg_nbr: i + 1,
        seg_nbr: 1,
      }
      AllFlightDetailslist.push(obj);
    });

    FlightinboundList.forEach((e, i) => {
      let obj = {
        airline_code: e.airline_code,
        flight_no: e.flight_no,
        aircraft_type_id: e._aircraft_type,
        from_airport: e.from_airport ? e.from_airport : "",
        to_airport: e.to_airport ? e.to_airport : "",
        departure_time: e.departure_Hour + ':' + e.departure_minutes + ':00',
        is_next_day_departure: e.is_next_day_departure,
        departure_terminal: e.departure_terminal,
        is_next_day_arrival: e.is_next_day_arrival,
        arrival_time: e.arrival_hour + ':' + e.arrival_minutes + ':00',
        arrival_terminal: e.arrival_terminal,
        flying_duration: e.flying_duration_hour + ':' + e.flying_duration_minutes + ':00',
        leg_nbr: i + 1,
        seg_nbr: 2,
      }
      AllFlightDetailslist.push(obj);
    });

    // flight Rate 
    let FlightRate = []
    FlightRateVal.forEach(e => {
      let Ratepostdata = new FlightRateArray();
      Ratepostdata.contract_id = e?.contract_id;
      Ratepostdata.rbd = e?.rbd;
      Ratepostdata.fare_family_group_id = e?.fare_family_group_id.toString();
      Ratepostdata.fare_family_name = e?.fare_family_name;
      Ratepostdata.cabin_class = e?.cabin_class;
      Ratepostdata.adt_base_fare = e?.adt_base_fare ? parseFloat(e?.adt_base_fare) : 0;
      Ratepostdata.adt_tax = e?.adt_tax ? parseFloat(e?.adt_tax) : 0;
      Ratepostdata.chd_base_fare = e?.chd_base_fare ? parseFloat(e?.chd_base_fare) : 0;
      Ratepostdata.chd_tax = e?.chd_tax ? parseFloat(e?.chd_tax) : 0;
      Ratepostdata.inf_base_fare = e?.inf_base_fare ? parseFloat(e?.inf_base_fare) : 0;
      Ratepostdata.inf_tax = e?.inf_tax ? parseFloat(e?.inf_tax) : 0;
      Ratepostdata.round_trip_discount_type = e?.round_trip_discount_type;
      Ratepostdata.is_apply_discount_with_same_vc_only = e?.is_apply_discount_with_same_vc_only;
      Ratepostdata.adult_round_trip_discount = e?.adult_round_trip_discount ? e?.adult_round_trip_discount : 0;
      Ratepostdata.child_round_trip_discount = e?.child_round_trip_discount ? e?.child_round_trip_discount : 0;
      Ratepostdata.infant_round_trip_discount = e?.infant_round_trip_discount ? e?.infant_round_trip_discount : 0;
      Ratepostdata.seat_allocation = e?.seat_allocation ? parseFloat(e?.seat_allocation) : 0;
      Ratepostdata.seat_booked = 0;
      Ratepostdata.seat_cancelled = 0;
      Ratepostdata.is_checked_bag_included = e?.is_checked_bag_included;
      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.chd_cabin_bag = e?.chd_cabin_bag;
      Ratepostdata.inf_cabin_bag = e?.inf_cabin_bag;
      Ratepostdata._cabin_bag_unit = e?._cabin_bag_unit;
      Ratepostdata.refund_type = e?.refund_type;
      Ratepostdata.adt_fare_rule = e?.adt_fare_rule;
      Ratepostdata.chd_fare_rule = e?.chd_fare_rule;
      Ratepostdata.inf_fare_rule = e?.inf_fare_rule;
      Ratepostdata.is_meal_included = e?.is_meal_included == 'Yes';
      Ratepostdata.meal_details = e?.meal_details;
      Ratepostdata.inclusions = e?.inclusions;
      Ratepostdata.pnr = value.pnr;
      FlightRate.push(Ratepostdata)
    })
    //  Flight Contracts
    let PostData = new FlightContracts();
    PostData.contract_name = value?.contract_name;
    PostData.is_active = value?.is_active;
    PostData.contract_description = value?.contract_description;
    PostData.trip_type = value?.trip_type;
    PostData.is_oneway_sale_allowed = value?.is_oneway_sale_allowed ? value?.is_oneway_sale_allowed : false;
    PostData.origin = value?.origin
    PostData.destination = value?.destination
    PostData.no_of_legs = AllFlightDetailslist.length;
    PostData.currency_code = value?.currency_code;
    PostData.is_instant_confirmation = value.is_instant_confirmation == 'INSTANT';
    PostData.contracted_cabin_class = value?.contracted_cabin_class ? value?.contracted_cabin_class.join(',') : '';
    PostData.contracted_pax_type = value?.contracted_pax_type ? value?.contracted_pax_type.join(',') : '';
    PostData.validating_airline = value?.validating_airline;
    PostData.is_multi_day = value?.is_multi_day ? value?.is_multi_day : false;
    PostData.multi_day_operation_type = value?.multi_day_operation_type ? value?.multi_day_operation_type : '';
    if (value?.operation_from) PostData.operation_from = value?.operation_from ? this._commonService.convertDateToSave(value?.operation_from) : '';
    if (value?.operation_to) PostData.operation_to = value?.operation_to ? this._commonService.convertDateToSave(value?.operation_to) : '';
    if (value?.departure_dates) {
      let departureDateList = [];
      value.departure_dates.forEach(e => departureDateList.push(this._commonService.convertDateToSaveWithoutTime(e)))
      PostData.departure_dates = departureDateList.length > 0 ? departureDateList.join(',') : '';
    }
    if (value?.departure_days) PostData.departure_days = value?.departure_days.join(',');
    if (value?.departure_date) PostData.departure_date = this._commonService.convertDateToSave(value?.departure_date);
    if (value?.return_date) PostData.return_date = this._commonService.convertDateToSave(value?.return_date);
    PostData.is_nearby_airports = value?.is_nearby_airports;
    PostData.nearby_from_airports = value?.nearby_from_airports && value?.nearby_from_airports.length > 0 ? value?.nearby_from_airports.join(',') : '';
    PostData.nearby_to_airports = value?.nearby_to_airports && value?.nearby_to_airports.length > 0 ? value?.nearby_to_airports.join(',') : '';
    let requestform = new FlightContractReq();
    requestform.FlightContract = PostData;
    requestform.FlightDetails = AllFlightDetailslist;
    requestform.FlightRates = FlightRate;
    this.ApiServ.Post('/FlightContract/SaveFlightContract', requestform).subscribe(res => {
      if (res) {
        this._commonService.showMessage(res['status'], res['message']);
        setTimeout(() => {
          if (res['status']) this.router.navigate(['/Services/FlightInventory/Search']);
        }, 500);
      }
    });

  };

  preventDefaultRemoval(value) {
    let array = this.Formdata.get('contracted_pax_type').value
    if (!array.includes(value)) {
      this.Formdata.get('contracted_pax_type').setValue([value, ...array])
    }
  };
  UpdateMultiDayOperation() {
    let val = this.Formdata.get('is_multi_day')?.value;
    if (val) {
      this.Formdata.removeControl('departure_date');
      this.Formdata.addControl('multi_day_operation_type', this.validationService.required);
    } else {
      this.Formdata.removeControl('multi_day_operation_type');
      this.Formdata.removeControl('operation_from');
      this.Formdata.removeControl('operation_to');
      this.Formdata.removeControl('departure_dates');
      this.Formdata.removeControl('departure_days');
      this.Formdata.addControl('departure_date', this.validationService.required);
    }
  };
  UpdateFareType(group) {
    let grpcontrols = group as FormGroup;
    let val = grpcontrols.get('fare_type_applicability').value;
    if (val == 'BOTH' || val == 'ROUNDTRIP') {
      grpcontrols.get('round_trip_discount_type')?.enable();
      grpcontrols.get('adult_round_trip_discount')?.enable();
      grpcontrols.get('child_round_trip_discount')?.enable();
      grpcontrols.get('infant_round_trip_discount')?.enable();
    } else {
      grpcontrols.get('round_trip_discount_type')?.disable();
      grpcontrols.get('adult_round_trip_discount')?.disable();
      grpcontrols.get('child_round_trip_discount')?.disable();
      grpcontrols.get('infant_round_trip_discount')?.disable();
      grpcontrols.get('round_trip_discount_type')?.setValue('');
      grpcontrols.get('adult_round_trip_discount')?.setValue('');
      grpcontrols.get('child_round_trip_discount')?.setValue('');
      grpcontrols.get('infant_round_trip_discount')?.setValue('');
    }
  };

  UpdateMultiDayOperationType() {
    let val = this.Formdata.get('multi_day_operation_type')?.value;
    if (val == 'RANGE') {
      this.Formdata.addControl('operation_from', this.validationService.required);
      this.Formdata.addControl('operation_to', this.validationService.required);
      this.Formdata.addControl('departure_days', this.validationService.required);
      this.Formdata.removeControl('departure_dates');
    } else if (val == 'SPECIFICDATES') {
      this.Formdata.addControl('departure_dates', this.validationService.required);
      this.Formdata.removeControl('departure_days');
      this.Formdata.removeControl('operation_from');
      this.Formdata.removeControl('operation_to');
    } else {
      this.Formdata.removeControl('departure_days');
      this.Formdata.removeControl('operation_from');
      this.Formdata.removeControl('operation_to');
      this.Formdata.removeControl('departure_dates');
    }
  };
  AllSelectedCabinClass = []
  ContractedCabins() {
    let val = this.Formdata.controls['contracted_cabin_class'].value;
    if (val && val.length > 0) {
      let string = val.join(',');
      this.AllSelectedCabinClass = this._staticService.CabinsClassType.filter(e => string.includes(e.value));
      this.FlightsRate.controls.forEach(e => {
        if (e.get('cabin_class').value && !string.includes(e.get('cabin_class').value)) e.get('cabin_class').setValue('');
      })
    } else {
      this.AllSelectedCabinClass = [];
    }
  };

  UpdateTripType() {
    let val = this.Formdata.controls['trip_type'].value;
    if (val == 'ONEWAY') {
      this.UpdateALLFlightsRateFormGroup(true);
      this.Formdata.addControl('is_multi_day', this.Fb.control(false));
      this.Formdata.removeControl('return_date');
      this.Formdata.removeControl('is_oneway_sale_allowed');
      this.inbound.clear();
    }
    else if (val == 'ROUNDTRIP') {
      this.UpdateALLFlightsRateFormGroup(false);
      this.UpdateDepartureDate(false);
      this.addFlightGroupBtn(true);
      this.Formdata.addControl('is_oneway_sale_allowed', this.Fb.control(false));
      this.Formdata.addControl('return_date', this.validationService.required);
      this.Formdata.removeControl('is_multi_day');
    } else {
      this.UpdateALLFlightsRateFormGroup(false);
      this.Formdata.removeControl('is_multi_day');
      this.Formdata.removeControl('return_date');
      this.Formdata.removeControl('is_oneway_sale_allowed');
      this.inbound.clear();
    }
    this.AddUpdatePaxWiseControls();
    this.UpdateMultiDayOperation();
  }
  UpdateDepartureDate(check) {
    let val = this.Formdata.controls['departure_date']?.value;
    if (val) {
      if (check && this.Formdata.controls['return_date']?.value && new Date(val) > new Date(this.Formdata.controls['return_date'].value)) {
        this.Formdata.controls['return_date'].setValue(new Date(val));
      }
      this.ReturnDateMinDate = val;
    } else {
      this.ReturnDateMinDate = new Date()
    }
  };

  UpdateALLFlightsRateFormGroup(check) {
    this.FlightsRate.controls.forEach((e, index) => {
      if (e) {
        let formgroup = e as FormGroup;
        if (check) {
          formgroup.addControl('round_trip_discount_type', this.Fb.control(null));
          formgroup.addControl('adult_round_trip_discount', this.Fb.control(null));
        } else {
          formgroup.removeControl('round_trip_discount_type');
          formgroup.removeControl('adult_round_trip_discount');
          formgroup.removeControl('child_round_trip_discount');
          formgroup.removeControl('infant_round_trip_discount');
        }
      }
    })
  };
  UpdateFlightsRateFormGroup() {
    let val = this.Formdata.controls['trip_type'].value;
    let grp = this.FlightsRate.controls[this.FlightsRate.controls.length - 1] as FormGroup;
    if (val == 'ONEWAY') {
      grp.addControl('round_trip_discount_type', this.Fb.control(null));
      grp.addControl('adult_round_trip_discount', this.Fb.control(null));
    } else {
      grp.removeControl('round_trip_discount_type');
      grp.removeControl('adult_round_trip_discount');
      grp.removeControl('child_round_trip_discount');
      grp.removeControl('infant_round_trip_discount');
    }
  };
  Editid;
  AllSelectedAirports = [];
  AllSelectedAircraft = [];
  AllSelectedAirline = [];
  GetFlightContract() {
    this.Editid = this.activateRoute.snapshot.paramMap.get('RuleId');
    if (this.Editid) {
      this.ApiServ.Get('/FlightContract/CloneGetFlightContractByID/' + this.Editid).subscribe(res => {
        if (res) {
          this.SetValue(res.data);
          this.GetAllAirData(res.data);
        }
      })
    }
  };
  SetValue(data) {
    this.SetValueFlightContract(data.FlightContract);
    this.SetValueFlightDetails(data.FlightDetails);
    this.SetValueFlightRates(data.FlightRates);
  };
  SetValueFlightContract(data) {
    console.log(data);
    this.Formdata.get('contract_name')?.setValue(data?.contract_name);
    this.Formdata.get('is_active')?.setValue(data?.is_active);
    this.Formdata.get('contract_description')?.setValue(data?.contract_description);
    this.Formdata.get('trip_type')?.setValue(data?.trip_type);
    this.UpdateTripType();
    this.Formdata.get('is_oneway_sale_allowed')?.setValue(data?.is_oneway_sale_allowed);
    this.Formdata.get('origin')?.setValue(data?.origin);
    this.Formdata.get('destination')?.setValue(data?.destination);
    this.Formdata.get('no_of_legs')?.setValue(data?.no_of_legs);
    this.Formdata.get('currency_code')?.setValue(data?.currency_code);
    this.Formdata.get('is_instant_confirmation')?.setValue(data?.is_instant_confirmation ? 'INSTANT' : 'MANUAL');
    this.Formdata.get('contracted_cabin_class')?.setValue(data?.contracted_cabin_class ? data?.contracted_cabin_class.split(',') : []);
    this.ContractedCabins();
    this.Formdata.get('contracted_pax_type')?.setValue(data?.contracted_pax_type ? data?.contracted_pax_type.split(',') : []);
    this.UpdateAllPaxWiseControls();
    this.Formdata.get('validating_airline')?.setValue(data?.validating_airline);
    this.Formdata.get('is_multi_day')?.setValue(data?.is_multi_day);
    this.UpdateMultiDayOperation();
    this.Formdata.get('multi_day_operation_type')?.setValue(data?.multi_day_operation_type);
    this.UpdateMultiDayOperationType();
    this.Formdata.get('operation_from')?.setValue(null);
    this.Formdata.get('operation_to')?.setValue(null);
    this.Formdata.get('departure_date')?.setValue(null);
    this.Formdata.get('return_date')?.setValue(null);
    this.Formdata.get('departure_dates')?.setValue(null)
    // if (data.departure_dates && this.Formdata.get('departure_dates')) {
    //   let allDate = data.departure_dates.split(',');
    //   if (allDate && allDate.length > 0) {
    // this.Formdata.get('departure_dates').setValue(allDate.map(e => new Date(e)))
    //   }
    // };
    // this.Formdata.get('departure_date')?.setValue(data?.departure_date ? new Date(data.departure_date) : null);
    // this.Formdata.get('return_date')?.setValue(data?.return_date ? new Date(data.return_date) : null);
    this.Formdata.get('departure_days')?.setValue(data?.departure_days.split(','));
    this.Formdata.get('is_nearby_airports')?.setValue(data?.is_nearby_airports);
    this.UpdateNearByAirport();
    this.Formdata.get('nearby_from_airports')?.setValue(data?.nearby_from_airports.split(','));
    this.Formdata.get('nearby_to_airports')?.setValue(data?.nearby_to_airports.split(','));
  }
  SetValueFlightDetails(data) {
    console.log(data);
    let outbondlist = data.filter(e => e.seg_nbr == 1).sort((a, b) => a.leg_nbr - b.leg_nbr);
    outbondlist.forEach((e, i) => {
      if (i != 0) this.addFlightGroupBtn(false);
      this.outbound.controls[i]?.get('airline_code')?.setValue(e.airline_code);
      this.outbound.controls[i]?.get('flight_no')?.setValue(e.flight_no);
      this.outbound.controls[i]?.get('_aircraft_type')?.setValue(e.aircraft_type_id);
      this.outbound.controls[i]?.get('from_airport')?.setValue(e.from_airport);
      this.outbound.controls[i]?.get('to_airport')?.setValue(e.to_airport);
      this.outbound.controls[i]?.get('is_next_day_departure')?.setValue(e.is_next_day_departure);
      this.outbound.controls[i]?.get('departure_terminal')?.setValue(e.departure_terminal);
      this.outbound.controls[i]?.get('is_next_day_arrival')?.setValue(e.is_next_day_arrival);
      this.outbound.controls[i]?.get('arrival_terminal')?.setValue(e.arrival_terminal);
      if (e.departure_time) {
        this.outbound.controls[i]?.get('departure_Hour')?.setValue(e.departure_time.split(':')[0]);
        this.outbound.controls[i]?.get('departure_minutes')?.setValue(e.departure_time.split(':')[1]);
      }
      if (e.arrival_time) {
        this.outbound.controls[i]?.get('arrival_hour')?.setValue(e.arrival_time.split(':')[0]);
        this.outbound.controls[i]?.get('arrival_minutes')?.setValue(e.arrival_time.split(':')[1]);
      }
      if (e.flying_duration) {
        this.outbound.controls[i]?.get('flying_duration_hour')?.setValue(e.flying_duration.split(':')[0]);
        this.outbound.controls[i]?.get('flying_duration_minutes')?.setValue(e.flying_duration.split(':')[1]);
      }
    })
    let inbondlist = data.filter(e => e.seg_nbr == 2);
    if (inbondlist && inbondlist.length > 0) {
      inbondlist = inbondlist.sort((a, b) => a.leg_nbr - b.leg_nbr);
      inbondlist.forEach((e, i) => {
        if (i != 0) this.addFlightGroupBtn(true);
        this.inbound.controls[i]?.get('airline_code')?.setValue(e.airline_code);
        this.inbound.controls[i]?.get('flight_no')?.setValue(e.flight_no);
        this.inbound.controls[i]?.get('_aircraft_type')?.setValue(e.aircraft_type_id);
        this.inbound.controls[i]?.get('from_airport')?.setValue(e.from_airport);
        this.inbound.controls[i]?.get('to_airport')?.setValue(e.to_airport);
        this.inbound.controls[i]?.get('is_next_day_departure')?.setValue(e.is_next_day_departure);
        this.inbound.controls[i]?.get('departure_terminal')?.setValue(e.departure_terminal);
        this.inbound.controls[i]?.get('is_next_day_arrival')?.setValue(e.is_next_day_arrival);
        this.inbound.controls[i]?.get('arrival_terminal')?.setValue(e.arrival_terminal);
        if (e.departure_time) {
          this.inbound.controls[i]?.get('departure_Hour')?.setValue(e.departure_time.split(':')[0]);
          this.inbound.controls[i]?.get('departure_minutes')?.setValue(e.departure_time.split(':')[1]);
        }
        if (e.arrival_time) {
          this.inbound.controls[i]?.get('arrival_hour')?.setValue(e.arrival_time.split(':')[0]);
          this.inbound.controls[i]?.get('arrival_minutes')?.setValue(e.arrival_time.split(':')[1]);
        }
        if (e.flying_duration) {
          this.inbound.controls[i]?.get('flying_duration_hour')?.setValue(e.flying_duration.split(':')[0]);
          this.inbound.controls[i]?.get('flying_duration_minutes')?.setValue(e.flying_duration.split(':')[1]);
        }
      })
    }
  };
  // don't remove this code
  SetValueFlightRates(data, iscopyUi?) {
    console.log(data);
    data.forEach((e, i) => {
      if (iscopyUi) {
        e = data[0];
      } else {
        if (i != 0) this.addFlightsRateGroupBtn();
      }
      this.FlightsRate.controls[i].get('rbd')?.setValue(e?.rbd)
      this.FlightsRate.controls[i].get('fare_family_group_id')?.setValue(e?.fare_family_group_id);
      this.FlightsRate.controls[i].get('fare_family_name')?.setValue(e?.fare_family_name);
      this.FlightsRate.controls[i].get('cabin_class')?.setValue(e?.cabin_class);
      this.FlightsRate.controls[i].get('adt_base_fare')?.setValue(e?.adt_base_fare);
      this.FlightsRate.controls[i].get('adt_tax')?.setValue(e?.adt_tax);
      this.FlightsRate.controls[i].get('chd_base_fare')?.setValue(e?.chd_base_fare);
      this.FlightsRate.controls[i].get('chd_tax')?.setValue(e?.chd_tax);
      this.FlightsRate.controls[i].get('inf_base_fare')?.setValue(e?.inf_base_fare);
      this.FlightsRate.controls[i].get('inf_tax')?.setValue(e?.inf_tax);
      this.FlightsRate.controls[i].get('round_trip_discount_type')?.setValue(e?.round_trip_discount_type);
      this.FlightsRate.controls[i].get('is_apply_discount_with_same_vc_only')?.setValue(e?.is_apply_discount_with_same_vc_only);
      this.FlightsRate.controls[i].get('adult_round_trip_discount')?.setValue(e?.adult_round_trip_discount);
      this.FlightsRate.controls[i].get('child_round_trip_discount')?.setValue(e?.child_round_trip_discount);
      this.FlightsRate.controls[i].get('infant_round_trip_discount')?.setValue(e?.infant_round_trip_discount);
      this.FlightsRate.controls[i].get('seat_allocation')?.setValue(e?.seat_allocation)
      this.FlightsRate.controls[i].get('is_checked_bag_included')?.setValue(e?.is_checked_bag_included);
      this.UpdateBag(this.FlightsRate.controls[i])
      this.FlightsRate.controls[i].get('adt_check_bag')?.setValue(e?.adt_check_bag);
      this.FlightsRate.controls[i].get('chd_check_bag')?.setValue(e?.chd_check_bag);
      this.FlightsRate.controls[i].get('inf_check_bag')?.setValue(e?.inf_check_bag);
      this.FlightsRate.controls[i].get('_check_bag_unit')?.setValue(e?._check_bag_unit);
      this.FlightsRate.controls[i].get('adt_cabin_bag')?.setValue(e?.adt_cabin_bag);
      this.FlightsRate.controls[i].get('chd_cabin_bag')?.setValue(e?.chd_cabin_bag);
      this.FlightsRate.controls[i].get('inf_cabin_bag')?.setValue(e?.inf_cabin_bag);
      this.FlightsRate.controls[i].get('_cabin_bag_unit')?.setValue(e?._cabin_bag_unit);
      this.FlightsRate.controls[i].get('refund_type')?.setValue(e?.refund_type);
      this.FlightsRate.controls[i].get('adt_fare_rule')?.setValue(e?.adt_fare_rule);
      this.FlightsRate.controls[i].get('chd_fare_rule')?.setValue(e?.chd_fare_rule);
      this.FlightsRate.controls[i].get('inf_fare_rule')?.setValue(e?.inf_fare_rule);
      this.FlightsRate.controls[i].get('is_meal_included')?.setValue(e?.is_meal_included ? 'Yes' : 'No');
      this.UpdateMealTypeIncluded(this.FlightsRate.controls[i]);
      this.FlightsRate.controls[i].get('meal_details')?.setValue(e?.meal_details);
      this.FlightsRate.controls[i].get('inclusions')?.setValue(e?.inclusions);
      this.FlightsRate.controls[i].get('pnr')?.setValue(e?.pnr);
    })
  };
  copyFlightRatesGroup(ind, e?) {
    // data.forEach((e, i) => {
    // this.addFlightsRateGroupBtn();
    this.FlightsRate.insert(ind + 1, this.Fb.group({
      rbd: this.validationService.required,
      fare_family_group_id: this.validationService.required,
      fare_family_name: this.validationService.required,
      cabin_class: this.validationService.required,
      adt_base_fare: this.validationService.decimal,
      adt_tax: this.validationService.decimal,
      seat_allocation: this.validationService.number,
      is_checked_bag_included: [false],
      is_apply_discount_with_same_vc_only: [false],
      adt_check_bag: [{ value: '', disabled: true }],
      _check_bag_unit: [{ value: '', disabled: true }],
      adt_cabin_bag: this.validationService.required,
      _cabin_bag_unit: this.validationService.required,
      refund_type: this.validationService.required,
      adt_fare_rule: this.validationService.required,
      is_meal_included: this.validationService.required,
      meal_details: [],
      inclusions: [],
    }));
    this.AddUpdatePaxWiseControls();
    this.UpdateFlightsRateFormGroup();
    this.FlightsRate.controls[ind + 1].get('rbd')?.setValue(e?.rbd)
    this.FlightsRate.controls[ind + 1].get('fare_family_group_id')?.setValue(e?.fare_family_group_id);
    this.FlightsRate.controls[ind + 1].get('fare_family_name')?.setValue(e?.fare_family_name);
    this.FlightsRate.controls[ind + 1].get('cabin_class')?.setValue(e?.cabin_class);
    this.FlightsRate.controls[ind + 1].get('adt_base_fare')?.setValue(e?.adt_base_fare);
    this.FlightsRate.controls[ind + 1].get('adt_tax')?.setValue(e?.adt_tax);
    this.FlightsRate.controls[ind + 1].get('chd_base_fare')?.setValue(e?.chd_base_fare);
    this.FlightsRate.controls[ind + 1].get('chd_tax')?.setValue(e?.chd_tax);
    this.FlightsRate.controls[ind + 1].get('inf_base_fare')?.setValue(e?.inf_base_fare);
    this.FlightsRate.controls[ind + 1].get('inf_tax')?.setValue(e?.inf_tax);
    this.FlightsRate.controls[ind + 1].get('round_trip_discount_type')?.setValue(e?.round_trip_discount_type);
    this.FlightsRate.controls[ind + 1].get('is_apply_discount_with_same_vc_only')?.setValue(e?.is_apply_discount_with_same_vc_only);
    this.FlightsRate.controls[ind + 1].get('adult_round_trip_discount')?.setValue(e?.adult_round_trip_discount);
    this.FlightsRate.controls[ind + 1].get('child_round_trip_discount')?.setValue(e?.child_round_trip_discount);
    this.FlightsRate.controls[ind + 1].get('infant_round_trip_discount')?.setValue(e?.infant_round_trip_discount);
    this.FlightsRate.controls[ind + 1].get('seat_allocation')?.setValue(e?.seat_allocation)
    this.FlightsRate.controls[ind + 1].get('is_checked_bag_included')?.setValue(e?.is_checked_bag_included);
    this.UpdateBag(this.FlightsRate.controls[ind + 1])
    this.FlightsRate.controls[ind + 1].get('adt_check_bag')?.setValue(e?.adt_check_bag);
    this.FlightsRate.controls[ind + 1].get('chd_check_bag')?.setValue(e?.chd_check_bag);
    this.FlightsRate.controls[ind + 1].get('inf_check_bag')?.setValue(e?.inf_check_bag);
    this.FlightsRate.controls[ind + 1].get('_check_bag_unit')?.setValue(e?._check_bag_unit);
    this.FlightsRate.controls[ind + 1].get('adt_cabin_bag')?.setValue(e?.adt_cabin_bag);
    this.FlightsRate.controls[ind + 1].get('chd_cabin_bag')?.setValue(e?.chd_cabin_bag);
    this.FlightsRate.controls[ind + 1].get('inf_cabin_bag')?.setValue(e?.inf_cabin_bag);
    this.FlightsRate.controls[ind + 1].get('_cabin_bag_unit')?.setValue(e?._cabin_bag_unit);
    this.FlightsRate.controls[ind + 1].get('refund_type')?.setValue(e?.refund_type);
    this.FlightsRate.controls[ind + 1].get('adt_fare_rule')?.setValue(e?.adt_fare_rule);
    this.FlightsRate.controls[ind + 1].get('chd_fare_rule')?.setValue(e?.chd_fare_rule);
    this.FlightsRate.controls[ind + 1].get('inf_fare_rule')?.setValue(e?.inf_fare_rule);
    this.FlightsRate.controls[ind + 1].get('is_meal_included')?.setValue(e?.is_meal_included ? 'Yes' : 'No');
    this.UpdateMealTypeIncluded(this.FlightsRate.controls[ind + 1]);
    this.FlightsRate.controls[ind + 1].get('meal_details')?.setValue(e?.meal_details);
    this.FlightsRate.controls[ind + 1].get('inclusions')?.setValue(e?.inclusions);
    this.FlightsRate.controls[ind + 1].get('pnr')?.setValue(e?.pnr);
    // })
  };
  getIsMeal(iscopyUi, e) {
    if (iscopyUi) {
      return (e?.is_meal_included ? 'Yes' : 'No');
    } else {
      return (e?.is_meal_included);
    }
  };
  GetAllAirData(res) {
    this.AllSelectedAirports.push(res.FlightContract.origin);
    this.AllSelectedAirports.push(res.FlightContract.origin);
    this.AllSelectedAirline.push(res.FlightContract.validating_airline);
    if (res.FlightContract.nearby_from_airports) {
      this.AllSelectedAirports.push(...res.FlightContract.nearby_from_airports.split(','));
    }
    if (res.FlightContract.nearby_to_airports) {
      this.AllSelectedAirports.push(...res.FlightContract.nearby_to_airports.split(','));
    };
    if (res.FlightDetails && res.FlightDetails.length > 0) {
      res.FlightDetails.forEach(e => {
        this.AllSelectedAirports.push(e.from_airport);
        this.AllSelectedAirports.push(e.to_airport);
        this.AllSelectedAircraft.push(e.aircraft_type_id);
        this.AllSelectedAirline.push(e.airline_code);
      });
    };
    this._flightContractService.GetAirportsByAirportCode(this.AllSelectedAirports.join(','));
    this._flightContractService.GetAircraftTypeById(this.AllSelectedAircraft.join(','));
    this._flightContractService.GetAirlineByAirlineCode(this.AllSelectedAirline.join(','));
  }
  //  static dropdown
  Option = [
    { value: 'Yes', displayName: 'Yes' },
    { value: 'No', displayName: 'No' },
  ];
  updateAirportSelection(name: string, val: any) {
    const controlMap = {
      'orgin': this.outbound.controls[0].get('from_airport'),
      'destination': this.inbound?.controls?.[0]?.get('from_airport')
    };
    if (val && controlMap[name]) {
      controlMap[name].setValue(val);
    } else {
      controlMap[name]?.setValue(null);
    }
  };


  selectAllDays() {
    const weekDays = this._staticService.WeekDaysList.map(day => day.Itemkey2);
    this.Formdata.controls['departure_days'].setValue(weekDays);
    this.allDaysSelected = true;
  };

  IsAllDaysSelected(): boolean {
    let alldays = this._staticService.WeekDaysList.every(e => {
      if (this.Formdata.controls['departure_days']?.value && this.Formdata.controls['departure_days']?.value.includes(e.Itemkey2)) {
        return true
      }
      return false
    })
    return alldays
  }

  clearAllDays() {
    this.Formdata.controls['departure_days'].setValue([]);
    this.allDaysSelected = false;
  }


  storeDestAirportList(form, i) {
    let fb = form as FormArray;
    if (fb.controls[i].get('to_airport').value) {
      if (fb.controls[i + 1]) {
        fb.controls[i + 1].get('from_airport').setValue(fb.controls[i].get('to_airport').value);
      };
    };
  };

  backClick() {
    this.router.navigateByUrl("Services/FlightInventory/Search");
  }
}
