import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, 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';

@Component({
  selector: 'supplements-view',
  templateUrl: './supplements-view.component.html',
})
export class SupplementsViewComponent implements OnInit {

  AllRoomsData;
  Result;
  cols;
  SupplementSearchForm:FormGroup
  constructor(
    public activateRoute:ActivatedRoute,
    public apiserv:API,
    public _commonService:CommonFunctionService,
    public router:Router,
    private fb:FormBuilder
  ) { }
  Extranet_Hotel_Id;
  ngOnInit(): void {
    this.Extranet_Hotel_Id = this.activateRoute.snapshot.paramMap.get('Hotel_Eaxtranet_Id') as string;
    this.GetAllRooms();
    this.SupplementSearchForm = this.fb.group({
      extranet_hotel_id:this.Extranet_Hotel_Id,
      extranet_room_id:'',
      contract_name:'',
      supplement_name:'',
      supplement_rate_type:'',
      supplement_type:''
    });
    this.cols = [
      { field: 'supplement_name', header: 'Supplement Name' },
      { field: 'supplement_rate_type', header: 'Supplement Rate Type' },
      { field: 'room_name', header: 'Room Name' },
      { field: 'supplement_type', header: 'Supplement Type' },
      { field: 'date_range_arr', header: 'supplement_dates' },
      { field: 'custom_days', header: 'Supplement days' },
      { field: 'extranet_supplement_id', header: 'Supplement Id' },
      { field: 'status', header: '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' }
    ];
  }

  GetAllRooms(){
    let ReqObj = {
      extranet_hotel_id : this.Extranet_Hotel_Id,
      extranet_room_id : '',
      room_name : '',
      room_view_name : '',
    }
    this.apiserv.Post('/ExtranetRoomContract/GetAllExtranetHotelRoomName',ReqObj).subscribe(res=>{
      if(res && res.data){
        this.AllRoomsData = res.data;
      }
    })
  }
  Search(){
    let val = this.SupplementSearchForm.getRawValue();
    let obj = {
      extranet_hotel_id:val.extranet_hotel_id,
      extranet_room_id:val.extranet_room_id,
      contract_name:val.contract_name,
      supplement_name:val.supplement_name,
      supplement_rate_type:val.supplement_rate_type,
      supplement_type:val.supplement_type,
    }
    this.apiserv.Post('/ExtranetSupplement/GetAllExtranetSupplement',obj).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['supplement_rate_type'] = this.getSupplementRateType(e.supplement_rate_type);
            e['supplement_type'] = this.getSupplementType(e.supplement_type);
            e['Custom_created_on'] = e['created_on'] ?  this._commonService.convertDateWithTimeToShow(e.created_on) : e['created_on'];
            e['date_range_arr'] = e['supplement_dates'] ? JSON.parse(e['supplement_dates']) : e['supplement_dates'];
            if(typeof(e['date_range_arr']) != 'string'){
              e.date_range_arr.forEach((data,ind)=>{
                e.date_range_arr[ind] =  moment(data.from).format('DD MMM YYYY') + ' - ' + moment(data.to).format('DD MMM YYYY');
              })
            }
            e['custom_days'] = e['supplement_days'] ? e['supplement_days'].split(',') : ''
          });
          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('/ExtranetSupplement/UpdateExtranetSupplementStatus', obj).subscribe(res => {
      if (res) {
        this._commonService.showMessage(res['status'], res['message']);
        res['status'] ? this.Search() : '';
      }
    });
  }
  getSupplementType(value){
    if(value == 'ADDONRATE'){
      return 'Add-On Rate'
    }else if(value == 'NEWRATE'){
      return 'New Rate'
    }
    return ''
  }
  getSupplementRateType(value){
    if(value == 'PERROOMPERNIGHT'){
      return 'Per Room Per Night'
    }else if(value == 'PERPAXPERNIGHT'){
      return 'Per Pax Per Night'
    }else if(value == 'PERPAXPERSTAY'){
      return 'Per Pax Per Stay'
    }
    return ''
  }

  Edit(Id){
  this.router.navigateByUrl(`Services/Hotel/HotelManage/EditSuppliment/${this.Extranet_Hotel_Id}/${Id}`);
  }
  Reset(){
    this.SupplementSearchForm.get('extranet_room_id').setValue('');
    this.SupplementSearchForm.get('contract_name').setValue('');
    this.SupplementSearchForm.get('supplement_name').setValue('');
    this.SupplementSearchForm.get('supplement_rate_type').setValue('');
    this.SupplementSearchForm.get('supplement_type').setValue('');
  }
}