import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import * as moment from 'moment';
import { MessageService } from 'primeng/api';
import { StaticDataService } from 'src/app/core/common/static-data.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { ActivityCancellationDetails, ActivityContract, ActivityDetails, ActivityPaxRate, ActivityPrivateTransfer, ActivitySharedTransfer, ActivityVehicleRate, AgeRange, AllocationDetails, DateRange, RateRange, SaveActivityContractDetails, SlotDetails, Slots, Specific } from 'src/app/core/models/Experience-Service/experience-rate-config/experience-rate-config.model';
import { GetActivitySlot } from 'src/app/core/models/Experience-Service/slot/add-slots-model';
import { API } from 'src/app/core/services/api.service';
import { CommonService } from 'src/app/core/services/common.service';
interface grp {
  name: string;
  code: string;
}
@Component({
  selector: 'app-add-rate-config',
  templateUrl: './add-rate-config.component.html',
})
export class AddRateConfigComponent implements OnInit {
  minDate = new Date();
  RateConfigForm: FormGroup;
  currencyList;
  LangList = [];
  slotList = [];
  activityData;
  include_nationality_list;
  exclude_nationality_list;
  all_nationality_list;
  season_list = <any>[];
  fil_season_list = [];
  PhoneCode;
  allCityDetials;
  AgeRange:FormGroup;
  lovKeyDataObj = {
    RatePeriodType: [],
    RateSlotType: [],
    CancellationPolicyType: [],
    NoShowType: [],
    Language: [],
    RateConfigType: [],
    DaySelect: [],
    ActivityNoShowPolicyType: [],
    ActivityCancellationPolicyType: [],
    ActivityCancellationChargeType: [],
  };
  Vehicle_Selection = [
    { id: 1, name: 'Mercedes S Class' },
    { id: 2, name: 'Coach 20 Seater' },
    { id: 3, name: 'Helicopter' }
  ];
  Day = [
    { id: 1, name: 'Mon' },
    { id: 2, name: 'Tue' },
    { id: 3, name: 'Wed' },
    { id: 4, name: 'Thu' },
    { id: 5, name: 'Fri' },
    { id: 6, name: 'Sat' },
    { id: 0, name: 'Sun' },
    { id: 7, name: 'Select All' },
  ];
  DayList = this.Day[0].name;
  TransferType = [
    { id: 1, name: 'Private' },
    { id: 2, name: 'Shared' },
    { id: 3, name: 'Without Transfer' },
  ];
  constructor(
    public fb: FormBuilder,
    public validationService: ValidationService,
    public APIServ: API,
    public CommonVari: StaticDataService,
    public MsgService: MessageService,
    private router: Router,
  ) { }

  ngOnInit(): void {
    this.GetAllCurrency();
    this.GetPhoneCode();
    this.GetAllNationality();
    this.GetAllActivitySeason();
    this.GetAllVehicleSupplier();
    this.getCountry();
    this.initRateConfigForm();
    // this.CancellationPlicyformCheck(false);
    this.GetAllSlot();
    // this.GetAllVehicle();
    this.GetLOVKeys('RatePeriodType,RateSlotType,CancellationPolicyType,NoShowType,RateConfigType,Language,DaySelect,ActivityNoShowPolicyType,ActivityCancellationPolicyType,ActivityCancellationChargeType');
    this.AgeRange = this.fb.group({
      from_count: [''],
      to_count: [''],
      sequence: [''],
      rate: [''],
    });
  }

  // CONTROL
  get DateControl() {
    return this.RateConfigForm.get('datesForRates') as FormArray;
  }

  get DaysControl() {
    return this.RateConfigForm.get('contract_days') as FormArray;
  }

  get SlotsDetail() {
    return this.RateConfigForm.get('slotDetails') as FormArray;
  }

  get CancelControl() {
    return this.RateConfigForm.get('activityCancellationDetails') as FormArray;
  }

  get SlotsControl() {
    return this.RateConfigForm.get('slots') as FormArray;
  }

  get privateTransferDataList() {
    return this.RateConfigForm.get('privateTransferDataList') as FormArray;
  }

  VehicleControl(i) {
    return this.SlotsControl.controls[i].get('activityVehicleRate') as FormArray;
  }

  PaxControl(i) {
    return this.SlotsControl.controls[i].get('activityPaxRate') as FormArray;
  }
  get activityPaxRateGroup() {
    return this.RateConfigForm.get('activityPaxRate') as FormGroup;
  }

  TieredControl(i) {
    return this.SlotsControl.controls[i].get('allSlotRateRange') as FormArray;
  }

  AdultTControl(i, ind) {
    return this.TieredControl(i).controls[ind].get("adultAgeRange") as FormArray;
  }

  YouthTControl(i, ind) {
    return this.TieredControl(i).controls[ind].get("youthAgeRange") as FormArray;
  }

  SeniorTControl(i, ind) {
    return this.TieredControl(i).controls[ind].get("seniorAgeRange") as FormArray;
  }

  ChildTControl(i, ind) {
    return this.TieredControl(i).controls[ind].get("childAgeRange") as FormArray;
  }

  InfantTControl(i, ind) {
    return this.TieredControl(i).controls[ind].get("infantAgeRange") as FormArray;
  }


  initRateConfigForm() {
    this.RateConfigForm = this.fb.group({
      experience_name: [''],
      org_id: ['2105311837100000021'],
      supplier_id: ['2205221841391724322'],
      pricing_slots: [''],
      currency_code: this.validationService.required,
      country_name: [''],
      city_name: [''],
      option_name: this.validationService.required,
      rate_inclusion: [''],
      contract_remark: [''],
      _period_type: this.validationService.required,
      is_pickup_included: [false],
      is_drop_off_included: [false],
      is_guide_included: [false],

      _nationality_type: ['1'],
      is_exclude_nationality: [false],

      is_private_transfer_price_included: [false],
      is_shared_transfer_price_included: [false],
      is_slot_wise_cancellation_policy: [false],
      _no_show_policy_type: this.validationService.required,

      slotDetails: this.fb.array([
        this.fb.group({
          slots: this.validationService.required,
          transfer_type: [''],
        })
      ]),
      slots: this.fb.array([
        this.fb.group({
          applicableDays: this.validationService.required,
          _rate_type: this.validationService.required,
          _pricing_type: this.validationService.required,
          SlotId: [''],
          // activityPaxRate:
          //   this.fb.group({
          //     date: [''],
          //     allocation_count: [''],
          //     release_days: [''],
          //     is_free_sales: [false],
          //   }),
          // allSlotRateRange: this.fb.array([
          //   this.fb.group({
          //     allocation_count: [''],
          //     release_days: [''],
          //     is_free_sales: [false],
          //   })
          // ]),
          // activityVehicleRate:
          //   this.fb.array([
          //     this.fb.group({
          //       rate: this.validationService.decimal,
          //       vehicleSupplier: this.validationService.required,
          //       vehicle: this.validationService.required,
          //       vehicle_max_occupancy: [''],
          //       allocation_count: [''],
          //       release_days: [''],
          //       is_free_sales: [false],
          //     })
          //   ]),
          // activityCancellationDetails: this.fb.array([
          //   this.fb.group({
          //     from: [''],
          //     to: [''],
          //     CP_Type: [''],
          //     CP_Value: [''],
          //     cancellation_Type: [''],
          //   })
          // ])
        })
      ]),
      guide_languages: ['']
    });
    this.CancellationPlicyformCheck(false);
  }


  addSlotForm() {
    this.RateConfigForm.get('slots')
  }

  AddContolsForRateType(val) {
    if (val == 1) {
      this.SlotsControl.controls.forEach((e, i) => {
        let form = e as FormGroup
        form.addControl('allSlotRateRange', this.fb.array([
          this.fb.group({
            allocation_count: this.validationService.mobNo,
            release_days: this.validationService.mobNo,
            is_free_sales: [false],
          })
        ]));
        this.addcontolsforpax(this.SlotsControl.controls[i], 'allSlotRateRange')
        form.removeControl('activityVehicleRate')
        form.removeControl('activityPaxRate')
      })
    } else if (val == 2) {
      this.SlotsControl.controls.forEach((e, i) => {
        let form = e as FormGroup
        form.addControl('activityPaxRate',
          this.fb.group({
            date: [''],
            allocation_count: this.validationService.mobNo,
            release_days: this.validationService.mobNo,
            is_free_sales: [false],
          })
        )
        this.addcontolsforpax(this.SlotsControl.controls[i], 'activityPaxRate')
        form.removeControl('activityVehicleRate');
        form.removeControl('allSlotRateRange');
      })
    } else if (val == 3) {
      this.SlotsControl.controls.forEach((e, i) => {
        let form = e as FormGroup
        form.addControl('activityVehicleRate',
          this.fb.array([
            this.fb.group({
              rate: this.validationService.decimal,
              vehicleSupplier: this.validationService.required,
              vehicle: this.validationService.required,
              vehicle_max_occupancy: [''],
              allocation_count: this.validationService.mobNo,
              release_days: this.validationService.mobNo,
              is_free_sales: [false],
            })
          ]),
        );
        this.addcontolsforpax(this.SlotsControl.controls[i], '')
        form.removeControl('allSlotRateRange');
        form.removeControl('activityPaxRate');
      })
    }
  }

  AddSharedTransferControls(check) {
    if (check) {
      this.RateConfigForm.addControl('vehicle_supplier_id', this.fb.control('', [Validators.required]));
      if (this.PaxCheck.is_adult.value) this.RateConfigForm.addControl('adult_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
      if (this.PaxCheck.is_senior.value) this.RateConfigForm.addControl('senior_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
      if (this.PaxCheck.is_youth.value) this.RateConfigForm.addControl('youth_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
      if (this.PaxCheck.is_child.value) this.RateConfigForm.addControl('child_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
    } else {
      this.RateConfigForm.removeControl('vehicle_supplier_id');
      if (this.PaxCheck.is_adult.value) this.RateConfigForm.removeControl('adult_rate');
      if (this.PaxCheck.is_senior.value) this.RateConfigForm.removeControl('senior_rate');
      if (this.PaxCheck.is_youth.value) this.RateConfigForm.removeControl('youth_rate');
      if (this.PaxCheck.is_child.value) this.RateConfigForm.removeControl('child_rate');
    }
  }

  AddactivityVehicleRateGroup(group) {
    group.get('activityVehicleRate').push(this.fb.group({
      rate: this.validationService.decimal,
      vehicleSupplier: this.validationService.required,
      vehicle: this.validationService.required,
      vehicle_max_occupancy: [''],
      allocation_count: this.validationService.mobNo,
      release_days: this.validationService.mobNo,
      is_free_sales: [false],
    }));
  }
  RemoveactivityVehicleRateGroup(group, ind) {
    group.get('activityVehicleRate').removeAt(ind);
  }
  addSlotCancelPolicy(group) {
    group.get('activityCancellationDetails').push(this.fb.group({
      cancellation_Type: [''],
      from: [''],
      to: [''],
      CP_Type: [''],
      CP_Value: [''],
    }));
  }


  removeSlotCancelPolicy(group, ind) {
    group.get('activityCancellationDetails').removeAt(ind);
  }
  CancellationPlicyformCheck(check) {
    if (!check) {
      this.RateConfigForm.addControl('activityCancellationDetails', this.fb.array([
        this.fb.group({
          from: this.validationService.mobNo,
          to: this.validationService.mobNo,
          CP_Type: this.validationService.required,
          cancellation_Type: this.validationService.required,
        })
      ]));
      this.SlotsControl.controls.forEach(obj => {
        let form = obj as FormGroup;
        form.removeControl('activityCancellationDetails');
      })
    } else {
      this.SlotsControl.controls.forEach(obj => {
        let form = obj as FormGroup;
        form.addControl('activityCancellationDetails', this.fb.array([
          this.fb.group({
            from: this.validationService.mobNo,
            to: this.validationService.mobNo,
            CP_Type: this.validationService.required,
            cancellation_Type: this.validationService.required,
          })
        ]))
      })
      this.RateConfigForm.removeControl('activityCancellationDetails');
    }
  }

  Cancellation_Type(group, ind) {
    if (ind != 1) {
      group.addControl('CP_Value', this.fb.control('', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
    } else {
      group.removeControl('CP_Value');
    }
  }
  No_Show_Type(ind) {
    if (ind != 1) {
      this.RateConfigForm.addControl('no_show_charge_value', this.fb.control('', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
    } else {
      this.RateConfigForm.removeControl('no_show_charge_value');
    }
  }
  AddPrivateTransferControls(check) {
    if (check) {
      this.RateConfigForm.addControl('privateTransferDataList', this.fb.array([
        this.fb.group({
          vehicle_supplier_id: this.validationService.required,
          vehicle_id: this.validationService.required,
          vehicle_occupancy: [''],
          rate: this.validationService.decimal,
        })
      ]))
    } else {
      this.RateConfigForm.removeControl('privateTransferDataList');
    }
  }
  AddPrivateTransferGroup() {
    this.privateTransferDataList.push(this.fb.group({
      vehicle_supplier_id: this.validationService.required,
      vehicle_id: this.validationService.required,
      vehicle_occupancy: [''],
      rate: this.validationService.decimal,
    }))
  }





  // ADD FUNCTION
  AddSlots() {
    let val = this.RateConfigForm.get('is_slot_wise_cancellation_policy').value;
    if (val) {
      this.SlotsControl.push(
        this.fb.group({
          SlotId: [''],
          applicableDays: [''],
          activityCancellationDetails: this.fb.array([
            this.fb.group({
              cancellation_Type: [''],
              from: [''],
              to: [''],
              CP_Type: [''],
              CP_Value: [''],
            })
          ])
        })
      )
    } else {
      this.SlotsControl.push(
        this.fb.group({
          SlotId: [''],
          applicableDays: [''],
        })
      )
    }
    let formgroup = this.SlotsControl.controls[0].get('_rate_type').value;
    this.AddContolsForRateType(formgroup);
  }

  addcontolsforpax(formgroup, name) {
    if (this.PaxCheck.is_adult.value) {
      if (name == 'allSlotRateRange') {
        formgroup.get('allSlotRateRange')['controls'][0].addControl('adultAgeRange',
          this.fb.array([this.fb.group({
            from_count: this.validationService.mobNo,
            to_count: this.validationService.mobNo,
            sequence: [''],
            rate: this.validationService.decimal,
          })]),
        );
      }
      if (name == 'activityPaxRate') {
        formgroup.get('activityPaxRate').addControl('adult_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
      }
    }
    if (this.PaxCheck.is_child.value) {
      if (name == 'allSlotRateRange') {
        formgroup.get('allSlotRateRange')['controls'][0].addControl('childAgeRange',
          this.fb.array([this.fb.group({
            from_count: this.validationService.mobNo,
            to_count: this.validationService.mobNo,
            sequence: [''],
            rate: this.validationService.decimal,
          })]),
        );
      }
      if (name == 'activityPaxRate') {
        formgroup.get('activityPaxRate').addControl('senior_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
      }
    }
    if (this.PaxCheck.is_senior.value) {
      if (name == 'allSlotRateRange') {
        formgroup.get('allSlotRateRange')['controls'][0].addControl('seniorAgeRange',
          this.fb.array([this.fb.group({
            from_count: this.validationService.mobNo,
            to_count: this.validationService.mobNo,
            sequence: [''],
            rate: this.validationService.decimal,
          })]),
        );
      }
      if (name == 'activityPaxRate') {
        formgroup.get('activityPaxRate').addControl('youth_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
      }
    }

    if (this.PaxCheck.is_youth.value) {
      if (name == 'allSlotRateRange') {
        formgroup.get('allSlotRateRange')['controls'][0].addControl('youthAgeRange',
          this.fb.array([this.fb.group({
            from_count: this.validationService.mobNo,
            to_count: this.validationService.mobNo,
            sequence: [''],
            rate: this.validationService.decimal,
          })]),
        );
      }
      if (name == 'activityPaxRate') {
        formgroup.get('activityPaxRate').addControl('child_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
      }
    }

  }
  addDateCont() {
    this.DateControl.push(
      this.fb.group({
        start: this.validationService.required,
        end: this.validationService.required
      })
    )
  }

  addCancel() {
    this.CancelControl.push(this.fb.group({
      from: this.validationService.mobNo,
      to: this.validationService.mobNo,
      CP_Type: this.validationService.required,
      // CP_Value: [''],
      // cancellation_Type: this.validationService.required,
    }))
  }

  addSlotsDetail() {
    this.SlotsDetail.push(
      this.fb.group({
        slots: this.validationService.required,
        transfer_type: [''],
      })
    )
  }

  AllSelectedSlots = []
  AddRateSlots(obj, ind) {
    let id = this.AllSlot.filter(li => li.activity_slot_id == obj);
    let newslot = this.AllSelectedSlots.filter(e => e.activity_slot_id == id[0].activity_slot_id);
    if (newslot.length <= 0) {
      this.AllSelectedSlots[ind] = [];
      this.AllSelectedSlots[ind] = id[0];
    }
  }

  selectedSlots(obj, ind) {
    this.slotList = [];
    // this.RateConfigForm.get('slotDetails').value.map(li => {
    //   if (li.startHour && li.startMin && li.endHour && li.endMin) {
    //     this.slotList.push(li)
    //   }
    // })
  }
  addAdultAge(i, ind) {
    if (this.AdultTControl(i, ind).length <= 5) {
      this.AdultTControl(i, ind).push(this.fb.group({
        from_count: this.validationService.mobNo,
        to_count: this.validationService.mobNo,
        sequence: [''],
        rate: this.validationService.decimal,
      }))
    }
  }

  addYouthAge(i, ind) {
    if (this.YouthTControl(i, ind).length <= 5) {
      this.YouthTControl(i, ind).push(this.fb.group({
        from_count: this.validationService.mobNo,
        to_count: this.validationService.mobNo,
        sequence: [''],
        rate: this.validationService.decimal,
      }))
    }
  }

  addChildAge(i, ind) {
    if (this.ChildTControl(i, ind).length <= 5) {
      this.ChildTControl(i, ind).push(this.fb.group({
        from_count: this.validationService.mobNo,
        to_count: this.validationService.mobNo,
        sequence: [''],
        rate: this.validationService.decimal,
      }))
    }
  }

  addSeniordAge(i, ind) {
    if (this.SeniorTControl(i, ind).length <= 5) {
      this.SeniorTControl(i, ind).push(this.fb.group({
        from_count: this.validationService.mobNo,
        to_count: this.validationService.mobNo,
        sequence: [''],
        rate: this.validationService.decimal,
      }))
    }
  }

  // REMOVE FUNCTION

  removePrivateTransferGroup(ind) {
    this.privateTransferDataList.removeAt(ind);
  }
  removeSlotCont(ind) {
    this.SlotsControl.removeAt(ind)
  }

  removeDateCont(ind) {
    this.DateControl.removeAt(ind)
  }

  removeCancel(i) {
    this.CancelControl.removeAt(i)
  }

  removeSlotsDetail(ind) {
    this.SlotsDetail.removeAt(ind)
  }

  removeAdultAge(i, ind, secI) {
    this.AdultTControl(i, ind).removeAt(secI)
  }

  removeYouthAge(i, ind, secI) {
    this.YouthTControl(i, ind).removeAt(secI)
  }

  removeChildAge(i, ind, secI) {
    this.ChildTControl(i, ind).removeAt(secI)
  }

  removeSeniordAge(i, ind, secI) {
    this.SeniorTControl(i, ind).removeAt(secI)
  }

  removeInfantAge(i, ind, secI) {
    this.InfantTControl(i, ind).removeAt(secI)
  }

  isExcludeNationality(check) {
    if (check) {
      this.RateConfigForm.addControl('excNationalityCodes', this.fb.control([], Validators.required));
      this.remove_nationality('include')
    } else this.RateConfigForm.removeControl('excNationalityCodes');
  }

  isIncludeNationality(val) {
    if (val == '2') {
      this.RateConfigForm.addControl('incNationalityCodes', this.fb.control([], Validators.required));
      this.RateConfigForm.get('incNationalityCodes').setValue([]);
    } else if (val == '1') {
      this.RateConfigForm.removeControl('incNationalityCodes');
      this.remove_nationality('exclude');
    }
  }


  // FUNCTIONS
  checkFunc(check, controlName, val, arr) {
    check ? this.addvalid(controlName, 'add', val, arr) : this.addvalid(controlName, 'remove', val, arr)
  }

  addvalid(name, type, val, arr) {
    if (type == 'add') {
      let checkCont = arr != 'arr' ? this.fb.control(val, [Validators.required]) : this.fb.array([val], [Validators.required])
      this.RateConfigForm.addControl(name, checkCont)
      this.RateConfigForm.controls[name].updateValueAndValidity();
    } else this.RateConfigForm.removeControl(name);
  };

  periodType(val) {
    if (val == '1') {
      this.checkFunc(false, 'seasonIdsForRateDates', '', '')
      this.checkFunc(true, 'datesForRates', this.fb.group({ start: this.validationService.required, end: this.validationService.required }), 'arr')
    } else {
      this.checkFunc(true, 'seasonIdsForRateDates', '', '')
      this.checkFunc(false, 'datesForRates', '', '')
    }
  }

  SeasonFilter(val) {
    this.fil_season_list = []
    val.map(num => {
      this.fil_season_list.push(this.season_list.filter(obj => obj.activitySeason.activity_season_id == num))
    })
  }

  startDateChange(ind) {
    this.DateControl.controls[ind].get('end').setValue(this.DateControl.controls[ind].value.start)
  }

  daysChange(e) {
    e.option.id == 7 ? this.DaysControl.setValue(this.Day.map(ul => ul.id)) :
      this.DaysControl.value.map((li, i) => li == 7 ? this.DaysControl.value.splice(i, 1) : '');
  }

  SlotChange(e) {
    if (e == 1) this.AddSlotsControlValidations('SlotId', false);
    else if (e == 2) this.AddSlotsControlValidations('SlotId', true);
    if (e == 1 && this.SlotsControl.value.length != 1) {
      this.SlotsControl.controls.splice(1, this.SlotsControl.controls.length)
    }
  }

  AddSlotsControlValidations(name, check) {
    if (check) {
      this.SlotsControl.controls[0].get(name).addValidators([Validators.required]);
      this.SlotsControl.controls[0].get(name).updateValueAndValidity();
      this.SlotsControl.controls[0].get(name).markAsUntouched();
    } else {
      this.SlotsControl.controls[0].get(name).clearValidators();
      this.SlotsControl.controls[0].get(name).updateValueAndValidity();
      this.SlotsControl.controls[0].get(name).markAsUntouched();
    }
  };

  GetAllCurrency() {
    this.APIServ.Get('/Currency/GetCurrency').subscribe(d => {
      if (d) this.currencyList = d;
    });
  }

  GetPhoneCode() {
    this.APIServ.Get('/CountryPhone/GetCountryPhone').subscribe(data => {
      if (data) this.PhoneCode = data;
    });
  }



  GetAllNationality() {
    this.APIServ.Get('/Country/GetCountry').subscribe(res => {
      if (res) {
        this.all_nationality_list = res;
        this.include_nationality_list = res;
        this.exclude_nationality_list = res;
      }
    });
  }
  AllSlot;
  GetAllSlot() {
    let post = new GetActivitySlot();
    let activity_id = CommonService.getSessionStoage('activity_id');
    post.activity_id = activity_id;
    post.from_hour = null;
    post.from_minute = null;
    post.to_hour = null;
    post.to_minute = null;
    this.APIServ.Post('/ActivitySlot/GetAllSlot', post).subscribe(res => {
      if (res) {
        this.AllSlot = res['responseObject'];
      }
    });
  }
  AllCountry;
  getCountry() {
    this.APIServ.Get('/Country/GetCountry').subscribe(data => {
      if (data) {
        this.AllCountry = data;
      }
    });
  };

  GetAllActivitySeason() {
    this.APIServ.Get('/ActivitySeason/GetAllActivitySeason?activityId=' + CommonService.getSessionStoage('activity_id')).subscribe(d => {
      if (d && d.status) {
        this.season_list = d.responseObject;
      }
    });
  }
  AllVehicleSupplier;
  GetAllVehicleSupplier() {
    this.APIServ.Get('/Vehicle/GetAllVehicleSupplier').subscribe(res => {
      if (res) {
        this.AllVehicleSupplier = res.responseObject;
      }
    });
  }

  AllVehicleBySupplierId = {
    Shared: [],
    Slots: []
  };;
  GetAllVehicleBySupplierId(Id, name, i) {
    this.APIServ.Get('/Vehicle/GetAllVehicleBySupplier/' + Id).subscribe(res => {
      if (res) {
        this.AllVehicleBySupplierId[name][i] = []
        this.AllVehicleBySupplierId[name][i] = res.responseObject;
      }
    });
  }
  Set_Max_Occcupancy(obj, formgroup) {
    formgroup.get('vehicle_max_occupancy').setValue(obj.max_passenger_capacity);
  }

  setprivateOccupancy(obj, formgroup) {
    formgroup.get('vehicle_occupancy').setValue(obj.max_passenger_capacity);
  }

  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 : '';
        });
      }
    });
  }

  PaxCheck = {
    is_youth: {
      form: '',
      to: '',
      value: false
    },
    is_senior: {
      form: '',
      to: '',
      value: false
    },
    is_adult: {
      form: '',
      to: '',
      value: false
    },
    is_child: {
      form: '',
      to: '',
      value: false
    },
  }
  GetActivityById() {
    let activity_id = CommonService.getSessionStoage('activity_id');
    this.APIServ.Get('/Activity/GetActivity/' + activity_id).subscribe(d => {
      if (d && d.status) {
        if (d.responseObject.activityContents && d.responseObject.activityContents.length > 0) {
          this.activityData = d.responseObject;
          this.PaxCheck.is_adult.value = this.activityData.is_adult;
          this.PaxCheck.is_adult.to = this.activityData.adult_age_to;
          this.PaxCheck.is_adult.form = this.activityData.adult_age_from;

          this.PaxCheck.is_child.value = this.activityData.is_child;
          this.PaxCheck.is_child.form = this.activityData.child_age_from;
          this.PaxCheck.is_child.to = this.activityData.child_age_to;

          this.PaxCheck.is_senior.value = this.activityData.is_senior;
          this.PaxCheck.is_senior.form = this.activityData.senior_age_from;
          this.PaxCheck.is_senior.to = this.activityData.senior_age_to;

          this.PaxCheck.is_youth.value = this.activityData.is_youth;
          this.PaxCheck.is_youth.form = this.activityData.youth_age_from;
          this.PaxCheck.is_youth.to = this.activityData.youth_age_to;
          this.initRateConfigForm();
          this.RateConfigForm.get('experience_name').setValue(d.responseObject.activityContents[0].activity_name);
          let county = this.activityData.country_code.split(',')
          this.RateConfigForm.get('country_name').setValue(county);
          this.getcity(this.activityData.country_code);
          let city = this.activityData.city_id.split(',');
          this.RateConfigForm.get('city_name').setValue(city);
          let lang = d.responseObject._service_language.split(',');
          lang.map(ln => {
            this.lovKeyDataObj['Language'].map(li => {
              if (ln == li.lov_value) {
                this.LangList.push(li)
              }
            })
          })



        }
        console.log(this.PaxCheck)
      }
    });
  }
  FreeSalesCheck(group, check) {
    if (!check) {
      group.addControl('allocation_count', this.fb.control('', [Validators.required, Validators.pattern(/^[0-9]*$/)]));
    } else group.removeControl('allocation_count');
  }
  getcity(code) {
    this.APIServ.Get('/City/GetCity/' + code).subscribe(data => {
      if (data) {
        this.allCityDetials = data;
      }
    });
  };

  // select_nataionality_type(nationality_type) {
  //   (nationality_type == 'all_nationality') ? 
  //     this.RateConfigForm.removeControl('incNationalityCodes') : 
  //     this.RateConfigForm.addControl('incNationalityCodes', this.fb.control(''));
  // }

  remove_nationality(type) {
    let con = type == 'exclude' ? 'incNationalityCodes' : 'excNationalityCodes'
    type == 'exclude' ? this.exclude_nationality_list = [...this.all_nationality_list] : this.include_nationality_list = [...this.all_nationality_list];
    let list = type == 'exclude' ? this.exclude_nationality_list : this.include_nationality_list;
    let nationality_arr = this.RateConfigForm.get(con).value ? this.RateConfigForm.get(con).value : [];
    nationality_arr.forEach(nationality_code => {
      let ind = list.findIndex(nationality_obj => nationality_obj.alpha_2_code == nationality_code);
      (ind != -1) ? list.splice(ind, 1) : '';
      type == 'exclude' ? this.exclude_nationality_list = [...list] : this.include_nationality_list = [...list];
    });
  }

  SaveRate() {
    let value = this.RateConfigForm.getRawValue();
    console.log(this.RateConfigForm)
    if (this.RateConfigForm.status == 'INVALID') {
      this.validationService.showValidationsMsg(this.RateConfigForm);
      return;
    };

    let RateConfigModel = new SaveActivityContractDetails();
    let RateContract = new ActivityContract();
    let ArrRateContractDetail = new Array<ActivityDetails>();
    let ArrRateDateRange = new Array<DateRange>();

    // RATE CONTRACT 
    RateContract.org_id = value.org_id;
    RateContract.activity_id = CommonService.getSessionStoage('activity_id');
    RateContract.supplier_id = value.supplier_id;
    RateContract.currency_code = value.currency_code;
    RateContract._nationality_type = value._nationality_type;
    RateContract.is_exclude_nationality = value.is_exclude_nationality;
    RateContract._period_type = value._period_type.toString();
    RateContract.season_id = value.seasonIdsForRateDates ? value.seasonIdsForRateDates.join(',') : '';
    RateContract._rate_type = value.slots[0]._rate_type.toString();
    RateContract._pricing_type = value.slots[0]._pricing_type.toString();
    RateContract.is_pickup_included = value.is_pickup_included;
    RateContract.is_drop_off_included = value.is_drop_off_included;
    RateContract.is_guide_included = value.is_guide_included;
    RateContract.is_slot_wise_cancellation_policy = value.is_slot_wise_cancellation_policy;
    RateContract._no_show_policy_type = value._no_show_policy_type.toString();
    RateContract.no_show_charge_value = value._no_show_policy_type != 1 ? value.no_show_charge_value : 0;
    RateContract.guide_languages = value.guide_languages ? value.guide_languages.join(',') : '';
    RateContract.is_private_transfer_price_included = value.is_private_transfer_price_included;
    RateContract.reviewed_by = 'Razzak'
    RateContract.reviewer_comments = 'Razzak'
    RateContract.reviewer_user_type = 'Razzak'

    // Private Tranfer Price Included
    RateConfigModel.privateTransfer = [];
    if (value.is_private_transfer_price_included) {
      let val = this.privateTransferDataList.getRawValue()
      let postarr = []
      val.forEach(e => {
        let privateArr = new ActivityPrivateTransfer();
        privateArr.rate = e.rate;
        privateArr.vehicle_id = e.vehicle_id;
        privateArr.vehicle_occupancy = e.vehicle_occupancy;
        privateArr.vehicle_supplier_id = e.vehicle_supplier_id;
        postarr.push(privateArr);
      });
      RateConfigModel.privateTransfer = postarr;
    }

    // Shared Transfer Price Included
    RateContract.is_shared_transfer_price_included = value.is_shared_transfer_price_included;
    RateConfigModel.sharedTransfer = null;
    if (value.is_shared_transfer_price_included) {
      let SharetransferArr = new ActivitySharedTransfer();
      SharetransferArr.vehicle_supplier_id = value.vehicle_supplier_id
      SharetransferArr.adult_rate = value.adult_rate ? value.adult_rate : 0;
      SharetransferArr.senior_rate = value.senior_rate ? value.senior_rate : 0;
      SharetransferArr.youth_rate = value.youth_rate ? value.youth_rate : 0;
      SharetransferArr.child_rate = value.child_rate ? value.child_rate : 0;
      RateConfigModel.sharedTransfer = SharetransferArr;
    }


    // Rate Period Type
    RateConfigModel.datesForRates = [];
    if (value._period_type == 1) {
      value.datesForRates.map(li => {
        let RateDateRange = new DateRange();
        RateDateRange.Start = moment(li.start, "HH:mm:ss").utc().format('');
        RateDateRange.End = moment(li.end, "HH:mm:ss").utc().format('');
        ArrRateDateRange.push(RateDateRange)
      })
      RateConfigModel.datesForRates = ArrRateDateRange;
    }

    RateConfigModel.seasonIdsForRateDates = [];
    if (value._period_type == 2) {
      RateConfigModel.seasonIdsForRateDates = value.seasonIdsForRateDates;
    }


    // ACTIVITY DETAILS
    let RateContractDetail = new ActivityDetails();
    RateContractDetail.contract_remark = value.contract_remark;
    RateContractDetail.language_code = CommonService.getSessionStoage('Def_Lang_code');
    RateContractDetail.option_name = value.option_name;
    RateContractDetail.rate_inclusion = value.rate_inclusion;
    ArrRateContractDetail.push(RateContractDetail);

    //  Solts Details 
    let slotsDetaisl = []
    RateConfigModel.slotDetails = [];
    value.slots.forEach(e => {

      let postDataArr = new SlotDetails();
      postDataArr.applicableDays = e.applicableDays.join(',');
      if (value.slots[0]._rate_type == '1') {

        let slotDetail = e.allSlotRateRange[0];
        let RateTieredPricing = new RateRange();
        let ArrAdultAgeRange = new Array<AgeRange>();
        let ArrYouthAgeRange = new Array<AgeRange>();
        let ArrSeniorAgeRange = new Array<AgeRange>();
        let ArrChildAgeRange = new Array<AgeRange>();

        //  Adult
        slotDetail.adultAgeRange ? slotDetail.adultAgeRange.map((li, i) => {
          let AdultAgeRange = new AgeRange();
          AdultAgeRange.from_count = li.from_count;
          AdultAgeRange.to_count = li.to_count;
          AdultAgeRange.rate = li.rate;
          AdultAgeRange.sequence = i + 1;
          ArrAdultAgeRange.push(AdultAgeRange)
        }) : '';
        //  Youth
        slotDetail.youthAgeRange ? slotDetail.youthAgeRange.map((li, i) => {
          let YouthAgeRange = new AgeRange();
          YouthAgeRange.from_count = li.from_count;
          YouthAgeRange.to_count = li.to_count;
          YouthAgeRange.rate = li.rate;
          YouthAgeRange.sequence = i + 1;

          ArrYouthAgeRange.push(YouthAgeRange)
        }) : '';
        //  Senior
        slotDetail.seniorAgeRange ? slotDetail.seniorAgeRange.map((li, i) => {
          let SeniorAgeRange = new AgeRange();
          SeniorAgeRange.from_count = li.from_count;
          SeniorAgeRange.to_count = li.to_count;
          SeniorAgeRange.rate = li.rate;
          SeniorAgeRange.sequence = i + 1;

          ArrSeniorAgeRange.push(SeniorAgeRange)
        }) : '';
        // Child
        slotDetail.childAgeRange ? slotDetail.childAgeRange.map((li, i) => {
          let ChildAgeRange = new AgeRange();
          ChildAgeRange.from_count = li.from_count;
          ChildAgeRange.to_count = li.to_count;
          ChildAgeRange.rate = li.rate;
          ChildAgeRange.sequence = i + 1;

          ArrChildAgeRange.push(ChildAgeRange)
        }) : '';

        RateTieredPricing.adultAgeRange = ArrAdultAgeRange;
        RateTieredPricing.childAgeRange = ArrChildAgeRange;
        RateTieredPricing.seniorAgeRange = ArrSeniorAgeRange;
        RateTieredPricing.youthAgeRange = ArrYouthAgeRange;
        let post = new AllocationDetails();
        post._allocation_type = slotDetail.is_free_sales ? '1' : '3';
        post.allocation_count = slotDetail.is_free_sales ? 0 : slotDetail.allocation_count;
        post.release_days = slotDetail.release_days;
        post._release_type = '1';
        post.vehicle_id = 'er';
        RateTieredPricing.allocationDetails = post;
        postDataArr.rateRange = RateTieredPricing;
      }
      if (value.slots[0]._rate_type == '2') {
        let slotDetail = value.slots[0].activityPaxRate;
        let RatePerPerson = new ActivityPaxRate();
        RatePerPerson.adult_rate = slotDetail.adult_rate;
        RatePerPerson.child_rate = slotDetail.child_rate;
        RatePerPerson.senior_rate = slotDetail.senior_rate;
        RatePerPerson.youth_rate = slotDetail.youth_rate;

        let post = new AllocationDetails();
        post._allocation_type = slotDetail.is_free_sales ? '1' : '3';
        post.allocation_count = slotDetail.is_free_sales ? 0 : slotDetail.allocation_count;
        post.release_days = slotDetail.release_days;
        post._release_type = '1';
        post.vehicle_id = 'er';
        RatePerPerson.allocationDetails = post;
        postDataArr.activityPaxRate = RatePerPerson;
      }
      if (value.slots[0]._rate_type == '3') {
        let slotDetail = e.activityVehicleRate;
        let postdata = [];
        slotDetail.forEach(li => {
          let RateVehicle = new ActivityVehicleRate();
          RateVehicle.rate = slotDetail[0].rate ? li.rate : 0;
          // RateVehicle.vehicle_max_occupancy = li.vehicle_max_occupancy ? parseInt(li.vehicle_max_occupancy) : 0;
          RateVehicle.vehicle_max_occupancy = li.vehicle_max_occupancy;
          RateVehicle.vehicle_id = li.vehicle;
          RateVehicle.vehicle_supplier_id = li.vehicleSupplier;
          let post = new AllocationDetails();
          post._allocation_type = slotDetail.is_free_sales ? '1' : '3';
          post.allocation_count = slotDetail.is_free_sales ? 0 : slotDetail.allocation_count;
          post.release_days = slotDetail.release_days;
          post._release_type = '1';
          post.vehicle_id = 'er';
          RateVehicle.allocationDetails = post;
          postdata.push(RateVehicle);
        })
        postDataArr.activityVehicleRate = postdata;
      }
      if (value.is_slot_wise_cancellation_policy) {
        let slotspolicy = e.activityCancellationDetails;
        let postdata = [];
        slotspolicy.forEach(li => {
          let arr = new ActivityCancellationDetails();
          arr.CP_Type = li.CP_Type.toString();
          arr.CP_Value = li.CP_Type != 1 ? li.CP_Value : 0;
          arr.cancellation_Type = slotspolicy[0].cancellation_Type.toString();
          arr.from = li.from;
          arr.to = li.to;
          postdata.push(arr);
        })
        postDataArr.activityCancellationDetails = postdata;
      }
      if (value.slots[0]._pricing_type == 1) {
        let allslots = [];
        value.slotDetails.forEach(li => {
          let post = new Slots();
          post.slotId = li.slots
          post.is_private_transfer = false;
          post.is_without_transfer = false;
          post.is_shared_transfer = false;
          li.transfer_type.forEach(q => {
            if (q == 1) post.is_private_transfer = true;
            if (q == 2) post.is_without_transfer = true;
            if (q == 3) post.is_shared_transfer = true;
          })
          allslots.push(post);
        })
        postDataArr.slot = allslots;
      }
      else if (value.slots[0]._pricing_type == 2) {
        let allslots = [];
        e.SlotId.forEach(q => {
          let arr = value.slotDetails.filter(li => li.slots == q);
          let post = new Slots();
          post.slotId = arr[0].slots;
          post.is_private_transfer = false;
          post.is_without_transfer = false;
          post.is_shared_transfer = false;
          arr[0].transfer_type.forEach(z => {
            if (z == 1) post.is_private_transfer = true;
            if (z == 2) post.is_without_transfer = true;
            if (z == 3) post.is_shared_transfer = true;
          })
          allslots.push(post);
          postDataArr.slot = allslots;
        });
      }
      slotsDetaisl.push(postDataArr);
    })
    RateConfigModel.slotDetails = slotsDetaisl;

    //  Activity Cancellation Details
    RateConfigModel.activityCancellationDetails = [];
    if (!value.is_slot_wise_cancellation_policy) {
      let policyDetails = value.activityCancellationDetails;
      let postdata = [];
      policyDetails.forEach(li => {
        let arr = new ActivityCancellationDetails();
        arr.cancellation_Type = policyDetails[0].cancellation_Type.toString();
        arr.CP_Type = li.CP_Type.toString();
        arr.CP_Value = li.CP_Type != 1 ? li.CP_Value : 0;
        arr.from = li.from;
        arr.to = li.to;
        postdata.push(arr);
      })
      RateConfigModel.activityCancellationDetails = postdata;
    };

    RateConfigModel.activityContract = RateContract;
    RateConfigModel.incNationalityCodes = value.incNationalityCodes ? value.incNationalityCodes : [];
    RateConfigModel.excNationalityCodes = value.excNationalityCodes ? value.excNationalityCodes : [];
    RateConfigModel.activityContractDetails = ArrRateContractDetail;
    console.log(RateConfigModel);
    this.APIServ.Post('/ActivityContract/SaveActivityContract', RateConfigModel).subscribe(res => {
      if (res) {
        this.showToastrMsg(res)
      }
    })
  }

  showToastrMsg(respData) {
    this.MsgService.add({
      severity: respData['status'] ? 'success' : 'error',
      detail: respData['message'],
    });
    setTimeout(() => {
      respData['status'] ? this.btnClick() : '';
    }, 500);
  }
  btnClick() {
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage'])
  }
}
