import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { ManageHotelService } from 'src/app/core/services/HotelServices/manage-hotel.service';
import { API } from 'src/app/core/services/api.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-hotel-search',
  templateUrl: './hotel-search.component.html',
})
export class HotelSearchComponent implements OnInit {

  constructor(private apiserv: API, public fb: FormBuilder, public _commonService: CommonFunctionService, private router: Router, private hotelmanageserv: ManageHotelService) { }
  timer;
  Result;
  HotelList;
  AllVendors;
  cols;
  Cdn_url = environment.cdnFileUrl;
  All
  ddLoader = {
    Country: false,
    city: false,
    hotel_list: false,  }
  CountryList;
  CityList;
  HotelSearchForm: FormGroup;
  ngOnInit(): void {
    this.HotelSearchForm = this.fb.group({
      hotel_code_mapping: '',
      vendor_id: '',
      star_rating: '',
      country_code: null,
      city_code: null,
      is_active: ''
    });
    this.cols = [
      { field: 'hotel_name', header: 'Hotel Name' },
      { field: 'hotel_code_mapping', header: 'Hotel Mapping Code' },
      { field: "vendor_name", header: 'Vendor Name' },
      { field: 'star_rating', header: 'Star Rating' },
      { field: 'country', header: 'Country' },
      { field: 'city', header: 'City' },
      { field: 'currency', header: 'Currency' },
      { field: 'status', header: 'Status' },
      { field: 'extranet_hotel_id', header: 'Extranet Hotel Id' },
      { field: 'created_by', header: 'Created By' },
      { field: 'Custom_created_on', header: 'Created On' },
      { field: 'updated_by', header: 'Updated By' },
      { field: 'Custom_updated_on', header: 'Updated On' },
    ];
    this.GetallVendors();
  }

  getCountryList(event) {
    if (event.value.length >= 2) {
      this.ddLoader['Country'] = true;
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.apiserv.AdminGet(`/MasterSearch/GetAllCountry/en/${event.value}`).subscribe(res => {
          if (res) {
            this.CountryList = res;
            this.ddLoader['Country'] = false;
          }
        });
      }, 500);
    }
  }
  GetallVendors(){
    this.apiserv.Get('/ExtranetHotel/GetAllVendorNameByOrg').subscribe(res => {
      if(res && res.data){
        this.AllVendors = res.data;
      }
    })

  }
  getHotelCitySearch(event) {
    if (event.value.length >= 2) {
      let reqObj = {
        cityName: event.value,
        languageCode: 'en',
        lattitude: '0',
        longitude: '0'
      }
      this.ddLoader.city = true;
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.apiserv.AdminGoPost("/Hotel/GetHotelCities", reqObj).subscribe(res => {
          if (res) {
            this.CityList = res.cities;
            this.ddLoader.city = false;
          }
        });
      }, 500);
    }
    if (!event.value) {
      this.CityList = [];
    }
  };
  Search() {
    let val = this.HotelSearchForm.getRawValue();
    let ReqObj = {
      hotel_code_mapping: val.hotel_code_mapping ? val.hotel_code_mapping : '',
      vendor_id: val.vendor_id ? val.vendor_id : '',
      star_rating: val.star_rating ? parseInt(val.star_rating) : 0,
      country_code: val.country_code ? val.country_code : '',
      city_code: val.city_code ? val.city_code : '',
      is_active: val.is_active ? val.is_active : ''
    }
    this.apiserv.Post('/ExtranetHotel/GetAllExtranetHotel', ReqObj).subscribe(res => {
      if (res) {
        this.Result = res.data ? res.data :[];
        if (res.data) {
          this.Result.forEach(e => {
            e['status'] = e.is_active ? 'Active' : 'Deactive';
            e['Custom_updated_on'] = this._commonService.convertDateWithTimeToShow(e.updated_on);
            e['Custom_created_on'] = e['created_on'] ?  this._commonService.convertDateWithTimeToShow(e.created_on) : e['created_on'];
          });
          // customSort(event: SortEvent) {
            this.Result.sort((a: any, b: any) => {
                // Sort by status: Active first, then Deactive
                if (a.status !== b.status) {
                    return a.status === 'Active' ? -1 : 1;
                }
        
                // If both are Active, sort by activeDate
                if (a.status === 'Active') {
                    return new Date(b.updated_on).getTime() - new Date(a.updated_on).getTime();
                }
        
                // If both are Deactive, sort by deactiveDate
                return new Date(b.updated_on).getTime() - new Date(a.updated_on).getTime();
            });
        // }
        }
      }
    })
  }
  updateStatus(id, val) {
    let obj = {
      Id: id,
      Status: val ? false : true,
    };
    this.apiserv.Post('/ExtranetHotel/UpdateExtranetHotelStatus', obj).subscribe(res => {
      if (res) {
        this._commonService.showMessage(res['status'], res['message']);
        res['status'] ? this.Search() : '';
      }
    });
  }
  ManageHotel(Id) {
    this.hotelmanageserv.Active_tab = 'OverView'
    this.router.navigateByUrl(`Services/Hotel/HotelManage/${Id}`);
  }
  Reset() {
    this.HotelSearchForm = this.fb.group({
      hotel_code_mapping: '',
      vendor_id: '',
      star_rating: '',
      country_code: null,
      city_code: null,
      is_active: ''
    });
  }

  GetHotels(event){
    if (event.value.length >= 2) {
      let obj ={
        languageCode:'en',
        cityName:event.value,
        lattitude:'0',
        longitude:'0',
      }
      this.ddLoader['hotel_list'] = true;
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.apiserv.AdminGoPost(`/Hotel/GetHotels`,obj).subscribe(res => {
          if (res) {
            this.HotelList = res.hotels;
            this.ddLoader['hotel_list'] = false;
          }
        });
      }, 500);
    }
}
btnClick() {
  this.router.navigateByUrl("Services/Hotel/HotelAdd");
 }
 SelectImage(e, filedata, extranet_hotel_id) {
  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) {
              let formdata = new FormData();
              // fileArr.forEach((x) => {
                formdata.append("file", file);
                formdata.append("extranet_hotel_id", extranet_hotel_id);
              // });
              filedata.clear();
              // let file_info_list = JSON.stringify(fileInfo).replaceAll('ExtranetRoomId', edit_id);
              this.apiserv.PostFileExtranet("/ExtranetHotelUpload/UploadHotelContrctFromFile", formdata).subscribe(res=>{
                if(res){
                  this._commonService.showMessage(res.status,res.message);
                }
              });
            // }
          };
        }
      }
    }
  }
}
