import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatCheckbox } from '@angular/material/checkbox';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { MessageService } from 'primeng/api';
import { ValidationService } from 'src/app/core/common/validation.service';
import { EditActivityContractRate, GetRateDetails, PaxPricing, PaxRates, TieredPricingList, VehicleRates } from 'src/app/core/models/Experience-Service/experience-rate-config-Edit/edit-rate-confi/edit-rate-confi.model';
import { ActivityPrivateTransfer, ActivitySharedTransfer } from 'src/app/core/models/Experience-Service/experience-rate-config/experience-rate-config.model';
import { API } from 'src/app/core/services/api.service';
import { CommonService } from 'src/app/core/services/common.service';

@Component({
  selector: 'app-edit-modify-rate',
  templateUrl: './edit-modify-rate.component.html',
})
export class EditModifyRateComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    public Fb: FormBuilder,
    public ApiServ: API,
    public validationService: ValidationService,
    public MsgService: MessageService,
    private router: Router,
  ) { }
  Pickup: string[] = [];
  CommonCalender: string[] = [];
  //
  FormData: FormGroup;
  currencyList;
  activityContractId;
  PaxDetails;
  vahicleDetails;
  activityData;
  AllSlots;
  AllVehicleBySupplierId = {
    Shared: [],
    Slots: []
  };;
  lovKeyDataObj = {
    RatePeriodType: [],
    DaySelect: [],
    RateConfigType: [],
    ActivityNoShowPolicyType: [],
    ActivityCancellationPolicyType: [],
    ActivityCancellationChargeType: [],
  };
  season_list;
  AllVehicleSupplier;
  AllContractTieredRate;
  HeaderTieredRateGroup = {
    adult_range: [],
    youth_range: [],
    senior_range: [],
    child_range: [],
  }
  TieredRatedynamicgroup: FormGroup;


  ngOnInit(): void {
    this.ngOninitform();
    this.GetAllCurrency();
    this.GetAllVehicleSupplier();
    this.GetLOVKeys('RatePeriodType,DaySelect,ActivityNoShowPolicyType,RateConfigType,ActivityCancellationPolicyType,ActivityCancellationChargeType');
    this.GetAllActivitySeason();
  }

  /**
   * @author Abdul Razzak
   * to create a form group 
   */
  ngOninitform() {
    this.FormData = this.Fb.group({
      activity_name: [''],
      option_name: [''],
      currency_code: [''],
      searchgroup: this.Fb.group({
        slot_id: [''],
        _rate_type: [''],
        period_type: [''],
        dates: [''],
        seasonId: [[]],
        days: [''],
      })
    });
  }

  /**
   * @author Abdul Razzak
   * to get form controller
   */

  get privateTransfer() {
    return this.FormData.get('privateTransfer') as FormArray;
  }

  get sharedTransfer() {
    return this.FormData.get('sharedTransfer') as FormGroup;
  }

  get paxformGroup() {
    return this.FormData.get('PaxDetails') as FormArray;
  }
  get tieredPricingsGroup() {
    return this.FormData.get('tieredPricings') as FormArray;
  }

  get VahicleformGroup() {
    return this.FormData.get('vahicle_list') as FormArray;
  }


  /**
 * @author Abdul Razzak
 * to get activity details
 */
  GetActivityById() {
    let activity_id = CommonService.getSessionStoage('activity_id');
    this.ApiServ.Get('/Activity/GetActivity/' + activity_id).subscribe(res => {
      if (res) {
        this.activityData = res.responseObject;
        this.FormData.get('activity_name').setValue(res.responseObject.activityContents[0].activity_name);
        this.getRateConfig();
      }
    })
  }

  /**
   * @author Abdul razzak
   * to get contract details 
   */
  getRateConfig() {
    this.route.queryParams.subscribe((obj) => {
      if (obj['id']) {
        this.activityContractId = obj['id'];
        this.GetSlotsById(obj['id'])
        this.ApiServ.Get('/ActivityContract/GetRateConfig/' + obj['id']).subscribe((res) => {
          if (res) {
            this.FormData.get('option_name').setValue(res.responseObject.option_name);
            this.FormData.get('currency_code').setValue(res.responseObject.currency_code);
            let val = parseInt(res.responseObject._rate_type)
            this.FormData.get('searchgroup').get('_rate_type').setValue(val);
            if (val == 2) {
              this.FormData.addControl('PaxDetails', this.Fb.array([
                this.Fb.group({
                  activity_rate_per_pax_id: [''],
                  date: [''],
                })
              ]))
              this.AddPaxController(this.paxformGroup.controls[0], false);
            } else if (val == 3) {
              this.FormData.addControl('vahicle_list', this.Fb.array([
                this.Fb.group({
                  date: [''],
                  vehicle_rates: this.Fb.array([
                    this.Fb.group({
                      activity_rate_per_vehicle_id: [''],
                      rate: [''],
                      vehicle_id: [''],
                      vehicle_name: [''],
                    })
                  ])
                })
              ]))
            } else if (val == 1) {
              this.ApiServ.Get('/ActivityContract/GetTieredRateTableView/' + this.activityContractId).subscribe(res => {
                if (res) {
                  this.FormData.addControl('tieredPricings', this.Fb.array([
                  ]))
                  res.responseObject.forEach((e, i) => {
                    this.tieredPricingsGroup.push(this.Fb.group({
                      date: [''],
                      activity_rate_tiered_id: [''],
                    }))
                    let controls = this.tieredPricingsGroup.controls[0] as FormGroup
                    if (e.adult_range) {
                      let adult_range = JSON.parse(e.adult_range);
                      this.HeaderTieredRateGroup.adult_range = adult_range;
                      adult_range.forEach((r, i) => {
                        controls.addControl('adult_rate_range_' + (i + 1), this.Fb.control(''));
                      })
                    }
                    if (e.youth_range) {
                      let youth_range = JSON.parse(e.youth_range);
                      this.HeaderTieredRateGroup.youth_range = youth_range;
                      youth_range.forEach((r, i) => {
                        controls.addControl('youth_rate_range_' + (i + 1), this.Fb.control(''));
                      })
                    }
                    if (e.senior_range) {
                      let senior_range = JSON.parse(e.senior_range);
                      this.HeaderTieredRateGroup.senior_range = senior_range;
                      senior_range.forEach((r, i) => {
                        controls.addControl('senior_rate_range_' + (i + 1), this.Fb.control(''));
                      })
                    }
                    if (e.child_range) {
                      let child_range = JSON.parse(e.child_range);
                      this.HeaderTieredRateGroup.child_range = child_range;
                      child_range.forEach((r, i) => {
                        controls.addControl('child_rate_range_' + (i + 1), this.Fb.control(''));
                      })
                    }
                  })
                }
              });
            }
            if (res.responseObject.is_shared_transfer) this.AddSharedTransferControls(true, res.responseObject.shared_transfer);
            if (res.responseObject.is_private_transfer) this.AddPrivateTransferControls(true, res.responseObject.private_transfer);
          }
        });
      }
    });
  }


  /**
   * @author Abdul Razzak
   * to get slot data by contract id  
   * @param Id 
   */
  GetSlotsById(Id) {
    this.ApiServ.Get('/ActivityContract/GetSlotsById/' + Id).subscribe(res => {
      if (res) {
        this.AllSlots = res.responseObject;
      }
    })
  }

  /**
   * @author Abdul Razzak
   * to create Tiered Pricings FormGroup
   * @param ind 
   */
  createTieredGroup(ind) {
    this.tieredPricingsGroup.push(this.Fb.group({
      date: [''],
      activity_rate_tiered_id: [''],
    }))
    let controls = this.tieredPricingsGroup.controls[ind] as FormGroup
    if (this.HeaderTieredRateGroup.adult_range) {
      this.HeaderTieredRateGroup.adult_range.forEach((r, i) => {
        controls.addControl('adult_rate_range_' + (i + 1), this.Fb.control(''));
      })
    }
    if (this.HeaderTieredRateGroup.youth_range) {
      this.HeaderTieredRateGroup.youth_range.forEach((r, i) => {
        controls.addControl('youth_rate_range_' + (i + 1), this.Fb.control(''));
      })
    }
    if (this.HeaderTieredRateGroup.senior_range) {
      this.HeaderTieredRateGroup.senior_range.forEach((r, i) => {
        controls.addControl('senior_rate_range_' + (i + 1), this.Fb.control(''));
      })
    }
    if (this.HeaderTieredRateGroup.child_range) {
      this.HeaderTieredRateGroup.child_range.forEach((r, i) => {
        controls.addControl('child_rate_range_' + (i + 1), this.Fb.control(''));
      })
    }
  }



  /**
   * @author Abdul Razzak
   * To Get  All Activity Season
   */
  GetAllActivitySeason() {
    this.ApiServ.Get('/ActivitySeason/GetAllActivitySeason?activityId=' + CommonService.getSessionStoage('activity_id')).subscribe(d => {
      if (d && d.status) {
        this.season_list = d.responseObject;
      }
    });
  }


  /**
   * @author Abdul Razzak
   *  To Get All Vehicle Supplier
   */
  GetAllVehicleSupplier() {
    this.ApiServ.Get('/Vehicle/GetAllVehicleSupplier').subscribe((res) => {
      if (res) {
        this.AllVehicleSupplier = res.responseObject;
      }
    });
  }

  /**
   * @author Abdul Razzak
   * To get all curency
   */
  GetAllCurrency() {
    this.ApiServ.Get('/Currency/GetCurrency').subscribe((d) => {
      if (d) this.currencyList = d;
    });
  }


  /**
   * @author Abdul Razzak
   * TO get Get All Vehicle details by supplier Id
   * @param Id 
   * @param name 
   * @param i 
   */
  GetAllVehicleBySupplierId(Id, name, i) {
    this.ApiServ.Get('/Vehicle/GetAllVehicleBySupplier/' + Id).subscribe((res) => {
      if (res) {
        this.AllVehicleBySupplierId[name][i] = []
        this.AllVehicleBySupplierId[name][i] = res.responseObject;
      }
    });
  }


  /**
  * @author Abdul Razzak
  *  to get data from LOV
  * @param lov_key_names  
  */
  GetLOVKeys(lov_key_names) {
    let lov_key_names_arr = lov_key_names.split(',');
    let lov_obj = {
      "lov_types": [],
      "lov_lang": "en"
    }
    lov_key_names_arr.forEach(key_name => {
      lov_obj.lov_types.push({ "lov_type": key_name });
    });
    this.ApiServ.Post('/LovMaster/GetLov', lov_obj).subscribe(lov_data => {
      if (lov_data && lov_data.status) {
        this.GetActivityById();
        lov_key_names_arr.forEach(key_name => {
          let arr = lov_data.responseObject.filter(el => el.lov_type == key_name);
          arr.length > 0 ? this.lovKeyDataObj[key_name] = arr[0].keys : '';
        });
      }
    });
  }


  /**
  * @author Abdul Razzak
  * to get Per Pax Details , Vehicle Rate and Tiered Rate
  */
  Search() {
    let val = this.FormData.get('searchgroup').get('_rate_type').value;
    let searchform = this.FormData.get('searchgroup').value;
    let postdata = new GetRateDetails();
    postdata.contract_id = this.activityContractId;
    postdata.slot_id = searchform.slot_id;
    postdata.from_date = searchform.dates[0] ? moment(searchform.dates[0]).format('YYYY-MM-DD') : '';
    postdata.to_date = searchform.dates[1] ? moment(searchform.dates[1]).format('YYYY-MM-DD') : '';
    postdata.seasonId = searchform.seasonId;
    postdata.days = searchform.days ? searchform.days.join(',') : '';
    if (val == 2) {
      this.getPerPaxDetails(postdata);
    } else if (val == 3) {
      this.GetVehicleRate(postdata);
    } else if (val == 1) {
      this.GetActivityTieredRate(postdata);
    }
  }

  //  private Transfer  --------------------------------------------------------------------

  /**
   * @author Abdul Razzak
   * to create private Transfer form array
   * @param check 
   * @param Data 
   */
  AddPrivateTransferControls(check, Data) {
    if (check) {
      this.FormData.addControl('privateTransfer', this.Fb.array([
      ]))
      let Obj = JSON.parse(Data)
      Obj.forEach((e, i) => {
        this.AddPrivateTransferGroup(e, i);
      });
    }
  }

  /**
   * @author Abdul Razzak
   * to create pax controls on form group
   * @param Data 
   * @param ind 
   */
  AddPrivateTransferGroup(Data, ind) {
    Data ? this.GetAllVehicleBySupplierId(Data.vehicle_supplier_id, 'Shared', ind) : ''
    this.privateTransfer.push(this.Fb.group({
      // activity_pvt_transfer_add_on_id: [Data.activity_pvt_transfer_add_on_id],
      vehicle_supplier_id: [Data ? Data.vehicle_supplier_id : '', Validators.required],
      vehicle_id: [Data ? Data.vehicle_id : '', Validators.required],
      vehicle_occupancy: [Data ? Data.vehicle_occupancy : '', Validators.required],
      rate: [Data ? Data.rate : '', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]],
    }))
  }

  /**
   * @author Abdul Razzak
   * to remove form group on privete transfer
   * @param ind 
   */
  RemovePrivateformGroup(ind) {
    this.privateTransfer.removeAt(ind);
  }

  /**
   * @author Abdul Razzak
   * to clear formcontrols value when period type change
   */
  ClearDateAndSeason() {
    let val = this.FormData.get('searchgroup').get('period_type').value;
    if (val == 2) this.FormData.get('searchgroup').get('dates').setValue('');
    else if (val == 1) this.FormData.get('searchgroup').get('seasonId').setValue([]);
  }

  //  shared transfer --------------------------------------------------------------------

  /**
   * @author  Abdul Razzak
   * to add contols on shared transfer
   * @param check 
   */
  AddSharedTransferControls(check, data) {
    if (check) {
      this.FormData.addControl('sharedTransfer', this.Fb.group({}))
      let obj = JSON.parse(data)
      this.sharedTransfer.addControl('vehicle_supplier_id', this.Fb.control(obj[0].vehicle_supplier_id, [Validators.required]));
      this.sharedTransfer.addControl('activity_shared_transfer_add_on_id', this.Fb.control(obj[0].activity_shared_transfer_add_on_id, [Validators.required]));
      if (this.activityData.is_adult) this.sharedTransfer.addControl('adult_rate', this.Fb.control(obj[0].adult_rate, [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
      if (this.activityData.is_senior) this.sharedTransfer.addControl('senior_rate', this.Fb.control(obj[0].senior_rate, [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
      if (this.activityData.is_youth) this.sharedTransfer.addControl('youth_rate', this.Fb.control(obj[0].youth_rate, [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
      if (this.activityData.is_child) this.sharedTransfer.addControl('child_rate', this.Fb.control(obj[0].child_rate, [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
    }
    // else {
    //   this.sharedTransfer.removeControl('vehicle_supplier_id');
    //   this.sharedTransfer.removeControl('activity_shared_transfer_add_on_id');
    //   if (this.activityData.is_adult) this.sharedTransfer.removeControl('adult_rate');
    //   if (this.activityData.is_senior) this.sharedTransfer.removeControl('senior_rate');
    //   if (this.activityData.is_youth) this.sharedTransfer.removeControl('youth_rate');
    //   if (this.activityData.is_child) this.sharedTransfer.removeControl('child_rate');
    // }
  }

  //  per pax details --------------------------------------------------------------------

  /**
   * @author Abdul Razzak
   * to get contract pax details
   * @param postdata 
   */
  getPerPaxDetails(postdata) {
    this.ApiServ.Post('/ActivityContract/GetRatePerPax', postdata).subscribe((data) => {
      if (data) {
        this.PaxDetails = data.responseObject;
        data.responseObject ? this.setpaxValue(data.responseObject) : '';
      }
    });
  }

  /**
   * @author Abdul Razzak
   * to create form group and set value 
   * @param data 
   */
  setpaxValue(data) {
    this.paxformGroup.clear();
    this.paxformGroup.push(this.Fb.group({
      activity_rate_per_pax_id: [''],
      date: [''],
    }))
    this.AddPaxController(this.paxformGroup.controls[0], false);
    data.forEach((e, i) => {
      this.paxformGroup.push(
        this.Fb.group({
          activity_rate_per_pax_id: [e['activity_rate_per_pax_id']],
          date: [e['date']],
        })
      );
      this.AddPaxController(this.paxformGroup.controls[i + 1], data[i]);
    });
  }

  /**
   * @author Abdul Razzak
   * to create pax control  
   * @param group 
   * @param value 
   */
  AddPaxController(group, value) {
    if (this.activityData.is_adult) group.addControl('adult_rate', this.Fb.control(value ? value.adult_rate : '', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
    if (this.activityData.is_senior) group.addControl('senior_rate', this.Fb.control(value ? value.senior_rate : '', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
    if (this.activityData.is_youth) group.addControl('youth_rate', this.Fb.control(value ? value.youth_rate : '', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
    if (this.activityData.is_child) group.addControl('child_rate', this.Fb.control(value ? value.child_rate : '', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
  }

  /**
   * @author Abdul Razzak
   * to set all pax rate value  form copy on UI button
   */
  setallpaxdetails() {
    let val = this.paxformGroup.getRawValue();
    if (val[0].adult_rate != '') {
      this.setValueFormUi('adult_rate');
    }
    if (val[0].senior_rate != '') {
      this.setValueFormUi('senior_rate');
    }
    if (val[0].youth_rate != '') {
      this.setValueFormUi('youth_rate');
    }
    if (val[0].child_rate != '') {
      this.setValueFormUi('child_rate');
    }
  }

  setValueFormUi(name) {
    let obj = this.paxformGroup.getRawValue();
    for (let i = 1; i < obj.length; i++) {
      Object.keys(obj[i]).map((e) => {
        if (e == name) {
          this.paxformGroup.controls[i].get(e).setValue(obj[0][name]);
        }
      });
    }
  }

  //  Vehicle Rate --------------------------------------------------------------------

  /**
   * @author Abdul Razzak
   * to get contract vehicle details
   * @param postdata 
   */
  GetVehicleRate(postdata) {
    this.ApiServ.Post('/ActivityContract/GetVehicleRate', postdata).subscribe(
      (data) => {
        if (data) {
          console.log(data);
          if (data.responseObject) {
            this.vahicleDetails = data.responseObject;
            data.responseObject ? this.setvahicleValue(data.responseObject) : '';
          }
        }
      }
    );
  }

  /** 
   * @author Abdul Razzak
   * to creta form group and set value on vehicle rate group
   */
  setvahicleValue(data) {
    this.VahicleformGroup.clear();
    this.VahicleformGroup.push(
      this.Fb.group({
        date: [''],
        vehicle_rates: this.Fb.array([])
      })
    )
    this.CreateFormGroup(data[0], this.VahicleformGroup.controls[0].get('vehicle_rates'), false);
    data.forEach((value, i) => {
      this.VahicleformGroup.push(
        this.Fb.group({
          date: [value['date']],
          vehicle_rates: this.Fb.array([])
        })
      );
      let VehicleRatesGroup = this.VahicleformGroup.controls[i + 1].get('vehicle_rates') as FormArray;
      this.CreateFormGroup(value, VehicleRatesGroup, true);
    });
  }

  CreateFormGroup(value, VehicleRatesGroup, check) {
    value.vehicle_rates.forEach((e) => {
      VehicleRatesGroup.push(this.Fb.group({
        activity_rate_per_vehicle_id: [check ? e.activity_rate_per_vehicle_id : ''],
        rate: [check ? e.rate : ''],
        vehicle_id: [check ? e.vehicle_id : ''],
        vehicle_name: [check ? e.vehicle_name : ''],
      }))
    })
  }

  /**
   * @author Abdul Razzak
   * to set all vehicle rate price 
   */
  CopyOnUIvehicle() {
    let val = this.VahicleformGroup.controls[0].get('vehicle_rates').value;
    if (this.VahicleformGroup.controls.length > 1) {
      let obj = this.VahicleformGroup.getRawValue();
      obj.forEach((e, i) => {
        val.forEach((d, li) => {
          this.VahicleformGroup.controls[i].get('vehicle_rates')['controls'][li].get('rate').setValue(d.rate)
        });
      });
    };
  };


  // Tiered Rate --------------------------------------------------------------------

  /**
   * @author Abdul Razzak
   * to get all Tiered Rate details
   * @param PostData 
   */
  GetActivityTieredRate(PostData) {
    this.ApiServ.Post('/ActivityContract/GetActivityTieredRate', PostData).subscribe((res) => {
      if (res) {
        this.AllContractTieredRate = res.responseObject;
        this.tieredPricingsGroup.clear();
        this.createTieredGroup(0)
        this.AllContractTieredRate.forEach((e, i) => {
          let ind = i + 1;
          this.createTieredGroup(ind)
          let val = this.tieredPricingsGroup.controls[ind].value;
          Object.keys(val).forEach((l) => {
            this.tieredPricingsGroup.controls[ind].get(l).setValue(e[l]);
          });
        })
      }
    })
  }


  /**
   * @author Abdul Razzak
   * to set all Tiered Rate  value 
   */
  SetTieredRateValCopyUi() {
    let val = this.tieredPricingsGroup.controls[0].value;
    if (this.tieredPricingsGroup.controls.length > 1) {
      let obj = this.tieredPricingsGroup.getRawValue();
      obj.forEach((e, i) => {
        if (this.HeaderTieredRateGroup.adult_range) {
          this.HeaderTieredRateGroup.adult_range.forEach((d, li) => {
            let name = 'adult_rate_range_' + (li + 1)
            this.tieredPricingsGroup.controls[i].get(name).setValue(val[name]);
          })
        }
        if (this.HeaderTieredRateGroup.senior_range) {
          this.HeaderTieredRateGroup.senior_range.forEach((d, li) => {
            let name = 'senior_rate_range_' + (li + 1)
            this.tieredPricingsGroup.controls[i].get(name).setValue(val[name]);
          })
        }
        if (this.HeaderTieredRateGroup.youth_range) {
          this.HeaderTieredRateGroup.youth_range.forEach((d, li) => {
            let name = 'youth_rate_range_' + (li + 1)
            this.tieredPricingsGroup.controls[i].get(name).setValue(val[name]);
          })
        }
        if (this.HeaderTieredRateGroup.child_range) {
          this.HeaderTieredRateGroup.child_range.forEach((d, li) => {
            let name = 'child_rate_range_' + (li + 1)
            this.tieredPricingsGroup.controls[i].get(name).setValue(val[name]);
          })
        }
      });
    };
  }




  UpdateRate() {
    let val = this.FormData.getRawValue()
    let postdata = new EditActivityContractRate();
    postdata.activity_contract_id = this.activityContractId;
    postdata.activity_slot_id = '';

    // private Transfer
    let privateTransferArr = []
    if (val.privateTransfer) {
      val.privateTransfer.forEach((e) => {
        let PostPrivateTransfer = new ActivityPrivateTransfer();
        PostPrivateTransfer.rate = e.rate;
        PostPrivateTransfer.vehicle_id = e.vehicle_id;
        PostPrivateTransfer.vehicle_occupancy = e.vehicle_occupancy;
        PostPrivateTransfer.vehicle_supplier_id = e.vehicle_supplier_id;
        privateTransferArr.push(PostPrivateTransfer)
      })
    }
    postdata.privateTransfer = val.privateTransfer ? privateTransferArr : [];

    //  shared Transfer
    let PostSharedTransfer = new ActivitySharedTransfer();
    if (val.sharedTransfer) {
      let value = val.sharedTransfer
      PostSharedTransfer.vehicle_supplier_id = value.vehicle_supplier_id;
      PostSharedTransfer.adult_rate = value.adult_rate;
      PostSharedTransfer.child_rate = value.child_rate;
      PostSharedTransfer.senior_rate = value.senior_rate;
      PostSharedTransfer.youth_rate = value.youth_rate;
    }
    postdata.sharedTransfer = val.sharedTransfer ? PostSharedTransfer : null;

    //  per pax prices
    let PaxDetailsArr = []
    if (val.PaxDetails) {
      val.PaxDetails.splice(0, 1);
      val.PaxDetails.forEach((e) => {
        let postpaxrate = new PaxRates();
        postpaxrate.activity_rate_per_pax_id = e.activity_rate_per_pax_id;
        postpaxrate.adult_rate = e.adult_rate ? e.adult_rate : 0;
        postpaxrate.child_rate = e.child_rate ? e.child_rate : 0;
        postpaxrate.senior_rate = e.senior_rate ? e.senior_rate : 0;
        postpaxrate.youth_rate = e.youth_rate ? e.youth_rate : 0;
        PaxDetailsArr.push(postpaxrate)
      });
    }
    postdata.perPaxPrices = val.PaxDetails ? PaxDetailsArr : [];

    // per Vehicle Rates
    let VahiclelistArr = []
    if (val.vahicle_list) {
      val.vahicle_list.splice(0, 1);
      val.vahicle_list.forEach((q) => {
        q.vehicle_rates.forEach((e) => {
          let PostVahiclelist = new VehicleRates();
          PostVahiclelist.activity_rate_per_vehicle_id = e.activity_rate_per_vehicle_id;
          PostVahiclelist.rate = e.rate;
          PostVahiclelist.vehicle_id = e.vehicle_id;
          PostVahiclelist.vehicle_max_occupancy = e.vehicle_max_occupancy;
          PostVahiclelist.vehicle_supplier_id = e.vehicle_supplier_id;
          VahiclelistArr.push(PostVahiclelist)
        })
      })
    }
    postdata.perVehicleRates = val.vahicle_list ? VahiclelistArr : [];

    // tiered Pricings
    let PostTieredPricings = [];
    if (val.tieredPricings) {
      if (val.tieredPricings.length > 1) {
        val.tieredPricings.splice(0, 1);
        val.tieredPricings.forEach(e => {
          let postList = new TieredPricingList();
          postList.id = e.activity_rate_tiered_id;
          let pricingArr = []
          if (this.HeaderTieredRateGroup.adult_range) {
            this.HeaderTieredRateGroup.adult_range.forEach((r, i) => {
              let post = new PaxPricing();
              post.rate = e['adult_rate_range_' + (i + 1)];
              post.sequence = (i + 1);
              post.pax_type = 'adult';
              pricingArr.push(post);
            })
          }
          if (this.HeaderTieredRateGroup.youth_range) {
            this.HeaderTieredRateGroup.youth_range.forEach((r, i) => {
              let post = new PaxPricing();
              post.rate = e['youth_rate_range_' + (i + 1)];
              post.sequence = (i + 1);
              post.pax_type = 'youth';
              pricingArr.push(post);
            })
          }
          if (this.HeaderTieredRateGroup.senior_range) {
            this.HeaderTieredRateGroup.senior_range.forEach((r, i) => {
              let post = new PaxPricing();
              post.rate = e['senior_rate_range_' + (i + 1)];
              post.sequence = (i + 1);
              post.pax_type = 'senior';
              pricingArr.push(post);
            })
          }
          if (this.HeaderTieredRateGroup.child_range) {
            this.HeaderTieredRateGroup.child_range.forEach((r, i) => {
              let post = new PaxPricing();
              post.rate = e['child_rate_range_' + (i + 1)];
              post.sequence = (i + 1);
              post.pax_type = 'child';
              pricingArr.push(post);
            })
          }
          postList.pricing = pricingArr;
          PostTieredPricings.push(postList)
        })
      }
      postdata.tieredPricings = val.tieredPricings.length > 1 ? PostTieredPricings : [];
    }
    this.ApiServ.Post('/ActivityContract/UpdateRateConfig', postdata).subscribe((res) => {
      if (res) {
        this.showToastrMsg(res)
      }
    })
  }

  /**
    * @author Abdul Razzak
    * to show toaster
    * @param respData 
    */
  showToastrMsg(respData) {
    this.MsgService.add({
      severity: respData['status'] ? 'success' : 'error',
      detail: respData['message'],
    });
    setTimeout(() => {
      respData['status'] ? this.btnClick() : '';
    }, 500);
  }

  /**
   * @author Abdul razzak
   * to navigate overview tab
   */
  btnClick() {
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage'])
  }

  /**
   * @author Abdul Razzak
   * to reset search value
   */
  reset() {
    this.FormData.get('searchgroup').get('slot_id').setValue('');
    this.FormData.get('searchgroup').get('period_type').setValue('');
    this.FormData.get('searchgroup').get('dates').setValue('');
    this.FormData.get('searchgroup').get('seasonId').setValue([]);
    this.FormData.get('searchgroup').get('days').setValue('');
  }


  // ----------------------------------------------------------------------------------------

  // addvalid(name, type, num) {
  //   if (type == 'add') {
  //     if (num == 'number') {
  //       this.FormData.controls[name].addValidators([
  //         Validators.pattern(/^[0-9]*$/),
  //       ]);
  //       this.FormData.controls[name].updateValueAndValidity();
  //     } else {
  //       this.FormData.controls[name].addValidators([Validators.required]);
  //       this.FormData.controls[name].updateValueAndValidity();
  //     }
  //   } else {
  //     this.FormData.controls[name].clearValidators();
  //     this.FormData.controls[name].updateValueAndValidity();
  //     this.FormData.controls[name].markAsUntouched();
  //   }
  // }
  // ----------------------------------------------------------------------------------------------
  //  for calender 

  // checkcleander() {
  //   let value = this.FormData.getRawValue();
  //   if (value.Search_date[0] && value.Search_date[1]) {
  //     this.datePicker.overlayVisible = false;
  //   }
  // } 
}
