import { Component, NgModule, OnInit, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import * as moment from 'moment';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { API } from 'src/app/core/services/api.service';
import { HotelBookingManagementService } from 'src/app/core/services/HotelServices/hotel_booking_management.service';
import { Product } from 'src/app/core/services/product';
import { securityFunctions } from 'src/app/core/common/security';

@Component({
  selector: 'hotel-booking-search',
  templateUrl: './hotel-booking-search.component.html',
})
export class HotelBookingSearchComponent implements OnInit {
  analyticsData;
  cols: any[];
  exportColumns;
  products: Product[];
  HotelBookingFiltersForm: FormGroup;
  confirmationForm: FormGroup;
  selectedProducts: Product[];
  Agencylist;
  Companylist;
  Entitylist;
  Countrylist;
  Citylist;
  AssignUserList=[];
  AssignSupportList=[];
  AssignUser=[];
  AssignSupport=[];
  AssignUserSearch=[];
  User_Type;
  User_Name;
  User_Id = [{user_id:'',user_name:'Assign to me'}];
  User_Id_sup = [{user_id:'',user_name:'Assign to me'}];
  HotelSupplierlist;
  HotelBookingList;
  @ViewChild('dt') myTable;
  To_Date_Start;
  AllCurrency;
  isOpenAddConfirmationNumberModal: boolean = false;
  AgencyType = [
    { key: "B2C", value: "B2C" },
    { key: "B2B", value: "B2B" }
  ];
  Date_Type = [
    'Booking Date',
    'Check In',
    'Check Out',
    'Cancellation Deadline'
  ]
  StarRating = [
    { key: "0", value: "0 Star" },
    { key: "1", value: "1 Star" },
    { key: "2", value: "2 Star" },
    { key: "3", value: "3 Star" },
    { key: "4", value: "4 Star" },
    { key: "5", value: "5 Star" }
  ];
  BookingStatus = [
    { key:"0",  value:"In Progress"},
    { key:"1",  value:"Pending"},
    { key:"3",  value:"Confirmed"},
    { key:"4",  value:"Cancelled"},
    { key:"6",  value:"Reserved"}
 ];
  PaymentStatus = [
    { key: "PENDING", value: "Pending" },
    { key: "FAILED", value: "Failed" },
    { key: "PAID", value: "Paid" },
    { key: "PARTLYPAID", value: "Partly Paid" },
    { key: "PAID(AUTHORIZED)", value: "Paid (Authorized)" },
  ];
  InvoiceStatus = [
    { key: "INVOICED", value: "Invoiced" },
    { key: "INVOICEFAILED", value: "Invoice Failed" },
    { key: "INVOICEPENDING", value: "Invoice Pending" },
    { key: "INVOICEVOID", value: "Invoice Void" },
  ];

  constructor(
    private router: Router,
    private formBuilder: FormBuilder,
    private apiserv: API,
    private hotelBkgMgmtService: HotelBookingManagementService,
    private fb: FormBuilder,
    public commonserv: CommonFunctionService
  ) { }
  ngOnInit(): void {
    // this.apiserv.setTitle('Hotel Booking');
    this.cols = [
      { field: 'assigned_user_name', header: 'Assign User' },
      { field: 'assigned_user_name_2', header: 'Assign Support' },
      { field: 'trip_id', header: 'Trip Id' },
      { field: 'booking_id', header: 'Booking Id' },
      { field: 'payment_transaction_id', header: 'Payment Transaction Id' },
      { field: 'hotel_name', header: 'Hotel Name' },
      { field: 'hotel_country', header: 'Country' },
      { field: 'hotel_city', header: 'City' },
      { field: 'new_booking_date', header: 'Booking Date' },
      { field: 'checkin_date', header: 'Check In Date' },
      { field: 'checkout_date', header: 'Check Out Date' },
      { field: 'no_of_nights', header: 'No Of Nights' },
      { field: 'no_of_rooms', header: 'No Of Rooms' },
      { field: 'room_names_custom', header: 'Room Name' },
      { field: 'lead_guest', header: 'Lead Guest' },
      { field: 'guest_nationality_code', header: 'Lead Nationality' },
      { field: 'guest_mobile_no', header: 'Lead Mobile Number' },
      { field: 'guest_email_address', header: 'Lead Email Address ' },
      { field: 'supplier_name', header: 'Supplier' },
      { field: 'supplier_ref_no', header: 'Supplier Ref no.' },
      { field: 'agency_name', header: 'Agency' },
      { field: 'agency_type', header: 'Agency Type' },
      { field: 'booking_by', header: 'Booking By' },
      { field: 'quality_check', header: 'Quality Check' },
      { field: 'payment_status_custom', header: 'Payment Status' },
      { field: 'promo_code', header: 'Promo Code' },
      { field: 'payment_mode_custom', header: 'Payment Mode' },
      { field: 'total', header: 'Total Booking Amount' },
      { field: 'booking_status_custom', header: 'Booking Status' },
      { field: 'thirdparty_invoice_number', header: 'Accounting Invoice No.' },
      { field: 'thirdparty_invoice_status', header: 'AC Invoice No.' },
      { field: "NotesStr", header: "notes" },
    ];
    this.exportColumns = this.cols.map(col => ({
      title: col.header,
      dataKey: col.field
    }));
    this.User_Type = sessionStorage.getItem('userType');
    this.User_Name = sessionStorage.getItem('userName');
    this.User_Id[0]['user_id'] = sessionStorage.getItem('userId');
    this.User_Id_sup[0]['user_id'] = sessionStorage.getItem('userId');
    this.formInitialize();
    this.getAllCurrency();
    this.getCompanyList();
    this.getEntityList();
    this.getHotelSupplierListV2();
    this.getHotelCountryList();
    this.setDefaultDate();
  }
  formInitialize() {
    this.HotelBookingFiltersForm = this.formBuilder.group({
      fltr_trip_id: [''],
      fltr_booking_id: [''],
      fltr_payment_transaction_id: [''],
      fltr_company: [],
      fltr_branch: [],
      fltr_agency: [],
      fltr_agency_type: [],
      fltr_hotel_name: [''],
      fltr_country: [],
      fltr_city: [],
      fltr_star_rating: [],
      fltr_supplier: [],
      fltr_supplier_ref_no: [''],
      fltr_guest_name: [''],
      fltr_guest_contact_no: [''],
      fltr_guest_email: [''],
      fltr_booking_status: [],
      fltr_payment_status: [],
      fltr_invoice_status: [],
      fltr_date: [null],
      from_Date: [''],
      To_Date: [''],
      promo_code: [''],
      assigned_user: [''],
      under_cancel: [false],
      is_promo_code_applied: [false],
      fail_cancel: [false],
    });
  }

  getCompanyList() {
    this.hotelBkgMgmtService.getAllCompany().subscribe((res) => {
      if (res) {
        this.Companylist = res;
        console.log(this.Companylist);
      }
    });
  }
  getHotelCountryList() {
    this.hotelBkgMgmtService.getAllHotelCountry().subscribe((res) => {
      if (res) {
        this.Countrylist = res;
        console.log(this.Countrylist);
      }
    });
  }
  getHotelCityList(country_code) {
    this.Citylist = null;
    this.hotelBkgMgmtService.getAllHotelCityByCountry(country_code).subscribe((res) => {
      if (res) {
        this.Citylist = res;
      }
    });
  }
  getEntityList() {
    this.hotelBkgMgmtService.getAllEntity().subscribe((res) => {
      if (res) {
        this.Entitylist = res;
      }
    });
  }

  getAllCurrency() {
    this.hotelBkgMgmtService.getAllCurrency().subscribe((res) => {
      if (res) {
        this.AllCurrency = res;
      }
    });
  }
  getHotelSupplierList() {
    this.hotelBkgMgmtService.getAllHotelSupplier().subscribe((res) => {
      if (res) {
        this.HotelSupplierlist = res;
      }
    });
  }
  getHotelSupplierListV2() {
    this.hotelBkgMgmtService.getAllHotelSupplierV2().subscribe((res) => {
      if (res) {
        this.HotelSupplierlist = res;
      }
    });
  }
  getFormatedDate(obj) {
    if (obj != null && obj != '' && obj) {
      return moment(obj).format("DD MMM YYYY");
    } else {
      return "";
    }
  }
  /**
   * @Description setting the min date for To Date calender
   * @param Date From Date
   */

  applyToDate(date) {
    this.To_Date_Start = date
  }

  search_bookings() {
    let form_data = this.HotelBookingFiltersForm.value;
    let VData = securityFunctions.getSessionStorage('VData') ? JSON.parse(securityFunctions.getSessionStorage('VData')) : '';
    let reqData = {
      user_time_zone: this.commonserv.GetTimeZoneGMT(),
      trip_id: form_data.fltr_trip_id,
      booking_id: form_data.fltr_booking_id,
      payment_transaction_id: form_data.fltr_payment_transaction_id,
      agency_id: form_data.fltr_agency,
      agency_type: form_data.fltr_agency_type,
      user_id: "",
      company_id: form_data.fltr_company,
      entity_id: form_data.fltr_branch,
      hotel_name: form_data.fltr_hotel_name,
      country: form_data.fltr_country,
      city: form_data.fltr_city,
      star_rating: form_data.fltr_star_rating,
      vendor_id: VData ? VData.extranet_vendor_id : '',
      supplier: '',
      supplier_ref_no: form_data.fltr_supplier_ref_no,
      guest_name: form_data.fltr_guest_name,
      contact: form_data.fltr_guest_contact_no,
      email: form_data.fltr_guest_email,
      promo_code: form_data.promo_code,
      assigned_user: form_data.assigned_user?form_data.assigned_user:'',
      is_promo_code_applied: form_data.is_promo_code_applied ? form_data.is_promo_code_applied.toString() : '',
      fail_cancel: form_data.fail_cancel,
      booking_status: form_data.fltr_booking_status,
      payment_status: form_data.fltr_payment_status === 'PAID(AUTHORIZED)' ? 'PAID' : form_data.fltr_payment_status,
      invoice_status: form_data.fltr_invoice_status,
      booking_from_date: '',
      booking_to_date: '',

      check_in_from_date: '',
      check_in_to_date: '',

      check_out_from_date: '',
      check_out_to_date: '',

      cancellation_deadline_from : '',
      cancellation_deadline_to : '',
      under_cancel: form_data.under_cancel,
      is_authorized: form_data.fltr_payment_status === 'PAID(AUTHORIZED)' ? '1' : '0'
    };
    if (form_data.fltr_date == 'Booking Date') {
      reqData.booking_from_date = this.getFormatedDate(form_data.from_Date);
      reqData.booking_to_date = this.getFormatedDate(form_data.To_Date)
    }
    else if (form_data.fltr_date == 'Check In') {
      reqData.check_in_from_date = this.getFormatedDate(form_data.from_Date);
      reqData.check_in_to_date = this.getFormatedDate(form_data.To_Date);
    }
    else if (form_data.fltr_date == 'Check Out') {
      reqData.check_out_from_date = this.getFormatedDate(form_data.from_Date);
      reqData.check_out_to_date = this.getFormatedDate(form_data.To_Date);
    }
    else if (form_data.fltr_date == 'Cancellation Deadline') {
      reqData.cancellation_deadline_from = this.getFormatedDate(form_data.from_Date);
      reqData.cancellation_deadline_to = this.getFormatedDate(form_data.To_Date);
    }

    this.hotelBkgMgmtService.getHotelBookingList(reqData).subscribe((res) => {
      if (res) {
        this.myTable.first = 0;
        this.HotelBookingList = res.map((x,i) => {
          let obj_currency = this.AllCurrency.filter(g => g.currency_code == x.currency);
          let amountFormat = obj_currency && obj_currency.length > 0 ? obj_currency[0].amount_format : '#,###,###,###.##';
          let decimalSeperator = obj_currency && obj_currency.length > 0 ? obj_currency[0].decimal_seperator : '.';
          x['total'] = x.supplier_currency + ' ' + this.commonserv.amountFormater(x.supplier_total_amount, amountFormat, decimalSeperator);
          x['custom_booking_date'] = x.booking_date;
          x['room_names_custom'] = x.room_names ? x.room_names.replaceAll(' <-> ',', ') : x.room_names;
          x["NotesStr"] = x.notes ? x.notes.join(',') : "";
          x['new_booking_date'] = moment(x.booking_date).format('DD MMM YYYY, HH:mm:ss');
          x['custom_booking_date'] = x.booking_date;
          x.booking_date = this.commonserv.UtcToLocaleTime(x.booking_date, 'DD MMM YYYY, HH:mm:ss');
          x['custom_checkin_date'] = x.checkin_date
          x.checkin_date = moment(x.checkin_date).format('DD MMM YYYY');
          x['custom_checkout_date'] = x.checkout_date
          x.checkout_date = moment(x.checkout_date).format('DD MMM YYYY');
          x['booking_status_custom'] = this.map_booking_status(x.status_id, x.payment_status);
          x['payment_status_custom'] = this.map_payment_status(x.payment_status, x.is_authorised);
          x['payment_mode_custom'] = x.payment_mode;
          x["Index"] = i;
          if(x.assigned_user){
            x.assigned_user == this.User_Id[0]['user_id']? this.User_Id[0]['user_name'] = this.User_Name  :this.AssignUserList[i] = [{user_id:x.assigned_user,user_name:x.assigned_user_name}];
          }
          if(x.assigned_user_2){
            x.assigned_user_2 == this.User_Id_sup[0]['user_id']? this.User_Id_sup[0]['user_name'] = this.User_Name  :this.AssignSupportList[i] = [{user_id:x.assigned_user_2,user_name:x.assigned_user_name_2}];
          }
          this.AssignUser[i] = x.assigned_user?x.assigned_user:null;
          this.AssignSupport[i] = x.assigned_user_2?x.assigned_user_2:null;
          return x;
        });
        console.log(this.HotelBookingList);
      }
    });

  }
  map_payment_status(status, is_authorised) {
    if (status != null && status != "") {
      switch (status) {
        case "PAID": {
          return is_authorised ? 'Paid (Authorized)' : 'Paid';
        }
        case "PENDING": {
          return 'Pending';
        }
        case "FAILED": {
          return 'Failed';
        }
        case "PARTLYPAID": {
          return 'Partly Paid';
        }
        default : {
          return 'Not Attempt';
        }
      }
    } else {
      return 'Not Attempt';
    }
  }
  map_payment_mode(mode) {
    if (mode != null && mode != "") {
      switch (mode) {
        case "WALLET": {
          return 'Wallet';
        }
        case "CREDIT": {
          return 'Credit';
        }
        case "PAYATAGENCY": {
          return 'Pay at Agency';
        }
        case "PAYMENTGATEWAY": {
          return 'Payment Gateway';
        }
        case "PAYMENTGETWAY": {
          return 'Payment Gateway';
        }
        default : {
          return '-';
        }
      }
    } else {
      return '-';
    }
  }
  map_booking_status(booking_status, payment_status) {
    if (booking_status != null) {
      if (booking_status == 3) {
        return 'Confirmed';
      }
      else if (booking_status == 4) {
        return 'Cancelled';
      }
      else if(booking_status == 6) {
        return 'Reserved';
      }
      else if ((booking_status == 0 || booking_status == 2) && payment_status != null) {
        return 'Pending';
      }
      else {
        return 'In Progress';
      }
    } else {
      return 'In Progress';
    }
  }
  search_form_reset() {
    this.formInitialize();
    this.Citylist = null;
  }
  select_booking(trip_id) {
    let obj = {
      id: trip_id
    }
    const url = this.router.serializeUrl(
      this.router.createUrlTree(['/BookingManagement/HotelBooking/View'], { queryParams: obj })
    );
    window.open(url, '_blank');
  }
  quality_check(trip_tbl_id) {
    this.hotelBkgMgmtService.bookingQualityCheck(trip_tbl_id).subscribe((res) => {
      if (res) {
        this.search_bookings();
        console.log(res);
      }
    });
  }
  onCountrySelect(e) {
    this.HotelBookingFiltersForm.get('fltr_city').setValue(null);
    e ? this.getHotelCityList(e.country_code) : this.Citylist = null;
  }

  GetAssignUser(event,index){
    let Obj={
      user_type:this.User_Type,
      keyword:event.target.value
    }
    if(event.target.value.length>=3){
      this.apiserv.PostGo('/BookingManagement/GetOrgUserSearchDetails',Obj).subscribe(data=>{
        this.AssignUserList[index] = data.Result
        this.AssignSupportList[index] = data.Result
      })
    }
  }
  GetAssignUserValue(event){
    let Obj={
      user_type:this.User_Type,
      keyword:event.target.value
    }
    if(event.target.value.length>=3){
      this.apiserv.PostGo('/BookingManagement/GetOrgUserSearchDetails',Obj).subscribe(data=>{
        this.AssignUserSearch = data.Result
      })
    }
  }
  Save_User(trip_id,Value,i,update_type){
    let Obj = {
      trip_id:trip_id,
      user_id:Value?Value:'',
      user_type:this.User_Type,
      update_type: update_type
    }
    if(!Value){
      if(update_type == '1') {
        this.AssignUser[i] = null;
    } else {
      this.AssignSupport[i] = null;
    }
    }else if(Value == this.User_Id[0]['user_id'] && update_type == '1'){
      this.User_Id[0]['user_name'] = this.User_Name;
    } else if(Value == this.User_Id_sup[0]['user_id'] && update_type == '2'){
      this.User_Id_sup[0]['user_name'] = this.User_Name;
    }
    this.apiserv.PostGo('/BookingManagement/AssignTripToOrgUser',Obj).subscribe(data=>{
      // this.AssignUserList = data.Result
      this.commonserv.showMessage(data['Resp'],data['Message'])
    })
  }
  GetDatabyAgencyType() {
    this.HotelBookingFiltersForm.get('fltr_agency').setValue(null);
  }

  // Set Default for the  from date & to date
  setDefaultDate(){
    this.HotelBookingFiltersForm.get("fltr_date").setValue("Booking Date");
    let from_date = new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000);
    let to_date = new Date();
    this.HotelBookingFiltersForm.get("from_Date").setValue(from_date);
    this.HotelBookingFiltersForm.get("To_Date").setValue(to_date);
  }
  initConfirmationForm(itinerary_data) {
    let obj = {
      booking_id: itinerary_data != null && itinerary_data.booking_id != null && itinerary_data.booking_id != '' ? itinerary_data.booking_id : "",
      // hotel_confirmation_number: itinerary_data != null && itinerary_data.hotel_confirmation_number != null && itinerary_data.hotel_confirmation_number != '' ? itinerary_data.hotel_confirmation_number.split(',') : [],
      hotel_confirmation_number_date: itinerary_data != null && itinerary_data.hotel_confirmation_number_date != null && itinerary_data.hotel_confirmation_number_date != '' ? new Date(itinerary_data.hotel_confirmation_number_date) : new Date(),
      hotel_confirmation_staff_name: itinerary_data != null && itinerary_data.hotel_confirmation_staff_name != null && itinerary_data.hotel_confirmation_staff_name != '' ? itinerary_data.hotel_confirmation_staff_name : "",
      hotel_confirmation_staff_remarks: itinerary_data != null && itinerary_data.hotel_confirmation_staff_remarks != null && itinerary_data.hotel_confirmation_staff_remarks != '' ? itinerary_data.hotel_confirmation_staff_remarks : "",
      supplier_confirmation_number: itinerary_data != null && itinerary_data.supplier_confirmation_number != null && itinerary_data.supplier_confirmation_number != '' ? itinerary_data.supplier_confirmation_number : ""
    }
    this.confirmationForm = this.fb.group({
      booking_id: [obj.booking_id],
      // hotel_confirmation_number: [obj.hotel_confirmation_number],
      hotel_confirmation_number:this.fb.array([]),
      supplier_confirmation_number:[obj.supplier_confirmation_number],
      hotel_confirmation_number_date: [obj.hotel_confirmation_number_date],
      hotel_confirmation_staff_name: [obj.hotel_confirmation_staff_name],
      hotel_confirmation_staff_remarks: [obj.hotel_confirmation_staff_remarks],
    });
    let formarray = this.confirmationForm.controls['hotel_confirmation_number'] as FormArray;
    if(itinerary_data?.room_list.length > 0){
      itinerary_data.room_list.forEach(data=>{
        formarray.push(
          this.fb.group({
            room_name:data.room_name,
            room_id:data.hotel_room_id,
            confirmation_no:data.hotel_confirmation_number,
          })
        )
      })
    }
  }
  
  openConfirmationNumberModal( itinerary_data) {
    this.initConfirmationForm(itinerary_data);
    this.isOpenAddConfirmationNumberModal = true;
  }

  saveConfirmationNumber() {
    let obj = this.confirmationForm.value;
    let postdata = {
      booking_id:obj.booking_id,
      supplier_confirmation_number:obj.supplier_confirmation_number,
      hotel_confirmation_number_date:obj.hotel_confirmation_number_date,
      hotel_confirmation_staff_name:obj.hotel_confirmation_staff_name,
      hotel_confirmation_staff_remarks:obj.hotel_confirmation_staff_remarks,
      hotel_rooms:[]
    }
    let hotel_confirm_number = [];
    obj.hotel_confirmation_number.forEach(data=>{
      hotel_confirm_number.push(
        {
          hotel_room_id:data.room_id,
          hotel_confirmation_number:data.confirmation_no
        }
      );
    })
    postdata.hotel_rooms = hotel_confirm_number;
    this.hotelBkgMgmtService.saveConfirmationNumber(postdata).subscribe((data) => {
      if(data?.resp){
        this.isOpenAddConfirmationNumberModal = false;
        this.search_bookings();
      }
    });
  }

}
