import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators, AbstractControl, ValidatorFn } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { NgSelectComponent } from '@ng-select/ng-select';
import * as moment from 'moment';
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 { 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';

@Component({
  selector: 'app-edit-rate-inventory',
  templateUrl: './edit-rate-inventory.component.html',
})
export class EditRateInventoryComponent implements OnInit {

  constructor(
    public _staticService: StaticDataService,
    public activateRoute: ActivatedRoute,
    public validationService: ValidationService,
    public _flightContractService: FlightContractService,
    private Fb: FormBuilder,
    public _commonService: CommonFunctionService,
    private ApiServ: API,
    public router: Router,
  ) { }


  ContractId;
  Defaultdate;
  Formdata: FormGroup;
  ngOnInit(): void {
    this.PageSetUp();
  };
  PageSetUp() {
    this.ContractId = this.activateRoute.snapshot.paramMap.get('ContractId');
    this.GetFlightContratByID();
  };

  FlightContractDetails;
  DatesListArray = [];
  FareFamilyList = [];
  IsChild = false;
  IsInfant = false;
  GetFlightContratByID() {
    this.ApiServ.Get('/FlightContract/GetFlightContractByID/' + this.ContractId).subscribe(res => {
      if (res) {
        this.FlightContractDetails = res.data;
        if (this.FlightContractDetails.departure_dates && this.FlightContractDetails.multi_day_operation_type == 'SPECIFICDATES') {
          let datelist = this.FlightContractDetails.departure_dates.split(',');
          if (datelist && datelist.length > 0) {
            this.DatesListArray = datelist.map(e => {
              let date = new Date(e);
              date.setHours(0, 0, 0, 0);
              return moment(date).format('YYYY-MM-DD')
            });
          }
        };
        if (this.FlightContractDetails?.operation_from && this.FlightContractDetails?.operation_to) {
          let from_date = new Date(this.FlightContractDetails.operation_from);
          let to_date = new Date(this.FlightContractDetails.operation_from);
          if (this.FlightContractDetails.departure_dates && this.FlightContractDetails.multi_day_operation_type == 'SPECIFICDATES') {
            let datelist = this.FlightContractDetails.departure_dates.split(',');
            let dates = [];
            datelist.forEach(e => {
              if (new Date(e) >= new Date()) dates.push(e)
            });
            from_date = new Date(dates[0]);
            to_date = new Date(datelist[datelist.length - 1]);
          }
          let current_date = new Date();
          from_date.setHours(0, 0, 0, 0);
          to_date.setHours(0, 0, 0, 0);
          current_date.setHours(0, 0, 0, 0);
          if (from_date.getTime() < current_date.getTime() && to_date.getTime() > current_date.getTime()) {
            this.Defaultdate = current_date;
          } else {
            this.Defaultdate = from_date;
          }
        }
        if (this.FlightContractDetails['contracted_pax_type'].includes('C')) this.IsChild = true;
        if (this.FlightContractDetails['contracted_pax_type'].includes('I')) this.IsInfant = true;
        this.OnIntForm();
        for (let index = 1; index <= 3; index++) {
          this.FareFamilyList.push(index)
        };
      }
    });
  };
  WeekDaysList = [];
  AtoZ = []
  OnIntForm() {
    this.Formdata = this.Fb.group({
      Default: [''],
      _rbd: this.validationService.required,
      currency: [this.FlightContractDetails.currency_code],
      contracted_pax_type: [this.FlightContractDetails.contracted_pax_type],
      FlightsRate: this.Fb.array([])
    });
    this.AtoZ = this.FlightContractDetails.rbd?.split(',') || [];
    this.AtoZ = [...new Set(this.AtoZ)];
    if (this.FlightContractDetails?.is_multi_day) {
      this.Formdata.addControl('date_type', this.validationService.required);
      this.Formdata.addControl('from_date', this.validationService.required);
      this.Formdata.addControl('to_date', this.validationService.required);
      if (this.FlightContractDetails.multi_day_operation_type == 'RANGE') {
        this._staticService.WeekDaysList.forEach(e => {
          if (this.FlightContractDetails?.departure_days?.includes(e.Itemkey2)) this.WeekDaysList.push(e.Itemkey2);
        })
        this.Formdata.addControl('days', this.Fb.control(''));
      };
    } else {
      this.Formdata.get('Default').setValue(this.FlightContractDetails.departure_date);
    };
  };
  ResetForm() {
    this.Formdata.get('_rbd')?.setValue('');
    this.Formdata.get('contracted_pax_type')?.setValue('');
    this.Formdata.get('date_type')?.setValue('');
    this.Formdata.get('from_date')?.setValue(null);
    this.Formdata.get('to_date')?.setValue(null);
    this.Formdata.get('days')?.setValue(null);
    this.Formdata.markAsUntouched();
  }
  get FlightsRate() {
    return this.Formdata.get('FlightsRate') as FormArray;
  }

  GetFlightRateList() {
    if (
      this.Formdata.get('_rbd')?.invalid ||
      this.Formdata.get('date_type')?.invalid ||
      this.Formdata.get('from_date')?.invalid ||
      this.Formdata.get('to_date')?.invalid
    ) {
      this.validationService.showValidationsMsg(this.Formdata);
      setTimeout(() => {
        this.validationService.scrollToError();
      }, 50);
      return;
    }
    let value = this.Formdata.getRawValue();
    let requestObject = {
      contract_id: this.ContractId,
      date_type: value.date_type,
      from_date: '',
      to_date: '',
      days: '',
      rbd: value._rbd,
      flight_details: [],
    };
    if (this.FlightContractDetails?.is_multi_day) {
      requestObject.from_date = this._commonService.convertDateToSave(value.from_date);
      requestObject.to_date = this._commonService.convertDateToSave(value.to_date);
      requestObject.days = value.days ? value.days.join(',') : '';
    } else {
      requestObject.from_date = this._commonService.convertDateToSave(value.Default);
      requestObject.to_date = this._commonService.convertDateToSave(value.Default);
      const date = moment(value.Default);
      const dayName = date.format('dddd');
      requestObject.days = dayName;
    };
    this.ApiServ.Post('/FlightContract/GetAllFlightRateBySearch', requestObject).subscribe(res => {
      if (res) {
        if (res['status']) this.SetValForm(res.data);
        if (!res['status']) this._commonService.showMessage(res['status'], res['message']);
      }
    });
  };
  SaveFlightsRate() {
    if (this.FlightsRate.invalid) {
      this.validationService.showValidationsMsg(this.FlightsRate);
      setTimeout(() => {
        this.validationService.scrollToError();
      }, 50);
      return;
    }
    let value = this.FlightsRate.getRawValue();
    let FlightRate = [];
    value.forEach((e, i) => {
      if (this.FlightsRate.controls[i].dirty) {
        let postObject = new FlightRateArray();
        postObject.contract_id = this.ContractId;
        postObject.contract_date_unique_id = e.contract_date_unique_id;
        postObject.rate_id = e.rate_id;
        postObject.fare_family_group_id = e.fare_family_group_id.toString();
        postObject.fare_family_name = e.fare_family_name;
        postObject.adt_base_fare = e.adt_base_fare ? parseFloat(e.adt_base_fare) : 0;
        postObject.adt_tax = e.adt_tax ? parseFloat(e.adt_tax) : 0;
        postObject.chd_base_fare = e?.chd_base_fare ? parseFloat(e?.chd_base_fare) : 0;
        postObject.chd_tax = e.chd_tax ? parseFloat(e.chd_tax) : 0;
        postObject.inf_base_fare = e?.inf_base_fare ? parseFloat(e?.inf_base_fare) : 0;
        postObject.inf_tax = e?.inf_tax ? parseFloat(e?.inf_tax) : 0;
        postObject.round_trip_discount_type = e.round_trip_discount_type;
        postObject.is_apply_discount_with_same_vc_only = e.is_apply_discount_with_same_vc_only;
        postObject.adult_round_trip_discount = e.adult_round_trip_discount ? parseFloat(e.adult_round_trip_discount) : 0;
        postObject.child_round_trip_discount = e?.child_round_trip_discount ? parseFloat(e?.child_round_trip_discount) : 0;
        postObject.infant_round_trip_discount = e?.infant_round_trip_discount ? parseFloat(e?.infant_round_trip_discount) : 0;
        postObject.seat_allocation = e?.seat_allocation ? parseFloat(e?.seat_allocation) : 0;
        postObject.is_checked_bag_included = e.is_checked_bag_included;
        postObject.adt_check_bag = e.adt_check_bag;
        postObject.chd_check_bag = e?.chd_check_bag ? e?.chd_check_bag : '';
        postObject.inf_check_bag = e?.inf_check_bag ? e?.inf_check_bag : '';
        postObject._check_bag_unit = e._check_bag_unit;
        postObject.adt_cabin_bag = e.adt_cabin_bag;
        postObject.chd_cabin_bag = e?.chd_cabin_bag ? e?.chd_cabin_bag : '';
        postObject.inf_cabin_bag = e?.inf_cabin_bag ? e?.inf_cabin_bag : '';
        postObject._cabin_bag_unit = e._cabin_bag_unit;
        postObject.refund_type = e.refund_type;
        postObject.adt_fare_rule = e.adt_fare_rule;
        postObject.chd_fare_rule = e?.chd_fare_rule ? e?.chd_fare_rule : '';
        postObject.inf_fare_rule = e?.inf_fare_rule ? e?.inf_fare_rule : '';
        postObject.is_meal_included = e.is_meal_included == 'Yes' ? true : false;
        postObject.meal_details = e.meal_details;
        postObject.inclusions = e.inclusions;
        postObject.pnr = e.pnr;
        postObject.is_instant_confirmation = e.is_instant_confirmation == 'INSTANT' ? true : false;
        postObject.is_stop_sale = e.is_stop_sale;
        FlightRate.push(postObject);
      }
    });
    this.ApiServ.Post('/FlightContract/UpdateFlightRate', FlightRate).subscribe(res => {
      if (res) {
        this._commonService.showMessage(res['status'], res['message']);
        setTimeout(() => {
          res['status'] ? this.router.navigate(['/Services/FlightInventory/Search']) : '';
        }, 500);
      }
    });
  };
  SetValForm(RateList) {
    this.FlightsRate.clear();
    let datesort = RateList.sort((a, b) => {
      const timestampA = new Date(a.departure_date).getTime();
      const timestampB = new Date(b.departure_date).getTime();
      return timestampA - timestampB;
    });
    datesort.forEach((object, i) => {
      this.addFlightsRateGroupBtn();
      this.FlightsRate.controls[i]?.get('contract_date_unique_id')?.setValue(object?.contract_date_unique_id);
      this.FlightsRate.controls[i]?.get('rate_id')?.setValue(object?.rate_id);
      this.FlightsRate.controls[i]?.get('departure_date')?.setValue(object?.departure_date ? moment(object?.departure_date).format('DD MMM YYYY') : '');
      this.FlightsRate.controls[i]?.get('return_date')?.setValue(object?.return_date ? moment(object?.return_date).format('DD MMM YYYY') : '');
      this.FlightsRate.controls[i]?.get('is_stop_sale')?.setValue(object?.is_stop_sale);
      this.FlightsRate.controls[i]?.get('fare_family_group_id')?.setValue(object?.fare_family_group_id);
      this.FlightsRate.controls[i]?.get('fare_family_name')?.setValue(object?.fare_family_name);
      this.FlightsRate.controls[i]?.get('adt_base_fare')?.setValue(object?.adt_base_fare);
      this.FlightsRate.controls[i]?.get('adt_tax')?.setValue(object?.adt_tax);
      this.FlightsRate.controls[i]?.get('chd_base_fare')?.setValue(object?.chd_base_fare);
      this.FlightsRate.controls[i]?.get('chd_tax')?.setValue(object?.chd_tax);
      this.FlightsRate.controls[i]?.get('inf_base_fare')?.setValue(object?.inf_base_fare);
      this.FlightsRate.controls[i]?.get('inf_tax')?.setValue(object?.inf_tax);
      if (this.FlightContractDetails?.trip_type == 'ONEWAY') {
        this.FlightsRate.controls[i]?.get('round_trip_discount_type')?.setValue(object?.round_trip_discount_type);
        this.FlightsRate.controls[i]?.get('is_apply_discount_with_same_vc_only')?.setValue(object?.is_apply_discount_with_same_vc_only);
        this.UpdateFareType(this.FlightsRate.controls[i]);
        this.FlightsRate.controls[i]?.get('adult_round_trip_discount')?.setValue(object?.adult_round_trip_discount);
        this.FlightsRate.controls[i]?.get('child_round_trip_discount')?.setValue(object?.child_round_trip_discount);
        this.FlightsRate.controls[i]?.get('infant_round_trip_discount')?.setValue(object?.infant_round_trip_discount);
      }
      this.FlightsRate.controls[i]?.get('seat_allocation')?.setValue(object?.seat_allocation);
      this.FlightsRate.controls[i]?.get('seat_booked')?.setValue(object?.seat_booked);
      this.FlightsRate.controls[i]?.get('seat_cancelled')?.setValue(object?.seat_cancelled);
      this.FlightsRate.controls[i]?.get('seat_remains')?.setValue(object?.seat_remains);
      this.FlightsRate.controls[i]?.get('is_checked_bag_included')?.setValue(object?.is_checked_bag_included);
      this.UpdateBag(this.FlightsRate.controls[i]);
      if (object?.is_checked_bag_included) {
        this.FlightsRate.controls[i]?.get('adt_check_bag')?.setValue(object?.adt_check_bag);
        this.FlightsRate.controls[i]?.get('chd_check_bag')?.setValue(object?.chd_check_bag);
        this.FlightsRate.controls[i]?.get('inf_check_bag')?.setValue(object?.inf_check_bag);
        this.FlightsRate.controls[i]?.get('_check_bag_unit')?.setValue(object?._check_bag_unit);
      }
      this.FlightsRate.controls[i]?.get('adt_cabin_bag')?.setValue(object?.adt_cabin_bag);
      this.FlightsRate.controls[i]?.get('chd_cabin_bag')?.setValue(object?.chd_cabin_bag);
      this.FlightsRate.controls[i]?.get('inf_cabin_bag')?.setValue(object?.inf_cabin_bag);
      this.FlightsRate.controls[i]?.get('_cabin_bag_unit')?.setValue(object?._cabin_bag_unit);
      this.FlightsRate.controls[i]?.get('refund_type')?.setValue(object?.refund_type);
      this.FlightsRate.controls[i]?.get('pnr')?.setValue(object?.pnr);
      this.FlightsRate.controls[i]?.get('adt_fare_rule')?.setValue(object?.adt_fare_rule);
      this.FlightsRate.controls[i]?.get('chd_fare_rule')?.setValue(object?.chd_fare_rule);
      this.FlightsRate.controls[i]?.get('inf_fare_rule')?.setValue(object?.inf_fare_rule);
      this.FlightsRate.controls[i]?.get('is_instant_confirmation')?.setValue(object?.is_instant_confirmation ? 'INSTANT' : 'MANUAL');
      this.FlightsRate.controls[i]?.get('is_meal_included')?.setValue(object?.is_meal_included ? 'Yes' : 'No');
      this.UpdateMealTypeIncluded(this.FlightsRate.controls[i]);
      if (object?.is_meal_included) {
        this.FlightsRate.controls[i]?.get('meal_details')?.setValue(object?.meal_details);
      }
      this.FlightsRate.controls[i]?.get('inclusions')?.setValue(object?.inclusions);
      this.FlightsRate.controls[i]?.get('updated_by')?.setValue(object?.updated_by);
      this.FlightsRate.controls[i]?.get('updated_on')?.setValue(object?.updated_on ? this._commonService.convertDateToShow(object?.updated_on) : '');
    });
  };
  addFlightsRateGroupBtn() {
    this.FlightsRate.push(
      this.Fb.group({
        contract_date_unique_id: this.validationService.required,
        rate_id: this.validationService.required,
        departure_date: [''],
        return_date: [''],
        fare_family_group_id: this.validationService.required,
        fare_family_name: this.validationService.required,
        adt_base_fare: this.validationService.decimal,
        adt_tax: this.validationService.decimal,
        round_trip_discount_type: [''],
        seat_allocation: this.validationService.decimal,
        seat_booked: [],
        seat_remains: [],
        seat_cancelled: [],
        is_checked_bag_included: [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: [false],
        meal_details: [{ value: null, disabled: true }],
        inclusions: [''],
        pnr: [],
        is_instant_confirmation: [false],
        is_stop_sale: [false],
        is_apply_discount_with_same_vc_only: [false],
        updated_by: [],
        updated_on: [],
      })
    );
    this.AddUpdatePaxWiseControls();
  };
  //  ------------------------------------------------------------------------------------------------------------------------
  AddUpdatePaxWiseControls() {
    let grp = this.FlightsRate.controls[this.FlightsRate.controls.length - 1];
    if (this.IsChild) this.UpdatePaxWiseControls(grp, 'chd', true);
    if (this.IsInfant) this.UpdatePaxWiseControls(grp, 'inf', true);
  };
  UpdatePaxWiseControls(group, name, check) {
    let grp = group as FormGroup;
    let discountName = name == 'chd' ? 'child' : 'infant';
    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);
      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');
    }
  };
  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('');
      });
    }
  };
  UpdateValidationforDiscountTypegroup(group, event) {
    let grpcontrols = group as FormGroup;
    let vaidation_type = event ? 'add' : 'remove';
    this.UpdateControlsValidation(grpcontrols, 'adult_round_trip_discount', vaidation_type);
    if (this.IsChild) {
      this.UpdateControlsValidation(grpcontrols, 'child_round_trip_discount', vaidation_type)
    }
    if (this.IsInfant) {
      this.UpdateControlsValidation(grpcontrols, 'infant_round_trip_discount', vaidation_type)
    }

  }
  UpdateFareType(group) {
    let grpcontrols = group as FormGroup;
    if (this.FlightContractDetails?.trip_type == 'ONEWAY') {
      grpcontrols.addControl('adult_round_trip_discount', new FormControl(''));
      if (this.IsChild) {
        grpcontrols.addControl('child_round_trip_discount', new FormControl(''));
      }
      if (this.IsInfant) {
        grpcontrols.addControl('infant_round_trip_discount', new FormControl(''));
      }
    }
    this.UpdateValidationforDiscountTypegroup(group, grpcontrols.get('round_trip_discount_type').value);
  };
  UpdateMealTypeIncluded(grp) {
    let group = grp as FormGroup;
    if (group.get('is_meal_included').value == 'Yes') {
      group.get('meal_details').enable()
      this.UpdateControlsValidation(group, 'meal_details', 'add');
    }
    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();
    };
  };
  // -----------------------------------------------------------------------------------------------------------------------
  checkDateForHighlight(date) {
    if (!this.FlightContractDetails.is_multi_day) {
      return false; // If not multi-day event, don't highlight any date
    }
    let currentDate = new Date(date.year, date.month, date.day);
    currentDate.setHours(0, 0, 0, 0);
    if (this.FlightContractDetails?.multi_day_operation_type === 'RANGE') {
      let fromDate = new Date(this.FlightContractDetails.operation_from);
      let toDate = new Date(this.FlightContractDetails.operation_to);
      fromDate.setHours(0, 0, 0, 0);
      toDate.setHours(0, 0, 0, 0);
      if (currentDate < fromDate || currentDate > toDate) {
        return false; // currentDate is outside the range, don't highlight
      }
      return this.FlightContractDetails.departure_days.includes(currentDate.toLocaleDateString('en-US', { weekday: 'long' }));
    } else {
      return this.DatesListArray.some(e => e == moment(currentDate).format('YYYY-MM-DD'));
    }
  };
  @ViewChild('from_date') from_date;
  @ViewChild('to_date') to_date;
  onSelect(date, caleder) {
    if (date && !this.checkDateForHighlight(date)) {
      if (caleder == 'from_date') {
        this.from_date.overlayVisible = true;
        this.Formdata.get('from_date').setValue(null);
      } else {
        this.to_date.overlayVisible = true;
        this.Formdata.get('to_date').setValue(null);
      }
    };
  };
  Option = [
    { value: 'Yes' },
    { value: 'No' },
  ];


  // copy on UI function 
  @ViewChild('is_stop_sale') is_stop_sale: ElementRef;
  @ViewChild('fare_family_group_id') fare_family_group_id: NgSelectComponent;
  @ViewChild('fare_family_name') fare_family_name: ElementRef;
  @ViewChild('adt_base_fare') adt_base_fare: ElementRef;
  @ViewChild('adt_tax') adt_tax: ElementRef;
  @ViewChild('chd_base_fare') chd_base_fare: ElementRef;
  @ViewChild('chd_tax') chd_tax: ElementRef;
  @ViewChild('inf_base_fare') inf_base_fare: ElementRef;
  @ViewChild('inf_tax') inf_tax: ElementRef;
  @ViewChild('round_trip_discount_type') round_trip_discount_type: NgSelectComponent;
  @ViewChild('is_apply_discount_with_same_vc_only') is_apply_discount_with_same_vc_only: ElementRef;
  @ViewChild('adult_round_trip_discount') adult_round_trip_discount: ElementRef;
  @ViewChild('child_round_trip_discount') child_round_trip_discount: ElementRef;
  @ViewChild('infant_round_trip_discount') infant_round_trip_discount: ElementRef;
  @ViewChild('seat_allocation') seat_allocation: ElementRef;
  @ViewChild('is_checked_bag_included') is_checked_bag_included: ElementRef;
  @ViewChild('adt_check_bag') adt_check_bag: ElementRef;
  @ViewChild('chd_check_bag') chd_check_bag: ElementRef;
  @ViewChild('inf_check_bag') inf_check_bag: ElementRef;
  @ViewChild('_check_bag_unit') _check_bag_unit: NgSelectComponent;
  @ViewChild('adt_cabin_bag') adt_cabin_bag: ElementRef;
  @ViewChild('chd_cabin_bag') chd_cabin_bag: ElementRef;
  @ViewChild('inf_cabin_bag') inf_cabin_bag: ElementRef;
  @ViewChild('_cabin_bag_unit') _cabin_bag_unit: NgSelectComponent;
  @ViewChild('refund_type') refund_type: NgSelectComponent;
  @ViewChild('pnr') pnr: ElementRef;
  @ViewChild('is_instant_confirmation') is_instant_confirmation: NgSelectComponent;
  @ViewChild('adt_fare_rule') adt_fare_rule: ElementRef;
  @ViewChild('chd_fare_rule') chd_fare_rule: ElementRef;
  @ViewChild('inf_fare_rule') inf_fare_rule: ElementRef;
  @ViewChild('is_meal_included') is_meal_included: NgSelectComponent;
  @ViewChild('meal_details') meal_details: ElementRef;
  @ViewChild('inclusions') inclusions: ElementRef;

  MainFormGrpCopyOnUI(type, name, ViewChild) {
    if (type == 'CheckBox') {
      this.FlightsRate.controls.forEach((group) => {
        group.get(name)?.setValue(ViewChild['_checked']);
        group.markAsDirty();
      })
    } else if (type == 'dropdown') {
      if (ViewChild?.selectedValues[0]?.value) this.FlightsRate.controls.forEach((group) => {
        group.get(name)?.setValue(ViewChild.selectedValues[0]?.value);
        group.markAsDirty();
      })
      else this.FlightsRate.controls.forEach((group) => {
        group.get(name)?.setValue(ViewChild.selectedValues[0]);
        group.markAsDirty();
      })
    } else if (type == 'text') {
      if (ViewChild?.nativeElement?.value) this.FlightsRate.controls.forEach((group) => {
        group.get(name)?.setValue(ViewChild.nativeElement.value);
        group.markAsDirty();
      })
      else this.FlightsRate.controls.forEach((group) => {
        group.get(name)?.setValue(ViewChild.value);
        group.markAsDirty();
      })
    }
    this.FlightsRate.updateValueAndValidity();
  };
  copyOnUiFareTypeApplicability(ViewChild, check, name) {
    this.FlightsRate.controls.forEach((group) => {
      if (check == 'dropdown') {
        if (ViewChild?.selectedValues[0]?.value) group.get(name)?.setValue(ViewChild.selectedValues[0]?.value)
        else group.get(name)?.setValue(ViewChild.selectedValues[0])
        group.markAsDirty();
      } else if (check == 'text') {
        if (ViewChild?.nativeElement?.value) group.get(name)?.setValue(ViewChild.nativeElement.value)
        else group.get(name)?.setValue(ViewChild.value)
        group.markAsDirty();
      }
    });
  };
  copyOnUiCheckedBagIncluded(ViewChild, check, name) {
    this.FlightsRate.controls.forEach((group) => {
      if (check == 'main') {
        group.get('is_checked_bag_included')?.setValue(ViewChild['_checked']);
        this.UpdateBag(group);
        group.markAsDirty();
      } else {
        if (group.get('is_checked_bag_included').value) {
          if (check == 'dropdown') {
            if (ViewChild?.selectedValues[0]?.value) group.get(name)?.setValue(ViewChild.selectedValues[0]?.value)
            else group.get(name)?.setValue(ViewChild.selectedValues[0])
            group.markAsDirty();
          } else if (check == 'text') {
            if (ViewChild?.nativeElement?.value) group.get(name)?.setValue(ViewChild.nativeElement.value)
            else group.get(name)?.setValue(ViewChild.value)
            group.markAsDirty();
          }
        };
      }
    });
  };
  copyOnUiMealIncluded(ViewChild, check, name) {
    this.FlightsRate.controls.forEach((group) => {
      if (check == 'main') {
        if (ViewChild?.selectedValues[0]?.value) group.get('is_meal_included')?.setValue(ViewChild.selectedValues[0]?.value);
        else group.get('is_meal_included')?.setValue(ViewChild.selectedValues[0])
        this.UpdateMealTypeIncluded(group);
        group.markAsDirty();
      } else {
        if (group.get('is_meal_included').value == 'Yes') {
          if (check == 'text') {
            if (ViewChild?.nativeElement?.value) group.get(name)?.setValue(ViewChild.nativeElement.value)
            else group.get(name)?.setValue(ViewChild.value)
            group.markAsDirty();
          };
        };
      }
    });
  }
  copyOnUi() {
    this.FlightsRate.controls.forEach((group) => {
      group.get('is_stop_sale')?.setValue(this.is_stop_sale['_checked']);
      group.get('fare_family_group_id')?.setValue(this.fare_family_group_id?.selectedValues[0] || null);
      group.get('fare_family_name')?.setValue(this.fare_family_name.nativeElement.value);
      group.get('adt_base_fare')?.setValue(this.adt_base_fare.nativeElement.value);
      group.get('adt_tax')?.setValue(this.adt_tax.nativeElement.value);
      group.get('chd_base_fare')?.setValue(this.chd_base_fare.nativeElement.value);
      group.get('chd_tax')?.setValue(this.chd_tax.nativeElement.value);
      group.get('inf_base_fare')?.setValue(this.inf_base_fare.nativeElement.value);
      group.get('inf_tax')?.setValue(this.inf_tax.nativeElement.value);
      if (this.FlightContractDetails?.trip_type == 'ONEWAY') {
        group.get('round_trip_discount_type')?.setValue(this.round_trip_discount_type?.selectedValues[0]?.value);
        this.UpdateValidationforDiscountTypegroup(group, this.round_trip_discount_type?.selectedValues[0]?.value);
        group.get('is_apply_discount_with_same_vc_only')?.setValue(this.is_apply_discount_with_same_vc_only['_checked']);
        group.get('adult_round_trip_discount')?.setValue(this.adult_round_trip_discount.nativeElement.value);
        group.get('child_round_trip_discount')?.setValue(this.child_round_trip_discount.nativeElement.value);
        group.get('infant_round_trip_discount')?.setValue(this.infant_round_trip_discount.nativeElement.value);
      }
      group.get('seat_allocation')?.setValue(this.seat_allocation.nativeElement.value);
      group.get('is_checked_bag_included')?.setValue(this.is_checked_bag_included['_checked']);
      this.UpdateBag(group);
      if (this.is_checked_bag_included['_checked']) {
        group.get('adt_check_bag')?.setValue(this.adt_check_bag.nativeElement.value);
        group.get('chd_check_bag')?.setValue(this.chd_check_bag.nativeElement.value);
        group.get('inf_check_bag')?.setValue(this.inf_check_bag.nativeElement.value);
        group.get('_check_bag_unit')?.setValue(this._check_bag_unit?.selectedValues[0]?.value);
      }
      group.get('adt_cabin_bag')?.setValue(this.adt_cabin_bag.nativeElement.value);
      group.get('chd_cabin_bag')?.setValue(this.chd_cabin_bag.nativeElement.value);
      group.get('inf_cabin_bag')?.setValue(this.inf_cabin_bag.nativeElement.value);
      group.get('_cabin_bag_unit')?.setValue(this._cabin_bag_unit?.selectedValues[0]?.value);
      group.get('refund_type')?.setValue(this.refund_type?.selectedValues[0]?.value);
      group.get('pnr')?.setValue(this.pnr.nativeElement.value);
      group.get('is_instant_confirmation')?.setValue(this.is_instant_confirmation?.selectedValues[0]?.value);
      group.get('adt_fare_rule')?.setValue(this.adt_fare_rule.nativeElement.value);
      group.get('chd_fare_rule')?.setValue(this.chd_fare_rule.nativeElement.value);
      group.get('inf_fare_rule')?.setValue(this.inf_fare_rule.nativeElement.value);
      group.get('is_meal_included')?.setValue(this.is_meal_included?.selectedValues[0]?.value);
      this.UpdateMealTypeIncluded(group);
      group.get('meal_details')?.setValue(this.meal_details.nativeElement.value);
      group.get('inclusions')?.setValue(this.inclusions.nativeElement.value);
    })

  };

  public dateValidation(toDate): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value) {
        if (toDate && control.value < toDate) {
          return { 'range': true };
        }
      }
      return null;
    };
  }
  Update_Validation() {
    let from_date = this.Formdata.get('from_date').value;
    if (from_date) {
      this.Formdata.get("to_date").clearValidators();
      this.Formdata.get("to_date").setErrors(null);
      this.Formdata.get("to_date").addValidators(Validators.compose([Validators.required, this.dateValidation(from_date)]));
      this.Formdata.get("to_date").updateValueAndValidity();
    }
  }
  backClick() {
    this.router.navigateByUrl("Services/FlightInventory/Search");
  }
  selectAllDays() {
    const weekDays = this.WeekDaysList.map(day => day);
    this.Formdata.controls['days'].setValue(weekDays);
  };

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

  clearAllDays() {
    this.Formdata.controls['days'].setValue([]);
  }
}
