import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { NgSelectComponent } from '@ng-select/ng-select';
import * as moment from 'moment';
import { MessageService } from 'primeng/api';
import { ValidationService } from 'src/app/core/common/validation.service';
import { dtoFlightRate, FlightRateobj, UpdateFlightRate } from 'src/app/core/models/flight-service/flight-service-manage/edit-Rate-inventry.model';
import { API } from 'src/app/core/services/api.service';

@Component({
  selector: 'app-edit-rate-and-inventory',
  templateUrl: './edit-rate-and-inventory.component.html',
})
export class EditRateAndInventoryComponent implements OnInit {
  value: Date;
  constructor(public router: ActivatedRoute,
    private ApiServ: API, public fb: FormBuilder,
    public validationService: ValidationService, public MsgService: MessageService, public route: Router) { }
  contract_id;
  formdata: FormGroup;
  SearchForm: FormGroup;
  AtoZ = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
  is_search = false
  lovKeyDataObj = {
    AirCabinClass: [],
    AirPaxType: [],
    AirTripType: [],
    DaySelect: [],
    AirBaggageUnit: [],
    AirFareType: [],
  };
  // all Copy ui 

  @ViewChild('is_stop_sale') is_stop_sale: ElementRef;
  @ViewChild('adt_base_fare') adt_base_fare: ElementRef;
  @ViewChild('adt_tax') adt_tax: ElementRef;
  @ViewChild('chd_base_fare') chd_base_fare: ElementRef;
  @ViewChild('chd_tax') chd_tax: ElementRef;
  @ViewChild('inf_base_fare') inf_base_fare: ElementRef;
  @ViewChild('inf_tax') inf_tax: ElementRef;
  @ViewChild('pnr') pnr: ElementRef;
  @ViewChild('seat_allocation') seat_allocation: ElementRef;
  @ViewChild('adt_check_bag') adt_check_bag: ElementRef;
  @ViewChild('chd_check_bag') chd_check_bag: ElementRef;
  @ViewChild('inf_check_bag') inf_check_bag: ElementRef;
  @ViewChild('_check_bag_unit') _check_bag_unit: NgSelectComponent
  @ViewChild('adt_cabin_bag') adt_cabin_bag: ElementRef;
  @ViewChild('chd_cabin_bag') chd_cabin_bag: ElementRef;
  @ViewChild('inf_cabin_bag') inf_cabin_bag: ElementRef;
  @ViewChild('_cabin_bag_unit') _cabin_bag_unit: NgSelectComponent;
  @ViewChild('_fare_type') _fare_type: NgSelectComponent;
  @ViewChild('is_instant_confirmation') is_instant_confirmation: NgSelectComponent;
  @ViewChild('adt_fare_rule') adt_fare_rule: ElementRef;
  @ViewChild('chd_fare_rule') chd_fare_rule: ElementRef;
  @ViewChild('inf_fare_rule') inf_fare_rule: ElementRef;
  @ViewChild('is_meal_included') is_meal_included: ElementRef;
  @ViewChild('meal_details') meal_details: ElementRef
  @ViewChild('inclusions') inclusions: ElementRef
  ngOnInit(): void {
    this.GetLOVKeys('AirCabinClass,AirPaxType,AirTripType,DaySelect,AirBaggageUnit,AirFareType');
    this.SearchForm = this.fb.group({
      date: [''],
      days: [''],
      _rbd: [''],
      currency: [''],
    });

    this.formdata = this.fb.group({
      FlightRate: this.fb.array([
      ])
    });
    this.checkIsRangetype();
    this.GetFlightRate();
  };
  checkIsRangetype() {
    this.router.queryParams.subscribe(obj => {
      this.contract_id = obj['id']
      this.ApiServ.Get('/FlightContract/GetFlightDates?ContractId=' + obj['id']).subscribe(data => {
        if (data) {
          if (data.responseObject.is_multi_day && !data.responseObject.is_round_trip) {
            this.is_search = false;
            this.SetTimeAvali(data.responseObject.dates);
          } else this.is_search = true;
        }
        this.SearchForm.get('currency').setValue(data.responseObject.currency_code);
      });
    })
  }
  get FlightRate() {
    return this.formdata.get('FlightRate') as FormArray;
  }

  copyOnUi() {
    let value = this.FlightRate.getRawValue();
    value.map((obj, i) => {
      Object.keys(obj).forEach(e => {
        if (e == 'is_stop_sale') {
          this.FlightRate.controls[i].get(e).setValue(this.is_stop_sale['_checked'])
        } else if (e == 'adt_base_fare') {
          this.FlightRate.controls[i].get(e).setValue(this.adt_base_fare.nativeElement.value)
        } else if (e == 'adt_tax') {
          this.FlightRate.controls[i].get(e).setValue(this.adt_tax.nativeElement.value)
        } else if (e == 'chd_base_fare') {
          this.FlightRate.controls[i].get(e).setValue(this.chd_base_fare.nativeElement.value)
        } else if (e == 'inf_base_fare') {
          this.FlightRate.controls[i].get(e).setValue(this.inf_base_fare.nativeElement.value)
        } else if (e == 'inf_tax') {
          this.FlightRate.controls[i].get(e).setValue(this.inf_tax.nativeElement.value)
        } else if (e == 'seat_allocation') {
          this.FlightRate.controls[i].get(e).setValue(this.seat_allocation.nativeElement.value)
        } else if (e == 'adt_check_bag') {
          this.FlightRate.controls[i].get(e).setValue(this.adt_check_bag.nativeElement.value)
        } else if (e == 'chd_check_bag') {
          this.FlightRate.controls[i].get(e).setValue(this.chd_check_bag.nativeElement.value)
        } else if (e == 'inf_check_bag') {
          this.FlightRate.controls[i].get(e).setValue(this.inf_check_bag.nativeElement.value)
        } else if (e == 'adt_cabin_bag') {
          this.FlightRate.controls[i].get(e).setValue(this.adt_cabin_bag.nativeElement.value)
        } else if (e == 'chd_cabin_bag') {
          this.FlightRate.controls[i].get(e).setValue(this.chd_cabin_bag.nativeElement.value)
        } else if (e == 'inf_cabin_bag') {
          this.FlightRate.controls[i].get(e).setValue(this.inf_cabin_bag.nativeElement.value)
        } else if (e == 'adt_fare_rule') {
          this.FlightRate.controls[i].get(e).setValue(this.adt_fare_rule.nativeElement.value)
        } else if (e == 'chd_fare_rule') {
          this.FlightRate.controls[i].get(e).setValue(this.chd_fare_rule.nativeElement.value)
        } else if (e == 'inf_fare_rule') {
          this.FlightRate.controls[i].get(e).setValue(this.inf_fare_rule.nativeElement.value)
        } else if (e == 'is_meal_included') {
          this.FlightRate.controls[i].get(e).setValue(this.is_meal_included['_checked'] ? 'Yes' : 'No')
        } else if (e == 'meal_details') {
          this.FlightRate.controls[i].get(e).setValue(this.meal_details.nativeElement.value)
        } else if (e == 'inclusions') {
          this.FlightRate.controls[i].get(e).setValue(this.inclusions.nativeElement.value)
          console.log(this.inclusions.nativeElement)
        } else if (e == '_check_bag_unit') {
          let check_bag = this._check_bag_unit.selectedValues[0] ? this._check_bag_unit.selectedValues[0].lov_key : '';
          this.FlightRate.controls[i].get(e).setValue(check_bag);
        } else if (e == '_cabin_bag_unit') {
          let cabin_bag = this._cabin_bag_unit.selectedValues[0] ? this._cabin_bag_unit.selectedValues[0].lov_key : '';
          this.FlightRate.controls[i].get(e).setValue(cabin_bag);
        } else if (e == '_fare_type') {
          let fare_type = this._fare_type.selectedValues[0] ? this._fare_type.selectedValues[0].lov_key : '';
          this.FlightRate.controls[i].get(e).setValue(fare_type);
        } else if (e == 'is_instant_confirmation') {
          let fare_type = this.is_instant_confirmation.selectedValues[0] ? this.is_instant_confirmation.selectedValues[0].name : '';
          this.FlightRate.controls[i].get(e).setValue(fare_type);
        } else if (e == 'chd_tax') {
          this.FlightRate.controls[i].get(e).setValue(this.chd_tax.nativeElement.value);
        } else if (e == 'pnr') {
          this.FlightRate.controls[i].get(e).setValue(this.pnr.nativeElement.value);
        }
      })
    })

  };

  addformgroup() {
    this.FlightRate.push(
      this.fb.group({
        rate_id: [''],
        outbound_date: [''],
        adt_base_fare: this.validationService.decimal,
        adt_tax: this.validationService.decimal,
        chd_base_fare: this.validationService.decimal,
        chd_tax: this.validationService.decimal,
        inf_base_fare: this.validationService.decimal,
        inf_tax: this.validationService.decimal,
        seat_allocation: this.validationService.number,
        adt_check_bag: this.validationService.number,
        chd_check_bag: this.validationService.number,
        inf_check_bag: this.validationService.number,
        _check_bag_unit: this.validationService.required,
        adt_cabin_bag: this.validationService.number,
        chd_cabin_bag: this.validationService.number,
        inf_cabin_bag: this.validationService.number,
        _cabin_bag_unit: this.validationService.required,
        _fare_type: this.validationService.required,
        adt_fare_rule: this.validationService.required,
        chd_fare_rule: this.validationService.required,
        inf_fare_rule: this.validationService.required,
        is_meal_included: this.validationService.required,
        meal_details: [''],
        inclusions: [''],
        pnr: this.validationService.required,
        return_date: [''],
        is_instant_confirmation: this.validationService.required,
        is_stop_sale: [false],
      })
    )
  }

  GetFlightRate() {
    let postdata = new FlightRateobj();
    let val = this.SearchForm.getRawValue();
    postdata._id = this.contract_id;
    postdata._from_date = val.date[0] ? moment(val.date[0]).format('YYYY-MM-DD') : '';
    postdata._rbd = val._rbd ? val._rbd : '';
    postdata._to_date = val.date[1] ? moment(val.date[1]).format('YYYY-MM-DD') : '';
    postdata.days = val.days ? val.days.join(',') : '';

    this.ApiServ.Post('/FlightContract/GetFlightRate', postdata).subscribe(data => {
      if (data) {
        this.formdata.reset();
        this.FlightRate.clear();
        if (data.responseObject) {
          this.addformgroup()
          this.SetValue(data.responseObject);
        }
      }
    });
  };



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

  saveRateDetails() {
    if (this.formdata.status == "INVALID") {
      this.validationService.showValidationsMsg(this.formdata);
      return;
    }
    let value = this.FlightRate.getRawValue();
    let flight_list_arr = [];
    value.map(e => {
      let post_obj = new dtoFlightRate();
      post_obj.rate_id = e.rate_id;
      post_obj.outbound_date = e.outbound_date;
      post_obj.adt_base_fare = e.adt_base_fare;
      post_obj.adt_tax = e.adt_tax;
      post_obj.chd_base_fare = e.chd_base_fare;
      post_obj.chd_tax = e.chd_tax;
      post_obj.inf_base_fare = e.inf_base_fare;
      post_obj.inf_tax = e.inf_tax;
      post_obj.seat_allocation = e.seat_allocation;
      post_obj.adt_check_bag = e.adt_check_bag;
      post_obj.chd_check_bag = e.chd_check_bag;
      post_obj.inf_check_bag = e.inf_check_bag;
      post_obj._check_bag_unit = e._check_bag_unit;
      post_obj.adt_cabin_bag = e.adt_cabin_bag;
      post_obj.chd_cabin_bag = e.chd_cabin_bag;
      post_obj.inf_cabin_bag = e.inf_cabin_bag;
      post_obj._cabin_bag_unit = e._cabin_bag_unit;
      post_obj._fare_type = e._fare_type;
      post_obj.adt_fare_rule = e.adt_fare_rule;
      post_obj.chd_fare_rule = e.chd_fare_rule;
      post_obj.inf_fare_rule = e.inf_fare_rule;
      post_obj.is_meal_included = e.is_meal_included == 'Yes' ? true : false;
      post_obj.meal_details = e.is_meal_included == 'Yes' ? e.meal_details : '';
      post_obj.inclusions = e.inclusions;
      post_obj.pnr = e.pnr;
      post_obj.is_instant_confirmation = e.is_instant_confirmation == 'Instant' ? true : false;
      post_obj.is_stop_sale = e.is_stop_sale;
      flight_list_arr.push(post_obj);
    })

    let postdata = new UpdateFlightRate();
    postdata.contract_id = this.contract_id;
    postdata.flight_rate = flight_list_arr;

    this.ApiServ.Post('/FlightContract/UpdateRatesAndInventory', postdata).subscribe(data => {
      if (data) {
        this.MsgService.add({
          severity: data["status"] ? "success" : "error",
          detail: data["message"],
        });
        data["status"] ? setTimeout(() => {
          this.route.navigate(['/Services/FlightServices/Search'])
        }, 500) : '';
      }
    })
  };

  SetValue(data) {

    data ? data.map((obj, i) => {
      i != 0 ? this.addformgroup() : ''
      Object.keys(obj).forEach(e => {
        if (e == 'is_meal_included') this.FlightRate.controls[i].get(e).setValue(obj[e] ? 'Yes' : 'No');
        else if (e == 'is_instant_confirmation') this.FlightRate.controls[i].get(e).setValue(obj[e] ? 'Instant' : 'Manual');
        else this.FlightRate.controls[i].get(e).setValue(obj[e]);
      })
    }) : ''
  };

  Confirmation_Type = [
    { id: 0, name: 'Instant' },
    { id: 1, name: 'Manual' },
  ];

  Option = [
    { id: 2, name: 'Yes' },
    { id: 3, name: 'No' },
  ];

  formDate;
  datelist
  SetTimeAvali(allDate) {
    this.datelist = allDate.split(',');
    let obj = [];
    this.datelist.map(e => {
      obj.push(moment(e).format('MM-DD-YYYY'));
    })
    this.datelist = obj;
  }
  @ViewChild('calender') calender
  DateRangecheck() {
    let date_range = this.SearchForm.get('date').value
    if (date_range[1]) {
      this.calender.overlayVisible = false;
      let AllSelectDate = []
      this.datelist.filter(e => {
        let from = moment(date_range[0]).format('MM:DD:YYYY').split(':')
        let To = moment(date_range[1]).format('DD:MMM:YYYY').split(':')
        let maindate = moment(e).format('DD:MMM:YYYY').split(':')
        if (from[1] == maindate[1] || To[1] == maindate[1]) {
          let date = new Date(e).getDate();
          let St = new Date(date_range[0]).getDate();
          let et = new Date(date_range[1]).getDate();
          (date >= St && date <= et) ? AllSelectDate.push(e) : ''
        }
      })
      this.formDate = AllSelectDate;
      // this.GetFlightRate()
    };
  };

  checkDateForHighlight(date) {
    let month = date.month > 9 ? date.month : '0' + date.month;
    let d = new Date(date.year, date.month, date.day);
    let new_Date = month + '-' + date.day + '-' + date.year;
    let Checkformat = moment(new_Date).format('MM-DD-YYYY')
    let validate;
    validate = false;
    if (new_Date == Checkformat) {
      let format = moment(d).format('MM-DD-YYYY')
      let valid = this.datelist.filter(e => e == format)
      if (valid.length > 0) {
        validate = true;
      }
    }
    return validate;
  }

  MealTypeIncludedcheck(val, ind) {
    console.log(val)
    if (val == 'Yes') this.addvalidMealTypeIncluded(ind, 'meal_details', 'add')
    else this.addvalidMealTypeIncluded(ind, 'meal_details', 'remove')

  }

  addvalidMealTypeIncluded(index, name, type) {
    if (type == 'add') {
      this.formdata.controls[index].get(name).addValidators([Validators.required]);
      this.formdata.controls[index].get(name).updateValueAndValidity();
    } else {
      this.formdata.controls[index].get(name).clearValidators();
      this.formdata.controls[index].get(name).updateValueAndValidity();
      this.formdata.controls[index].get(name).markAsUntouched();
    }
  };
}
