import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { forkJoin } from 'rxjs';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { API } from 'src/app/core/services/api.service';

@Component({
  selector: 'rate-setting',
  templateUrl: './rate-setting.component.html',
})
export class RateSettingComponent implements OnInit {
  displayPosition: boolean;
  position: string;
  Extranet_Hotel_Id;
  AllMealPlan;
  AllRatePlan;
  Result;
  AllRoomsData;
  ExtranetMealPlan;
  ExtranetRatePlan;
  HotelRoomContractForm:FormGroup;
  ExtranetRoom;
  cols;
  constructor(public activateRoute:ActivatedRoute,private router:Router, public apiserv:API,public _commonService:CommonFunctionService,
    public validserv:ValidationService,public fb:FormBuilder) { }

  ngOnInit(): void {
    this.Extranet_Hotel_Id = this.activateRoute.snapshot.paramMap.get('Hotel_Eaxtranet_Id') as string;
    this.cols = [
      { field: 'extranet_contract_id', header: 'Contract Id' },
      { field: 'contract_name', header: 'Contract Name' },
      { field: 'extranet_room_id', header: 'Room Id' },
      { field: 'room_name', header: 'Room Name' },
      { field: 'rate_plan_name', header: 'Rate Plan' },
      { field: 'meal_plan_name', header: 'Meal Plan' },
      { field: 'nationality_type', header: 'Nationality Type' },
      { field: 'nationality_applicable_type', header: 'Nationality Applicability' },
      { field: 'nationality', header: 'Nationality' },
      { field: 'date_range', header: 'Date Range/Season' },
      { field: 'currency_code', header: 'Currency' },
      { field: 'is_meal_addon_applicable', header: 'Meal Add On' },
      { field: 'addon_name', header: 'Meals' },
      { field: 'status', header: 'Contract Status' },
      { 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' },
      { field: 'last_updated', header: 'Last Updated' },
    ];
    this.getAllData();
    this.HotelRoomContractForm = this.fb.group({
      contract_name:this.validserv.required,
    })
  }
  getAllData() {
    forkJoin(
      this.GetAllRooms(),
      this.GetAllPlan(),
      this.GetAllMealPlan()
    ).subscribe(res=>{
      if(res && res.length > 0){
        this.AllRoomsData = res[0] ? res[0].data : [];
        this.AllRatePlan = res[1] ? res[1].data : [];
        this.AllMealPlan = res[2].data;
      }
    });
  }
  showPositionDialog(position) {
    this.position = position;
    this.displayPosition = true;
  };
  GetAllPlan(){
    return this.apiserv.Get('/ExtranetRoomContract/GetAllExtranetHotelRatePlan/EN')
  }
  GetAllMealPlan(){
    return this.apiserv.Get('/ExtranetMealAddon/GetAllExtranetMeal/EN')
  }
  GetAllRooms(){
    let ReqObj = {
      extranet_hotel_id : this.Extranet_Hotel_Id,
      extranet_room_id : '',
      room_name : '',
      room_view_name : '',
    }
    return this.apiserv.Post('/ExtranetRoomContract/GetAllExtranetHotelRoomName',ReqObj)
  }
  updateStatus(id, val) {
    let obj = {
      Id: id,
      Status: val ? false : true,
    };
    this.apiserv.Post('/ExtranetRoomContract/UpdateExtranetRoomContractStatus', obj).subscribe(res => {
      if (res) {
        this._commonService.showMessage(res['status'], res['message']);
        res['status'] ? this.Search() : '';
      }
    });
  }
  Search(){
    let ReObj = {
      extranet_hotel_id:this.Extranet_Hotel_Id,
      extranet_room_id:this.ExtranetRoom ? this.ExtranetRoom : '',
      extranet_rate_plan_id:this.ExtranetRatePlan ? this.ExtranetRatePlan : '',
      extranet_meal_plan_id:this.ExtranetMealPlan ? this.ExtranetMealPlan : ''
    }
    this.apiserv.Post('/ExtranetRoomContract/GetAllExtranetRoomContract',ReObj).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['nationality_type'] = this.getNationalityType(e['nationality_type']) ;
            e['nationality_applicable_type'] = this.getNationalityApplicabilityType(e['nationality_applicable_type']) ;
            e['Custom_created_on'] = e['created_on'] ?  this._commonService.convertDateWithTimeToShow(e.created_on) : e['created_on'];
            e['date_range_arr'] = e['contract_dates'] ? JSON.parse(e['contract_dates']) : [];
            if(typeof(e['date_range_arr']) != 'string'){
              e.date_range_arr.forEach((data,ind)=>{
                e.date_range_arr[ind] =  moment(data.date_from).format('DD MMM YYYY') + ' - ' + moment(data.date_to).format('DD MMM YYYY');
              })
            }
            e['date_range'] = e.date_range_arr.length > 0 ? e.date_range_arr.join(',') : '';
          });
          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();
          });
        }
      }
    })
  }
  Reset(){
    this.ExtranetMealPlan = undefined;
    this.ExtranetRatePlan = undefined;
    this.ExtranetRoom = undefined;
  }
  Update(Id,pagename){
    this.router.navigateByUrl(`Services/Hotel/HotelManage/${pagename}/${this.Extranet_Hotel_Id}/${Id}`);
  }
  EditContract(Id){
    this.router.navigateByUrl(`Services/Hotel/HotelManage/RoomContractEdit/${this.Extranet_Hotel_Id}/${Id}`);
  }
  getNationalityType(value){
    if(value == 'INCLUDE'){
      return 'Include'
    }else if(value == 'EXCLUDE'){
      return 'Exclude'
    }
    return ''
  }
  getNationalityApplicabilityType(value){
    if(value == 'ALL'){
      return 'All'
    }else if(value == 'SPECIFIC'){
      return 'Specific'
    }
    return ''
  }
  RoomView(Id){
    this.router.navigateByUrl(`Services/Hotel/HotelManage/CloneContract/${this.Extranet_Hotel_Id}/${Id}`);
  }
}
