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';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-hotel-room-add',
  templateUrl: './hotel-room-add.component.html',
})
export class HotelRoomAddComponent implements OnInit {

  Extranet_Hotel_Id;
  AllLang;
  AllRoomView;
  max_Child_Occ = 7;
  max_Adult_Occ = 10;
  max_Total_Occ = 16;
  max_child_age = 12;
  Clone_Rule;
  showPaidchild = true;
  Edit_Id;
  ShowChildEditDet = true;
  ShoeHideChildFields = false;
  fileInfo = [];
  fileArr = [];
  public isCollapsed: boolean[];
  Sub_Ameneties_checked_Obj={};
  Amenities;
  Age_Limit_Child = [0,1,2,3,4,5,6,7,8,9,10,11];
  occupancy_Limit_Child = [0,1,2,3,4,5,6,7,8,9,10,11];
  Max_occupancy_Limit_Child = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
  HotelRoomForm:FormGroup;
  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('CloneRoom') || !this.Edit_Id ? true :false;
    this.initForm()
    this.GetAllLAng();
    if(this.Edit_Id){
      this.GetById()
    }
  }
  initForm(){
    this.HotelRoomForm = this.fb.group({
      extranet_room_id:'',
      extranet_room_view_id:'',
      default_lang_code:this.validserv.required,
      room_name:this.validserv.required,
      max_adult_occupancy:this.validserv.required,
      max_child_occupancy:this.validserv.required,
      max_occupancy_type:this.validserv.required,
      is_extra_bed_supported:false,
      is_free_child:false,
      is_paid_child:false,
      is_adult_extra_bed_supported:false,
      room_size:'',
      bed_details:'',
      room_description:'',
      extranet_room_details_id:'',
      room_images:this.fb.control([]),
      room_images_url:this.fb.control([]),
      max_occupancy_options:this.fb.array([]),
      room_thumbnail_url:[''],
      room_thumbnail_url_display:[''],
      age_range1_child1:false,
      age_range1_child2:false,
      age_range1_child3:false,
      age_range1_child4:false,
      age_range1_child5:false,
      age_range1_child6:false,
      age_range2_child1:false,
      age_range2_child2:false,
      age_range2_child3:false,
      age_range2_child4:false,
      age_range2_child5:false,
      age_range2_child6:false,
    })
  }
  getAllData(Edit_Data?) {
    this.Sub_Ameneties_checked_Obj = {};
    this.Amenities = undefined;
    forkJoin(
      this.GetAllRoomView(),
      this.GetAllAmenities(),
    ).subscribe(result => {
      if (result && result.length > 0) {
        this.AllRoomView = result[0] ? result[0].data : result[0];
        let amenity_json = result[1] ? result[1].data :'';
        this.Amenities = amenity_json && amenity_json['extranet_hotel_room_amenity_json'] ? JSON.parse(amenity_json.extranet_hotel_room_amenity_json) : [];
        this.Amenities.forEach(data=>{
          this.Sub_Ameneties_checked_Obj[data.parent_amenity_id] = [];
        });
        if(this.Amenities && this.Amenities.length > 0){
          this.isCollapsed = new Array(this.Amenities.length).fill(true);
        }
        if(Edit_Data && Edit_Data.length > 0){
          Edit_Data.forEach(data=>{
            this.Sub_Ameneties_checked_Obj[data.parent_amenity_id] = data.sub_amenities && data.sub_amenities.length > 0 ? data.sub_amenities : [];
          })
        }
      }
    })
  }
  GetAllLAng(){
    this.apiserv.AdminGet('/LanguageMapping/GetLanguagesByOrgId').subscribe(data=>{
      if(data){
        this.AllLang = data;
      }
    })
  }
  GetById(){
    this.apiserv.Get('/ExtranetHotelRoom/GetExtranetHotelRoomById/'+ this.Edit_Id).subscribe(res=>{
      if(res){
        this.SetRoomdata(res.data);
      }
    })
  }
  GetAllRoomView(){
    return this.apiserv.Get('/ExtranetHotelRoom/GetAllExtranetHotelRoomView?lang_code='+this.HotelRoomForm.get('default_lang_code').value)
  }
  GetAllAmenities(){
    return this.apiserv.Get('/ExtranetHotelRoom/GetAllExtranetHotelRoomAmenities/'+this.HotelRoomForm.get('default_lang_code').value)
  }

  BackButton(){
    this.hotelmanageserv.Active_tab = 'Room';
    this.router.navigateByUrl(`Services/Hotel/HotelManage/${this.Extranet_Hotel_Id}`);
  }
  CheckOccpancyType(val){
    if(val  == 'MAXTOTALOCCUPANCY'){
      this.HotelRoomForm.addControl('max_total_occupancy',new FormControl('',Validators.required));
      let formarray = this.HotelRoomForm.controls['max_occupancy_options'] as FormArray;
      formarray.clear();
    }else if(val  == 'MAXOCCUPANCYCOMBINATIONS'){
      this.AddMaxOccupancyCombination();
      this.HotelRoomForm.removeControl('max_total_occupancy');
    }
  }
  GetAdultOcuupancy(val){
    if(val){
      this.max_Adult_Occ = val+1;
      this.max_Total_Occ = val  + this.max_Child_Occ;
      let max_occ_val = this.HotelRoomForm.controls['max_total_occupancy'] ? this.HotelRoomForm.controls['max_total_occupancy'].value : 0; 
      if(max_occ_val > this.max_Total_Occ){
        this.HotelRoomForm.get('max_total_occupancy').setValue('');
      }
      let formarray = this.HotelRoomForm.controls['max_occupancy_options'] as FormArray;
      formarray.controls.forEach(control=>{
        if(control.get('max_adult').value > val){
          control.get('max_adult').setValue('');
        }
      })
    }else {
      this.max_Adult_Occ = 10;
    }
    this.AdultBedSupport();
  }
  SetRoomdata(Resp){
    if(!this.Clone_Rule){
      this.HotelRoomForm.get('extranet_room_id').setValue(Resp.extranet_room_id);
      this.HotelRoomForm.get('extranet_room_view_id').setValue(Resp.extranet_room_view_id);
      this.HotelRoomForm.get('max_adult_occupancy').disable();
      this.HotelRoomForm.get('max_occupancy_type').disable();
      this.HotelRoomForm.get('max_child_occupancy').disable();
    }
    this.HotelRoomForm.get('default_lang_code').setValue(Resp.default_lang_code);
    this.HotelRoomForm.get('max_adult_occupancy').setValue(Resp.max_adult_occupancy);
    this.HotelRoomForm.get('max_occupancy_type').setValue(Resp.max_occupancy_type);
    this.HotelRoomForm.get('max_child_occupancy').setValue(Resp.max_child_occupancy);
    this.HotelRoomForm.get('room_size').setValue(Resp.room_size);
    this.HotelRoomForm.get('bed_details').setValue(Resp.bed_details);
    this.HotelRoomForm.get('room_description').setValue(Resp.room_description);
    this.HotelRoomForm.get('is_free_child').setValue(Resp.is_free_child);
    this.HotelRoomForm.get('is_extra_bed_supported').setValue(Resp.is_extra_bed_supported);
    this.HotelRoomForm.get('is_paid_child').setValue(Resp.is_paid_child);
    this.HotelRoomForm.get('is_adult_extra_bed_supported').setValue(Resp.is_adult_extra_bed_supported);
    this.CheckOccpancyType(Resp.max_occupancy_type)
    if(Resp.max_occupancy_type == 'MAXTOTALOCCUPANCY'){
      this.HotelRoomForm.get('max_total_occupancy').setValue(Resp.max_total_occupancy);
      if(!this.Clone_Rule)this.HotelRoomForm.get('max_total_occupancy').disable();
    }else if(Resp.max_occupancy_type == 'MAXOCCUPANCYCOMBINATIONS'){
      let val  = Resp.max_occupancy_options ? JSON.parse(Resp.max_occupancy_options) : [];
      val.forEach((data,i)=>{
        if(i > 0) this.AddMaxOccupancyCombination();
        this.HotelRoomForm.controls['max_occupancy_options']['controls'][i].get('max_adult').setValue(data.max_adult);
        this.HotelRoomForm.controls['max_occupancy_options']['controls'][i].get('max_child')?.setValue(data.max_child);
        data.child_age.forEach((child_age,child_ind)=>{
          this.HotelRoomForm.controls['max_occupancy_options']['controls'][i].addControl('child_age_'+(child_ind+1),new FormControl(child_age,Validators.required))
        })
        if(!this.Clone_Rule){
          this.HotelRoomForm.controls['max_occupancy_options']['controls'][i].get('max_adult').disable();
          this.HotelRoomForm.controls['max_occupancy_options']['controls'][i].get('max_child')?.disable();
          for(let ind=1 ; ind<=6 ; ind++){
            this.HotelRoomForm.controls['max_occupancy_options']['controls'][i].get('child_age_'+ ind)?.disable();
          }
        }
      })
    }

    if(Resp.max_child_occupancy){
      this.ShowHideChildAgeFields(Resp.max_child_occupancy)
      this.ShowChildEditDet = this.Clone_Rule ? true : false;
      // this.ShoeHideChildFields = this.Clone_Rule ? true : false;
      this.HotelRoomForm.get('max_child_age').setValue(Resp.max_child_age);
      if(!this.Clone_Rule){
        this.HotelRoomForm.get('max_child_age').disable();
      }
    }
    if(Resp.is_extra_bed_supported){
      this.ExtraBedControls(true);
      this.HotelRoomForm.get('extra_bed_details').setValue(Resp.extra_bed_details);
    }
    if(Resp.is_free_child){
      this.FreeChildControls(true);
      this.HotelRoomForm.get('max_free_child').setValue(Resp.max_free_child);
      this.HotelRoomForm.get('free_child_age_from').setValue(Resp.free_child_age_from);
      this.HotelRoomForm.get('free_child_age_to').setValue(Resp.free_child_age_to);
    }
    if(Resp.ExtranetChildAgeRange && Resp.ExtranetChildAgeRange.length > 0){
      Resp.ExtranetChildAgeRange.forEach((Paid_child_Obj,ind)=>{
        ind == 0 ? this.PaidChildArr(true) : this.AddChildArr();
        this.HotelRoomForm.controls['ExtranetChildAgeRange']['controls'][ind].get('from_age').setValue(Paid_child_Obj.from_age);
        this.ChangeFeeMinValue('to_age',Paid_child_Obj.from_age,ind);
        this.HotelRoomForm.controls['ExtranetChildAgeRange']['controls'][ind].get('to_age').setValue(Paid_child_Obj.to_age);
        if(!this.Clone_Rule)this.HotelRoomForm.controls['ExtranetChildAgeRange']['controls'][ind].get('extranet_child_age_range_id').setValue(Paid_child_Obj.extranet_child_age_range_id);
      })
    }
    if(Resp.ExtranetHotelRoomDetails){
      if(!this.Clone_Rule)this.HotelRoomForm.get('room_name').setValue(Resp.ExtranetHotelRoomDetails.room_name);
      this.HotelRoomForm.get('room_description').setValue(Resp.ExtranetHotelRoomDetails.room_description);
      if(!this.Clone_Rule)this.HotelRoomForm.get('extranet_room_details_id').setValue(Resp.ExtranetHotelRoomDetails.extranet_room_details_id);
    }
    if(Resp.room_amenities){
      let amenity_data = JSON.parse(Resp.room_amenities);
      this.getAllData(amenity_data)
    }
    if(Resp.paid_child_extrabed_details){
      let extrabed_details = JSON.parse(Resp.paid_child_extrabed_details);
      extrabed_details.forEach((range_data,range_ind)=>{
        range_data.Child_Extra_bed_detail.forEach((is_extraned,child_ind)=>{
          this.HotelRoomForm.get(`age_range${range_ind+1}_child${child_ind+1}`).setValue(is_extraned);
        })
      })
    }
    if(Resp.room_images){
      let Images_Arr = Resp.room_images.split(',');
      Images_Arr.forEach(data=>{
        this.HotelRoomForm.get('room_images').value.push(data);
        this.HotelRoomForm.get('room_images_url').value.push(data);
      })
    }
    if(Resp.room_thumbnail_url){
      this.HotelRoomForm.get('room_thumbnail_url').setValue(Resp.room_thumbnail_url);
      this.HotelRoomForm.get('room_thumbnail_url_display').setValue(Resp.room_thumbnail_url);
    }
    if(Resp.is_adult_extra_bed_supported){
      let adult_bed_obj = Resp.adult_extrabed_details_json ? JSON.parse(Resp.adult_extrabed_details_json) : '';
      this.AdultBedSupport(adult_bed_obj);
      this.HotelRoomForm.get('adult_extrabed_details').setValue(Resp.adult_extrabed_details);
    }
  }
  ExtraBedControls(event){
      if(event){
        this.HotelRoomForm.addControl('extra_bed_details',new FormControl('',Validators.required));
      }else {
        this.HotelRoomForm.removeControl('extra_bed_details');
      }
  }
  FreeChildControls(event){
      if(event){
        this.HotelRoomForm.addControl('max_free_child',new FormControl('',Validators.required));
        this.HotelRoomForm.addControl('free_child_age_from',new FormControl('',Validators.required));
        this.HotelRoomForm.addControl('free_child_age_to',new FormControl('',Validators.required));
      }else {
        this.HotelRoomForm.removeControl('max_free_child');
        this.HotelRoomForm.removeControl('free_child_age_from');
        this.HotelRoomForm.removeControl('free_child_age_to');
        this.addRemoveValidation('is_paid_child',true);
        this.ChangeFeeMinValue('from_age','',0)
      }
  }
  PaidChildArr(event){
    if(event){
      this.addRemoveValidation('is_free_child',false);
      this.HotelRoomForm.addControl('ExtranetChildAgeRange',new FormArray([this.fb.group({
        from_age:['', Validators.compose([Validators.required,this.AmountRangeValidation(this.HotelRoomForm.get('free_child_age_to') ? this.HotelRoomForm.get('free_child_age_to').value : '')])],
        to_age:this.validserv.required,
        extranet_child_age_range_id:''
      })]));
    }else {
      this.addRemoveValidation('is_free_child',true);
      if(this.HotelRoomForm.get('is_free_child').value == false){
        this.addRemoveValidation('is_paid_child',true);
      }
      this.HotelRoomForm.removeControl('ExtranetChildAgeRange');
    }
    this.CheckMaxChildCriteria();
  }
  CheckMaxChildCriteria(){
    let max_child_occupancy = this.HotelRoomForm.get('max_child_occupancy').value;
    let max_free_child_occ = this.HotelRoomForm.get('max_free_child') ? this.HotelRoomForm.get('max_free_child').value : 0;
    if(max_child_occupancy == max_free_child_occ && max_child_occupancy !== 0){
      this.addRemoveValidation('is_paid_child',false);
        let min_amt = this.HotelRoomForm.get('free_child_age_to').value ? this.HotelRoomForm.get('free_child_age_to').value : '';
        this.AddValidationPaidAgeFields(0,min_amt,'from_age')
        this.HotelRoomForm.controls['ExtranetChildAgeRange']?.['controls'][0].get('from_age').enable();
        this.HotelRoomForm.controls['ExtranetChildAgeRange']?.['controls'][0].get('to_age').enable();
    }else if(max_free_child_occ && this.HotelRoomForm.get('is_free_child').value && max_child_occupancy !== 0){
      this.addRemoveValidation('is_paid_child',true);
      this.addRemoveValidation('is_free_child',false);
      if(max_free_child_occ){
        this.AddValidationPaidAgeFields(0,'','from_age');
        this.AddValidationPaidAgeFields(0,'','to_age');
        let from_age = this.HotelRoomForm.get('free_child_age_from').value;
        let to_age = this.HotelRoomForm.get('free_child_age_to').value;
        this.HotelRoomForm.controls['ExtranetChildAgeRange']?.['controls'][0].get('from_age').setValue( from_age || from_age === 0 ? this.HotelRoomForm.get('free_child_age_from').value : '');
        this.HotelRoomForm.controls['ExtranetChildAgeRange']?.['controls'][0].get('from_age').disable();
        this.HotelRoomForm.controls['ExtranetChildAgeRange']?.['controls'][0].get('to_age').setValue(to_age || to_age === 0 ? this.HotelRoomForm.get('free_child_age_to').value : '');
        this.HotelRoomForm.controls['ExtranetChildAgeRange']?.['controls'][0].get('to_age').disable();
        let min_amt = this.HotelRoomForm.get('free_child_age_to').value ? this.HotelRoomForm.get('free_child_age_to').value : '';
        this.AddValidationPaidAgeFields(1,min_amt,'from_age');
      }
    }else {
      this.addRemoveValidation('is_paid_child',false);
      this.addRemoveValidation('is_free_child',false);
    }
  }
  AddValidationPaidAgeFields(i,min_amt,control){
    this.HotelRoomForm.controls['ExtranetChildAgeRange']?.['controls'][i]?.get(control).clearValidators();
    this.HotelRoomForm.controls['ExtranetChildAgeRange']?.['controls'][i]?.get(control).addValidators([Validators.required, this.AmountRangeValidation(min_amt ? min_amt : '')]);
    this.HotelRoomForm.controls['ExtranetChildAgeRange']?.['controls'][i]?.get(control).updateValueAndValidity();
  }
  AddChildArr(){
    let formArray = this.HotelRoomForm.controls['ExtranetChildAgeRange'] as FormArray;
    formArray.push(
      this.fb.group({
        from_age:['', Validators.compose([Validators.required,this.AmountRangeValidation(formArray.controls[0].get('to_age') ? formArray.controls[0].get('to_age').value : '')])],
        to_age:this.validserv.required,
        extranet_child_age_range_id:'',
      })
    )
  }
  RemoveChildArr(i){
    let formArray = this.HotelRoomForm.controls['ExtranetChildAgeRange'] as FormArray;
    formArray.removeAt(i);
    this.ChangeFeeMinValue('from_age',(this.HotelRoomForm.get('free_child_age_to') ? this.HotelRoomForm.get('free_child_age_to').value : ''),0)
  }
  AddMaxOccupancyCombination(){
    let formArray = this.HotelRoomForm.controls['max_occupancy_options'] as FormArray;
    let group_obj = {
      max_adult:this.validserv.required
    }
    if(this.HotelRoomForm.get('max_child_occupancy').value > 0){
      group_obj['max_child'] = this.validserv.required;
    }
    formArray.push(
      this.fb.group(group_obj)
    )
  }
  RemoveMaxOccupancyCombination(i){
    let formArray = this.HotelRoomForm.controls['max_occupancy_options'] as FormArray;
    formArray.removeAt(i);
  }
  SelectParent(event,parent_Id){
    if(event.checked){
      let filter_selectced_parent = this.Amenities.find(e=> e.parent_amenity_id == parent_Id);
      this.Sub_Ameneties_checked_Obj[parent_Id] = filter_selectced_parent.sub_amenities;
    }else {
      this.Sub_Ameneties_checked_Obj[parent_Id] = [];
    }
  }
  Select_Sub_Amenity(event,parent_Id,sub_amenity){
    if(event.checked){
      this.Sub_Ameneties_checked_Obj[parent_Id].push(sub_amenity);
    }else {
      this.Sub_Ameneties_checked_Obj[parent_Id] = this.Sub_Ameneties_checked_Obj[parent_Id].filter(e=>e !== sub_amenity)
    }
  }
  
  SelectImage(e, filedata,contol) {
    if (e.currentFiles.length != 0) {
      for (let i = 0; i < e.files.length; i++) {
        let file = e.files[i];
        if (file.size < 1048576 && (file.type == 'image/png' || file.type == 'image/jpeg')) {
          const reader = new FileReader();
          console.log(file)
          reader.readAsText(file); // Read as binary data
          reader.onload = (res) => {
            const binaryString = res.target.result as string;
            const hasScriptTag = this.commonMasterSer.hasScriptTagInBinary(binaryString);
            if (hasScriptTag) {
              filedata.clear();
              this.commonMasterSer.showMessage(false, 'Invalid file (contains script tag)');
            } else {
              //base 64
              if(contol == 'room_thumbnail_url'){
                this.HotelRoomForm.get(contol).setValue(file);
              }else {
                this.HotelRoomForm.get(contol).value.push(file);
              }
              const reader = new FileReader();
              reader.readAsDataURL(file);
              reader.onload = () => {
                if(contol == 'room_thumbnail_url'){
                  this.HotelRoomForm.get('room_thumbnail_url_display').setValue(reader.result.toString());
                }else {
                  this.HotelRoomForm.get('room_images_url').value.push(reader.result.toString());
                }
              }
            };
          }
        }
      }
    }

  }
  RemoveImage(ind,contol) {
    if(contol == 'room_thumbnail_url'){
      this.HotelRoomForm.get(contol).setValue('');
      this.HotelRoomForm.get('room_thumbnail_url_display').setValue('');
    }else {
      let image_url_list = this.HotelRoomForm.get(contol).value;
      image_url_list.splice(ind, 1);
      let image_display_url_list = this.HotelRoomForm.get('room_images_url').value;
      image_display_url_list.splice(ind, 1);
    }
  }

  saveImg(fileInfo, fileArr,edit_id) {
    if (fileInfo && fileInfo.length > 0 && fileArr && fileArr.length > 0) {
      var formdata = new FormData();
      fileArr.forEach((x) => {
        formdata.append("files", x);
      });
      let file_info_list = JSON.stringify(fileInfo).replaceAll('ExtranetRoomId', edit_id);
      formdata.append("fileInfo", file_info_list);
      return this.apiserv.PostFile("/FileUpload/SaveFile", formdata);
    } else {
      return of({
        resp: true,
        respMsg: "No images to save"
      });
    }
  }
  ChangeFeeMinValue(controlname,min,i?) {
    let min_amt = min;
    if ((i == 0 || i) && (this.HotelRoomForm.controls['ExtranetChildAgeRange'] && this.HotelRoomForm.controls['ExtranetChildAgeRange']['controls'][i])) {
      this.HotelRoomForm.controls['ExtranetChildAgeRange']['controls'][i].get(controlname).clearValidators();
      this.HotelRoomForm.controls['ExtranetChildAgeRange']['controls'][i].get(controlname).addValidators([Validators.required, this.AmountRangeValidation(min_amt)]);
      this.HotelRoomForm.controls['ExtranetChildAgeRange']['controls'][i].get(controlname).markAsUntouched();
      this.HotelRoomForm.controls['ExtranetChildAgeRange']['controls'][i].get(controlname).setErrors(null);
      this.HotelRoomForm.controls['ExtranetChildAgeRange']['controls'][i].get(controlname).updateValueAndValidity();
    }else if(i == null || i == undefined){
      this.HotelRoomForm.controls[controlname].clearValidators();
      this.HotelRoomForm.controls[controlname].addValidators([Validators.required, this.AmountRangeValidation(min_amt)]);
      this.HotelRoomForm.controls[controlname].markAsUntouched();
      this.HotelRoomForm.controls[controlname].setErrors(null);
      this.HotelRoomForm.controls[controlname].updateValueAndValidity();
    }
    this.CheckMaxChildCriteria()
  };
  private AmountRangeValidation(initialValue): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value || control.value === 0) {
        if ((initialValue || initialValue === 0)&& parseInt(control.value) <= parseInt(initialValue)) {
          return { 'range': true };
        }
      }
      return null;
    };
  }
  Save(){
    if (this.HotelRoomForm.status == "VALID") {
      let val = this.HotelRoomForm.getRawValue();
      let Amenities_Obj = [];
      if(this.Amenities && this.Amenities.length > 0){
        this.Amenities.forEach(data=>{
          if(this.Sub_Ameneties_checked_Obj[data.parent_amenity_id] && this.Sub_Ameneties_checked_Obj[data.parent_amenity_id].length > 0){
            data['sub_amenities'] = this.Sub_Ameneties_checked_Obj[data.parent_amenity_id];
            Amenities_Obj.push(data);
          }
        })
      }
      let PostData = {
        extranet_room_id:val.extranet_room_id ? val.extranet_room_id : '',
        extranet_hotel_id: this.Extranet_Hotel_Id,
        extranet_room_view_id:val.extranet_room_view_id ? val.extranet_room_view_id : '',
        default_lang_code : val.default_lang_code,
        max_adult_occupancy : val.max_adult_occupancy,
        max_child_occupancy : val.max_child_occupancy,
        max_child_age : val.max_child_age,
        max_total_occupancy : val.max_total_occupancy ? val.max_total_occupancy : 0,
        max_occupancy_type : val.max_occupancy_type ? val.max_occupancy_type : '',
        max_occupancy_options : '',
        adult_extrabed_details_json : '',
        adult_extrabed_details:val.adult_extrabed_details ? val.adult_extrabed_details : '',
        is_extra_bed_supported : val.is_extra_bed_supported,
        extra_bed_details : val.is_extra_bed_supported ? val.extra_bed_details : '',
        is_adult_extra_bed_supported : val.is_adult_extra_bed_supported,
        is_free_child : val.is_free_child,
        max_free_child : val.max_free_child ?  val.max_free_child : 0,
        free_child_age_from : val.free_child_age_from ?  val.free_child_age_from : 0,
        free_child_age_to : val.free_child_age_to ?  val.free_child_age_to : 0,
        is_paid_child : val.is_paid_child,
        room_size : val.room_size ? val.room_size : '',
        bed_details : val.bed_details ? val.bed_details : '',
        paid_child_extrabed_details:'',
        room_amenities:JSON.stringify(Amenities_Obj),
        ExtranetHotelRoomDetails:{
          extranet_hotel_id:this.Extranet_Hotel_Id,
          extranet_room_details_id:val.extranet_room_details_id ? val.extranet_room_details_id : '',
          lang_code:val.default_lang_code ? val.default_lang_code : '',
          room_name : val.room_name,
          room_description : val.room_description ? val.room_description :'',
        },
        ExtranetChildAgeRange:[]
      }
      let paid_child_extrabed_obj = [];
      if(val.ExtranetChildAgeRange && val.ExtranetChildAgeRange.length > 0){
        val.ExtranetChildAgeRange.forEach((child_age_arr,i)=>{
          PostData.ExtranetChildAgeRange.push({
            from_age:child_age_arr.from_age,
            to_age:child_age_arr.to_age,
            extranet_child_age_range_id:child_age_arr.extranet_child_age_range_id,
            range_sequence:i,
          });
          if(val.is_extra_bed_supported){
            let age_range_obj = {paid_child_extrabed_obj:`${child_age_arr.from_age} to ${child_age_arr.to_age}`,Child_Extra_bed_detail:[]}
            for(let ind=1;ind<=val.max_child_occupancy;ind++){
              age_range_obj.Child_Extra_bed_detail.push(val[`age_range${i+1}_child${ind}`])
            }
            paid_child_extrabed_obj.push(age_range_obj);
          }
        })
      }
      PostData['paid_child_extrabed_details'] = JSON.stringify(paid_child_extrabed_obj);
      if(val.is_adult_extra_bed_supported){
        let adult_bed_obj = {}
        for(let i=1;i<=9;i++){
          adult_bed_obj['adult_'+i] = val['adult_'+i] ? val['adult_'+i] : false;
        } 
        PostData.adult_extrabed_details_json = JSON.stringify(adult_bed_obj);
      }
      let room_images_arr = []
      val.room_images.forEach((img_data,img_Ind)=>{
        if (typeof(img_data) == 'object' && img_data) {
          let image_type =  img_data.name.split('.');
          this.fileArr.push(img_data);
          this.fileInfo.push({ 'fileName': "Extranet/Hotel/Rooms/ExtranetRoomId/Room_Images_"+ img_Ind   + '.' + image_type[image_type.length - 1], 'pathToSave': 'OrganizationData/ORGID' });
          let image_url = `${environment.cdnFileUrl}OrganizationData/ORGID/Extranet/Hotel/Rooms/ExtranetRoomId/Room_Images_${img_Ind}.${image_type[image_type.length - 1]}?t=${moment(new Date()).format("yyMMddHHmmssfffffff")}`;
          room_images_arr.push(image_url)
        }else {
          room_images_arr.push(img_data);
        }
      })
      let thumbnail_image_url = '';
      if (typeof(val.room_thumbnail_url) == 'object' && val.room_thumbnail_url) {
        let image_type = val.room_thumbnail_url.name.split('.');
        this.fileArr.push(val.room_thumbnail_url);
        this.fileInfo.push({ 'fileName': "Extranet/Hotel/Rooms/ExtranetRoomId/Thumbnail_Img"  + '.' + image_type[image_type.length - 1], 'pathToSave': 'OrganizationData/ORGID' });
        thumbnail_image_url = `${environment.cdnFileUrl}OrganizationData/ORGID/Extranet/Hotel/Rooms/ExtranetRoomId/Thumbnail_Img.${image_type[image_type.length - 1]}?t=${moment(new Date()).format("yyMMddHHmmssfffffff")}`;
      }else {
        thumbnail_image_url = val.room_thumbnail_url;
      }
      PostData['room_images'] = room_images_arr.length > 0 ? room_images_arr.join(',') : '';
      PostData['room_thumbnail_url'] = thumbnail_image_url;
      if(val.max_occupancy_options) {
        let max_occupancy_arr = [];
        val.max_occupancy_options.forEach(occupancy_arr=>{
          let child_age_arr = [];
          for(let i=1 ; i <= 6 ; i++){
            if(occupancy_arr[`child_age_${i}`]){
              child_age_arr.push(occupancy_arr[`child_age_${i}`])
            }
          }
          max_occupancy_arr.push({
            max_adult:occupancy_arr.max_adult,
            max_child:occupancy_arr.max_child,
            child_age:child_age_arr,
          })
        });
        PostData['max_occupancy_options'] = JSON.stringify(max_occupancy_arr)
      }
      this.apiserv.Post('/ExtranetHotelRoom/SaveExtranetHotelRoom',PostData).subscribe(resp=>{
        if(resp){
          if(this.fileInfo.length > 0 && resp.status){
            this.saveImg(this.fileInfo, this.fileArr,resp.data.extranet_room_id).subscribe(res=>{
              if(res && res.resp){
                this.BackButton();
              }
              this.commonMasterSer.showMessage(resp.status,resp.message)
            })
          }else if(resp.status){
            this.BackButton();
          }
          this.commonMasterSer.showMessage(resp.status,resp.message);
          
        }
      })
    }else{
      this.validserv.showValidationsMsg(this.HotelRoomForm);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
    }
  }
  ShowHideChildAgeFields(event){
    if(event){
      this.HotelRoomForm.addControl('max_child_age',new FormControl('',Validators.required));
      this.ShoeHideChildFields = true;
      if(this.HotelRoomForm.controls['max_free_child']?.value > event){
        this.HotelRoomForm.get('max_free_child').setValue('');
      };
      this.CheckMaxChildCriteria();
      if(!this.HotelRoomForm.get('is_paid_child').value){
        this.addRemoveValidation('is_free_child',true);
      }
      this.addRemoveValidation('is_paid_child',true);
    }else {
      this.ShoeHideChildFields = false;
      this.HotelRoomForm.removeControl('max_child_age');
      this.HotelRoomForm.get('is_extra_bed_supported').setValue(false);
      this.HotelRoomForm.get('is_free_child').setValue(false);
      this.HotelRoomForm.get('is_paid_child').setValue(false);
      this.addRemoveValidation('is_free_child',false);
      this.addRemoveValidation('is_paid_child',false);
      this.PaidChildArr(false);
      this.FreeChildControls(false);
      this.ExtraBedControls(false);
    }
    this.max_Child_Occ = event+1;
    this.max_Total_Occ = event + this.max_Adult_Occ;
    let max_occ_val = this.HotelRoomForm.controls['max_total_occupancy'] ? this.HotelRoomForm.controls['max_total_occupancy'].value : 0; 
    if(max_occ_val > this.max_Total_Occ){
      this.HotelRoomForm.get('max_total_occupancy').setValue('');
    }
    this.Paid_Child_Show_Hide();
    this.maxOccupancyCombination(event);
  }
  GetMaxChildAge(event){
    if(event || event===0){
      this.max_child_age = event + 1;
      this.SetFieldsValueEmpty(this.HotelRoomForm,'free_child_age_from',event);
      this.SetFieldsValueEmpty(this.HotelRoomForm,'free_child_age_to',event);
      if(this.HotelRoomForm.controls['ExtranetChildAgeRange']){
        this.HotelRoomForm.controls['ExtranetChildAgeRange']['controls'].forEach(formgroup=>{
          this.SetFieldsValueEmpty(formgroup,'from_age',event);
          this.SetFieldsValueEmpty(formgroup,'to_age',event);
        })
      }
    }else {
      this.max_child_age = 12;
    }
    this.Paid_Child_Show_Hide();
    this.maxAgeCombination(event);
  }
  SetFieldsValueEmpty(group,control,val?){
    if(group.controls[control]?.value > val){
      group.get(control).setValue('');
    }
  }
    // common function
  addRemoveValidation(name, check) {
    if (check) {
      this.HotelRoomForm.get(name).addValidators([Validators.requiredTrue]);
    } else {
      this.HotelRoomForm.get(name).clearValidators();
    }
    this.HotelRoomForm.get(name).updateValueAndValidity();
  };
  Paid_Child_Show_Hide(){
    let child_occ = this.HotelRoomForm.controls['max_child_occupancy'].value ? this.HotelRoomForm.controls['max_child_occupancy'].value : undefined; 
    let free_child_occ = this.HotelRoomForm.controls['free_child_age_from']?.value ? this.HotelRoomForm.controls['max_child_occupancy'].value : ''; 
    if((free_child_occ == child_occ) && this.HotelRoomForm.controls['free_child_age_to'].value == this.max_child_age -1){
      this.showPaidchild = false;
      this.addRemoveValidation('is_paid_child',false);
      this.PaidChildArr(false);
    }else {
      this.showPaidchild = true;
      this.CheckMaxChildCriteria();
    }
  }

  maxChildAge(child_occ,ind){
    for(let i=1;i<=6;i++){
      let group = this.HotelRoomForm.controls['max_occupancy_options']['controls'][ind] as FormGroup;
      if(!group?.get('child_age_'+i) && i <= child_occ){
        this.HotelRoomForm.controls['max_occupancy_options']['controls'][ind].addControl('child_age_'+i,new FormControl('',Validators.required))
      }else if(group?.get('child_age_'+i) && i > child_occ){
        this.HotelRoomForm.controls['max_occupancy_options']['controls'][ind].removeControl('child_age_'+i);
      }
    }
  }

  maxOccupancyCombination(child_Occ){
    if(child_Occ > 0){
      this.HotelRoomForm.controls['max_occupancy_options']?.['controls'].forEach(occ_Combination_grp=>{
        let child_occ_Cobination_val = occ_Combination_grp.get('max_child')?.value;
        if(child_occ_Cobination_val > child_Occ){
          occ_Combination_grp.get('max_child').setValue('');
        }else if(!occ_Combination_grp.get('max_child')){
          occ_Combination_grp.addControl('max_child', new FormControl('',Validators.required))
        }
      })
    }else {
      this.HotelRoomForm.controls['max_occupancy_options']?.['controls'].forEach((occ_Combination_grp,ind)=>{
        occ_Combination_grp.removeControl('max_child');
        this.maxChildAge(0,ind);
      })
    }
  }
  maxAgeCombination(child_Occ){
    if(child_Occ > 0){
      this.HotelRoomForm.controls['max_occupancy_options']?.['controls'].forEach(occ_Combination_grp=>{
        for(let i=1 ; i<=6 ; i++){
          let child_occ_Cobination_val = occ_Combination_grp.get('child_age_'+i)?.value;
          if(child_occ_Cobination_val > child_Occ){
            occ_Combination_grp.get('child_age_'+i)?.setValue('');
          }
        }
      })
    }else if(child_Occ == 0){
      this.HotelRoomForm.controls['max_occupancy_options']?.['controls'].forEach((occ_Combination_grp,ind)=>{
        for(let i=1 ; i<=6 ; i++){
            occ_Combination_grp.get('child_age_'+i)?.setValue(0);
        }
      })
    }
  }

  AdultBedSupport(value_Obj?){
    let value = this.HotelRoomForm.get('is_adult_extra_bed_supported').value;
    let adult_occ = this.HotelRoomForm.get('max_adult_occupancy').value;
    if(value && adult_occ){
      this.HotelRoomForm.addControl('adult_extrabed_details',new FormControl('',this.validserv.required));
      for(let i = 1; i <= adult_occ; i++){
        if(!this.HotelRoomForm.get('adult_'+i)){
          this.HotelRoomForm.addControl('adult_' + i,new FormControl(value_Obj ? value_Obj['adult_'+ i] : false));
        }
      }
      for(let i = 9; i > adult_occ; i--){
        if(this.HotelRoomForm.get('adult_'+i)){
          this.HotelRoomForm.removeControl('adult_'+i);
        }
      }
    }else {
      this.HotelRoomForm.removeControl('adult_extrabed_details');
      for(let i = 9; i > 0; i--){
        if(this.HotelRoomForm.get('adult_'+i)){
          this.HotelRoomForm.removeControl('adult_'+i);
        }
      }
    }
  }
}
