import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormArray, FormBuilder, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { isSameDay, addDays, parseISO } from 'date-fns';
import { forkJoin, of } from 'rxjs';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { ManageHotelService } from 'src/app/core/services/HotelServices/manage-hotel.service';
import { API } from 'src/app/core/services/api.service';

@Component({
  selector: 'supplements-add',
  templateUrl: './supplements-add.component.html',
})
export class SupplementsAddComponent implements OnInit {

  Edit_Id;
  CountryList;
  timer;
  Nationality_type = [{Label:'All',Value:'ALL'},{Label:'Specific',Value:'SPECIFIC'}];
  Residence_type = [{Label:'All',Value:'ALL'},{Label:'Specific',Value:'SPECIFIC'}];
  MinDate = new Date();
  ActiveTab = 0;
  MainActiveTab = 0;
  selectAll = ['Select All'];
  SelectAllRoom = [];
  ClearAllRoom = [];
  AllDaysArr = [
    { Key: 'Mon', Value: 'Monday' },
    { Key: 'Tue', Value: 'Tuesday' },
    { Key: 'Wed', Value: 'Wednesday' },
    { Key: 'Thu', Value: 'Thursday' },
    { Key: 'Fri', Value: 'Friday' },
    { Key: 'Sat', Value: 'Saturday' },
    { Key: 'Sun', Value: 'Sunday' }
  ];
  ddLoader = {
    Country:false,
    Residence:false,
  };  Extranet_Hotel_Id;
  AllContrtact;
  enabledDates: Date[] = [];
  Supplement_Form: FormGroup;
  constructor(private router: Router,
    public activateRoute: ActivatedRoute,
    private hotelmanageserv: ManageHotelService,
    public apiserv: API, public fb: FormBuilder, public validserv: ValidationService, public commonMasterSer: CommonFunctionService) { }

  ngOnInit(): void {
    this.Extranet_Hotel_Id = this.activateRoute.snapshot.paramMap.get('Hotel_Eaxtranet_Id') as string;
    this.Edit_Id = this.activateRoute.snapshot.paramMap.get('RuleId') as string;
    this.InitForm();
    this.GetAllData();
  }

  BackButton() {
    this.hotelmanageserv.Active_tab = 'Supplements';
    this.router.navigateByUrl(`Services/Hotel/HotelManage/${this.Extranet_Hotel_Id}`);
  }
  GetAllData() {
    forkJoin(
      this.GetAllContract(),
      this.GetHotelDetail(),
      this.GetSupplementById(this.Edit_Id)
    ).subscribe(res => {
      if (res && res.length > 0) {
        this.AllContrtact = res[0].data;
        if(res[0].data){
          this.SelectAllRoom = ['Select All'];  
        }
        if (res[1] && res[1].data) this.Supplement_Form.get('currency').setValue(res[1].data.currency);
        this.SetSupplementFormValue(res[2] ? res[2].data :'')
      }
    })
  }
  GetAllContract() {
    let obj = {
      extranet_hotel_id: this.Extranet_Hotel_Id
    }
    return this.apiserv.Post('/ExtranetOffer/GetAllExtranetOfferAndSupplementContracts', obj)
  }
  GetHotelDetail() {
    return this.apiserv.Get('/ExtranetHotel/GetExtranetHotelById/' + this.Extranet_Hotel_Id)
  }
  GetSupplementById(Editid) {
    if (Editid)
      return this.apiserv.Get('/ExtranetSupplement/GetExtranetSupplementById/' + Editid)
    else
      return of(null)
  };
  InitForm() {
    this.Supplement_Form = this.fb.group({
      extranet_room_id: this.validserv.required,
      currency: '',
      extranet_supplement_id: '',
      supplement_name: this.validserv.required,
      supplement_nationality_type: '',
      nationality_applicable_type:  '',
      supplement_days: this.validserv.required,
      supplement_rate_type: this.validserv.required,
      residence_type:'',
      dinner_supplement:false,
      residence_applicable_type:'',
      supplement_type: this.validserv.required,
      supplement_dates: this.fb.array([]),
      ExtranetSupplementNewRate:this.fb.array([]),
      // AdultNewRates: this.fb.group({
      //   Adult_Contract_Arr: this.fb.array([]),
      //   Copy_Group: this.fb.group({})
      // }),
      // ChildNewRates1: this.fb.group({
      //   Child_Contract_Arr: this.fb.array([]),
      //   Copy_Group: this.fb.group({})
      // }),
      // ChildNewRates2: this.fb.group({
      //   Child_Contract_Arr: this.fb.array([]),
      //   Copy_Group: this.fb.group({})
      // }),
    });
    this.addDate()
  }
  getCountryList(event,name) {
    if (event.value.length >= 2) {
      this.ddLoader[name] = true;
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.apiserv.AdminGet(`/MasterSearch/GetAllCountry/en/${event.value}`).subscribe(res => {
          if (res) {
            this.CountryList = res;
            this.ddLoader[name] = false;
          }
        });
      }, 500);
    }
  }
  NationalityShowhide(event) {
    if (event == 'SPECIFIC') {
      this.Supplement_Form.addControl('nationality', new FormControl('', Validators.required))
    } else {
      this.Supplement_Form.removeControl('nationality');
    }
  }
  NationalityTypeCheck(event){
    if(event == 'INCLUDE'){
      this.Nationality_type = [{Label:'All',Value:'ALL'},{Label:'Specific',Value:'SPECIFIC'}];
    }else{
      this.Nationality_type = [{Label:'Specific',Value:'SPECIFIC'}];
      if(this.Supplement_Form.controls['nationality_applicable_type'].value == 'ALL'){
        this.Supplement_Form.get('nationality_applicable_type').setValue('');
      }
    }
  }
  Check_day_type() {
    let daysArr = [
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
      'Sunday'
    ];
    let value = this.Supplement_Form.get('supplement_days').value;
    if (value && value.length > 0 && (value.includes('Select All') || value.length == 7)) {
      this.Supplement_Form.get('supplement_days').setValue(daysArr);
      this.selectAll = [];
    } else {
      this.selectAll = ['Select All'];
    }
    this.CheckRateCriteria();
  }

  Check_Supplement_Rate_Type(value) {
    if (value == 'PERROOMPERNIGHT') {
      this.Supplement_Form.addControl('per_room_per_night_supplement_rate', new FormControl('', Validators.required));
      this.Supplement_Form.removeControl('supplement_type');
    } else {
      this.Supplement_Form.removeControl('per_room_per_night_supplement_rate');
      this.Supplement_Form.addControl('supplement_type', new FormControl('', Validators.required));

    }
    this.CheckRateCriteria();
  }
  addDate() {
    let formArray = this.Supplement_Form.controls['supplement_dates'] as FormArray;
    let date = new Date();
    let currentDate = date;
    currentDate = new Date(currentDate.getTime() - 1 * 24 * 60 * 60 * 1000);
    // if(formArray.length > 0){
    if (formArray.length > 0) {
      let formdate = formArray.controls[formArray.length - 1].get('date').value;
      if (formdate && formdate.length == 2) {
        currentDate = formdate[1];
      }
    }
    formArray.push(this.fb.group({
      date: ['', Validators.compose([
        Validators.required,
        this.dateValidation(currentDate)
      ])]
    }));
    //  }
  }
  public dateValidation(toDate): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value) {
        if (control.value.length <= 1 || control.value[1] == null) {
          return { 'todate': true };
        }
        if (toDate && control.value.length <= 1 || control.value[0] <= toDate) {
          return { 'range': true };
        }
      }
      return null;
    };
  }
  removeDate(index) {
    let formArray = this.Supplement_Form.controls['supplement_dates'] as FormArray;
    formArray.removeAt(index);
    let date = new Date();
    let currentDate = date;
    currentDate = new Date(currentDate.getTime() - 1 * 24 * 60 * 60 * 1000);
    if (formArray.length > 0) {
      if (index > 0) {
        let formdate = formArray.controls[index - 1].get('date').value;
        if (formdate && formdate.length == 2) {
          currentDate = formdate[1];
        }
      }
      if (formArray.controls.length >= (index + 1)) {
        formArray.controls[index].get("date").clearValidators();
        formArray.controls[index].get("date").setErrors(null);
        formArray.controls[index].get("date").addValidators([Validators.required, this.dateValidation(currentDate)]);
        // formArray.controls[index].get("date").markAsTouched();
        formArray.controls[index].get("date").updateValueAndValidity();
        // formArray.controls[index].get("date").markAsTouched();
      }
    }
    this.CheckRateCriteria();
  }
  CloseCalender(element, index) {
    let formArray = this.Supplement_Form.controls['supplement_dates']['controls'];
    if (element.value[0] && element.value[1]) {
      element.overlayVisible = false;
      element.datepickerClick = true;
      if (formArray.length >= (index + 2)) {
        formArray[index + 1].get("date").clearValidators();
        formArray[index + 1].get("date").setErrors(null);
        formArray[index + 1].get("date").addValidators([Validators.required, this.dateValidation(element.value[1])]);
        formArray[index + 1].get("date").markAsTouched();
        formArray[index + 1].get("date").updateValueAndValidity();
        formArray[index + 1].get("date").markAsTouched();
      }
      this.CheckRateCriteria();
    }
  }
  CheckRateCriteria(adultarr?,child1arr?,child2arr?) {
    let rate_type = this.Supplement_Form.controls['supplement_rate_type'] ? this.Supplement_Form.get('supplement_rate_type').value : '';
    let supplement_type = this.Supplement_Form.controls['supplement_type'] ? this.Supplement_Form.get('supplement_type').value : '';
    let contract_id = this.Supplement_Form.get('extranet_room_id').value;
    if (contract_id && contract_id.length > 0 && (contract_id.includes('Select All') || contract_id.length == this.AllContrtact.length) && !contract_id.includes('Clear All')) {
      let room_id_List = []
      this.AllContrtact.forEach(d=>{
        room_id_List.push(d.extranet_room_id)
      });
      this.Supplement_Form.get('extranet_room_id').setValue(room_id_List);
      this.SelectAllRoom = [];
      this.ClearAllRoom = ['Clear All'];
    } else if (contract_id && contract_id.length > 0 && (contract_id.includes('Clear All'))){
      this.Supplement_Form.get('extranet_room_id').setValue([]);
      this.SelectAllRoom = ['Select All'];
      this.ClearAllRoom = [];
    } else {
      this.SelectAllRoom = ['Select All'];
      if(contract_id?.length > 0){
        this.ClearAllRoom = ['Clear All'];
      }
    }
    if(rate_type == 'PERPAXPERSTAY' && supplement_type == 'NEWRATE'){
      this.Supplement_Form.get('supplement_type').setValue('');
    }
    contract_id = this.Supplement_Form.get('extranet_room_id').value;
    let contract_filter_data = this.AllContrtact.filter(e => contract_id.includes(e.extranet_room_id));
    if(contract_id?.length != this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'].length){
      for(let i = this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'].length -1; i >= 0 ;i--){
        let new_rate_contract_id = this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][i].get('extranet_room_id').value
        if(!contract_id.includes(new_rate_contract_id)){
          let formArray = this.Supplement_Form.get('ExtranetSupplementNewRate') as FormArray;
          formArray.removeAt(i);
        }
      }
    }
    contract_filter_data.forEach((contract_data,contract_ind)=>{
      let selected_rooms_arr = [];
      this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'].forEach(control=>{
        selected_rooms_arr.push(control.get('extranet_room_id').value)
      })
      if(!selected_rooms_arr.includes(contract_data.extranet_room_id)){
        let formArray = this.Supplement_Form.get('ExtranetSupplementNewRate') as FormArray;
        formArray.push(this.fb.group({
          extranet_room_name:contract_data.room_name,
          extranet_room_id:contract_data.extranet_room_id,
          Child_range1: '',
          Child_range2: '',
          AdultNewRates: this.fb.group({
            Adult_Contract_Arr: this.fb.array([]),
            Copy_Group: this.fb.group({})
          }),
          ChildNewRates1: this.fb.group({
            Child_Contract_Arr: this.fb.array([]),
            Copy_Group: this.fb.group({})
          }),
          ChildNewRates2: this.fb.group({
            Child_Contract_Arr: this.fb.array([]),
            Copy_Group: this.fb.group({})
          }),
        }));
      }
      contract_data = contract_filter_data.find(e=> e.extranet_room_id == this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].get('extranet_room_id').value)
      // this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].get('extranet_room_name').setValue(contract_data.room_name);
      let range = contract_data ? JSON.parse(contract_data.age_range) : [];
      range.forEach((data, ind) => {
        this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].get('Child_range' + (ind + 1)).setValue(data.from + ' to ' + data.to);
      })
      if ((rate_type == 'PERPAXPERSTAY' || rate_type == 'PERPAXPERNIGHT') && supplement_type == 'ADDONRATE') {
        if (!this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].contains('addon_adult_rate')) {
          this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].addControl(`addon_adult_rate`, this.validserv.required);
        }
        if (contract_data) {
          range.forEach((data, ind) => {
            if (!this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind]?.contains(`addon_child_age_range${ind + 1}_rate`)) {
              this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].addControl(`addon_child_age_range${ind + 1}_rate`, this.validserv.required);
            }
          });
          if (range.length <= 1) {
            this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].removeControl(`addon_child_age_range2_rate`);
            if (range.length == 0) {
              this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].removeControl(`addon_child_age_range1_rate`);
            }
          }
        }
        this.RemovePaxControls(this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls['AdultNewRates'],'Adult_Contract_Arr');
        this.RemovePaxControls(this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls['ChildNewRates1'],'Child_Contract_Arr');
        this.RemovePaxControls(this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls['ChildNewRates2'],'Child_Contract_Arr');
      }
      else if (rate_type == 'PERPAXPERNIGHT' && supplement_type == 'NEWRATE' && this.Supplement_Form.get('supplement_days').value && contract_data) {
        // let dates = [];
        if(!this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind]?.get('ChildNewRates1')){
          this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].addControl('ChildNewRates1',new FormGroup({}))
        }
        if(!this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind]?.get('ChildNewRates2')){
          this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].addControl('ChildNewRates2',new FormGroup({}))
        }
        if(!this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind]?.get('AdultNewRates')){
          this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].addControl('AdultNewRates',new FormGroup({}))
        }
        this.enabledDates = [];
        let date_range_arr = this.Supplement_Form.get('supplement_dates').value;
        let weekDays = this.Supplement_Form.get('supplement_days').value;
        let ChildArr1 = this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].get('ChildNewRates1') as FormGroup;
        let ChildArr2 = this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].get('ChildNewRates2') as FormGroup;
        let AdultArr = this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].get('AdultNewRates') as FormGroup;
        let ChildArrValue1 = ChildArr1.contains('Child_Contract_Arr') ? ChildArr1.get('Child_Contract_Arr').value : [];
        let ChildArrValue2 = ChildArr2.contains('Child_Contract_Arr') ? ChildArr2.get('Child_Contract_Arr').value : [];
        let AdultArrValue = AdultArr.contains('Adult_Contract_Arr') ? AdultArr.get('Adult_Contract_Arr').value : [];
        let CopyAdultArrValue = AdultArr.contains('Copy_Group') ? AdultArr.get('Copy_Group').value : [];
        let CopyChild1ArrValue = ChildArr1.contains('Copy_Group') ? ChildArr1.get('Copy_Group').value : [];
        let CopyChild2ArrValue = ChildArr2.contains('Copy_Group') ? ChildArr2.get('Copy_Group').value : [];
  
        if(adultarr)AdultArrValue = adultarr;
        if(child1arr)ChildArrValue1 = child1arr;
        if(child2arr)ChildArrValue2 = child2arr;
  
        date_range_arr.forEach(date_range => {
          if (date_range && date_range.date[0] && date_range.date[1]) {
            const startDate = new Date(date_range.date[0]);
            const endDate = date_range.date[1];
            startDate.setHours(0, 0, 0, 0);
            endDate.setHours(0, 0, 0, 0);
            for (let d = startDate; d <= endDate; d = addDays(d, 1)) {
              const dayName = moment(d).format('dddd'); // Get the day name (e.g., 'Monday')
              if (weekDays.includes(dayName)) {
                this.enabledDates.push(d);
              }
            }
          }
        })
        //Adult Occupancy data
        // this.RemovePaxControls(this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind]['controls']['AdultNewRates'],'Adult_Contract_Arr')
        let adult_copy_group = this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind]['controls']['AdultNewRates']['controls']['Copy_Group'] as FormGroup;
        for (let i = 1; i <= contract_data['max_adult_occupancy']; i++) {
          if(!adult_copy_group.get(`adult_${i}`)){
            adult_copy_group.addControl(`adult_${i}`, new FormControl(CopyAdultArrValue ? CopyAdultArrValue[`adult_${i}`] : ''));
          }
        }
  
        //Child range 1 occupancy data
          // this.RemovePaxControls(this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind]['controls']['ChildNewRates1'],'Child_Contract_Arr')
        let child_copy_group1 = ChildArr1['controls']['Copy_Group'] as FormGroup;
        for (let i = 1; i <= contract_data['max_child_occupancy']; i++) {
          if(!child_copy_group1.get(`child_${i}`)){
            child_copy_group1.addControl(`child_${i}`, new FormControl(CopyChild1ArrValue ? CopyChild1ArrValue[`child_${i}`] : ''))
          }
        }
  
        //child range 2 occupancy data
          // this.RemovePaxControls(this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls['ChildNewRates2'],'Child_Contract_Arr')
          let child_copy_group2 = ChildArr2['controls']['Copy_Group'] as FormGroup;
          for (let i = 1; i <= contract_data['max_child_occupancy']; i++) {
            if(!child_copy_group2.get(`child_${i}`)){
              child_copy_group2.addControl(`child_${i}`, new FormControl(CopyChild2ArrValue ? CopyChild2ArrValue[`child_${i}`] : ''))
            }
          }
        if (this.enabledDates.length > 0) {
          this.enabledDates.sort((a, b) => new Date(a).getTime() - new Date(b).getTime());
          let selected_date_arr = [];
          this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls['AdultNewRates']['controls']['Adult_Contract_Arr']['controls'].forEach(adult_group=>{
            selected_date_arr.push(adult_group.get('date').value)
          })
          this.enabledDates.forEach(dates_data => {
            // Adult Table data
            if(!selected_date_arr.includes(moment(dates_data).format('DD MMM YYYY'))){
              this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls['AdultNewRates']['controls']['Adult_Contract_Arr'].push(this.fb.group({
                date: moment(dates_data).format('DD MMM YYYY')
              }))
              let adultformgroup = this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls['AdultNewRates']['controls']['Adult_Contract_Arr']['controls'][this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls['AdultNewRates']['controls']['Adult_Contract_Arr']['controls'].length - 1] as FormGroup;
              let setvalue_data;
              if (AdultArrValue && AdultArrValue.length > 0) {
                setvalue_data = AdultArrValue.find(e => moment(dates_data).format('DD MMM YYYY') == e.date);
              }
              // adultformgroup.addControl('date',new FormControl(moment(dates_data).format('DD MMM YYYY')));
              for (let i = 1; i <= contract_data['max_adult_occupancy']; i++) {
                if(!adultformgroup.get(`adult_${i}`)){
                  adultformgroup.addControl(`adult_${i}`, new FormControl((setvalue_data && setvalue_data[`adult_${i}`] ? setvalue_data[`adult_${i}`] : 0), Validators.required));
                }
              }
    
              //child Table data
              for (let i = 1; i <= range.length; i++) {
                this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls[`ChildNewRates${i}`]['controls']['Child_Contract_Arr'].push(this.fb.group({
                  date: moment(dates_data).format('DD MMM YYYY')
                }))
                let childformgroup = this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls[`ChildNewRates${i}`]['controls']['Child_Contract_Arr']['controls'][this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls[`ChildNewRates${i}`]['controls']['Child_Contract_Arr']['controls'].length - 1] as FormGroup;
                let setvalue_data;
                if (ChildArrValue1 && ChildArrValue1.length > 0 && i == 1) {
                  setvalue_data = ChildArrValue1.find(e => moment(dates_data).format('DD MMM YYYY') == e.date);
                }
                if (ChildArrValue2 && ChildArrValue2.length > 0 && i == 2) {
                  setvalue_data = ChildArrValue2.find(e => moment(dates_data).format('DD MMM YYYY') == e.date);
                }
                for (let i = 1; i <= contract_data['max_child_occupancy']; i++) {
                  if(!childformgroup.get(`child_${i}`)){
                    childformgroup.addControl(`child_${i}`, new FormControl((setvalue_data && setvalue_data[`child_${i}`] ? setvalue_data[`child_${i}`] : 0), Validators.required));
                  }
                }
              }
            }
          })
        }
        this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].removeControl(`addon_child_age_range2_rate`);
        this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].removeControl(`addon_child_age_range1_rate`);
        this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].removeControl(`addon_adult_rate`);
      } else {
        this.RemovePaxControls(this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls['AdultNewRates'],'Adult_Contract_Arr');
        this.RemovePaxControls(this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls['ChildNewRates1'],'Child_Contract_Arr');
        this.RemovePaxControls(this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].controls['ChildNewRates2'],'Child_Contract_Arr');
        this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].removeControl(`addon_child_age_range2_rate`);
        this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].removeControl(`addon_child_age_range1_rate`);
        this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].removeControl(`addon_adult_rate`);
      }
      this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][contract_ind].updateValueAndValidity();
    })
  }
  RemovePaxControls(formarray,formGroup){
    if(formarray){
      let Pax_Value_Group = formarray['controls'][formGroup] as FormArray;
      for (let i = Pax_Value_Group.controls.length - 1; i >= 0; i--) {
        Pax_Value_Group.removeAt(i);
      }
      let copy_group = formarray['controls']['Copy_Group'] as FormGroup;
        Object.keys(copy_group.controls).forEach(key => {
          copy_group.removeControl(key);
        });
    }
  }
  Adultcopycolumn(colname, ind, controlval?) {
    let value = controlval ? controlval : this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][ind].controls['AdultNewRates']['controls']['Adult_Contract_Arr']['controls'][0].get(colname).value;
    if (this.enabledDates && this.enabledDates.length > 0) {
      for (let i = 0; i < this.enabledDates.length; i++) {
        this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][ind].controls['AdultNewRates']['controls']['Adult_Contract_Arr']['controls'][i].get(colname).setValue(value);
      }
    }
  }
  AdultCopyOnUi(ind) {
    let val = this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][ind].controls['AdultNewRates']['controls']['Copy_Group'].getRawValue();
    let contract_id = this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][ind].get('extranet_room_id').value
    let contract_data = this.AllContrtact.find(e => contract_id.includes(e.extranet_room_id));
    for (let i = 1; i <= contract_data['max_adult_occupancy']; i++) {
      if (val[`adult_${i}`]) {
        this.Adultcopycolumn(`adult_${i}`,ind, val[`adult_${i}`]);
      }
    }
  }
  CheckTabInd(event){
    this.ActiveTab = event.index;
  }
  Childcopycolumn(colname, formgroup, ind, controlval?) {
    let value = controlval ? controlval : this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][ind].controls[formgroup]['controls']['Child_Contract_Arr']['controls'][0].get(colname).value;
    if (this.enabledDates && this.enabledDates.length > 0) {
      for (let i = 0; i < this.enabledDates.length; i++) {
        this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][ind].controls[formgroup]['controls']['Child_Contract_Arr']['controls'][i].get(colname).setValue(value);
      }
    }
  }
  ChildCopyOnUi(formgroup,ind) {
    let val = this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][ind].controls[formgroup]['controls']['Copy_Group'].getRawValue();
    let contract_id = this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][ind].get('extranet_room_id').value;
    let contract_data = this.AllContrtact.find(e => contract_id.includes(e.extranet_room_id));
    for (let i = 1; i <= contract_data['max_child_occupancy']; i++) {
      if (val[`child_${i}`]) {
        this.Childcopycolumn(`child_${i}`, formgroup, ind, val[`child_${i}`]);
      }
    }
  }
  Save(){
    this.Supplement_Form.updateValueAndValidity();
    if (this.Supplement_Form.status == "VALID") {
      let val = this.Supplement_Form.getRawValue();
      let mainObj = [];
      val.ExtranetSupplementNewRate.forEach((new_rate_det,room_ind)=>{
        let PostObj={
          extranet_supplement_id:val.extranet_supplement_id,
          extranet_room_id:val.extranet_room_id[room_ind],
          supplement_name:val.supplement_name,
          dinner_supplement:val.supplement_rate_type == 'PERPAXPERNIGHT'? val.dinner_supplement : false,
          supplement_nationality_type:val.supplement_nationality_type ? val.supplement_nationality_type : '',
          nationality_applicable_type:val.nationality_applicable_type ? val.nationality_applicable_type : '',
          nationality:val.nationality ? val.nationality.join(',') : '',
          residence_type:val.residence_type,
          residence_applicable_type:val.residence_applicable_type,
          residence:val.residence_applicable_type == 'SPECIFIC' ? val.residence.join(',') : '',
          supplement_dates:'',
          supplement_days:val.supplement_days ? val.supplement_days.join(',') : '',
          supplement_rate_type:val.supplement_rate_type,
          supplement_type:val.supplement_type,
          per_room_per_night_supplement_rate:val.per_room_per_night_supplement_rate ? parseFloat(val.per_room_per_night_supplement_rate) : 0,
          addon_adult_rate:new_rate_det.addon_adult_rate ? parseFloat(new_rate_det.addon_adult_rate) : 0,
          addon_child_age_range1_rate:new_rate_det.addon_child_age_range1_rate ? parseFloat(new_rate_det.addon_child_age_range1_rate) : 0,
          addon_child_age_range2_rate:new_rate_det.addon_child_age_range2_rate ? parseFloat(new_rate_det.addon_child_age_range2_rate) : 0,
          ExtranetSupplementNewRate:[]
        }
        let date_Arr = [];
        val.supplement_dates.forEach(season_date=>{
          date_Arr.push({
            from: moment(season_date.date[0]).format('YYYY-MM-DD'),
            to: moment(season_date.date[1]).format('YYYY-MM-DD'),
          })
        });
        PostObj.supplement_dates = JSON.stringify(date_Arr);
        if((val.supplement_rate_type == 'PERPAXPERNIGHT' || val.supplement_rate_type == 'PERPAXPERSTAY') && val.supplement_type == 'NEWRATE'){
          this.enabledDates.forEach((date,ind)=>{
            let array_obj = {
              date : moment(date).format('YYYY-MM-DD')
            }
            let contract_data = this.AllContrtact.find(e => val.extranet_room_id.includes(e.extranet_room_id));
            let range = contract_data ? JSON.parse(contract_data.age_range) : [];
            if(new_rate_det.AdultNewRates.Adult_Contract_Arr && new_rate_det.AdultNewRates.Adult_Contract_Arr.length > 0){
              for (let i = 1; i <= contract_data['max_adult_occupancy']; i++) {
                array_obj[`adult_${i}`] = parseFloat(new_rate_det.AdultNewRates.Adult_Contract_Arr[ind][`adult_${i}`])
              }
            }
            range.forEach((data, index) => {
              if(new_rate_det[`ChildNewRates${index+1}`].Child_Contract_Arr && new_rate_det[`ChildNewRates${index+1}`].Child_Contract_Arr.length > 0){
                for (let i = 1; i <= contract_data['max_child_occupancy']; i++) {
                  array_obj[`age_range${index+1}_child_${i}`] = parseFloat(new_rate_det[`ChildNewRates${index+1}`].Child_Contract_Arr[ind][`child_${i}`])
                }
              }
            })
            PostObj.ExtranetSupplementNewRate.push(array_obj);
          })
        }
        mainObj.push(PostObj);
      })
      

      // console.log(PostObj);
      this.apiserv.Post('/ExtranetSupplement/SaveExtranetSupplement',mainObj).subscribe(resp=>{
        if(resp){
          this.commonMasterSer.showMessage(resp.status,resp.message);
          resp.status ? this.BackButton() : '';
        }
      })
    }else {
      this.validserv.showValidationsMsg(this.Supplement_Form);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
    }
  }
  SetSupplementFormValue(data){
    if(data){
      this.Supplement_Form.get('extranet_room_id').setValue(data.extranet_room_id ? data.extranet_room_id.split(',') : []);
      this.Supplement_Form.get('extranet_room_id').disable();
      this.Supplement_Form.get('extranet_supplement_id').setValue(data.extranet_supplement_id);
      this.Supplement_Form.get('supplement_name').setValue(data.supplement_name);
      this.Supplement_Form.get('supplement_nationality_type').setValue(data.supplement_nationality_type);
      this.Supplement_Form.get('nationality_applicable_type').setValue(data.nationality_applicable_type);
      this.Supplement_Form.get('supplement_days').setValue(data.supplement_days ? data.supplement_days.split(','):'');
      this.Supplement_Form.get('supplement_rate_type').setValue(data.supplement_rate_type);
      this.Supplement_Form.get('supplement_type').setValue(data.supplement_type);
      this.Supplement_Form.get('dinner_supplement').setValue(data.dinner_supplement);
      this.Supplement_Form.get('supplement_rate_type').disable()
      this.Supplement_Form.get('supplement_type').disable();
      this.Check_Supplement_Rate_Type(data.supplement_rate_type);
      this.Supplement_Form.get('residence_type').setValue(data.residence_type);
      this.Supplement_Form.get('residence_applicable_type').setValue(data.residence_applicable_type);
      if(data.residence_applicable_type == 'SPECIFIC'){
        this.ResidenceShowhide(data.residence_applicable_type);
        this.Supplement_Form.get('residence').setValue((data.residence.split(',')));
        this.CountryList = data.country ? JSON.parse(data.country) : [];
      }
      if(data.supplement_rate_type == 'PERROOMPERNIGHT'){
        this.Supplement_Form.get('per_room_per_night_supplement_rate').setValue(data.per_room_per_night_supplement_rate);
      }
      if(data.nationality_applicable_type == 'SPECIFIC'){
        this.NationalityShowhide('SPECIFIC');
        this.Supplement_Form.get('nationality').setValue(data.nationality.split(','));
        this.CountryList = data.country ? JSON.parse(data.country) : [];
      }
      if(data.supplement_dates){
        let dates_arr = JSON.parse(data.supplement_dates);
        dates_arr.forEach((dates,ind)=>{
          if(ind > 0)this.addDate();
          this.Supplement_Form.controls['supplement_dates']['controls'][ind]['controls']['date'].setValue([new Date(dates.from),new Date(dates.to)])
        })
      }
      if((data.supplement_rate_type == 'PERPAXPERSTAY' ||data.supplement_rate_type == 'PERPAXPERNIGHT') && data.supplement_type == 'ADDONRATE'){
        this.CheckRateCriteria(); 
        this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][0].get('addon_adult_rate').setValue(data.addon_adult_rate);
        if(data.addon_child_age_range1_rate)this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][0].get('addon_child_age_range1_rate').setValue(data.addon_child_age_range1_rate);
        if(data.addon_child_age_range2_rate)this.Supplement_Form.controls['ExtranetSupplementNewRate']['controls'][0].get('addon_child_age_range2_rate').setValue(data.addon_child_age_range2_rate);
      }
      if((data.supplement_rate_type == 'PERPAXPERSTAY' ||data.supplement_rate_type == 'PERPAXPERNIGHT') && data.supplement_type == 'NEWRATE'){
        let Child1arr = [];
        let Child2arr = [];
        let adultarr = [];
        data.ExtranetSupplementNewRate.forEach(data_on_date=>{
          Child1arr.push({
            date:moment(data_on_date.date).format('DD MMM YYYY'),
            child_1:data_on_date.age_range1_child_1,
            child_2:data_on_date.age_range1_child_2,
            child_3:data_on_date.age_range1_child_3,
            child_4:data_on_date.age_range1_child_4,
            child_5:data_on_date.age_range1_child_5,
            child_6:data_on_date.age_range1_child_6,
          })
          Child2arr.push({
            date:moment(data_on_date.date).format('DD MMM YYYY'),
            child_1:data_on_date.age_range2_child_1,
            child_2:data_on_date.age_range2_child_2,
            child_3:data_on_date.age_range2_child_3,
            child_4:data_on_date.age_range2_child_4,
            child_5:data_on_date.age_range2_child_5,
            child_6:data_on_date.age_range2_child_6,
          })
          adultarr.push({
            date:moment(data_on_date.date).format('DD MMM YYYY'),
            adult_1:data_on_date.adult_1,
            adult_2:data_on_date.adult_2,
            adult_3:data_on_date.adult_3,
            adult_4:data_on_date.adult_4,
            adult_5:data_on_date.adult_5,
            adult_6:data_on_date.adult_6
          })
        })
        this.CheckRateCriteria(adultarr,Child1arr,Child2arr);
      }
    }
  }
  ResidenceTypeCheck(event){
    if(event == 'INCLUDE'){
      this.Residence_type = [{Label:'All',Value:'ALL'},{Label:'Specific',Value:'SPECIFIC'}];
    }else{
      this.Residence_type = [{Label:'Specific',Value:'SPECIFIC'}];
      if(this.Supplement_Form.controls['residence_applicable_type'].value == 'ALL'){
        this.Supplement_Form.get('residence_applicable_type').setValue('');
      }
    }
  }
  ResidenceShowhide(event){
    if(event == 'SPECIFIC'){
      this.Supplement_Form.addControl('residence',new FormControl('',Validators.required))
    }else{
      this.Supplement_Form.removeControl('residence');
    }
  }
    CheckTabMainInd(event){
    this.MainActiveTab = event.index;
}
}
