import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, ValidatorFn, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import * as moment from 'moment';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { StaticDataService } from 'src/app/core/common/static-data.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { FlightDetailsSearchModel } from 'src/app/core/models/flight-service/flight-contracts.model';
import { FlightContractSearhObj } from 'src/app/core/models/flight-service/flight-service-search/flight-service-search.model';
import { API } from 'src/app/core/services/api.service';
import { FlightContractService } from 'src/app/core/services/flight-contract.service.ts/flight-contract.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-flight-inventory-search',
  templateUrl: './flight-inventory-search.component.html',
})
export class FlightInventorySearchComponent implements OnInit {
  Formdata: FormGroup;
  AirlineList;
  FlightAllDetails;
  Cdn_url = environment.cdnFileUrl;
  constructor(
    public ApiServ: API,
    public fb: FormBuilder,
    public router: Router,
    public _commonService: CommonFunctionService,
    public _staticService: StaticDataService,
    public _flightContractService: FlightContractService,
    public validationService: ValidationService
  ) { }
  cols: any[];
  tripType = [
    { value: 'ONEWAY', displayName: 'One Way' },
    { value: 'ROUNDTRIP', displayName: 'Round Trip' },
  ];
  confirmation_type = [
    { value: 'INSTANT', displayName: 'Instant' },
    { value: 'MANUAL', displayName: 'Manual' },
];
  ngOnInit(): void {
    this.pageSetUp()
  }
  pageSetUp() {
    this.OnInitForm();
    this.cols = [
      { field: 'contract_id', header: 'Contract Id' },
      { field: 'contract_name', header: 'Contract Name' },
      { field: 'validating_airline', header: 'Validating Airline' },
      { field: 'trip_type', header: 'Trip Type' },
      { field: 'flight_no', header: 'Flight No' },
      { field: 'origin', header: 'Origin' },
      { field: 'destination', header: 'Destination' },
      { field: 'contracted_cabin_class', header: 'Contracted Cabins' },
      { field: 'contracted_pax_type', header: 'Contracted Pax Types' },
      { field: 'Custom_multi_day', header: 'Multi Day Operation' },
      { field: 'currency_code', header: 'Currency' },
      { field: 'updated_by', header: 'Updated By' },
      { field: 'Custom_updated_on', header: 'Updated On' },
      { field: 'status', header: 'Status' },
    ];
  };

  OnInitForm() {
    this.Formdata = this.fb.group({
      contract_name: [null],
      airline_code : [null],
      validating_airline: [null],
      flight_no: [null],
      trip_type: [null],
      cabin_class: [null],
      origin: [null],
      destination: [null],
      departure_days: [null],
      date_type: [null],
      from_date: [null],
      to_date: [null],
      pnr: [null],
      currency_code: [null],
      refund_type: [null],
      rbd: [null],
      confirmation_type: [],
      is_multi_day: [false],
      is_oneway_sale_allowed: [false],
    });
    // remove this when User want Round Trip
    if (this._commonService.clientId == '2109111018200000021') {
      this.Formdata.get('trip_type').setValue('ONEWAY');
    }
  };
  FlightContractForm: FormGroup;
  OnInitFlightContractForm(data) {
    this.FlightContractForm = this.fb.group({
      contract_id: [data.contract_id],
      contract_name: [data.contract_name, Validators.required],
      contract_description: [data.contract_description],
    })
  };
  saveFlightContract() {
    let value = this.FlightContractForm.getRawValue();
    if (this.FlightContractForm.status == "INVALID") {
      this.validationService.showValidationsMsg(this.FlightContractForm);
      return;
    }
    let payloadObject = {
      contract_id: value.contract_id,
      contract_name: value.contract_name,
      contract_description: value.contract_description,
    };
    this.ApiServ.Post('/FlightContract/UpdateContractFlight', payloadObject).subscribe(res => {
      if (res) {
        this._commonService.showMessage(res['status'], res['message']);
        this.displayPosition = false;
        if (res['status']) this.GetFlightDetails();
      }
    });
  };

  GetFlightDetails() {
    let value = this.Formdata.getRawValue();
    if (this.Formdata.status == "INVALID") {
      this.validationService.showValidationsMsg(this.Formdata);
      setTimeout(() => {
        this.validationService.scrollToError();
      }, 50);
      return;
    }
    let Postdata = new FlightDetailsSearchModel();
    Postdata.contract_name = value.contract_name ? value.contract_name : '';
    Postdata.validating_airline = value.validating_airline ? value.validating_airline : '';
    Postdata.airline_code = value.airline_code ? value.airline_code : '';
    Postdata.trip_type = value.trip_type ? value.trip_type : '';
    Postdata.flight_no = value.flight_no ? value.flight_no : '';
    Postdata.cabin_class = value.cabin_class ? value.cabin_class: '';
    Postdata.origin = value.origin ? value.origin : '';
    Postdata.destination = value.destination ? value.destination : '';
    Postdata.departure_days = value.departure_days ? value.departure_days.join(',') : '';
    Postdata.date_type = value.date_type ? value.date_type : '';
    Postdata.from_date = value.from_date ? this._commonService.convertDateToSave(value.from_date) : '';
    Postdata.to_date = value.to_date ? this._commonService.convertDateToSave(value.to_date) : '';
    Postdata.pnr = value.pnr ? value.pnr : '';
    Postdata.currency_code = value.currency_code ? value.currency_code : '';
    Postdata.refund_type = value.refund_type ? value.refund_type : '';
    Postdata.rbd = value.rbd ? value.rbd : '';
    Postdata.confirmation_type = value.confirmation_type ? value.confirmation_type: '';
    Postdata.is_multi_day = value.is_multi_day ? value.is_multi_day : false;
    Postdata.is_oneway_sale_allowed = value.is_oneway_sale_allowed ? value.is_oneway_sale_allowed : false;
    this.ApiServ.Post('/FlightContract/GetAllFlightContractBySearch', Postdata).subscribe(res => {
      if (res) {
        this.FlightAllDetails = res.data;
        if (res.data && res.data.length > 0) {
          this.FlightAllDetails.forEach(e => {
            e['Custom_confirmation_type'] = e.confirmation_type ? 'Yes' : 'No';
            e['Custom_multi_day'] = e.is_multi_day ? 'Yes' : 'No';
            e['Custom_updated_on'] = this._commonService.convertDateWithTimeToShow(e.updated_on);
            e['status'] = e.is_active ? 'Active' : 'Deactive';
          });
        }
      }
    });
  };
    updateStatus(id, val) {
    let obj = {
      Id: id,
      Status: !val,
    };
    this.ApiServ.Post('/FlightContract/UpdateStatusContractFlight', obj).subscribe(res => {
      if (res) {
        this._commonService.showMessage(res['status'], res['message']);
        res['status'] ? this.GetFlightDetails() : '';
      }
    });
  }


  ResetForm() {
    let val = this.Formdata.getRawValue()
    Object.keys(val).forEach(e => {
      if (e == 'is_multi_day') this.Formdata.get(e).setValue(false);
      // remove this when User want Round Trip
      else if (e == 'trip_type') {
        if(this._commonService.clientId == '2109111018200000021')this.Formdata.get(e).setValue('ONEWAY');
        else this.Formdata.get(e).setValue(null);
      }
      else this.Formdata.get(e).setValue(null);
    })
  };
  // 

  editRateInventry(contract_id) {
    let obj = { id: contract_id };
    this.router.navigate(['/Services/FlightServices/Manage/EditRateAndInventory'], { queryParams: obj });
  };

  displayPosition: boolean;
  position: string;
  closeFlightContract() {
    this.displayPosition = false;
    this.FlightContractForm.reset();
  };
  showPositionDialog(position: string, data) {
    this.OnInitFlightContractForm(data);
    this.position = position;
    this.displayPosition = true;
  };


  EditFlightDetails(ContractId) {
    this.router.navigate(['/Services/FlightInventory/Manage/EditFlight/' + ContractId]);
  };
  CloneFlightRule(ContractId) {
    this.router.navigate(['/Services/FlightInventory/Clone/' + ContractId]);
  };
  EditRateInventry(ContractId) {
    this.router.navigate(['/Services/FlightInventory/Manage/EditRateInventory/' + ContractId]);
  };
  SelectImage(e, filedata) {
    if (e.currentFiles.length != 0) {
        let file = e.files[0];
        if (file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
          const reader = new FileReader();
          console.log(file)
          reader.readAsText(file); // Read as binary data
          reader.onload = (res) => {
            const binaryString = res.target.result as string;
            const hasScriptTag = this._commonService.hasScriptTagInBinary(binaryString);
            if (hasScriptTag) {
              filedata.clear();
              this._commonService.showMessage(false, 'Invalid file (contains script tag)');
            } else {
              //base 64
              // this.HotelRoomForm.get(contol).setValue(file);
              // if (fileInfo && fileInfo.length > 0 && fileArr && fileArr.length > 0) {
                var formdata = new FormData();
                // fileArr.forEach((x) => {
                  formdata.append("file", file);
                // });
                filedata.clear();
                // let file_info_list = JSON.stringify(fileInfo).replaceAll('ExtranetRoomId', edit_id);
                this.ApiServ.PostFileExtranet("/FlightContract/UploadFlightContrctFromFile", formdata).subscribe(res=>{
                  if(res){
                    this._commonService.showMessage(res.status,res.message);
                  }
                });
              // }
            };
          }
        }
      }

  }
  DateTypeSelection() {
    let date_type = this.Formdata.value.date_type;
    let from_date = this.Formdata.get('from_date').value;
    this.Formdata.get("from_date").clearValidators();
    this.Formdata.get("from_date").setErrors(null);
    this.Formdata.get("to_date").clearValidators();
    this.Formdata.get("to_date").setErrors(null);
    if (date_type && date_type != "") {
      this.Formdata.get("from_date").addValidators([Validators.required]);
      this.Formdata.get("to_date").addValidators([Validators.required,this.dateValidation(from_date)]);
    }
    this.Formdata.get("from_date").updateValueAndValidity();
    this.Formdata.get("from_date").markAsUntouched();
    this.Formdata.get("to_date").updateValueAndValidity();
    this.Formdata.get("to_date").markAsUntouched();
    this.clearDateType();
    this.ManageDateValidations();
  }

  clearDateType() {
    // Trigger 'SelectDateEvent' if both 'from_date' and 'to_date' are unset.
    if(!this.Formdata.get("from_date").value && !this.Formdata.get("to_date").value) this.SelectDateEvent();
  }
  public dateValidation(toDate): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value) {
        if (toDate && control.value <= toDate) {
          return { 'range': true };
        }
      }
      return null;
    };
  }
  Update_Validation(){
    let from_date = this.Formdata.get('from_date').value;
    if(from_date){
      this.Formdata.get("to_date").clearValidators();
      this.Formdata.get("to_date").setErrors(null);
      this.Formdata.get("to_date").addValidators(Validators.compose([Validators.required,this.dateValidation(from_date)]));
      // this.Formdata.get("date_to").markAsTouched();
      this.Formdata.get("to_date").updateValueAndValidity();
    }
    this.ManageDateValidations();
  }

  SelectDateEvent() {
    let from_date = this.Formdata.value.from_date;
    let to_date = this.Formdata.value.to_date;
    this.Formdata.get("date_type").clearValidators();
    this.Formdata.get("date_type").setErrors(null);
    if ((from_date || to_date) && (from_date != "" || to_date != "")) {
      this.Formdata.get("date_type").addValidators([Validators.required]);
    }
    this.Formdata.get("date_type").updateValueAndValidity();
    // this.Formdata.get("date_type").markAsUntouched();
    this.Update_Validation()
  }
  ManageDateValidations() {    
    const from_date = this.Formdata.get('from_date').value;
    const to_date = this.Formdata.get('to_date').value;
    const date_type = this.Formdata.get('date_type').value;
    const hasValue = from_date || to_date || date_type;
    if (hasValue) {
        this.Formdata.get("date_type").setValidators(date_type ? null : Validators.required);
        this.Formdata.get("from_date").setValidators(from_date ? null : Validators.required);
        if(from_date){
          this.Formdata.get("to_date").addValidators([Validators.required, this.dateValidation(from_date)]);
        }
    } else {
        this.Formdata.get("from_date").clearValidators();
        this.Formdata.get("to_date").clearValidators();
        this.Formdata.get("date_type").clearValidators();
    }
  
    this.Formdata.get("from_date").updateValueAndValidity();
    this.Formdata.get("to_date").updateValueAndValidity();
    this.Formdata.get("date_type").updateValueAndValidity();
  }
  btnClick() {
    this.router.navigateByUrl("Services/FlightInventory/Add");
   }
}
