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-offers-add',
  templateUrl: './offers-add.component.html',
})
export class OffersAddComponent implements OnInit {

  Extranet_Hotel_Id;
  AllContrtact;
  combineOfferList;
  timer;
  Check_Same_Value_Arr = [];
  MinDate = new Date();
  ddLoader = {
    Country:false,
    Residence:false,
  };
  CountryList;
  Adult_Occupancy_List;
  Child_Occupancy_List;
  selectAll = ['Select All'];
  Nationality_type = [{Label:'All',Value:'ALL'},{Label:'Specific',Value:'SPECIFIC'}];
  Residence_type = [{Label:'All',Value:'ALL'},{Label:'Specific',Value:'SPECIFIC'}];
  selectAllAdult = [];
  selectAllChild = [];
  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'}
  ];
  Offers_Form:FormGroup;
  Edit_Id;
  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();
  }
  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)
  }
  GetAllData(){
    forkJoin(
      this.GetAllContract(),
      this.GetHotelDetail(),
      this.GetOfferById(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]?.data)this.Offers_Form.get('currency').setValue(res[1].data.currency);
          this.SetOfferFormValue(res[2] ? res[2].data :'')
        }
    })
  }
  GetOfferById(Editid) {
    if (Editid)
      return this.apiserv.Get('/ExtranetOffer/GetExtranetOfferById/' + Editid)
    else
      return of(null)
  };
  Initform(){
    this.Offers_Form = this.fb.group({
      extranet_offer_id:'',
      extranet_room_id:this.validserv.required,
      offer_name:this.validserv.required,
      currency:this.validserv.required,
      offer_type:this.validserv.required,
      is_combinable_offer:false,
      combinable_offer_id:'',
      offer_days:this.validserv.required,
      is_min_stay:false,
      is_max_stay:false,
      is_stay_pay_multiple:false,
      max_reoccurence:'',
      residence_type:'',
      residence_applicable_type:'',
      offer_nationality_type:'',
      nationality_applicable_type:'',
      cancellation_policy_type:this.validserv.required,
      type:this.validserv.required,
      applicable_on:this.validserv.required,
      applicable_adult_occupancy:'',
      applicable_child_occupancy:'',
      offer_description:'',
      date_criteria:this.fb.array([]),
      custom_cancellation_policy:this.fb.array([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,
      })])
    });
    this.addDate()
  }
  addDate() {
    let formArray = this.Offers_Form.controls['date_criteria'] as FormArray;
    formArray.push(this.fb.group({
      booking_date_range: ['', Validators.compose([
        Validators.required,
        this.dateValidation()
      ])],
      checkin_date_range: ['', Validators.compose([
        Validators.required,
        this.dateValidation()
      ])],
    }));
    if(this.Offers_Form.controls['offer_type'].value != 'CONTRACTREMARK'){
      let group = formArray.controls[formArray.controls.length - 1] as FormGroup;
      group.addControl('checkin_before_days',new FormControl('',Validators.required));
    }
    this.Check_Same_Value_Arr[formArray.controls.length - 1] = false;
  }
  public dateValidation(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value) {
        if (control.value.length <= 1 || control.value[1] == null) {
          return { 'todate': true };
        }
      }
      return null;
    };
  }
  removeDate(index) {
    let formArray = this.Offers_Form.controls['date_criteria'] as FormArray;
    this.Check_Same_Value_Arr[index] = false;
    formArray.removeAt(index);
    this.check_Unique_Values();
  }
  Check_Offer_Type(event){
    if(event == 'STAYPAY'){
      this.Offers_Form.addControl('stay_pay_applicable_on',new FormControl('',Validators.required));
      this.Offers_Form.addControl('stay_night',new FormControl('',Validators.required));
      this.Offers_Form.addControl('pay_night',new FormControl('',Validators.required));
      if(!this.Offers_Form['discount_code']){
        this.Offers_Form.addControl('discount_code',new FormControl('',Validators.required));
      }
      this.Offers_Form.removeControl('contract_remark');
      this.Offers_Form.removeControl('long_stay_night')
      this.CheckAddremovecontrol('offer_days',this.Offers_Form,true);
      this.CheckAddremovecontrol('cancellation_policy_type',this.Offers_Form,true);
      this.CheckAddremovecontrol('type',this.Offers_Form,true);
      this.CheckAddremovecontrol('applicable_on',this.Offers_Form,true);
      this.Offers_Form.removeControl('discount_type');
      this.Offers_Form.removeControl('discount_value');
      let formArray = this.Offers_Form.controls['date_criteria'] as FormArray;
      formArray.controls.forEach((control:FormGroup)=>{
        this.CheckAddremovecontrol('checkin_before_days',control,true)
      });
      this.Check_Cancel_Type();
    }
    if(event != 'STAYPAY' && event!= 'CONTRACTREMARK'){
      if(!this.Offers_Form['discount_type']){
        this.Offers_Form.addControl('discount_type',new FormControl('',Validators.required));
        this.Offers_Form.addControl('discount_value',new FormControl('',Validators.required));
      }
      if(!this.Offers_Form['discount_code']){
        this.Offers_Form.addControl('discount_code',new FormControl('',Validators.required));
      }
      let formArray = this.Offers_Form.controls['date_criteria'] as FormArray;
      formArray.controls.forEach((control:FormGroup)=>{
        this.CheckAddremovecontrol('checkin_before_days',control,true)
      });
      this.CheckAddremovecontrol('offer_days',this.Offers_Form,true);
      this.CheckAddremovecontrol('cancellation_policy_type',this.Offers_Form,true);
      this.CheckAddremovecontrol('type',this.Offers_Form,true);
      this.CheckAddremovecontrol('applicable_on',this.Offers_Form,true);
      this.Check_Cancel_Type();
    }
    if(event == 'CONTRACTREMARK'){
      this.Offers_Form.addControl('contract_remark',new FormControl('',Validators.required));
      this.Offers_Form.removeControl('stay_pay_applicable_on');
      this.Offers_Form.removeControl('stay_night');
      this.Offers_Form.removeControl('pay_night');
      this.Offers_Form.removeControl('discount_code');
      this.Offers_Form.removeControl('long_stay_night');
      this.Offers_Form.removeControl('discount_type');
      this.Offers_Form.removeControl('discount_value');
      let formArray = this.Offers_Form.controls['date_criteria'] as FormArray;
      formArray.controls.forEach((control:FormGroup)=>{
        this.CheckAddremovecontrol('checkin_before_days',control,false)
      });
      this.CheckAddremovecontrol('offer_days',this.Offers_Form,false);
      this.CheckAddremovecontrol('cancellation_policy_type',this.Offers_Form,false);
      this.CheckAddremovecontrol('type',this.Offers_Form,false);
      this.CheckAddremovecontrol('custom_cancellation_policy',this.Offers_Form,false);
      this.CheckAddremovecontrol('applicable_on',this.Offers_Form,false);
    }
    if(event == 'LONGSTAY'){
      this.Offers_Form.addControl('long_stay_night',new FormControl('',Validators.required));
      if(!this.Offers_Form['discount_code']){
        this.Offers_Form.addControl('discount_code',new FormControl('',Validators.required));
      }
      this.Offers_Form.removeControl('stay_pay_applicable_on');
      this.Offers_Form.removeControl('stay_night');
      this.Offers_Form.removeControl('pay_night');
      this.Offers_Form.removeControl('contract_remark');
      let formArray = this.Offers_Form.controls['date_criteria'] as FormArray;
        formArray.controls.forEach((control:FormGroup)=>{
          this.CheckAddremovecontrol('checkin_before_days',control,true)
        });
      this.CheckAddremovecontrol('offer_days',this.Offers_Form,true);
      this.CheckAddremovecontrol('cancellation_policy_type',this.Offers_Form,true);
      this.CheckAddremovecontrol('type',this.Offers_Form,true);
      this.CheckAddremovecontrol('applicable_on',this.Offers_Form,true);
      this.Check_Cancel_Type();
    }else if(event == 'EARLYBIRD'){
      if(!this.Offers_Form['discount_code']){
        this.Offers_Form.addControl('discount_code',new FormControl('',Validators.required));
      }
      this.Offers_Form.removeControl('contract_remark');
      this.Offers_Form.removeControl('stay_pay_applicable_on');
      this.Offers_Form.removeControl('stay_night');
      this.Offers_Form.removeControl('pay_night');
      this.Offers_Form.removeControl('long_stay_night');
      let formArray = this.Offers_Form.controls['date_criteria'] as FormArray;
        formArray.controls.forEach((control:FormGroup)=>{
          this.CheckAddremovecontrol('checkin_before_days',control,true)
        });
      this.CheckAddremovecontrol('offer_days',this.Offers_Form,true);
      this.CheckAddremovecontrol('cancellation_policy_type',this.Offers_Form,true);
      this.CheckAddremovecontrol('type',this.Offers_Form,true);
      this.CheckAddremovecontrol('applicable_on',this.Offers_Form,true);
      this.Check_Cancel_Type();
    }
  }
  CheckAddremovecontrol(controlname,formgroup,check){
    if(check){
      if(!formgroup.get(controlname)){
        formgroup.addControl(controlname,new FormControl('',Validators.required));
      }
    }else {
      formgroup.removeControl(controlname);
    }
  }
  ChangeFeeMinValue(controlname,min,i?) {
    let min_amt = min;
    if(this.Offers_Form.controls['custom_cancellation_policy']['controls'][i] && controlname != 'from'){
      this.Offers_Form.controls['custom_cancellation_policy']['controls'][i].get(controlname).clearValidators();
      this.Offers_Form.controls['custom_cancellation_policy']['controls'][i].get(controlname).addValidators([Validators.required, this.AmountRangeValidation(min_amt)]);
      this.Offers_Form.controls['custom_cancellation_policy']['controls'][i].get(controlname).markAsUntouched();
      this.Offers_Form.controls['custom_cancellation_policy']['controls'][i].get(controlname).setErrors(null);
      this.Offers_Form.controls['custom_cancellation_policy']['controls'][i].get(controlname).updateValueAndValidity();
    }
    if(controlname == 'from' &&  this.Offers_Form.controls['custom_cancellation_policy']['controls'][i]){
      this.Offers_Form.controls['custom_cancellation_policy']['controls'][i].get(controlname).setValue(min_amt ? (parseInt(min_amt) + 1) : 0)
      this.ChangeFeeMinValue('to',min_amt ? (parseInt(min_amt) + 1) : 0 ,i);
    }
  }
  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;
    };
  }
  AddCancelArr(ind){
    let formArray = this.Offers_Form.controls['custom_cancellation_policy'] as FormArray;
    let cancel_arr = this.Offers_Form.controls['custom_cancellation_policy']['controls'][ind];
    let min_amnt = cancel_arr.get('to').value;
    formArray.push(
      this.fb.group({
        from: [min_amnt ? (parseInt(min_amnt) + 1) : '',Validators.compose([Validators.required])],
        to: this.validserv.required,
        charge_type: this.validserv.required,
        charge_value: this.validserv.required,
      })
    )
    if(min_amnt){
      formArray.controls[formArray['controls'].length -1].get('from').setValue(min_amnt ? parseInt(min_amnt) : '')
      this.ChangeFeeMinValue('to',min_amnt ? parseInt(min_amnt) : min_amnt ,ind+1);
    }
  }
  removeCancelArr(room_ind){
    let formArray = this.Offers_Form.controls['custom_cancellation_policy'] as FormArray;
    formArray.removeAt(room_ind);
    if(formArray.controls[room_ind]){
      let amount = room_ind == 0 ? '' : formArray.controls[room_ind-1].get('to').value;
      this.ChangeFeeMinValue('from',amount,room_ind);
    }
  }
  Checkcanceltype(event,room_ind){
    let formcontrol = this.Offers_Form.controls['custom_cancellation_policy']['controls'][room_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');
    }
  }
  MinStay(event){
    if(event){
      this.Offers_Form.addControl('min_stay_value',new FormControl('',Validators.required));
    }else {
      this.Offers_Form.removeControl('min_stay_value')
    }
  }
  MaxStay(event){
    if(event){
      this.Offers_Form.addControl('max_stay_value',new FormControl('',Validators.required));
    }else {
      this.Offers_Form.removeControl('max_stay_value')
    }
  }
  CheckcontractType(){
    let val = this.Offers_Form.get('extranet_room_id').value;
    this.Adult_Occupancy_List = [];
    this.Child_Occupancy_List = [];
    let child_occ = 0;
    let adult_occ = 0;
    if (val && val.length > 0 && (val.includes('Select All') || val.length == this.AllContrtact.length) && !val.includes('Clear All')) {
      let room_id_List = []
      this.AllContrtact.forEach(d=>{
        room_id_List.push(d.extranet_room_id)
      });
      this.Offers_Form.get('extranet_room_id').setValue(room_id_List);
      this.SelectAllRoom = [];
      this.ClearAllRoom = ['Clear All'];
    } else if (val && val.length > 0 && (val.includes('Clear All'))){
      this.Offers_Form.get('extranet_room_id').setValue([]);
      this.SelectAllRoom = ['Select All'];
      this.ClearAllRoom = [];
    } else {
      this.SelectAllRoom = ['Select All'];
      if(val?.length > 0){
        this.ClearAllRoom = ['Clear All'];
      }
    }
    if(val && val.length > 0){
        let arr = [];
        val.forEach(item=>{
          let contract_det = this.AllContrtact.find(e=>item == e.extranet_room_id);
          arr.push(contract_det.extranet_room_id);
          if(contract_det.max_child_occupancy > child_occ){
            child_occ = contract_det.max_child_occupancy;
            this.Child_Occupancy_List = [];
            let selected_val = this.Offers_Form.get('applicable_child_occupancy').value
            if(selected_val){
              for(let i=selected_val.length;i>0;i--){
                if(selected_val[i] > child_occ){
                  selected_val.splice(i,1)
                }
              }
              this.Offers_Form.get('applicable_child_occupancy').setValue(selected_val);
            }
            for(let i=0;i<child_occ;i++)this.Child_Occupancy_List.push((i+1).toString());
          }
          if(contract_det.max_adult_occupancy > adult_occ){
            adult_occ = contract_det.max_adult_occupancy;
            this.Adult_Occupancy_List = [];
            let selected_val = this.Offers_Form.get('applicable_adult_occupancy').value
            if(selected_val){
              for(let i=selected_val.length;i>0;i--){
                if(selected_val[i] > adult_occ){
                  selected_val.splice(i,1)
                }
              }
              this.Offers_Form.get('applicable_adult_occupancy').setValue(selected_val);
            }
            for(let i=0;i<adult_occ;i++)this.Adult_Occupancy_List.push((i+1).toString());
          }
        });
        let Obj = {
          extranet_hotel_id:this.Extranet_Hotel_Id,
          is_combinable_offer:'1',
          extranet_room_id:arr ? arr.join(',') : ''
        }
        this.apiserv.Post('/ExtranetOffer/GetAllExtranetOffer',Obj).subscribe(res=>{
          if(res?.data){
            let filter_array  =  res.data.filter(elm=>elm.extranet_offer_id != this.Edit_Id);
            this.combineOfferList = filter_array.length > 0 ? filter_array : undefined;
          }else {
            this.combineOfferList = undefined;
            this.Offers_Form.get('combinable_offer_id').setValue('')
          }
        })
    }else {
      this.Offers_Form.get('applicable_child_occupancy').setValue(null);
      this.Offers_Form.get('applicable_adult_occupancy').setValue(null);

    }
    this.CheckAdultSelection();
    this.CheckChildSelection();
  }
  NationalityShowhide(event){
    if(event == 'SPECIFIC'){
      this.Offers_Form.addControl('nationality',new FormControl('',Validators.required))
    }else{
      this.Offers_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.Offers_Form.controls['nationality_applicable_type'].value == 'ALL'){
        this.Offers_Form.get('nationality_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);
    }
  }
  Check_day_type(){
    let daysArr = [
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
      'Sunday'
    ];
    let value = this.Offers_Form.get('offer_days').value;
    if(value && value.length > 0 && (value.includes('Select All') || value.length == 7)){
      this.Offers_Form.get('offer_days').setValue(daysArr);
      this.selectAll = []
    }else {
      this.selectAll = ['Select All']
    }
  }
  CheckAdultSelection() {
    if (this.Offers_Form.controls['applicable_adult_occupancy']) {
      let value = this.Offers_Form.get('applicable_adult_occupancy').value;
      if (value && value.length > 0 && (value.includes('Select All') || value.length == this.Adult_Occupancy_List.length)) {
        this.Offers_Form.get('applicable_adult_occupancy').setValue(this.Adult_Occupancy_List);
        this.selectAllAdult = []
      } else {
        this.selectAllAdult =  this.Adult_Occupancy_List && this.Adult_Occupancy_List.length > 0 ? ['Select All'] : [];
      }
    }else {
      this.selectAllAdult = []
    }
  }
  CheckChildSelection() {
    if (this.Offers_Form.controls['applicable_child_occupancy']) {
      let value = this.Offers_Form.get('applicable_child_occupancy').value;
      if (value && value.length > 0 && (value.includes('Select All') || value.length == this.Child_Occupancy_List.length)) {
        this.Offers_Form.get('applicable_child_occupancy').setValue(this.Child_Occupancy_List);
        this.selectAllChild = []
      } else {
        this.selectAllChild = this.Child_Occupancy_List && this.Child_Occupancy_List.length > 0 ? ['Select All'] : [];
      }
    }else {
      this.selectAllChild = []
    }
  }
  check_Unique_Values(){
    let val = this.Offers_Form.getRawValue();
    if(val.date_criteria.length > 0){
      val.date_criteria.forEach((obj, index) => {
        if((obj.checkin_before_days || val.offer_type != 'CONTRACTREMARK') && obj.booking_date_range && obj.checkin_date_range){
          //finding the duplicate first remove the current array to check the current from the others 
          const isDuplicate = val.date_criteria.filter((e,i)=>i != index).some(item => JSON.stringify(item) === JSON.stringify(obj));
  
          if (isDuplicate) {
            this.Check_Same_Value_Arr[index] = true;
          }else {
            this.Check_Same_Value_Arr[index] = false;
          }
        }
        else {
          this.Check_Same_Value_Arr[index] = false;

        }
      });
      // if(!duplicates){
      //   this.commonMasterSer.showMessage(false,'two or more booking date range rows has same values');
      // }
      // return duplicates;
    }
  }
  Save(){
    let val = this.Offers_Form.getRawValue();
    if (this.Offers_Form.status == "VALID" && this.Check_Same_Value_Arr.every(value => !value)) {
      let PostObj={
        extranet_offer_id:val.extranet_offer_id,
        extranet_room_id:val.extranet_room_id ? val.extranet_room_id.join(',') : '',
        offer_name:val.offer_name,
        is_combinable_offer:val.is_combinable_offer && val.offer_type != 'CONTRACTREMARK',
        combinable_offer_id:val.combinable_offer_id && val.offer_type != 'CONTRACTREMARK' ? val.combinable_offer_id.join(',') : '',
        offer_type:val.offer_type ? val.offer_type : '',
        discount_code:val.discount_code ? val.discount_code : '',
        offer_nationality_type:val.offer_nationality_type ? val.offer_nationality_type : '',
        nationality_applicable_type:val.nationality_applicable_type ? val.nationality_applicable_type : '',
        nationality:val.nationality ? val.nationality.join(',') : '',
        is_min_stay:val.is_min_stay && val.offer_type != 'CONTRACTREMARK',
        min_stay_value:val.min_stay_value && val.offer_type != 'CONTRACTREMARK' ? parseInt(val.min_stay_value) : 0,
        is_max_stay:val.is_max_stay && val.offer_type != 'CONTRACTREMARK' ,
        max_stay_value:val.max_stay_value && val.offer_type != 'CONTRACTREMARK' ? parseInt(val.max_stay_value) : 0,
        date_criteria:'',
        offer_days:val.offer_days && val.offer_type != 'CONTRACTREMARK' ? val.offer_days.join(',') : '',
        applicable_adult_occupancy:val.applicable_adult_occupancy && val.offer_type != 'CONTRACTREMARK' ? val.applicable_adult_occupancy.join(',') : '',
        applicable_child_occupancy:val.applicable_child_occupancy && val.offer_type != 'CONTRACTREMARK' ? val.applicable_child_occupancy.join(',') : '',
        cancellation_policy_type: val.offer_type != 'CONTRACTREMARK' ? val.cancellation_policy_type : '',
        offer_residence_type:val.residence_type,
        residence_applicable_type:val.residence_applicable_type,
        residence:val.residence_applicable_type == 'SPECIFIC' ? val.residence.join(',') : '',
        custom_cancellation_policy:'[]',
        applicable_on:val.applicable_on && val.offer_type != 'CONTRACTREMARK' ? val.applicable_on : '',
        stay_pay_applicable_on:val.stay_pay_applicable_on ? val.stay_pay_applicable_on : '',
        stay_night:val.stay_night ? parseInt(val.stay_night) : 0,
        pay_night:val.pay_night ? parseInt(val.pay_night) : 0,
        is_stay_pay_multiple:val.offer_type == 'STAYPAY' ? val.is_stay_pay_multiple :false,
        max_reoccurence:val.offer_type == 'STAYPAY' && val.is_stay_pay_multiple ? parseInt(val.max_reoccurence) : 0,
        long_stay_night:val.long_stay_night ? parseInt(val.long_stay_night) : 0,
        discount_type:val.discount_type ? val.discount_type:'',
        discount_value:val.discount_value ? parseFloat(val.discount_value) : 0,
        offer_description:val.offer_description && val.offer_type != 'CONTRACTREMARK' ? val.offer_description:'',
        contract_remark:val.contract_remark?val.contract_remark:'',
      }
      if(val.custom_cancellation_policy){
        val.custom_cancellation_policy.map(item=>{
          item['type']=val.type;
          item['charge_value'] = item['charge_value'] ? item['charge_value'] : 0;
        });
        PostObj.custom_cancellation_policy = JSON.stringify(val.custom_cancellation_policy);
      }
      if(val.date_criteria){
        val.date_criteria.map(e=>{
          e['booking_date_range'] = [moment(e['booking_date_range'][0]).format('YYYY-MM-DD'),moment(e['booking_date_range'][1]).format('YYYY-MM-DD')]
          e['checkin_date_range'] = [moment(e['checkin_date_range'][0]).format('YYYY-MM-DD'),moment(e['checkin_date_range'][1]).format('YYYY-MM-DD')]
        });
        PostObj.date_criteria = val.date_criteria ? JSON.stringify(val.date_criteria) : '';
      }
      // console.log(PostObj);
      this.apiserv.Post('/ExtranetOffer/SaveExtranetOffer',PostObj).subscribe(resp=>{
        if(resp){
          this.commonMasterSer.showMessage(resp.status,resp.message);
          resp.status ? this.BackButton() : '';
        }
      })
    }else {
      this.validserv.showValidationsMsg(this.Offers_Form);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
    }
  }
  Check_Cancel_Type(){
    let rate_plan_id = this.Offers_Form.get('cancellation_policy_type')?.value;
    if(rate_plan_id != 'CUSTOMPOLICY'){
      // this.Offers_Form.controls['RoomPricingDetail']['controls'].forEach(formgroup=>{
        this.Offers_Form.removeControl('custom_cancellation_policy');
        this.Offers_Form.removeControl('type');
      // })
    }else{
      // this.Offers_Form.controls['RoomPricingDetail']['controls'].forEach(formgroup=>{
        // formgroup.removeControl('cancel_policy');
        // formgroup.removeControl('type');
        if(!this.Offers_Form.contains('custom_cancellation_policy')){
          this.Offers_Form.addControl(`type`,new FormControl([],Validators.required))
          this.Offers_Form.addControl(`custom_cancellation_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,
          })]))
        }
      // })
    }
  }
  BackButton(){
    this.hotelmanageserv.Active_tab = 'Offers';
    this.router.navigateByUrl(`Services/Hotel/HotelManage/${this.Extranet_Hotel_Id}`);
  }
  SetOfferFormValue(data){
    if(data){
      this.Offers_Form.get('extranet_offer_id').setValue(data.extranet_offer_id);
      this.Offers_Form.get('extranet_room_id').setValue(data.extranet_room_id ? data.extranet_room_id.split(','):[]);
      this.Offers_Form.get('extranet_room_id').disable();
      if(data.extranet_room_id){
        this.CheckcontractType();
      }
      this.Offers_Form.get('offer_name').setValue(data.offer_name);
      this.Offers_Form.get('offer_type').setValue(data.offer_type);
      this.Check_Offer_Type(data.offer_type);
      this.Offers_Form.get('is_combinable_offer').setValue(data.is_combinable_offer);
      this.Offers_Form.get('is_stay_pay_multiple').setValue(data.is_stay_pay_multiple);
      this.Offers_Form.get('max_reoccurence').setValue(data.max_reoccurence != 0 ? data.max_reoccurence : '');
      this.Offers_Form.get('offer_nationality_type').setValue(data.offer_nationality_type);
      this.Offers_Form.get('cancellation_policy_type')?.setValue(data.cancellation_policy_type);
      this.Offers_Form.get('nationality_applicable_type').setValue(data.nationality_applicable_type);
      this.Offers_Form.get('offer_description').setValue(data.offer_description);
      this.Offers_Form.get('applicable_on')?.setValue(data.applicable_on);
      this.Offers_Form.get('combinable_offer_id').setValue(data.combinable_offer_id ? data.combinable_offer_id.split(','):[]);
      this.Offers_Form.get('applicable_adult_occupancy').setValue(data.applicable_adult_occupancy ? data.applicable_adult_occupancy.split(','):[]);
      this.Offers_Form.get('applicable_child_occupancy').setValue(data.applicable_child_occupancy ? data.applicable_child_occupancy.split(','):[]);
      this.Offers_Form.get('offer_days')?.setValue(data.offer_days ? data.offer_days.split(','):[]);
      this.Offers_Form.get('residence_type').setValue(data.offer_residence_type);
      this.Offers_Form.get('residence_applicable_type').setValue(data.residence_applicable_type);
      if(data.residence_applicable_type == 'SPECIFIC'){
        this.ResidenceShowhide(data.residence_applicable_type);
        this.Offers_Form.get('residence').setValue((data.residence.split(',')));
        this.CountryList = data.country ? JSON.parse(data.country) : [];
      }
      if(data.offer_days){
        this.Check_day_type();
      }
      this.Offers_Form.get('is_min_stay').setValue(data.is_min_stay);
      if(data.is_min_stay){
        this.MinStay(true);
        this.Offers_Form.get('min_stay_value').setValue(data.min_stay_value);
      }
      this.Offers_Form.get('is_max_stay').setValue(data.is_max_stay);
      if(data.is_max_stay){
        this.MaxStay(true);
        this.Offers_Form.get('max_stay_value').setValue(data.max_stay_value);
      }
      if(data.nationality_applicable_type == 'SPECIFIC'){
        this.NationalityShowhide('SPECIFIC');
        this.Offers_Form.get('nationality').setValue(data.nationality.split(','));
        this.CountryList = data.country ? JSON.parse(data.country) : [];
      }
      if(data.offer_type == 'STAYPAY'){
        this.Offers_Form.get('stay_pay_applicable_on').setValue(data.stay_pay_applicable_on);
        this.Offers_Form.get('stay_night').setValue(data.stay_night);
        this.Offers_Form.get('pay_night').setValue(data.pay_night);
        this.Offers_Form.get('discount_code').setValue(data.discount_code);
      }
      if(data.offer_type != 'STAYPAY' && data.offer_type != 'CONTRACTREMARK'){
        this.Offers_Form.get('discount_type').setValue(data.discount_type);
        this.Offers_Form.get('discount_value').setValue(data.discount_value);
        this.Offers_Form.get('discount_code').setValue(data.discount_code);
      }
      if(data.offer_type == 'CONTRACTREMARK'){
        this.Offers_Form.get('contract_remark').setValue(data.contract_remark);
      }
      if(data.offer_type == 'LONGSTAY'){
        this.Offers_Form.get('long_stay_night').setValue(data.long_stay_night);
        this.Offers_Form.get('discount_code').setValue(data.discount_code);
      }
      if(data.offer_type == 'EARLYBIRD'){
        this.Offers_Form.get('discount_code').setValue(data.discount_code);
      }
      if(data.date_criteria){
        let Date_Arr = JSON.parse(data.date_criteria);
        Date_Arr.forEach((date_data,ind)=>{
          if(ind > 0)this.addDate();
          this.Offers_Form.controls['date_criteria']['controls'][ind].get('booking_date_range').setValue([new Date(date_data.booking_date_range[0]),new Date(date_data.booking_date_range[1])])
          this.Offers_Form.controls['date_criteria']['controls'][ind].get('checkin_date_range').setValue([new Date(date_data.checkin_date_range[0]),new Date(date_data.checkin_date_range[1])])
          this.Offers_Form.controls['date_criteria']['controls'][ind].get('checkin_before_days')?.setValue(date_data.checkin_before_days)
        })
      }
      if( data.cancellation_policy_type == 'CUSTOMPOLICY'){
        let Cancel_Arr = JSON.parse(data.custom_cancellation_policy);
        this.Offers_Form.get('type').setValue(Cancel_Arr[0].type)
        Cancel_Arr.forEach((cancel_data,ind)=>{
          if(ind > 0)this.AddCancelArr(ind -1);
          this.Offers_Form.controls['custom_cancellation_policy']['controls'][ind].get('from').setValue(cancel_data.from)
          this.Offers_Form.controls['custom_cancellation_policy']['controls'][ind].get('to').setValue(cancel_data.to)
          this.Offers_Form.controls['custom_cancellation_policy']['controls'][ind].get('charge_type').setValue(cancel_data.charge_type)
          this.Offers_Form.controls['custom_cancellation_policy']['controls'][ind].get('charge_value').setValue(cancel_data.charge_value)
          this.Checkcanceltype(cancel_data.charge_type,ind);
          if(this.Offers_Form.controls['custom_cancellation_policy']['controls'][ind]['controls']['night_type']){
            this.Offers_Form.controls['custom_cancellation_policy']['controls'][ind].get('night_type').setValue(cancel_data.night_type)
          }
        })
      }else {
        this.Check_Cancel_Type()
      }
    }
  }
  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.Offers_Form.controls['residence_applicable_type'].value == 'ALL'){
        this.Offers_Form.get('residence_applicable_type').setValue('');
      }
    }
  }
  ResidenceShowhide(event){
    if(event == 'SPECIFIC'){
      this.Offers_Form.addControl('residence',new FormControl('',Validators.required))
    }else{
      this.Offers_Form.removeControl('residence');
    }
  }
}
