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 { 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: 'app-rate-setting-add',
  templateUrl: './rate-setting-add.component.html',
})
export class RateSettingAddComponent implements OnInit {
  displayPosition: boolean;
  position: string;
  ActiveTab = 0;
  Extranet_Hotel_Id;
  Clone_Rule;
  SelectAllRoom = [];
  ClearAllRoom = [];
  CancelModal = false;
  HotelRoomContractForm:FormGroup;
  AllRoomsData;
  Nationality_type = [{Label:'All',Value:'ALL'},{Label:'Specific',Value:'SPECIFIC'}];
  Residence_type = [{Label:'All',Value:'ALL'},{Label:'Specific',Value:'SPECIFIC'}];
  AllRatePlan;
  timer;
  Season_List = [];
  Selected_Room_List = [];
  AllSeason;
  SelectAll=["Select All"];
  showRate_Plan_Name;
  showRate_meal_Name;
  AllMeal;
  MinDate = new Date();
  CountryList;
  Edit_Id;
  AllMealPlan;
  ddLoader = {
    Country:false,
    Residence:false,
  }
  IsMobile;
  AllDaysArr = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  SelectAllVal=[];
  DaysArrValue=[];
  constructor(public activateRoute:ActivatedRoute,private router:Router,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.Clone_Rule = this.activateRoute.snapshot['_routerState'].url.includes('CloneContract') && this.Edit_Id ? true :false;
    this.InitForm();
    this.getAllData();
  }
  CheckTabInd(event){
    this.ActiveTab = event.index;
}
  InitForm(){
    this.HotelRoomContractForm = this.fb.group({
      room_name:this.validserv.required,
      extranet_rate_plan_id:this.validserv.required,
      extranet_meal_plan_id:this.validserv.required,
      currency_code:'',
      nationality_type:'',
      nationality_applicable_type:'',
      residence_type:'',
      residence_applicable_type:'',
      date_type:this.validserv.required,
      is_meal_addon_applicable:false,
      RoomPricingDetail:this.fb.array([])
    });
  }
  getAllData() {
    forkJoin(
      this.GetAllRooms(),
      this.GetAllPlan(),
      this.GetAllMealPlan(),
      this.GetHotelDataById(),
      this.GetAllSeason(),
      this.GetAllMeal(),  
      this.GetContractById(this.Edit_Id)
    ).subscribe(res=>{
      if(res && res.length > 0){
        this.AllRoomsData = res[0] ? res[0].data : [];
        if(res[0].data){
          this.SelectAllRoom = ['Select All'];
        }
        this.AllRatePlan = res[1] ? res[1].data : [];
        this.AllMealPlan = res[2].data;
        this.HotelRoomContractForm.get('currency_code').setValue(res[3].data ? res[3].data['currency'] : '');
        this.AllSeason = res[4].data ? res[4].data : [];
        this.AllMeal = res[5].data ? res[5].data : [];
        this.SetContractFormValue(res[6] ? res[6].data :'')
      }
    });
  }
  GetContractById(Editid) {
    if (Editid)
      return this.apiserv.Get('/ExtranetRoomContract/GetExtranetRoomContractById/' + Editid)
    else
      return of(null)
  };
  GetAllPlan(){
    return this.apiserv.Get('/ExtranetRoomContract/GetAllExtranetHotelRatePlan/EN')
  }
  GetAllMeal(){
    return this.apiserv.Get('/ExtranetMealAddon/GetAllExtranetMealAddonByOrg/'+ this.Extranet_Hotel_Id)
  }
  GetAllRooms(){
    let ReqObj = {
      extranet_hotel_id : this.Extranet_Hotel_Id,
      extranet_room_id : '',
      room_name : '',
      room_view_name : '',
    }
    return this.apiserv.Post('/ExtranetRoomContract/GetAllExtranetHotelRoomName',ReqObj)
  }
  GetHotelDataById() {
    if (this.Extranet_Hotel_Id)
      return this.apiserv.Get('/ExtranetHotel/GetExtranetHotelById/' + this.Extranet_Hotel_Id)
    else
      return of(null)
  };
  GetAllMealPlan(){
    return this.apiserv.Get('/ExtranetMealAddon/GetAllExtranetMeal/EN')
  }
  GetAllSeason(){
    let ReqObj = {
      season_name:'',
      hotel_id:this.Extranet_Hotel_Id
    }
    return this.apiserv.Post('/ExtranetSeason/GetAllExtranetSeason',ReqObj)
  }
  showPositionDialog(position) {
    this.position = position;
    this.displayPosition = true;
  };

  BackButton(){
    this.hotelmanageserv.Active_tab = 'RoomContract';
    this.router.navigateByUrl(`Services/Hotel/HotelManage/${this.Extranet_Hotel_Id}`);
  }
  NationalityShowhide(event){
    if(event == 'SPECIFIC'){
      this.HotelRoomContractForm.addControl('nationality',new FormControl('',Validators.required))
    }else{
      this.HotelRoomContractForm.removeControl('nationality');
    }
  }
  ResidenceShowhide(event){
    if(event == 'SPECIFIC'){
      this.HotelRoomContractForm.addControl('residence',new FormControl('',Validators.required))
    }else{
      this.HotelRoomContractForm.removeControl('residence');
    }
  }
  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.HotelRoomContractForm.controls['nationality_applicable_type'].value == 'ALL'){
        this.HotelRoomContractForm.get('nationality_applicable_type').setValue('');
      }
    }
  }
  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.HotelRoomContractForm.controls['residence_applicable_type'].value == 'ALL'){
        this.HotelRoomContractForm.get('residence_applicable_type').setValue('');
      }
    }
  }
  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);
    }
  }
  ShowDateTypeFields(event){
    this.Season_List = [];
    if(event == 'SPECIFICDATES'){
      this.HotelRoomContractForm.addControl('ContractDatesArr',new FormArray([this.fb.group({
        date:['', Validators.compose([Validators.required, this.dateValidation(new Date(new Date().setDate(new Date().getDate() - 1)))])],
      })]));
      this.HotelRoomContractForm.removeControl('Season_Id');
    }else if(event == 'SEASON'){
      this.HotelRoomContractForm.addControl('Season_Id',new FormControl('',Validators.required))
      this.HotelRoomContractForm.removeControl('ContractDatesArr');
    }else {
      this.HotelRoomContractForm.removeControl('Season_Id');
      this.HotelRoomContractForm.removeControl('ContractDatesArr');
    }
  }
  addDate() {
    let formArray = this.HotelRoomContractForm.controls['ContractDatesArr'] 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({
        extranet_season_detail_id:'',
        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.HotelRoomContractForm.controls['ContractDatesArr'] 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();
      }
    }
  }
  CloseCalender(element, index) { 
    let formArray = this.HotelRoomContractForm.controls['ContractDatesArr']['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();
      }
    }
  }
  MealHideShow(check){
    if(check){
      this.HotelRoomContractForm.addControl('extranet_meal_addon_id',new FormControl('',Validators.required))
    }else {
      this.HotelRoomContractForm.removeControl('extranet_meal_addon_id');
    }
  }
  SeasonDataAddRemove(){
    this.Season_List = [];
    let selected_season = this.HotelRoomContractForm.controls['Season_Id'].value;
    selected_season.forEach(data=>{
      let matched_season_by_id = this.AllSeason.find(e=>e.extranet_season_id == data);
      if(matched_season_by_id){
        if(typeof(matched_season_by_id['date_range']) == 'string'){
          matched_season_by_id['date_range'] = matched_season_by_id.date_range.split(', ');
          matched_season_by_id['date_range'].forEach((z,i)=>{
            matched_season_by_id['date_range'][i] =  moment(z.split(' - ')[0]).format('DD MMM YYYY') + ' to ' + moment(z.split(' - ')[1]).format('DD MMM YYYY')
          })
        }
        this.Season_List.push(matched_season_by_id);
        console.log(this.Season_List)
      }
    })
  }
  AddRemoveRoomContract(event,formVal?){
    const contract_id = this.HotelRoomContractForm.get('room_name').value
    if (contract_id && contract_id.length > 0 && (contract_id.includes('Select All') || contract_id.length == this.AllRoomsData.length) && !contract_id.includes('Clear All')) {
      let room_id_List = []
      this.AllRoomsData.forEach(d=>{
        room_id_List.push(d.extranet_room_id)
      });
      this.HotelRoomContractForm.get('room_name').setValue(room_id_List);
      event = this.HotelRoomContractForm.get('room_name').value
      this.SelectAllRoom = [];
      this.ClearAllRoom = ['Clear All'];
    } else if (contract_id && contract_id.length > 0 && (contract_id.includes('Clear All'))){
      this.HotelRoomContractForm.get('room_name').setValue([]);
      this.SelectAllRoom = ['Select All'];
      this.ClearAllRoom = [];
      event = this.HotelRoomContractForm.get('room_name').value
    } else {
      this.SelectAllRoom = ['Select All'];
      if(contract_id?.length > 0){
        this.ClearAllRoom = ['Clear All'];
      }
    }
    const addedItems = event.filter(item => !this.Selected_Room_List.includes(item));
    const removedItems = this.Selected_Room_List.filter(item => !event.includes(item));
    if(addedItems.length){
      addedItems.forEach(item=>{
        this.AddItems(item,formVal)
      })
    }else if(removedItems.length){
      removedItems.forEach(item=>{
        this.RemoveItems(item);
      })
    }
    this.Selected_Room_List = [...event];
  }
  AddItems(item,formVal){
      let Room_Details =   this.AllRoomsData.find(e=>e.extranet_room_id == item);
      let formArray = this.HotelRoomContractForm.get('RoomPricingDetail') as FormArray;
      if(Room_Details){
        let age_range = JSON.parse(Room_Details.age_range)
        formArray.push(this.fb.group({
          contract_name:this.validserv.required,
          extranet_room_name:Room_Details.room_name,
          // type: this.validserv.required,
          contract_days: this.fb.array([
            this.fb.group({
              extranet_room_id:Room_Details.extranet_room_id,
              days:this.fb.control(formVal && formVal.ExtranetRoomContractRate[0]?.days ? formVal.ExtranetRoomContractRate[0].days : [], [Validators.required]),
              age_range1:'',
              age_range2:'',
            })
          ]),
        }));
        if(formVal && formVal.ExtranetRoomContractRate[0]?.days){
          this.ChangeinWeekDays( 0,formVal.ExtranetRoomContractRate[0]?.days,0);
        }
        if(this.Clone_Rule){
          this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][0].get('contract_name').setValue(formVal ? formVal.ExtranetRoomContractRate[0]?.contract_name : '')
        }
        let rate_plan_id = this.HotelRoomContractForm.get('extranet_rate_plan_id').value;
        if(rate_plan_id != '20240724044902547713' && rate_plan_id != '20240724044902546366'){
          let formgroup = formArray.controls[formArray.controls.length - 1] as FormGroup;
          formgroup.addControl(`type`,new FormControl(formVal ? formVal.ExtranetRoomContractCancellationPolicy[0].type : [],Validators.required));
          formgroup.addControl(`cancel_policy`,new FormArray([this.fb.group({
            from: [formVal ? formVal.ExtranetRoomContractCancellationPolicy[0].from : 0,Validators.compose([Validators.required])],
            to: [formVal ? formVal.ExtranetRoomContractCancellationPolicy[0].to :  '',Validators.compose([Validators.required,this.AmountRangeValidation(0)])],
            charge_type: this.fb.control(formVal && formVal.ExtranetRoomContractCancellationPolicy[0] ? formVal.ExtranetRoomContractCancellationPolicy[0].charge_type : [], [Validators.required]),
            charge_value: this.fb.control(formVal && formVal.ExtranetRoomContractCancellationPolicy[0]? formVal.ExtranetRoomContractCancellationPolicy[0].charge_value : [], [Validators.required]),
          })]));
          this.Checkcanceltype(formVal?.ExtranetRoomContractCancellationPolicy[0].charge_type,0,0);
          if(formVal && formVal.ExtranetRoomContractCancellationPolicy[0] && formVal && formVal.ExtranetRoomContractCancellationPolicy[0].charge_type == 'NIGHTCOUNT'){
            formgroup.controls['cancel_policy']['controls'][0].get('night_type').setValue(formVal.ExtranetRoomContractCancellationPolicy[0].night_type)
          }
        }
        let Adult_Bed_Obj = Room_Details.adult_extrabed_details_json ? JSON.parse(Room_Details.adult_extrabed_details_json) : '';
        for(let i=1;i <= Room_Details.max_adult_occupancy;i++){
          formArray.controls[formArray.controls.length -1]['controls']['contract_days']['controls'][0].addControl(`adult_${i}`,new FormControl(formVal ? formVal.ExtranetRoomContractRate[0][`adult_${i}`] : '',Validators.required))
          formArray.controls[formArray.controls.length -1]['controls']['contract_days']['controls'][0].addControl(`supplement_${i}`,new FormControl({value: Adult_Bed_Obj ? Adult_Bed_Obj[`adult_${i}`] : false, disabled: true}))
        }
        let paid_child_extrabed_obj = JSON.parse(Room_Details.paid_child_extrabed_details);
        for(let i=1;i <= age_range.length;i++){
          formArray.controls[formArray.controls.length -1]['controls']['contract_days']['controls'][0].get(`age_range${i}`).setValue(age_range[i-1]['from'] + ' to ' + age_range[i-1]['to']);
          formArray.controls[formArray.controls.length -1]['controls']['contract_days']['controls'][0].addControl(`is_child_extra_bed_age_range${i}`,new FormControl(formVal ? formVal.ExtranetRoomContractRate[0][`is_child_extra_bed_age_range${i}`] : false));
          for(let j=1;j <= Room_Details.max_child_occupancy;j++){ 
            if(Room_Details.max_child_occupancy == Room_Details.max_free_child || j > Room_Details.max_free_child || i == 2){
              formArray.controls[formArray.controls.length -1]['controls']['contract_days']['controls'][0].addControl(`age_range${i}_child_${j}`,new FormControl(formVal ? formVal.ExtranetRoomContractRate[0][`age_range${i}_child_${j}`] : [],Validators.required))
              formArray.controls[formArray.controls.length -1]['controls']['contract_days']['controls'][0].addControl(`age_range${i}_extrabed_${j}`,new FormControl({value: false, disabled: true}));
              if(paid_child_extrabed_obj?.length > 0){
                formArray.controls[formArray.controls.length -1]['controls']['contract_days']['controls'][0].get(`age_range${i}_extrabed_${j}`).setValue(paid_child_extrabed_obj ? paid_child_extrabed_obj[i-1].Child_Extra_bed_detail[j-1] : false);
              }
            }
          }
        }
        this.DaysArrValue[formArray.controls.length -1] = this.AllDaysArr;
        this.SelectAllVal[formArray.controls.length -1] = this.SelectAll;
        if(formVal?.ExtranetRoomContractRate[0].days){
          this.ChangeinWeekDays(0,0);
        }
      }
  }
  RemoveItems(item){
    let formdata  = this.HotelRoomContractForm.get('RoomPricingDetail').value;
      let index = 0;
      formdata.forEach((data,ind)=>{
        if(data.contract_days[0].extranet_room_id == item){
          index = ind
        }
      })
      let formArray = this.HotelRoomContractForm.get('RoomPricingDetail') as FormArray;
      formArray.removeAt(index);
      let formvalue  = this.HotelRoomContractForm.get('RoomPricingDetail').value;
      for(let i=0;i < formvalue.length;i++){
        this.ChangeinWeekDays(i);
      }
  }
  AddCancelArr(ind,formVal?){
    let formArray = this.HotelRoomContractForm.get('RoomPricingDetail') as FormArray;
    let cancel_arr = formArray.controls[ind]['controls']['cancel_policy'];
    let min_amnt = cancel_arr.controls[cancel_arr.controls.length - 1].get('to').value;
    formArray.controls[ind]['controls']['cancel_policy'].push(
      this.fb.group({
        from: [formVal?.from ? formVal?.from : '',Validators.compose([Validators.required])],
        to: [formVal?.to ? formVal.to : '',Validators.compose([Validators.required,this.AmountRangeValidation(0)])],
        charge_type: this.fb.control(formVal?.charge_type ? formVal.charge_type : [], [Validators.required]),
        charge_value: this.fb.control(formVal?.charge_value ? formVal.charge_value : [], [Validators.required]),
      })
    );
    if(min_amnt){
      formArray.controls[ind]['controls']['cancel_policy']['controls'][formArray.controls[ind]['controls']['cancel_policy']['controls'].length -1].get('from').setValue(min_amnt ? (parseInt(min_amnt) + 1) : '')
      this.ChangeFeeMinValue('to',min_amnt ? (parseInt(min_amnt) + 1) : min_amnt ,ind,formArray.controls[ind]['controls']['cancel_policy']['controls'].length -1);
    }
    formVal ? this.Checkcanceltype(formVal?.charge_type,0,formArray.controls[ind]['controls']['cancel_policy']['controls'].length -1) :'';
    if(formVal?.charge_type == 'NIGHTCOUNT'){
      formArray.controls[ind]['controls']['cancel_policy']['controls'][formArray.controls[ind]['controls']['cancel_policy']['controls'].length -1].get('night_type').setValue(formVal.night_type)
    }
  }
  removeCancelArr(room_ind,arr_ind){
    let formArray = this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][room_ind]['controls']['cancel_policy'] as FormArray;
    formArray.removeAt(arr_ind);
    if(formArray.controls[arr_ind]){
      let amount = arr_ind == 0 ? '' : formArray.controls[arr_ind-1].get('to').value;
      this.ChangeFeeMinValue('from',amount,room_ind,arr_ind);
    }
  }
  Checkcanceltype(event,room_ind,cancel_ind){
    let formcontrol = this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][room_ind]['controls']['cancel_policy']['controls'][cancel_ind] as FormGroup;
    if(event == 'NIGHTCOUNT'){
      formcontrol.addControl('night_type',new FormControl('',Validators.required));
      if(!formcontrol.controls['charge_value']){
        formcontrol.addControl('charge_value',new FormControl('',Validators.required));
      }
    } else if(event == 'FULLCHARGES'){
      formcontrol.removeControl('night_type');
      formcontrol.removeControl('charge_value');
    } else {
      if(!formcontrol.controls['charge_value']){
        formcontrol.addControl('charge_value',new FormControl('',Validators.required));
      }      
      formcontrol.removeControl('night_type');
    }
  }
  AddContractArr(room_ind,room_id,formVal?){
    let Room_Details =   this.AllRoomsData.find(e=>e.extranet_room_id == room_id);
    let formArray = this.HotelRoomContractForm.get('RoomPricingDetail') as FormArray;
    if(Room_Details){
      let age_range = JSON.parse(Room_Details.age_range)
      formArray.controls[room_ind]['controls']['contract_days'].push(
        this.fb.group({
          extranet_room_id:Room_Details.extranet_room_id,
          days:this.fb.control(formVal?.days ? formVal.days : [], [Validators.required]),
          age_range1:'',
          age_range2:'',
        })
      )
      if(formVal?.days){
        this.ChangeinWeekDays( 0,formVal.days,formArray.controls[room_ind]['controls']['contract_days']['controls'].length -1);
      }
      let room_days_arr = formArray.controls[room_ind]['controls']['contract_days'] as FormArray;
      let Adult_Bed_Obj = Room_Details.adult_extrabed_details_json ? JSON.parse(Room_Details.adult_extrabed_details_json) : '';
      for(let i=1;i <= Room_Details.max_adult_occupancy;i++){
        formArray.controls[room_ind]['controls']['contract_days']['controls'][room_days_arr.controls.length -1].addControl(`adult_${i}`,new FormControl(formVal ? formVal[`adult_${i}`] :'',Validators.required))
        formArray.controls[room_ind]['controls']['contract_days']['controls'][room_days_arr.controls.length -1].addControl(`supplement_${i}`,new FormControl({value: Adult_Bed_Obj ? Adult_Bed_Obj[`adult_${i}`] : false, disabled: true}))
      }
      let paid_child_extrabed_obj = JSON.parse(Room_Details.paid_child_extrabed_details);
      for(let i=1;i <= age_range.length;i++){
        formArray.controls[room_ind]['controls']['contract_days']['controls'][room_days_arr.controls.length -1].get(`age_range${i}`).setValue(age_range[i-1]['from'] + ' to ' + age_range[i-1]['to']);
        formArray.controls[room_ind]['controls']['contract_days']['controls'][room_days_arr.controls.length -1].addControl(`is_child_extra_bed_age_range${i}`,new FormControl(formVal ? formVal[`is_child_extra_bed_age_range${i}`] : false));
        for(let j=1;j <= Room_Details.max_child_occupancy;j++){ 
          if(Room_Details.max_child_occupancy == Room_Details.max_free_child || j > Room_Details.max_free_child || i == 2){
            formArray.controls[room_ind]['controls']['contract_days']['controls'][room_days_arr.controls.length -1].addControl(`age_range${i}_child_${j}`,new FormControl(formVal ? formVal[`age_range${i}_child_${j}`] : '',Validators.required))
            formArray.controls[room_ind]['controls']['contract_days']['controls'][room_days_arr.controls.length -1].addControl(`age_range${i}_extrabed_${j}`,new FormControl({value: false, disabled: true}));
            if(paid_child_extrabed_obj?.length > 0){
              formArray.controls[room_ind]['controls']['contract_days']['controls'][room_days_arr.controls.length -1].get(`age_range${i}_extrabed_${j}`).setValue(paid_child_extrabed_obj ? paid_child_extrabed_obj[i-1].Child_Extra_bed_detail[j-1] : false);
            }
          }
        }
      }
    }
    console.log(formArray)
  }
  RemoveContractArr(room_ind,contract_day_ind){
    let formArray = this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][room_ind]['controls']['contract_days'] as FormArray;
    formArray.removeAt(contract_day_ind);
  }
  CopyAdultValues(room_ind,contract_day_ind,adult_value,room_id){
    if(adult_value || adult_value == 0){
      let Room_Details =   this.AllRoomsData.find(e=>e.extranet_room_id == room_id);
      let formArray = this.HotelRoomContractForm.get('RoomPricingDetail') as FormArray;
        for(let i=1;i <= Room_Details.max_adult_occupancy;i++){
          formArray.controls[room_ind]['controls']['contract_days']['controls'][contract_day_ind].get(`adult_${i}`).setValue(adult_value)
        }
    }
  }
  ChangeinWeekDays(i,event?,j?){
    let selected_days_by_room = [];
    let formdata = this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][i]['controls']['contract_days'].value;
    if( event && event.includes('Select All')){
      formdata[j].days.splice(formdata[j].days.indexOf('Select All'), 1);
      this.DaysArrValue[i].forEach(days_val=>{
        formdata[j].days.push(days_val);
      })
      this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][i]['controls']['contract_days'].controls[j]['controls']['days'].setValue(formdata[j].days);
    }
    formdata.forEach(e=>{
      if(e.days && e.days.length > 0){
        e.days.forEach(days=>{
          selected_days_by_room.push(days);
        })
      }
    })
    this.DaysArrValue[i] =  this.AllDaysArr.filter(item => !selected_days_by_room.includes(item));
    if(this.DaysArrValue[i].length == 0){
      this.SelectAllVal[i] = []
    }else {
      this.SelectAllVal[i] = this.SelectAll;
    }
  }
  Save(){
    if (this.HotelRoomContractForm.status == "VALID") {
      let formvalue = this.HotelRoomContractForm.getRawValue();
      let postData = {
        extranet_hotel_id:this.Extranet_Hotel_Id,
        extranet_rate_plan_id:formvalue.extranet_rate_plan_id,
        extranet_meal_plan_id:formvalue.extranet_meal_plan_id,
        currency_code:formvalue.currency_code,
        nationality_type:formvalue.nationality_type ? formvalue.nationality_type : '',
        nationality_applicable_type:formvalue.nationality_applicable_type ? formvalue.nationality_applicable_type : '',
        nationality:formvalue.nationality_applicable_type == 'SPECIFIC' ? formvalue.nationality.join(',') : '',
        residence_type:formvalue.residence_type,
        residence_applicable_type:formvalue.residence_applicable_type,
        residence:formvalue.residence_applicable_type == 'SPECIFIC' ? formvalue.residence.join(',') : '',
        contract_dates:'',
        is_meal_addon_applicable:formvalue.is_meal_addon_applicable,
        date_type:formvalue.date_type,
        season:formvalue.Season_Id ? formvalue.Season_Id.join(',') : '',
        extranet_meal_addon_id:formvalue.is_meal_addon_applicable ? formvalue.extranet_meal_addon_id.join(',') : '',
        RoomPricingDetail:[]
      }
      if(formvalue.date_type == 'SPECIFICDATES'){
        let date_Arr = [];
        formvalue.ContractDatesArr.forEach(data=>{
          date_Arr.push({
            date_from: moment(data.date[0]).format('YYYY-MM-DD'),
            date_to: moment(data.date[1]).format('YYYY-MM-DD'),
          })
        });
        postData['contract_dates'] = JSON.stringify(date_Arr);
      }
      if(formvalue.date_type == 'SEASON'){
        let date_Arr = [];
        this.Season_List.forEach(data=>{
          data.date_range.forEach(season_date=>{
            date_Arr.push({
              date_from: moment(season_date.split(' to ')[0]).format('YYYY-MM-DD'),
              date_to: moment(season_date.split(' to ')[1]).format('YYYY-MM-DD'),
            })
          })
        });
        postData['contract_dates'] = JSON.stringify(date_Arr);
      }
      if(formvalue.RoomPricingDetail && formvalue.RoomPricingDetail.length > 0){
        formvalue.RoomPricingDetail.forEach(roomdata=>{
          let subObj = {
            contract_days : [],
            cancel_policy : []
          }
          if(roomdata.contract_days && roomdata.contract_days.length > 0){
            roomdata.contract_days.forEach(contract_data=>{
              subObj.contract_days.push({
                extranet_room_id:contract_data.extranet_room_id,
                contract_name:roomdata.contract_name,
                days:contract_data.days ? contract_data.days.join(',').toLowerCase() : '',
                adult_1:contract_data['adult_1'] ? parseFloat(contract_data['adult_1']) : null,
                adult_2:contract_data['adult_2'] ? parseFloat(contract_data['adult_2']) : null,
                adult_3:contract_data['adult_3'] ? parseFloat(contract_data['adult_3']) : null,
                adult_4:contract_data['adult_4'] ? parseFloat(contract_data['adult_4']) : null,
                adult_5:contract_data['adult_5'] ? parseFloat(contract_data['adult_5']) : null,
                adult_6:contract_data['adult_6'] ? parseFloat(contract_data['adult_6']) : null,
                adult_7:contract_data['adult_7'] ? parseFloat(contract_data['adult_7']) : null,
                adult_8:contract_data['adult_8'] ? parseFloat(contract_data['adult_8']) : null,
                adult_9:contract_data['adult_9'] ? parseFloat(contract_data['adult_9']) : null,
                age_range1_child_1:contract_data['age_range1_child_1'] ? parseFloat(contract_data['age_range1_child_1']) : null,
                age_range1_child_2:contract_data['age_range1_child_2'] ? parseFloat(contract_data['age_range1_child_2']) : null,
                age_range1_child_3:contract_data['age_range1_child_3'] ? parseFloat(contract_data['age_range1_child_3']) : null,
                age_range1_child_4:contract_data['age_range1_child_4'] ? parseFloat(contract_data['age_range1_child_4']) : null,
                age_range1_child_5:contract_data['age_range1_child_5'] ? parseFloat(contract_data['age_range1_child_5']) : null,
                age_range1_child_6:contract_data['age_range1_child_6'] ? parseFloat(contract_data['age_range1_child_6']) : null,
                age_range2_child_1:contract_data['age_range2_child_1'] ? parseFloat(contract_data['age_range2_child_1']) : null,
                age_range2_child_2:contract_data['age_range2_child_2'] ? parseFloat(contract_data['age_range2_child_2']) : null,
                age_range2_child_3:contract_data['age_range2_child_3'] ? parseFloat(contract_data['age_range2_child_3']) : null,
                age_range2_child_4:contract_data['age_range2_child_4'] ? parseFloat(contract_data['age_range2_child_4']) : null,
                age_range2_child_5:contract_data['age_range2_child_5'] ? parseFloat(contract_data['age_range2_child_5']) : null,
                age_range2_child_6:contract_data['age_range2_child_6'] ? parseFloat(contract_data['age_range2_child_6']) : null,
              })
            })
          }
          if(roomdata.cancel_policy && roomdata.cancel_policy.length > 0){
            roomdata.cancel_policy.forEach(cancel_data=>{
              subObj.cancel_policy.push({
                type:roomdata.type,
                from:cancel_data.from.toString(),
                to:cancel_data.to,
                charge_type:cancel_data.charge_type,
                charge_value:cancel_data.charge_value ? parseInt(cancel_data.charge_value):0,
                night_type:cancel_data['night_type'] ? cancel_data['night_type'] : '',
              })
            })
          }
          postData.RoomPricingDetail.push(subObj);
        })
      }
      console.log(postData)
      this.apiserv.Post('/ExtranetRoomContract/SaveExtranetRoomContract',postData).subscribe(data=>{
        if(data){
          this.commonMasterSer.showMessage(data.status,data.message);
          data.status ? this.BackButton() : '';
        }
      })
    }else{
      this.validserv.showValidationsMsg(this.HotelRoomContractForm);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
    }
  }
  Rate_Plan_Check(){
    let rate_plan_id = this.HotelRoomContractForm.get('extranet_rate_plan_id').value;
    if(rate_plan_id == '20240724044902547713' || rate_plan_id == '20240724044902546366'){
      this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'].forEach(formgroup=>{
        formgroup.removeControl('cancel_policy');
        formgroup.removeControl('type');
      })
    }else{
      this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'].forEach(formgroup=>{
        // formgroup.removeControl('cancel_policy');
        // formgroup.removeControl('type');
        if(!formgroup.contains('cancel_policy')){
          formgroup.addControl(`type`,new FormControl([],Validators.required))
          formgroup.addControl(`cancel_policy`,new FormArray([this.fb.group({
            from: [0,Validators.compose([Validators.required])],
            to: [[],Validators.compose([Validators.required,this.AmountRangeValidation(0)])],
            charge_type: this.validserv.required,
            charge_value: this.validserv.required,
          })]))
        }
      })
    }
    if(rate_plan_id){
      let planName = this.AllRatePlan.find(e=>e.extranet_rate_plan_id == rate_plan_id);
      this.showRate_Plan_Name = planName.rate_plan_name;
    }else {
      this.showRate_Plan_Name = undefined;
    }
  }
  Meal_Plan_Show(){
    let meal_plan_id = this.HotelRoomContractForm.get('extranet_meal_plan_id').value;
    if(meal_plan_id){
      let planName = this.AllMealPlan.find(e=>e.extranet_meal_plan_id == meal_plan_id);
      this.showRate_meal_Name = planName.meal_plan_name;
    }else {
      this.showRate_meal_Name = undefined;
    }
  }
  ChangeFeeMinValue(controlname,min,i,j) {
      let min_amt = min;
      if(this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][i]['controls']['cancel_policy']['controls'][j] && controlname != 'from'){
        this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][i]['controls']['cancel_policy']['controls'][j].get(controlname).clearValidators();
        this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][i]['controls']['cancel_policy']['controls'][j].get(controlname).addValidators([Validators.required, this.AmountRangeValidation(min_amt)]);
        this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][i]['controls']['cancel_policy']['controls'][j].get(controlname).markAsUntouched();
        this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][i]['controls']['cancel_policy']['controls'][j].get(controlname).setErrors(null);
        this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][i]['controls']['cancel_policy']['controls'][j].get(controlname).updateValueAndValidity();
      }
      if(controlname == 'from' &&  this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][i]['controls']['cancel_policy']['controls'][j]){
        this.HotelRoomContractForm.controls['RoomPricingDetail']['controls'][i]['controls']['cancel_policy']['controls'][j].get(controlname).setValue(min_amt ? (parseInt(min_amt) + 1) : 0)
        this.ChangeFeeMinValue('to',min_amt ? (parseInt(min_amt) + 1) : 0,i,j);
      }
  }
  private AmountRangeValidation(initialValue): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value || control.value == 0) {
        if (initialValue && parseInt(control.value) <= parseInt(initialValue)) {
          return { 'range': true };
        }
      }
      return null;
    };
  }
  //set form data 
  SetContractFormValue(formValue) {
    if (formValue) {
      let Val = formValue;
      // console.log(Val);
      this.HotelRoomContractForm.get('room_name').setValue(Val.extranet_room_id ? Val.extranet_room_id.split(','):[]);
      this.HotelRoomContractForm.get('extranet_rate_plan_id').setValue(Val.extranet_rate_plan_id);
      this.HotelRoomContractForm.get('extranet_meal_plan_id').setValue(Val.extranet_meal_plan_id);
      this.HotelRoomContractForm.get('nationality_applicable_type').setValue(Val.nationality_applicable_type);
      this.HotelRoomContractForm.get('nationality_type').setValue(Val.nationality_type);
      this.HotelRoomContractForm.get('residence_applicable_type').setValue(Val.nationality_applicable_type);
      this.HotelRoomContractForm.get('residence_type').setValue(Val.nationality_type);
      this.HotelRoomContractForm.get('date_type').setValue(Val.date_type);
      this.HotelRoomContractForm.get('is_meal_addon_applicable').setValue(Val.is_meal_addon_applicable);
      this.Meal_Plan_Show();
      this.Rate_Plan_Check();
      if(Val.nationality_applicable_type == 'SPECIFIC'){
        this.NationalityShowhide(Val.nationality_applicable_type);
        this.HotelRoomContractForm.get('nationality').setValue(Val.nationality ? Val.nationality.split(','):[]);
        this.CountryList = Val.country ? JSON.parse(Val.country) : [];
      }
      if(Val.nationality_applicable_type == 'SPECIFIC'){
        this.ResidenceShowhide(Val.nationality_applicable_type);
        this.HotelRoomContractForm.get('residence').setValue(Val.residence ? Val.residence.split(','):[]);
        this.CountryList = Val.country ? JSON.parse(Val.country) : [];
      }
      if(Val.is_meal_addon_applicable){
        this.MealHideShow(Val.is_meal_addon_applicable);
        this.HotelRoomContractForm.get('extranet_meal_addon_id').setValue(Val.extranet_meal_addon_id ? Val.extranet_meal_addon_id.split(','):[]);
      }
      if (Val.ExtranetRoomContractRate) {
        Val.ExtranetRoomContractRate.forEach((data,ind) => {
          Val.ExtranetRoomContractRate[ind]['days'] = data.days ? data.days.split(',') : [];
          for (let i = 0; i < Val.ExtranetRoomContractRate[ind]['days'].length; i++) {
            Val.ExtranetRoomContractRate[ind]['days'][i] = Val.ExtranetRoomContractRate[ind]['days'][i][0].toUpperCase() + Val.ExtranetRoomContractRate[ind]['days'][i].substr(1);
          }
        })
        Val.ExtranetRoomContractRate.forEach((formvalue,formInd)=>{
          if(formInd == 0){
            this.AddRemoveRoomContract(this.HotelRoomContractForm.get('room_name').value, Val);
          }
          if(formInd > 0){
            // this.AddCancelArr(0,Val.ExtranetRoomContractCancellationPolicy[formInd]);
            this.AddContractArr(0,formvalue.extranet_room_id,formvalue);
          }
        });
      }
      if(Val.ExtranetRoomContractCancellationPolicy){
        Val.ExtranetRoomContractCancellationPolicy.forEach((cancellation_data,cancel_ind)=>{
          if(cancel_ind > 0){
            this.AddCancelArr(0,cancellation_data);
          }
        })
      }
      this.ShowDateTypeFields(Val.date_type);
      if(Val.date_type == 'SPECIFICDATES'){
        let date_arr = Val.contract_dates ? JSON.parse(Val.contract_dates) : [];
        date_arr.forEach((date_data,date_ind)=>{
          if(date_ind)this.addDate();
          this.HotelRoomContractForm.controls['ContractDatesArr']['controls'][date_ind].get('date').setValue([new Date(date_data.date_from),new Date(date_data.date_to)])
        })
      }else if(Val.date_type == 'SEASON'){
        this.HotelRoomContractForm.get('Season_Id').setValue(Val.season ? Val.season.split(',') : []);
        this.SeasonDataAddRemove();
      }
      if(this.Clone_Rule){
        this.HotelRoomContractForm.disable();
      }
    }
  }
}