
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//  IMPORTS
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Core Angular Imports
//----------------------------------------------------------


import { Component, ElementRef, HostListener, OnInit, QueryList, ViewChild, ViewChildren } from "@angular/core";
//import { ModalDirective } from "ngx-bootstrap/modal";
import { environment } from "../../../../environments/environment";
import { ApicallService } from "../../../_services/apiCall/apicall.service";
import { HttpClient, HttpEventType } from "@angular/common/http";
//import { MessageService } from "../../../@pages/components/message/message.service";
import { NgForm, FormGroupDirective, FormBuilder, FormGroup, Validators } from "@angular/forms";
import { DatePipe } from "@angular/common";
//import { ScreensizeService } from "../../../_services/screenBreakPointSVC/screensize.service";
import { WebsocketService } from "../../../_services/websocketSVC/websocket.service";
import { Router } from "@angular/router";
import { TooltipModule  } from 'ngx-bootstrap/tooltip';
//import { ResourceService } from "../resource.service";

// 3rd Party Libraray Imports
//---------------------------------------



import { Subscription } from "rxjs";
import { PopupService } from "src/app/_services/popup/services/popup.service";
import * as moment from "moment";
//import * as moment from "moment";

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//  COMPONENT DECLARATION
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
interface FilePreview {
  file: File;
  url: string;
  progress: number;
  status: string;
}

@Component({
  selector: "app-machines",
  templateUrl: "./machines.component.html",
  styleUrls: ["./machines.component.scss"],
  host: {ngSkipHydration: 'true'},
})

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//  EXECUTION
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

export class MachinesComponent implements OnInit {
  myForm: FormGroup;
 
// Modal addMachinesModal,incrementGroupModal,ActiveConfirmModal,updateMachineModal,machineGroupWarning,checkINOut
//-----------------------------------------------------------------------------------------------------------------
//   @ViewChild("addMachinesModal", { static: true })
//  // public addMachinesModal: ModalDirective;
//   @ViewChild("incrementGroupModal", { static: true })
//   public incrementGroupModal: ModalDirective;
//   @ViewChild("ActiveConfirmModal", { static: true })
//   public ActiveConfirmModal: ModalDirective;
//   @ViewChild("updateMachineModal", { static: true })
//   public updateMachineModal: ModalDirective;
//   @ViewChild("addMachineTablet", { static: true })
//   public addMachineTablet: ModalDirective;
//   @ViewChild("machineGroupWarning", { static: true })
//   public machineGroupWarning: ModalDirective;
//   @ViewChild("checkINOut", { static: true })
//   public checkINOut: ModalDirective;

//   @ViewChild("addServiceModel", { static: true })
//   public addServiceModel: ModalDirective;

//   @ViewChild("addRepairModel", { static: true })
//   public addRepairModel: ModalDirective;
  
//   @ViewChild("Accessrestriction", { static: true })
//   public Accessrestriction: ModalDirective;// Access Restriction Modal

//   @ViewChild("successAddEquipment", { static: true })
//   public successAddEquipment: ModalDirective;// Access Restriction Modal
// Form
//-------------------------------------------------

@ViewChild("addEquipForm", { static: true }) addEquipForm: FormGroupDirective;

@ViewChild("ADLE", { static: true }) ADLE: FormGroupDirective;

@ViewChild("EditCommercial", { static: true }) EditCommercial: FormGroupDirective;

@ViewChild("RPADD", { static: true }) RPADD: FormGroupDirective;

@ViewChild("deactivateMachine", { static: true }) deactivateMachine: FormGroupDirective;
@ViewChild("deactivateRepairMachine", { static: true }) deactivateRepairMachine: FormGroupDirective;

@ViewChild("addQuickEquipForm", { static: true }) addQuickEquipForm: FormGroupDirective;
@ViewChild('imageInput', { static: false }) imageInput!: ElementRef<HTMLInputElement>;
@ViewChild("inEqipForm", { static: true }) inEqipForm: NgForm;
@ViewChild("INCEQG", { static: true }) INCEQG: FormGroupDirective;
@ViewChild('canvas', { static: false }) canvas!: ElementRef<HTMLCanvasElement>;
@ViewChild("upmForm", { static: true }) upmForm: FormGroupDirective;
@ViewChild("warningModel", { static: true })
// public warningModel: ModalDirective;

// @ViewChild("ActiveConflictModal", { static: true })
// public ActiveConflictModal: ModalDirective;

// @ViewChild("chooseQuickORCustomModal", { static: true })
// public chooseQuickORCustomModal: ModalDirective;

// @ViewChild("addQickMachinesModal", { static: true })
// public addQickMachinesModal: ModalDirective;

// @ViewChild("ActiveClassConflictModal", { static: true })
// public ActiveClassConflictModal: ModalDirective;

public mask = [/\d/, /\d/, ":", /\d/, /\d/];
@ViewChild('scrollContent', { read: ElementRef, static: false }) scrollContent: ElementRef;

@ViewChildren('scrollContent') scrollContents: QueryList<ElementRef>;


private ctx!: CanvasRenderingContext2D | null;
private image!: HTMLImageElement;
private isResizingCorner: boolean = false;
private resizeCorner: string = '';
private cornerSize = 10;
croppedImage: string | null = null;
isEditCommercialImg: boolean = false;
startX: number = 50;
startY: number = 50;
cropWidth: number = 200;
cropHeight: number = 200;
currentX = this.startX;
currentY = this.startY;
isDragging = false;
isResizing: boolean = false;
resizeStartX: number = 0;
resizeStartY: number = 0;
// ID's...
// ------------------------------------------------
catCount:number;
optionAct:number;
optionLast:number;
configAct:number;
configLast:number;
optionPercent:number;
lateThreshold:any;
  sldAssetId: number;
  sldAssetsForDeactivate:number
  sldGroupID: number;
  GroupMode=""
  variantID: number = null;
  userID: number;
  XBID: number = null;
  FCID: number;
  machinePerPage: number;
  machinePerPageListView: number =5;
  assetPerPage: number;
  loginPerPage: number = 5;
  p: number = 1;
  assetCurrentpage: number = 1;
  resvPage: number = 1;
  equtGRPPage: number;
  AssetID:any
  sldUserType = "Quick"; // User Type
  sldTag="" // tag for quick add 
  sldGroupAssetID:number
  inactiveType='cancel'
  ModelImage=""
  priceImage:any;
  CancellationList:any;
isLeftVisible = false;   // Initialize visibility state for the left button
// Arrays ...
// ---------------------------------------------------------------

subscriptions: Array<Subscription> = []; 
allequipMents = [];
listOfAllEquiments=[]
showallitems=[];
allreserveitems=[];
allAssetsList = [];
sldAssetsIDS = [];
slotDurationList = [];
states: string[] = [
  "Alabama",
  "Alaska",
  "Arizona",
  "Arkansas",
  "California",
  "Colorado",
  "Connecticut",
  "Delaware",
  "Florida",
];
slotDurationMapping: { [key: number]: number } = {
  15: 1,
  30: 2,
  45: 3,
  60: 4,
};
items = [];
modalList = [];
categoryList = [];
sldCategoryID: number = 1;
variantList = [];
brandList=[]
pageOfItems: Array<any>;
sldServiceList:any;
// imageChangedEvent:any = "";
// usercroppedImage: any = "";// cropped image 
//croppedImage: string | null = null;
originalImage: HTMLImageElement | null = null;
sldRepairList:any;
sldCheckboxSelectionRowEquipmentList:any
typeList = "Group";
sldConfigureAssetsList=[] // selecetd assest details 
sldDeleteAssetsList=[]
filterList1 = [
  {
    id: 1,
    value: "Machine",
  },
  {
    id: 2,
    value: "Group",
  },

];

usageTrackerList = [
  {
    id: 1,
    value: "Weekly",
  },
  {
    id: 2,
    value: "Monthly",
  },
  {
    id: 3,
    value: "Quarterly",
  },
  {
    id: 4,
    value: "Annual",
  },

];

categoryListForDropDown = [
  {
    id: 1,
    value: "All",
  },
  {
    id: 2,
    value: "Cardio",
  },
  {
    id: 3,
    value: "Strength",
  },
  {
    id: 4,
    value: "Functional",
  },
];

reasonList=[
  {
    id: 1,
    value: "Service",
  },
  {
    id: 2,
    value: "Repair",
  },
  {
    id: 3,
    value: "Other",
  },
  
]

timeline=[
  {
    id: 1,
    value: "Weekly",
  },
  {
    id: 2,
    value: "Monthly",
  },
  {
    id: 3,
    value: "Quarterly",
  },
  {
    id: 3,
    value: "Annual",
  },
  
]

timelineView="Week";
reasonType=""

sldAssetsList:any={}// selectd assets list
sldEquipmentListForAdd:any={}
// General ....
// -------------------------------------------------------------
  CategoryName: any; // category name
  BrandName=""; // display brand name
  AssetInvoice=""
  ModelNumber="" // display model number
  sldQRCodePic=""
  apiServer: string = environment.apiUrl; // Server API URL
  minDate = new Date();
  sldEquipID = null;
  sldEquiptIDForListView=null
  sldEQModalID = null;
  sldEQBrandID = null;
  sldEQVariantID = null;
  sldEQCatTypeID = null;
  sldEQTotal = null;
  sldEQActiveCount = null;
  sldEQDeActiveCount = null;
  total=null
  sldEQDeletedCount = null;
  sldEQBrandName = "";
  sldEQCatName = "";
  sldEQActTypeID = "";
  sldEQslotDuration: number = 30;
  sldEQslotCapacity = "";
  sldEQImage = "";
  sldEQModalName = "";
  sldEQVariantName = "";
  noDataFound = "";
  categoryType = "All";
  catactivityTypeID: number = 1;
  menuType = "All";
  activityType = "Cardio";
  addEQactivityTypeID: number = 1;
  category = "";
  variant = "";
  brand = "";
  model = "";
  quantity: number;
  slotDuration: number;
  capacity = "";
  maximum:number;
  activationStatus = "Active";
  applyType = "No";
  totalVariant = 0;
  totalAssets = 0;
  sldBrandID: number = null;
  sldVarientId: number = null;
  sldQuickAddcategoryID: number = null;
  sldModalID: number = null;
  cardheight: number; 
  cardheightreserve: number; 
  isretract: boolean = true;
  mGroupquantity = 0;
  sldVarType = "upright";
  sldVarintID: number;
  startTime=null
  endRepairTime=null
  endTime=null
  remarks=""
  serviceCost=""
  senddate=""
  sstartdate:any
  MaintenanceID=""
  MaintenanceIDForRepair=""
  variantTypeName=""// drop down selection value while configure
  variantTypeID:any// drop down selection value while configure
  scost:number;
  repairremarks=""
  rtartTime=null
  rstartdate:any

  repirendtTime=null;
  repairenddate=""
  selectedModelImage=""
  selectedTagNo=""
   selectedTagSerialNo=""
  selectedManufactureNo=""
  selectedModelNo=""
  selectedQRCode=""
  GroupStatMembersList:any;
  resourceequipmentAccess="All"
  catype:string;
// for machine view pagination reseravtion
paginatedAssets= [];
currentPage: number = 0;
itemsPerPage: number = 5;
selectedFilters: string[] = [];
//Flags 
// --------------------------------------------------------------------------
  isMachineProfile = false;
  isMachineTracker = false;
  isEQActiveAdd:boolean = true;
  isEQActiveDelete:boolean = false;
  isEQActiveEdit:boolean  = false;

  isSEActiveDelete:boolean=false;
  isSEActiveEdit:boolean=false;
  isSEActiveAdd:boolean=true;
  showForm: boolean = false; // btn for the next step
  isREActiveDelete:boolean=false;
  isREActiveEdit:boolean=false;
  isREActiveAdd:boolean=true;
  isOpenConfiguration:boolean=false;
  isOpen: boolean = false;// check QV is open or not
  reservationsList = [];
  serviceList=[]
  othersList=[]
  groupRSOList:any;
  repairList:any
  equipmentViewList=[]
  fullEquipmentList=[]
  noReservation: boolean = false;
  IsShowModelBrand: boolean = false;
  noMachineReservation:boolean=false
  selecedUIAID: number = null;
  machineViewType = "Stats";
  isLoading: boolean = false;
  reservationCount: number;
  isAddEquipLoading = false;
  isUpdateEquitLoading = false;
  isActiveCatList: boolean = false;
  isActiveDelete = false;
  isAssetActiveEdit = false;
  switchToggle = false;
  isOpenedInCrementModal = "False";
  isShowScroll :boolean = false;
  isShowPagination :boolean = false;
  isReservation:boolean=false;
  isOthers:boolean=false;
  isService:boolean=false;
  isRepair:boolean=false;
  isEditActiveForMachineMOde:boolean=false
  isShowPaginationResesrve:boolean = false;
  isShowPaginationMachine:boolean = false;

  isViewGroupEquipment:boolean = true;
  isViewListEquipment:boolean = false;
  
//-------------------------------------------
// Update Machine
  tagname = null;
  SRNumber = null;
  isActiveLeftIconAsset=null
  endDate = null;
  startDate = null;
  purchaseType = "Purchase";
  sldMachineProfileDetails = {};
  sldAssetSNO = null;
  sldEqupiments:any; //
  isUpdateEQGroup = false;
  checkInStatus = "";
  checkResnID = "";
  checkInMsg = "";
  sldAssetDetails: any = {};
  userDetails: any = {};
  isCheckError:boolean=false;
  isActiveQRcode:any;
  isActiveQRcode1:any;
  maintenanceType=""
  equipGrpid:any;
  showmenu:boolean;
  sldEquipmentId=""
  duraion = "Week";
  machineDowntimeCount:any;
  repairsCount="0"
  machineloadHrs:any;
  machineCancelsCount:any;
  machineWalksCount:any;
  machinereservation:any;
  activityRestrictionMsg=""// display error message of access restrictions
  isViewAccessRestricton:boolean=false; // view access restriction message in html 
  isShowAddEquipment:boolean=false // add equipment view
  isOpenDeactivate:boolean=false;
  isOpenUsageTracking:boolean=false;
  isEditCommercial:boolean=false;
 // isEditCommercialImg:boolean=false;
  iseditRepairList:boolean=false;
  iseditServiceList:boolean=false;
  isAddServiceList:boolean=false;
  isViewCommercialUsage:number=1;// view usage and commercial tab
  isViewResidentialUsage:boolean=true;

  isReservationType="Current";

//------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
Totalnumberclassconflicts: number;
conflictCategoryName = "";
varientName=""
conflictDates: any;
startingTime = null;
endingTime = null;
names=""
emails=""
models: any = {};
bodyClass: any;// allocates body class css property
slotvariant="" // select varaiant in drop down for configure
slotBrand=""// brand
ModelName:number=null;// model name
brandId:number=null;
listvariant=[]
serviceType ="Scheduled";
assetsTag=""
//selectedFiles: FilePreview[] = [];
selectedFiles: any[] = [];
maxSizeInMB = 5; // Maximum file size in MB
fileSizeError: string;
// Commercial details info
manufacturingNo:number;
purchaseDate:any;
price = null;
warrantyDate:any;
servicelast:any;
servicenext:any;
fileinfo=""
showDropdown = false;
searchQuery: string = '';
filteredSlots = [];
isModalOpen = false;// open model reserve spot
isModalOpenDelete=false;
groupStatCancelation:any;
groupStatDownTime:any;
groupStatLoad:any;
groupStatReservation:any;
groupStatWalkin:any;

// Commercial details info end

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ HEADER +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Constructor
//------------------------------------------------------------------------ 

  constructor(

// A. Declarations 
//--------------------------

    //private _notification: MessageService,
    private apiCall: ApicallService,
    private http: HttpClient,
    private datePipe: DatePipe,
    //private screenSize: ScreensizeService,
   //private socketSVC: WebsocketService,
    private router: Router,
   // private resourceSVC: ResourceService,
   private notificationService:PopupService,
    private el: ElementRef,
  ) 
  
  {
 
  }
  ngAfterViewInit() {
    if (!this.canvas) {
      console.error("Canvas element is not available yet.");
      return;
    }
  
    // Load an image after the canvas is ready
    this.loadImage('/assets/sample-image.jpg'); // Change to your actual image path
  }
  
  
 // @HostListener('click')
// Angular LifeCycle 
//----------------------------------------------------


  ngOnInit() {

// Local Storage 
//----------------------------------------------------
   
    this.userDetails = JSON.parse(localStorage.getItem("userDetails"));
    this.userID = this.userDetails.XID;
    this.XBID = this.userDetails.BID;
    
    this.getSlotDuration();
    const body = document.getElementsByTagName("body")[0];
    body.classList.remove("reservation");
    body.classList.remove("dashboard");
    body.classList.add("resource");
    body.classList.add("resourceclass");
    
    //const body = document.getElementsByTagName("body")[0];
    this.bodyClass = body.classList;

  //----------------------------------------------------  
    this.items = Array(150)
      .fill(0)
      .map((x, i) => ({ id: i + 1, name: `Item ${i + 1}` }));

    this.getEquipmentsByCategory("All");
    //this.setPagination();
//----------------------------------------------------

    // update reservations in stats card
    //----------------------------------------------------
    // this.socketSVC
    //   .reservationBookReceive("ReservationBookStatus-" + this.XBID)
    //   .subscribe((res: any) => {
    //     console.log(res);
    //     if (res.EquipGrpID == this.sldEquipID) {
    //       if (res.AssetID == this.selecedUIAID) {
    //         this.getReservations(this.selecedUIAID);
    //       }
    //     }
    //   });

      // +++++++++++++++++++++++++++++++++++++++++++++
      // MAchine Sockets Edit ,Delete and add trough Socket
     //----------------------------------------------------
    // this.socketSVC
    //   .getEquipmentAdd("addingequipment-" + this.XBID)
    //   .subscribe((res: any) => {
    //     console.log("hi");
    //     console.log(res);
    //     if (res.Status === "Success") {
    //       this.refreshCard("EQPG");
    //     }
    //   });

  //----------------------------------------------------
  // deleteequipment Sockets

    // this.socketSVC
    //   .getEquipmentDelete("deleteequipment-" + this.XBID)
    //   .subscribe((res: any) => {
    //     console.log("hi");
    //     console.log(res);
    //     if (res.Status === "Success") {
    //       this.refreshCard("EQPG");
    //       this.refreshCard("EQML");
    //       console.log("good evening");
    //     }
    //   });

//----------------------------------------------------
  // updateequipmentgroup Sockets

      // this.socketSVC
      // .getEquipmentUpdate("updateequipmentgroup-" + this.XBID)
      // .subscribe((res: any) => {
      //   console.log("hi");
      //   console.log(res);
      //   if (res.Status === "Success") {
      //     this.refreshCard("EQPG");
          
      //     console.log("good evening");
      //   }
      // });

      //----------------------------------------------------
      // Assets Sockets Edit ,Delete and add trough Socket

      // this.socketSVC
      // .getUpdateEquipmentDetails("UpdateEquipmentDetails-" + this.XBID)
      // .subscribe((res: any) => {
      //   console.log("hi");
      //   console.log("Update Equipment USage tracker for Repair service");
      //   console.log(res);
      //   if (res.Status === "Success") {
      //    // this.chooseStats("Weekly","UID");
      //     this.refreshCard("EQML");
      //     this.chooseStats("Weekly","UID");
      //  // this.getServiceEquipmentList()
      //  //this.getRepairEquipmentList()
      //     console.log("good evening");
      //     this.getEquipmentsByCategory("All");
      //     this.getEquipmentListView("All")
      //   }
      // });

    //----------------------------------------------------
  // UpdateAssetsDetails Sockets  

      // this.socketSVC
      // .getUpdateAssetsDetails("UpdateAssetsDetails-" + this.XBID)
      // .subscribe((res: any) => {
      //   console.log("hi");
      //   console.log(res);
      //   if (res.Status === "Success") {
          
      //     this.refreshCard("EQML");
      //     console.log("good evening");
      //   }
      // });

    //----------------------------------------------------
  // DeleteAssets Sockets  


      // this.socketSVC
      // .getDeleteAssets("DeleteAssets-" + this.XBID)
      // .subscribe((res: any) => {
      //   console.log("hi");
      //   console.log(res);
      //   if (res.Status === "Success") {
          
      //     this.refreshCard("EQML");
      //     console.log("good evening");
      //   }
      // });

// ----------------------------------------------------------------------
//-------------------------------------------------------------------------
// Service and Repair Socket 

// this.socketSVC
// .getServiceAndRepairList("deleterepairstartandendentry-" + this.XBID)
// .subscribe((res: any) => {
//   console.log("Delete Service and Repair Socket Start Here");
//   console.log(res);
//   if (res.Status === "Success") {
//   this.chooseStats("Weekly","UID");
//   this.getServiceEquipmentList()
//   this.getRepairEquipmentList()
//   console.log("Delete Service and Repair Socket End Here");
//   }
// });

//-------------------------------------------------------------------------
// Service ADD and Update Socket 

// this.socketSVC
// .getAddUpdateService("addserviceentryandupdate-" + this.XBID)
// .subscribe((res: any) => {
//   console.log("Add Service and Repair Socket Start Here");
//   console.log(res);
//   if (res.Status === "Success") {
//   this.chooseStats("Weekly","UID");
//   this.getServiceEquipmentList()
//  // this.getRepairEquipmentList()
//   console.log("Add Service and Repair Socket End Here");
//   }
// });

// End Socket ------------------------------------------------------------
//-------------------------------------------------------------------------



  //this.ReservationRepairsService("Reservations")
  //this.chooseStats("Weekly","UID");
  this.serviceScheduleCall()
  this.getEquipmentView("Group",1)
  this.chooseCategory("All")

  }

  
 //----------------------------------------------------
  // Angular Destroy 

  ngOnDestroy()
  {
    const body = document.getElementsByTagName("body")[0];
    body.classList.remove("showall");
    body.classList.remove("showallmachine");
    body.classList.remove("showallreserve");
    body.classList.remove("resourceclass");

  }

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  //
  //  METHODS
  //
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++













  openModal() {
    this.isModalOpen = true;
  }

  closeModal() {
    this.isModalOpen = false;
  }
 /**
   * @method function
   * @name showDeatails
   * @description tab of usage and commercial 
   */

  showDeatails(value){
    if(value=='commercial'){
      this.isViewCommercialUsage=1
    }
    else if(value=='Groupstats'){
      this.isViewCommercialUsage=3
    }
    else {
      this.isViewCommercialUsage=2
    }
    
    //  if(value=='Stats'){
    //   this.isViewResidentialUsage=false
    // }
    // else{
    //   this.isViewResidentialUsage=false
    
    // }
 
}
equipt = {
  Image: '../../../../assets/img/m.JPG' // Replace with your dynamic image URL
};

// showDetails(tab: string) {
//   // Reset all tabs
//   this.isViewCommercialUsage = false;
//   this.isViewMachineStats = false;
//   this.isViewGroupStats = false;

//   // Activate only the selected tab
//   if (tab === 'commercial') this.isViewCommercialUsage = true;
//   if (tab === 'machine-stats') this.isViewMachineStats = true;
//   if (tab === 'group-stats') this.isViewGroupStats = true;
// }
  

   /**
   * @method function
   * @name onSearch
   * @description search equiment 
*/
  onSearch(): void {
    console.log(this.searchQuery)
    if (this.searchQuery) {
      this.allequipMents = this.allequipMents.filter(item =>
        item.CategoryName.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
      console.log(this.searchQuery)
    } else {
    this.allequipMents = this.filteredSlots;
      console.log(this.searchQuery)
    }
  }

  toggleDropdown() {
    this.showDropdown = !this.showDropdown;
  }  
// --------------------------------------------------------------------------------------  
// Machine View Start
 /**
   * @method function
   * @name refreshCard
   * @description Get Latest Data From Server
   */
 refreshCard(value) {
  this.sldGroupID=null
 this.sldGroupAssetID=null
  this.sldEqupiments=[]
  this.sldCheckboxSelectionRowEquipmentList = [];
  this.isEQActiveEdit=false;
  this.isEQActiveDelete=false;
  this.isEQActiveAdd=true

  if (value === "EQPG") {
    this.getEquipmentsByCategory("All");
   // this.getEquipmentListView("All");
  } else if (value === "EQML") {
    this.getAssets(this.sldEquipID);
  }
  else if (value === "MCHV") {
    this.getEquipmentListView("All");
  }
}

    /**
   * @method Method
   * @name oncheckEquiptForListView
   * @param { Selected Equipment in List View }
   * @description Checkbox
   */

oncheckEquiptForListView(equipt, event) {

      console.log(equipt);
     // this.equipGrpid=equipt.EquipID;
      const checked = event.target.checked;
      // --------------------------------------------------
      if (checked) {
        this.sldCheckboxSelectionRowEquipmentList=equipt;
       this.sldGroupAssetID = equipt.AssetID;
       this.sldDeleteAssetsList.push(equipt.AssetID)
       if(equipt.isActive===0){
        this.isEQActiveEdit = true;
        this.isEQActiveAdd = false;
        this.isEQActiveDelete = true;
       }
       else{
        this.isEQActiveEdit = true;
        this.isEQActiveAdd = false;
        this.isEQActiveDelete = false;
       }
      
      } 
    
      
      // --------------------------------------------------
      else {
        this.sldCheckboxSelectionRowEquipmentList = [];
        this.sldEqupiments=[]
        this.sldDeleteAssetsList=[]
        this.isEQActiveEdit = false;
        this.isEQActiveAdd = true;
        this.isEQActiveDelete = false;
      }
      // --------------------------------------------------
     
      console.log(this.sldCheckboxSelectionRowEquipmentList);
      console.log(this.sldCheckboxSelectionRowEquipmentList.AssetID);
}
/**
   * @method Method
   * @name getEquipmentListView
   * @description toggle switch on and off in List View
*/

getEquipmentListView(value){
  this.equipmentViewList=[]
  this.fullEquipmentList=[]
  console.log("GET API equipmentViewList")
  const DATETIME = new Date();
 let TodayDateCheck=this.datePipe.transform(DATETIME,"yyyy-MM-dd");
  let currentTime =this.datePipe.transform(DATETIME, 'HH:mm')

 const url = this.apiServer + "resource/getassetsforlistview/" + this.XBID + "/" + value +
 "/" + TodayDateCheck + "/" + currentTime + "/" + this.userID ;

  this.apiCall.makeGetApiCall(url).then((res: any) => {

   console.log(res);
   if(res.length > 0){
    this.fullEquipmentList=res;
    //this.getGymRole()
    //this.equipmentViewList=res;
   
     this.selectEquipmentForListView(res[0]) 
    const currentDate = new Date();
   currentDate.setHours(currentDate.getHours() + 2);
   let currentTimePlusOne = this.datePipe.transform(currentDate, 'HH:MM');
    const currentDate1 = new Date();
    let currentDateTime =this.datePipe.transform(currentDate1, 'HH:MM')
   // const weekarry = [];
    for(let i of res){

      var setArray = {
        ActiveCount:i.ActiveCount,
        AssetID:i.AssetID,
        AssetManufactureNo:i.AssetManufactureNo,
        AssetSerailNo:i.AssetSerailNo,
        AssetStatus:i.AssetStatus,
        AssetTag:i.AssetTag,
        BID: i.BID,
        BrandID:i.BrandID,
        BrandName:i.BrandName,
        SlotDetails: [],
        CategoryImage:i.CategoryImage,
        MachineStatus:i.MachineStatus,
        CategoryName:i.CategoryName,
        DeActiveCount:i.DeActiveCount,
        DeletedCount:i.DeletedCount,
        EquipCatTypeID:i.EquipCatTypeID,
        EquipGrpID:i.EquipGrpID,
        EquipSlotDuration:i.EquipSlotDuration,
        GroupMode:i.GroupMode,
        GroupTag:i.GroupTag,
        ModelImage:i.ModelImage,
        ModelNumber:i.ModelNumber,
        QrCodeStatus:i.QrCodeStatus,
        QrCodePic:i.QrCodePic,
        QrCodeID:i.QrCodeID,
        TotalCount:i.TotalCount,
        isActive:i.isActive,
        VariantName:i.VariantName,
        VariantImage:i.VariantImage,
        PurchasePrice:i.PurchasePrice,
        PurchaseDate:i.PurchaseDate,
        isConfigured:i.isConfigured,
      };
      const weekarry = [];
    for(let j of i.SlotDetails){
      this.showallitems.push(j)
     // console.log(currentDateTime)
      //console.log(typeof(currentDateTime))
      //console.log(j.SlotStartTime)
     // console.log(typeof(j.SlotStartTime))
 
      if(j.SlotStartTime >= currentDateTime && j.SlotEndTime <= currentTimePlusOne && j.SlotEndTime!="00:00"){
      
      // console.log("STEP 1" + j.SlotStartTime)
      // console.log("STEP 2" + j.SlotEndTime)
        //console.log(currentTimePlusOne)
        weekarry.push(j)
      }
    }
    setArray.SlotDetails = weekarry;
    this.equipmentViewList.push(setArray);
   }
  // this.equipmentViewList.SlotDetails=weekarry
  // console.log(this.equipmentViewList)
   }


   else if(res.success =="false" || res.success ==false){
    this.equipmentViewList=[]
    this.showallitems=[];
   // this.Accessrestriction.show();
    this.activityRestrictionMsg=res.message;
    //this.getGymRole()
  }
   else{
   // this.getGymRole()
     this.equipmentViewList=[]
    }
   

  });
  console.log(this.equipmentViewList)
  
    
 }

 /**
   * @method Method
   * @name orderQRCode
   * @description Navigate to business QRcode
*/
orderQRCode(event){
    // this.router.navigate(["/business/qrcodes"])

 }
 /**
   * @method Method
   * @name  scrollLeft
   * @description 
*/
    scrollLeft(event,rowId) {

   const currentDate = new Date();
   currentDate.setHours(currentDate.getHours() + 2);
   let currentTimePlusOne = this.datePipe.transform(currentDate, 'HH:MM');
    const currentDate1 = new Date();
    let currentDateTime =this.datePipe.transform(currentDate1, 'HH:MM')

  console.log(rowId)
  console.log(currentDateTime)
  console.log(currentTimePlusOne)
console.log(this.fullEquipmentList)
const scrollContent = document.querySelector(`[data-row="${rowId}"]`);

if (scrollContent) {
  // Update scroll position and set button visibility
  scrollContent.scrollLeft -= 200;
  this.isLeftVisible = scrollContent.scrollLeft > 0;
}

for(let i of this.fullEquipmentList){
  for (let k of this.equipmentViewList){
  if(i.AssetID==rowId && k.AssetID==i.AssetID){
    this.isActiveLeftIconAsset=null;
    
       k.SlotDetails=[]
  for (let j of i.SlotDetails){
    if(j.SlotStartTime > currentDateTime && j.SlotEndTime < currentTimePlusOne && j.SlotEndTime!="00:00"){
      //for (let k of this.equipmentViewList){
      k.SlotDetails.push(j)
    }
  }
}
}
 }

console.log(this.equipmentViewList)
 }

 scrollRight(event,rowId) {
  this.isLeftVisible = true;
  const currentDate = new Date();
  currentDate.setHours(currentDate.getHours() + 1);
  let currentTimePlusOne = this.datePipe.transform(currentDate, 'HH:MM');
  const currentDate1 = new Date();
  currentDate1.setHours(currentDate.getHours() + 2);
   let currentDateTime =this.datePipe.transform(currentDate1, 'HH:MM')

  console.log(rowId)
  console.log(currentDateTime)
  console.log(currentTimePlusOne)
console.log(this.fullEquipmentList)


for(let i of this.fullEquipmentList){
  for (let k of this.equipmentViewList){
  if(i.AssetID==rowId && k.AssetID==i.AssetID){
    this.isActiveLeftIconAsset=rowId;
       k.SlotDetails=[]
  for (let j of i.SlotDetails){
    if(j.SlotStartTime > currentTimePlusOne && j.SlotEndTime < currentDateTime && j.SlotEndTime!="00:00"){
      //for (let k of this.equipmentViewList){
      k.SlotDetails.push(j)
    }
  }
}
}
 }
console.log(this.equipmentViewList)
 }

/**
   * @method Method
   * @name orderQRCode
   * @description Navigate to business QRcode
*/
 updatePaginatedAssets() {
  const start = this.currentPage * this.itemsPerPage;
  const end = start + this.itemsPerPage;
  this.paginatedAssets = this.showallitems.slice(start, end);
  console.log(this.paginatedAssets)
}

// scrollLeft() {
//   if (this.currentPage > 0) {
//     this.currentPage--;
//     this.updatePaginatedAssets();
//   }
// }

// scrollRight() {
//   if ((this.currentPage + 1) * this.itemsPerPage < this.showallitems.length) {
//     this.currentPage++;
//     this.updatePaginatedAssets();
//   }
// }
// --------------------------------------------------------------------------------------  
// Machine View End

// --------------------------------------------------------------------------------------  
// Edit Commercial details Start
// --------------------------------------------------------------------------------------


/**
   * @method Method
   * @name orderQRCode
   * @description Navigate to business QRcode
*/
editCommerecialDetails(event){
  console.log(event)
  this.selectedFiles=[]
 this.isEditCommercial=true;
 console.log(this.sldAssetsList)
 const date = new Date(this.sldAssetsList.LastServiceDate);
 const date1 = new Date(this.sldAssetsList.NextServiceDate);
 const date2 = new Date(this.sldAssetsList.WarrantyDate);
 this.servicelast=this.formatDateForInput(date);
 this.servicenext=this.formatDateForInput(date1);
this.warrantyDate=this.formatDateForInput(date2);
this.AssetInvoice =this.sldAssetsList.AssetInvoice

 console.log(this.selectedFiles)
}

editCommerecialImgDetails(event){
  console.log(event);
  this.isEditCommercialImg = true;
  
}

/**
   * @method function
   * @name removeExistingInvoice
   * @description  Remove existing invoice link
*/

removeExistingInvoice() {
  this.AssetInvoice = null;
}
 // Function to convert ISO date to yyyy-MM-dd
 private formatDateForInput(date: Date): string {
  const year = date.getFullYear();
  const month = ('0' + (date.getMonth() + 1)).slice(-2); // Month with leading zero
  const day = ('0' + date.getDate()).slice(-2); // Day with leading zero
  return `${year}-${month}-${day}`;
}

// Function to convert yyyy-MM-dd back to mm/dd/yyyy format
// public getFormattedDateForDisplay(): string {
//   const [year, month, day] = this.servicenext.split('-');
//   return `${month}/${day}/${year}`;
// }


/**
   * @method function
   * @name closeEditCommercial
   * @description It is used to close the Edit 
*/
closeEditCommercial(event){
 console.log("Close Edit Commercial")
  this.isEditCommercial=false;
  this.selectedFiles=[]
  this.servicenext=""
  this.warrantyDate=""
  this.purchaseDate=""
  this.manufacturingNo=null
  //this.EditCommercial.resetForm();
  this.getAssets(this.sldEquipID)
  //this.getEquipmentListView("All");
  //this.getEquipmentsByCategory("All");
}
/**
   * @method function
   * @name onEditCommercialSubmit
   * @description 
*/
onEditCommercialSubmit(form){
  if (form.valid) {
    console.log('Form submitted:', this.models);
    this.updateAssestCommercial()

  } else {
    console.log('Form is invalid');
  }
}
/**
   * @method method
   * @name updateAssestCommercial
   * @description 
   * @HttpMethod Post

*/
updateAssestCommercial(){
  let assetsInvoice
  let Document1=null
  let Document2=null
  let Document3=null
  let Document4=null
 console.log(this.selectedFiles[0]); 
//  if(this.selectedFiles[0]==undefined){
//   assetsInvoice=null
//  }
//  else{
  //assetsInvoice=this.selectedFiles[0].url
 
  
  if(this.selectedFiles.length==1){
  
    Document1=this.selectedFiles[0].url;
  }
  else if(this.selectedFiles.length==2){
    Document1=this.selectedFiles[0].url;
    Document2=this.selectedFiles[1].url;
  }
  else if(this.selectedFiles.length==3){
    Document1=this.selectedFiles[0].url;
    Document2=this.selectedFiles[1].url;
    Document3=this.selectedFiles[2].url;
  }
  else if(this.selectedFiles.length==4){
    Document1=this.selectedFiles[0].url;
    Document2=this.selectedFiles[1].url;
    Document3=this.selectedFiles[2].url;
    Document4=this.selectedFiles[3].url;
  }
   
 //}
  //return false;
  const url = this.apiServer + "resource/updatecommercialmachinedetails";
  //for (let i of this.selectedFiles){
    var equipData = {
      AssetID: this.selecedUIAID,
      BID: this.XBID,
      AssetManufactureNo: this.manufacturingNo,
      PurchaseDate: this.purchaseDate,
      PurchasePrice: this.price,
      WarrantyDate: this.warrantyDate,
      LastServiceDate : this.servicelast,
     
      NextServiceDate: this.servicenext,
      RentalPrice: null,
      RentalStartDate: null,

      RentalEndDate: null,
      LeasePrice: null,
      LeaseStartDate: null,
      LeaseEndDate: null,
      PssnTypeID: 1,
      //AssetInvoice: assetsInvoice,
      AssetInvoice1:Document1,
      AssetInvoice2:Document2,
      AssetInvoice3:Document3,
      AssetInvoice4:Document4
   
    };
  //}
    
  
  
  // -----------------------------------------------
  console.log(equipData);
  this.apiCall.makePostApiCall(url, equipData).then((res: any) => {
    console.log(res);
// -----------------------------------------------
    if (res.status === "Success") {
      // this._notification.create("success", "Successfully Updated", {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
      this.notificationService.showNotification("Success","Updated successfully.");
      //this.myForm.reset(); // Reset the form values after submission
      this.isEditCommercial=false;
     //this.EditCommercial.reset();
     //this.EditCommercial.resetForm();
      this.getEquipmentsByCategory("All");
 
    
    } 
 // -----------------------------------------------   
    else {
      this.isAddEquipLoading = false;
      // this._notification.create("danger", res.error.message, {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
      this.notificationService.showNotification("Error","Something Went Wrong");
    }
  });
}
// --------------------------------------------------------------------------------------  
// Edit Commercial details End
// --------------------------------------------------------------------------------------


// --------------------------------------------------------------------------------------  
// Deactivation Machine start
// --------------------------------------------------------------------------------------

// onFileSelectedForCommercial(event: any) {
//   const files = event.target.files;
//   this.selectedFiles=[]
//   console.log(files)
//   for (let i = 0; i < files.length; i++) {
//     const file = files[i];
//     const reader = new FileReader();
//     reader.onload = (e: any) => {
//       this.selectedFiles.push({
//         file,
//         url: e.target.result,
//         progress: 0,
//         status: 'Pending'
//       });
//     };
//     reader.readAsDataURL(file);
//   }
// //}
// console.log( this.selectedFiles)
  
// } 
/**
   * @method function
   * @name onFileSelected
   * @description  It ensures that selected files are within the allowed size limit and stores their details for further processing
  

*/

onFileSelected(event: any) {
  const files = event.target.files;

  if (files.length > 4) {
    this.fileSizeError = `You can upload a maximum of 4 files at a time.`;
    this.notificationService.showNotification("Error","You can upload a maximum of 4 files at a time.");
    return;
  }

  this.selectedFiles = [];
console.log(files.length);

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    const fileSizeInMB = file.size / (1024 * 1024); // Convert size to MB

    if (fileSizeInMB > this.maxSizeInMB) {
      this.fileSizeError = `File size exceeds 100 MB. Please upload a smaller file.`;
      this.notificationService.showNotification("Error","File size exceeds 100 MB. Please upload a smaller file.");
    } else {
      this.fileSizeError = '';
      const reader = new FileReader();
      reader.onload = (e: any) => {
        this.selectedFiles.push({
          file,
          url: e.target.result,
          progress: 0,
          status: 'Pending'
        });
      };
      reader.readAsDataURL(file);
    }
  }

  console.log(this.selectedFiles);
}


selectedImage: string | ArrayBuffer | null = null;

/**
   * @method function
   * @name onImageSelected
   * @description it used to select the Image for edit or crop
*/
 triggerFileUpload() {
  this.imageInput.nativeElement.click();
}

// Handle file input change
onImageSelected(event: any) {
  const file = event.target.files[0];

  if (file) {
    const reader = new FileReader();

    reader.onload = (e: ProgressEvent) => {
      const fileReader = e.target as FileReader;
      if (fileReader && fileReader.result) {
        const result = fileReader.result as string;
        this.resetCanvas(); // Reset canvas and crop box before loading new image
        this.loadImage(result);
      }
    };

    reader.readAsDataURL(file);

    // Reset input value to allow the same file to be uploaded again
    event.target.value = '';

    this.isEditCommercialImg = true; // Open modal
  }
}




// Load Image into Canvas
loadImage(imageSrc: string) {
  this.image = new Image();
  this.image.src = imageSrc;

  this.image.onload = () => {
    setTimeout(() => {
      if (!this.canvas) {
        console.error("Canvas not found!");
        return;
      }

      const canvas = this.canvas.nativeElement;
      this.ctx = canvas.getContext('2d');

      if (this.ctx) {
        // Resize image to fit canvas
        this.ctx.clearRect(0, 0, canvas.width, canvas.height);
        this.ctx.drawImage(this.image, 0, 0, canvas.width, canvas.height);
        this.drawCropBox();
      }
    }, 100);
  };
}


drawCropBox() {
  if (!this.ctx) return;

  this.ctx.strokeStyle = 'Black'; // Change to 'black' if needed
  this.ctx.lineWidth = 2;
  this.ctx.setLineDash([5, 3]); // Dashed line
  this.ctx.strokeRect(this.currentX, this.currentY, this.cropWidth, this.cropHeight);

  // Draw corner handles
  this.ctx.fillStyle = 'Black';
  this.ctx.setLineDash([]);

  // Top-left corner
  this.ctx.fillRect(this.currentX - this.cornerSize / 2, this.currentY - this.cornerSize / 2, this.cornerSize, this.cornerSize);

  // Top-right corner
  this.ctx.fillRect(this.currentX + this.cropWidth - this.cornerSize / 2, this.currentY - this.cornerSize / 2, this.cornerSize, this.cornerSize);

  // Bottom-left corner
  this.ctx.fillRect(this.currentX - this.cornerSize / 2, this.currentY + this.cropHeight - this.cornerSize / 2, this.cornerSize, this.cornerSize);

  // Bottom-right corner
  this.ctx.fillRect(this.currentX + this.cropWidth - this.cornerSize / 2, this.currentY + this.cropHeight - this.cornerSize / 2, this.cornerSize, this.cornerSize);
}

onMouseDown(event: MouseEvent) {
  const x = event.offsetX;
  const y = event.offsetY;

  // Top-left corner
  if (this.isInCorner(x, y, this.currentX, this.currentY)) {
    this.isResizingCorner = true;
    this.resizeCorner = 'top-left';
  }
  // Top-right corner
  else if (this.isInCorner(x, y, this.currentX + this.cropWidth, this.currentY)) {
    this.isResizingCorner = true;
    this.resizeCorner = 'top-right';
  }
  // Bottom-left corner
  else if (this.isInCorner(x, y, this.currentX, this.currentY + this.cropHeight)) {
    this.isResizingCorner = true;
    this.resizeCorner = 'bottom-left';
  }
  // Bottom-right corner
  else if (this.isInCorner(x, y, this.currentX + this.cropWidth, this.currentY + this.cropHeight)) {
    this.isResizingCorner = true;
    this.resizeCorner = 'bottom-right';
  } else {
    // Drag the crop box
    this.isDragging = true;
    this.startX = x - this.currentX;
    this.startY = y - this.currentY;
  }
}

isInCorner(x: number, y: number, cornerX: number, cornerY: number) {
  return (
    x >= cornerX - this.cornerSize / 2 &&
    x <= cornerX + this.cornerSize / 2 &&
    y >= cornerY - this.cornerSize / 2 &&
    y <= cornerY + this.cornerSize / 2
  );
}

onMouseMove(event: MouseEvent) {
  if (!this.ctx) return;

  const x = event.offsetX;
  const y = event.offsetY;

  if (this.isResizingCorner) {
    switch (this.resizeCorner) {
      case 'top-left':
        this.cropWidth += this.currentX - x;
        this.cropHeight += this.currentY - y;
        this.currentX = x;
        this.currentY = y;
        break;
      case 'top-right':
        this.cropWidth = x - this.currentX;
        this.cropHeight += this.currentY - y;
        this.currentY = y;
        break;
      case 'bottom-left':
        this.cropWidth += this.currentX - x;
        this.cropHeight = y - this.currentY;
        this.currentX = x;
        break;
      case 'bottom-right':
        this.cropWidth = x - this.currentX;
        this.cropHeight = y - this.currentY;
        break;
    }
  } else if (this.isDragging) {
    this.currentX = x - this.startX;
    this.currentY = y - this.startY;
  }

  // Clear and redraw
  this.ctx.clearRect(0, 0, this.canvas.nativeElement.width, this.canvas.nativeElement.height);
  this.ctx.drawImage(this.image, 0, 0, this.canvas.nativeElement.width, this.canvas.nativeElement.height);
  this.drawCropBox();
}
onMouseUp() {
  this.isDragging = false;
  this.isResizingCorner = false;

  this.cropImage();
}

// Check if mouse is near the edges of the crop box
isNearEdge(x: number, y: number): boolean {
  const edgeThreshold = 10;
  return (
    Math.abs(x - (this.currentX + this.cropWidth)) < edgeThreshold &&
    Math.abs(y - (this.currentY + this.cropHeight)) < edgeThreshold
  );
}

// Crop the selected area
cropImage() {
  if (!this.ctx) return;

  const canvas = document.createElement('canvas');
  canvas.width = this.cropWidth;
  canvas.height = this.cropHeight;
  const ctx = canvas.getContext('2d');

  if (ctx) {
    ctx.drawImage(
      this.canvas.nativeElement,
      this.currentX,
      this.currentY,
      this.cropWidth,
      this.cropHeight,
      0,
      0,
      this.cropWidth,
      this.cropHeight
    );
    this.croppedImage = canvas.toDataURL('image/png');
  }
}
resetCanvas() {
  this.currentX = 50;
  this.currentY = 50;
  this.cropWidth = 100;
  this.cropHeight = 100;
  this.croppedImage = null;

  if (this.ctx) {
    this.ctx.clearRect(0, 0, this.canvas.nativeElement.width, this.canvas.nativeElement.height);
  }

  this.image = new Image(); // Create a new image object
}

closeEditCommercialImg(event: Event) {
  event.stopPropagation();
  this.isEditCommercialImg = false;
}


/**
   * @method function
   * @name onCancel
   * @description it used to cancel the selectedfiles
*/
onCancel(index: number) {
  this.selectedFiles.splice(index, 1);
}
/**
   * @method Method
   * @name formatDate
   * @description  Months are zero-indexed
*/
formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0'); 
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
}
/**
   * @method Method
   * @name chooseDeactivateReason
   * @description Select Service Type selection box
*/
chooseDeactivateReason(events,value){
 console.log(events)
 this.reasonType=events;

 if(this.reasonType=='Repair'){
  const DATETIME = new Date();
    console.log(DATETIME);
    this.rtartTime = this.datePipe.transform(DATETIME, "HH:mm:ss");
    this.rstartdate = this.formatDate(DATETIME);
   //this.rstartdate = this.datePipe.transform(DATETIME, "MM/dd/yyyy");
   //this.sstartdate=date;

}
else{
  this.rtartTime=""
  this.rstartdate=""
}
}

/**
   * @method Method
   * @name selectServiceType
   * @description Select Service Type Radio
*/
selectServiceType(value){
  console.log(value)
this.serviceType=value;
if(this.serviceType=='Now'){
  const DATETIME = new Date();
    console.log(DATETIME);
    this.startTime = this.datePipe.transform(DATETIME, "HH:mm:ss");
   this.sstartdate = this.formatDate(DATETIME);
   //this.sstartdate=date;

}
else{
  this.startTime = "";
  this.sstartdate = "";
}
}





// --------------------------------------------------------------------------------------  
// Deactivation Machine ENd
// --------------------------------------------------------------------------------------


// --------------------------------------------------------------------------------------
// Configuration Start Here
// --------------------------------------------------------------------------------------
/**
   * @method Method
   * @name  openConfiguration
   * @description  check QV is open or not
*/
  openConfiguration(event){
    console.log(this.sldConfigureAssetsList);
    console.log(this.sldAssetsList);
    if(this.sldConfigureAssetsList.length==1){
      this.slotDuration=this.sldAssetsList.SlotDuration;
      this.capacity=this.sldAssetsList.SlotCapacity
      this.configAct=this.sldAssetsList.isResvnAllowed;
      this.configLast=this.sldAssetsList.isLateCheckinAllowed;
      this.lateThreshold=this.sldAssetsList.ToleranceType
    }
    this.selectedFiles=[]
    this.bodyClass.add("slideprofile");
    this.isOpen = true;
     this.isOpenConfiguration=true
     this.getVariantByCategoryID()
     //this.getBrandByCategoryID()
  }

/**
   * @method Method
   * @name chooseVariant
   * @description Get All Varients By Category ID
*/

  chooseVariant(event,val){

    console.log(val)
    console.log(event)
  this.variantTypeID=event;
  this.brandList=[]
   this.getBrandByCategoryID(this.variantTypeID)
  //this.getBrandByModel(this.brandId)
   //this.getVariantByCategoryID()
  //this.getVarientGenericEquipment("All")
  }
  // chooseVariant(selectedVariantID: number, event: any) {
  //   // Fetch or filter the models based on the selected variant ID
  //   this.modalList = this.getModelsByVariant(selectedVariantID);
  //   console.log(this.modalList); // Check if models are fetched correctly
  //   this.getBrandByCategoryID()
  // }
  
  // // Example function to fetch models
  // getModelsByVariant(variantID: number) {
  //   return this.models.filter(model => model.variantID === variantID);
  // }

  /**
   * @method function
   * @name chooseBrand
   * @description select a brand based on the event value and perform actions accordingly.
*/

  chooseBrand(event,val){

    console.log(val)
    console.log(event)
   this.variantTypeName=event;
  // this.getBrandByCategoryID(this.variantTypeID)
   //let brandId:number;
   if(this.variantTypeName!='Other'){
    if(this.variantTypeName=='Generic'){
      this.brandId=1
    }
    else if(this.variantTypeName=='Techno Gym'){
      this.brandId=2
    }
    else if(this.variantTypeName=='Matrix Gym'){
      this.brandId=3
    }
    else {
      this.brandId=4
    }
    
    this.getBrandByModel(this.brandId)
   }
  
  }

 /**
   * @method Method
   * @name getBrandByCategoryID
   * @description Get All brand By Category ID
   */

 getBrandByModel(value) {
  this.modalList=[]
   const url = this.apiServer + "resource/getmodel/"+ this.variantTypeID +"/" + this.sldEQCatTypeID+ "/" + value;
   this.apiCall.makeGetApiCall(url).then((res: any) => {
   console.log(res);
   if (res.length > 0) {
    
      this.modalList=res;
    

  }
});

}




   /**
   * @method Method
   * @name getBrandByCategoryID
   * @description Get All brand By Category ID
   */

  getBrandByCategoryID(val) {
    this.brandList=[]
     const url = this.apiServer + "resource/getallbrands/" + val;
     this.apiCall.makeGetApiCall(url).then((res: any) => {
     console.log(res);
     if (res.length > 0) {
     // for(let i of this.variantList){
        if( this.brandId===1){
          console.log(this.variantList[0])
          this.brandList=res;
          console.log( this.brandList)
          }
          else{
            this.brandList=[]
           this.brandList=res;
         }
     // }
      // if(this.variantTypeID==46){
        
      // }
      // else{
      //   this.brandList=res;
      // }
    
    }
  });

  }


 /**
   * @method Method
   * @name getVariantByCategoryID
   * @description Get All Varients By Category ID
   */
 getVariantByCategoryID() {
  this.modalList = [];
  // -----------------------------------------------------------
  // GET API Call

  const url = this.apiServer + "resource/getvariant/" + this.sldEQCatTypeID;
  this.apiCall.makeGetApiCall(url).then((res: any) => {
    console.log(res);
    if (res.length > 0) {
      this.variantList = res;
      // this.dgFilters=this.dgFilters.reverse();
      let variantListAll=res[res.length-1];
     this.variantList.unshift(variantListAll)
     this.variantList.pop()

    // this.getBrandByCategoryID()
      this.totalVariant = res.length;
     
    } 
 // -----------------------------------------------------------   
    else {
      this.totalVariant = 0;
    }
  });
}
// Close toggle
//---------------------------

/**
   * @func   closetoggle
   * @desc   toggle close flags setting false.
*/

closetoggle(){
  this.bodyClass.remove("slideprofile");
     console.log(this.isOpen) 
     this.assetsTag=""

     this.isOpenConfiguration=false
     this.isOpen = false;
     console.log(this.isOpen) 

}
 /**
   * @method function
   * @name onServiceAddSubmit
   * @description  handles the submission of a form related to adding service equipment. 
   */
onServiceAddSubmit(form){
  if (form.valid) {
    console.log('Form submitted:', this.models);
    this.addServiceEquipment()

  } else {
    console.log('Form is invalid');
  }
}
  /**
   * @method function
   * @name onOthersAddSubmit
   * @description  handles the submission of a form for adding "Other" equipment. 
   */

onOthersAddSubmit(form){
  if (form.valid) {
    console.log('Form submitted:', this.models);
    this.addOthersEquipment()

  } else {
    console.log('Form is invalid');
  }
}

// Configuration End Here
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
  onSubmit(form) {
    if (form.valid) {
      console.log('Form submitted:', this.models);
      this.addEquipment()

    } else {
      console.log('Form is invalid');
    }
  }

// Configuration End Here
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
onConfigureSubmit(form) {
  if (form.valid) {
    console.log('Form submitted:', this.models);
    this.configureAssets()

  } else {
    console.log('Form is invalid');
  }
}
 /**
   * @method function
   * @name onDeactivationOtherSubmit
   * @description  handles the submission process for deactivating an "Other" category item.
   */
onDeactivationOtherSubmit(form) {
  if (form.valid) {
    console.log('Form submitted:', this.models);
    this.otherDeactivation()

  } else {
    console.log('Form is invalid');
  }
}

/**
   * @func   configureAssets
   * @desc   POST API 
*/
configureAssets(){
  if(this.IsShowModelBrand==false){
   this.brandId=1
  }
   if(this.brandId===4){
     var url = this.apiServer + "resource/configureassets/"+ this.sldEquipID+ "/"+ this.sldEQCatTypeID+ "/" + this.variantTypeID + "/" + 
     this.brandId + "/" + this.ModelName + "/" + this.assetsTag;
   }
   else{
     var url = this.apiServer + "resource/configureassets/"+ this.sldEquipID+ "/"+ this.sldEQCatTypeID+ "/" + this.variantTypeID + "/" + 
     this.brandId + "/" + this.sldModalID + "/" + this.assetsTag;
   }
   console.log(typeof(this.sldModalID));
   
   let assetsID=[]
 
   if(this.sldConfigureAssetsList.length >0){
     for(let assets of this.sldConfigureAssetsList){
      assetsID.push(assets.AssetID)
     }
     }


   let data={
     AssetsID:assetsID,
     EquipSlotCapacity:this.capacity,
     MaxSlotsPerResvn:this.maximum,
     EquipSlotDuration:this.slotDuration,
     LateCheckinThresholdLimit:this.lateThreshold?this.lateThreshold:null,
     isLateCheckinAllowed:this.configLast==1?1:0,
     isResvnAllowed:this.configAct==1?1:0,
     SessnSlotDurnTypeID :this.slotDuration==15?1:2,
   }
 
   
  
   this.apiCall.makePostApiCall(url,data).then((res: any) => {
     console.log(res);
 // -----------------------------------------------
     if (res.Status === "Success") {
       // this._notification.remove()
       // this._notification.create("success", "Successfully Added", {
       //   Position: "top-right",
       //   Style: "flip bar",
       //   Duration: 5000,
       // });
       this.notificationService.showNotification("Success","Successfully Added");
      // this.myForm.reset(); // Reset the form values after submission
       this.slotBrand=""
       this.ModelName=null
       this.sldModalID=null
       this.slotvariant=""
       this.sldConfigureAssetsList=[]
       this.clearValue();
       this.closetoggle()
       this.categoryType ="All"
       this.getEquipmentsByCategory("All");
 
     }
 });
 }
  /**
   * @method Method
   * @name switchTGListView
   * @description toggle switch on and off in List View
   */
  switchTGListView(assets,event)  {

    console.log(event);
    console.log(assets);
    this.sldEquipID= ""
    this.sldAssetId =null
    this.sldEQCatTypeID=""
    this.sldEQslotDuration=null
    this.selecedUIAID = null;
    this.sldAssetsForDeactivate=assets.AssetID
    this.sldEQslotDuration=assets.EquipSlotDuration;
    this.sldEquipID= assets.EquipGrpID
    this.sldAssetId =assets.AssetID
    this.selecedUIAID = assets.AssetID;
    //this.selecedUIAID
    this.sldEQCatTypeID=assets.EquipCatTypeID
    this.sldAssetId = assets.AssetID;
    this.switchToggle = event.target.checked;
    if (this.switchToggle === true) {
      // this.updateAssetStatus("Active");
     
      this.bodyClass.remove("slideprofile");
       this.isOpenDeactivate=false
     } else {
       this.bodyClass.add("slideprofile");
       this.isOpenDeactivate=true
       
      
}
    // if (this.switchToggle === true) {
    //   this.isEditActiveForMachineMOde=false
    //   this.updateAssetStatus("Active");
    // } 
    // else {
    //   this.isEditActiveForMachineMOde=true
    //   this.isUpdateEquitLoading = false;
    //   this.openActiveModal();
      
    // }
  
  }
  /**
   * @method Method
   * @name switchTG
   * @description toggle switch on and off
   */

  switchTG(assets, event) {

    console.log(event);
    console.log(assets);
    this.sldAssetId = assets.AssetID;
    this.sldAssetsForDeactivate=assets.AssetID
    this.switchToggle = event.target.checked;

        console.log(this.switchToggle)
        if (this.switchToggle === true) {
         // this.updateAssetStatus("Active");
        
         this.bodyClass.remove("slideprofile");
          this.isOpenDeactivate=false
        } else {
          this.bodyClass.add("slideprofile");
          this.isOpenDeactivate=true
          this.reasonType="";
          this.sstartdate=""
         this.startTime=""
         this.senddate=""
         this.endTime=""
         this.remarks=""
         this.selectedFiles=[]
         this.serviceCost=""
         this.rstartdate=""
         this.rtartTime=""
         this.repairremarks=""
   }
 
 
  }
/**
   * @method Method
   * @name closeDecativate
   * @description It is used to close the profile
   */
  closeDecativate(){
    this.bodyClass.remove("slideprofile");
    this.isOpenDeactivate=false
    this.isOpenUsageTracking=false
  }

// --------------------------------------------------------------------------------------
// Usage Tracking Start Here
//
//  --------------------------------------------------------------------------------------
 
/**
   * @method function
   * @name openUsageTracking()
   * @description appears to handle the UI state for opening a usage tracking section
   */


openUsageTracking(value,count){
  console.log(value);
  this.catCount=count
  this.bodyClass.add("slideprofile");
  this.isOpenUsageTracking=true
  this.catype=value
  this.ReservationRepairsService("event",value)
}
 
/**
   * @method function
   * @name openUsageTracking()
   * @description appears to handle the UI state for close a usage tracking section
   */

 closeUsageTracking(){
    this.bodyClass.remove("slideprofile");
   
    
    this.isOpenUsageTracking=false
  }
/**
   * ~ ReservationRepairsService
   * * ReservationRepairsService check 
   * # Method
   */

ReservationRepairsService(event,val){
  console.log(event);
  console.log(val)
  this.timelineView=this.duraion
  this.isAddServiceList=false
  this.iseditRepairList=false;
  this.iseditServiceList=false
  this.MaintenanceID=null
  if(this.catype=='msReservation'||val=='msReservation'){
    this.getReservations(this.selecedUIAID); 
    this.isReservation=true;
    this.isRepair=false;
    this.isOthers=false
    this.isService=false;
  }
  else if(val=='gsReservation'||val=='gsCancel'||val=='gsWalk'){
    this.getGroupStatReservations(this.sldEquipID ); 
  }
  else if(val=='msCancel'||val=='msWalk'){
    this.getCancellation(this.selecedUIAID);
  }
   else if(val==="Repairs"||val==="msDowntime"||val=="gsDowntime"){
    this.isRepair=true;
    this.isReservation=false;
    this.isReservationType="Current"
    this.isService=false;
    this.isOthers=false
    let value=0
    if(this.catype!="gsDowntime"){
    this.getRepairEquipmentList(value);
    }
    else if(this.catype=="gsDowntime"){
      this.getRSOGroupStat(this.sldEquipID,"Repair",value);
    }
   }

   else if(val==="Service"){
    this.isService=true;
    this.isRepair=false;
    this.isReservation=false;
    this.isReservationType="Current"
    this.isOthers=false
    let value=0
    if(this.catype!="gsDowntime"){
    this.getServiceEquipmentList(value);
    }
    else if(this.catype=="gsDowntime"){
      this.getRSOGroupStat(this.sldEquipID,"Service",value);
    }
   }

   else if(val==="Others"){
    this.isService=false;
    this.isRepair=false;
    this.isReservation=false;
    this.isReservationType="Current"
    this.isOthers=true
    let value=0
    if(this.catype!="gsDowntime"){
    this.getOthersEquipmentList(value);
    }
    else if(this.catype=="gsDowntime"){
      this.getRSOGroupStat(this.sldEquipID,"Others",value);
    }
   }

  }


/**
   * ~ RepairsService
   * * check current or removed status in repair usage tracker
   * # Method
*/

RepairsService(event,val){
  this.isReservationType=val;
  if(this.isRepair==true){
    this.serviceList=[]
    if(val=="Current"){
      this.isReservationType="Current"
      let value=0
     if(this.catype=='msDowntime'){
      this.getRepairEquipmentList(value)
     }
     else if(this.catype=='gsDowntime'){
      this.getRSOGroupStat(this.sldEquipID,"Repair",value)
    }
    }
    else{
      let value=1
       this.isReservationType="Removed"
       if(this.catype=='msDowntime'){
        this.getRepairEquipmentList(value)
       }
       else if(this.catype=='gsDowntime'){
        this.getRSOGroupStat(this.sldEquipID,"Repair",value)
      }
    }
  }
  else if(this.isService==true){
    this.serviceList=[]
    if(val=="Current"){
      this.isReservationType="Current"
      let value=0
      if(this.catype=='msDowntime'){
        this.getServiceEquipmentList(value)
       }
       else if(this.catype=='gsDowntime'){
        this.getRSOGroupStat(this.sldEquipID,"Service",value)
      }
      
    }
    else{
      let value=1
       this.isReservationType="Removed"
       if(this.catype=='msDowntime'){
        this.getServiceEquipmentList(value)
       }
       else if(this.catype=='gsDowntime'){
        this.getRSOGroupStat(this.sldEquipID,"Service",value)
      }
    }
  }

  else if(this.isOthers==true){
    this.serviceList=[]
    if(val=="Current"){
      let value=0
      this.isReservationType="Current"
      if(this.catype=='msDowntime'){
        this.getOthersEquipmentList(value)
       }
       else if(this.catype=='gsDowntime'){
        this.getRSOGroupStat(this.sldEquipID,"Others",value)
      }
    }
    else{
      let value=1
        this.isReservationType="Removed"
        if(this.catype=='msDowntime'){
          this.getOthersEquipmentList(value)
         }
         else if(this.catype=='gsDowntime'){
          this.getRSOGroupStat(this.sldEquipID,"Others",value)
        }
    }
  }

}

/**
   * @method Method
   * @name getTimeLineView()
   * @description 
   */
  getTimeLineView(event,value){
    console.log(event);
    this.timelineView=event;
    if(this.isReservation==true){
      this.getReservations(this.selecedUIAID); 
    }
    else if(this.isRepair==true){
      let value=0
      this.isReservationType="Current";
      this.getRepairEquipmentList(value)
    }
    else if(this.isService==true){
      this.isReservationType="Current";
      let value=0
      this.getServiceEquipmentList(value)
    }
    else{
      
        let value=0
        this.getOthersEquipmentList(value)
    
      
    }
  }

  /**
   * ~ getOthersEquipmentList
   * * GET API Others List
   * # Method GET API
   */ 
  getOthersEquipmentList(value){
    this.othersList=[]
    console.log("GET API Others")
    let maintainceType="Others"
   const url = this.apiServer + "resource/getassetmaintenanceInfo/" + this.XBID + "/" + this.selecedUIAID + "/" + maintainceType+ "/" + this.timelineView+ "/" +value ;
 
    this.apiCall.makeGetApiCall(url).then((res: any) => {
 
     console.log(res);
    if(res.length > 0){
       this.othersList=res;
     }
    else{
      this.othersList=[]
     }
     
     console.log(this.othersList)
    });
    console.log(this.othersList)

  }


  getRSOGroupStat(AID,maintainceType,value){
    this.groupRSOList=[];
    const url = this.apiServer + "resource/getassetmaintenanceinfoforequipgrp/" + this.XBID + "/" + AID + "/" + maintainceType+ "/" + this.timelineView+ "/" +value ;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
 
      console.log(res);
      if(res.length > 0){
        this.groupRSOList=res;
      }
      else{
        this.groupRSOList=[]
      }
     console.log(this.groupRSOList);  
     
     });
  }
  /**
   * ~ getRepairEquipmentList
   * * GET API Repair List
   * # Method GET API
   */


  getRepairEquipmentList(value){
    this.repairList=[]
    console.log("GET API Repair")
    let maintainceType="Repair"
   const url = this.apiServer + "resource/getassetmaintenanceInfo/" + this.XBID + "/" + this.selecedUIAID + "/" + maintainceType+ "/" + this.timelineView+ "/" +value ;
 
    this.apiCall.makeGetApiCall(url).then((res: any) => {
 
     console.log(res);
    if(res.length > 0){
       this.repairList=res;
     }
    else{
      this.repairList=[]
     }
     
     console.log(this.repairList)
    });
    console.log(this.repairList)
   }

  
 /**
   * ~ getServiceEquipmentList
   * * GET API Service List
   * # Method GET API
   */

  getServiceEquipmentList(value){
    this.serviceList=[]
   console.log("GET API Service")
   let maintainceType="Service"
  const url = this.apiServer + "resource/getassetmaintenanceInfo/" + this.XBID + "/" + this.selecedUIAID + "/" + maintainceType + "/" + this.timelineView+ "/" + value ;

   this.apiCall.makeGetApiCall(url).then((res: any) => {

    console.log(res);
    if(res.length > 0){
      this.serviceList=res;
    }
    else{
      this.serviceList=[]
     }
    

   });
   console.log(this.serviceList)
  }

  /**
   * ~ oncheckService
   * * checkbox selection service List
   * # Method
   */

  oncheckService(val,event){
    console.log(val)
  //this.MaintenanceID=
  const checked = event.target.checked;
    if(checked){
      this.sldServiceList=val;
     // this.MaintenanceID=val.MaintenanceID
     this.MaintenanceIDForRepair=val.MaintenanceID
      this.isSEActiveDelete=true
      this.isSEActiveEdit=true
       this.isSEActiveAdd=false
    }
    else{
    
      this.MaintenanceID=""
      this.isSEActiveDelete=false
      this.isSEActiveEdit=false
       this.isSEActiveAdd=true
       const index = this.sldServiceList.findIndex(
        (eid) => eid.MaintenanceID === val.MaintenanceID
      );
      this.sldServiceList.splice(index, 1);
    }
    console.log(this.sldServiceList)
  }

/**
   * ~ oncheckRepair
   * * checkbox selection Repair List
   * # Method
   */
  
  oncheckRepair(val,event){
    console.log(val)
  //this.MaintenanceID=
  const checked = event.target.checked;
    if(checked){
      this.sldRepairList=val;
      this.MaintenanceIDForRepair=val.MaintenanceID
      if(val.Status=="End"){
        this.isREActiveDelete=true
      this.isREActiveEdit=false
       this.isREActiveAdd=false
      }
      else{
        this.isREActiveDelete=true
        this.isREActiveEdit=true
         this.isREActiveAdd=false
      }
      
    }
    else{
      this.iseditRepairList=false;
      this.MaintenanceIDForRepair=""
      this.isREActiveDelete=false
      this.isREActiveEdit=false
       this.isREActiveAdd=true
       const index = this.sldRepairList.findIndex(
        (eid) => eid.MaintenanceID === val.MaintenanceID
      );
      this.sldRepairList.splice(index, 1);
    }
    console.log(this.sldRepairList)
  }
/**
   * @method function
   * @name editRepairList()
   * @description function seems to handle editing a repair entry.
   */
  editRepairList(event,val){
  console.log(val)
  
  const DATETIME = new Date();
  this.selectedFiles=[]
  this.MaintenanceID=val.MaintenanceID
  this.iseditRepairList=true;
  //this.purchaseDate = this.datePipe.transform(val.StartDate, "MM/dd/yyyy");
  this.purchaseDate = this.formatDate(DATETIME);
  this.purchaseDate = val.StartDate.split('T')[0];
  //this.purchaseDate=val.StartDate;
  this.startTime=val.StartTime;
  this.endRepairTime=val.EndTime
  this.remarks=val.Description
  this.populateExistingDocuments(val);
  }

/**
   * @method method
   * @name  cancelRepairEdit()
   * @description 
   */

  cancelRepairEdit(){
    this.selectedFiles=[]
    this.iseditRepairList=false;
    this.MaintenanceID=""
    this.purchaseDate="";
    this.startTime="";
    this.remarks=""
  }
  /**
   * @method method
   * @name   closeEditRepairList()
   * @description 
   */
  closeEditRepairList(event){
    this.selectedFiles=[]
    this.iseditRepairList=false;
  }
/**
   * @method method
   * @name   editServiceList()
   * @description 
   */
  editServiceList(event,value){
    this.selectedFiles=[]
    this.isAddServiceList=false;
    this.iseditServiceList=true
    console.log(value)
    this.MaintenanceID=value.MaintenanceID
    this.sstartdate=value.StartDate.split('T')[0];
    this.startTime=value.StartTime
    this.endTime=value.EndTime
    this.senddate= value.EndDate.split('T')[0];
    this.remarks=value.Description
    this.scost=value.Cost
 // Populate selectedFiles with existing documents
 this.populateExistingDocuments(value);
  }
/**
   * @method method
   * @name  cancelRepairEdit()
   * @description 
   */
  populateExistingDocuments(data) {
    const existingDocs = [
      { url: data.Document1, name: 'Document 1' },
      { url: data.Document2, name: 'Document 2' },
      { url: data.Document3, name: 'Document 3' },
      { url: data.Document4, name: 'Document 4' }
    ];
  
    this.selectedFiles = existingDocs.filter(doc => doc.url); // Only include non-null documents
  }
  /**
   * @method method
   * @name  cancelRepairEdit()
   * @description 
   */
  cancelServiceUpdate(){
    this.selectedFiles=[]
    this.MaintenanceID=null;
    this.isSEActiveDelete=false;

    this.isAddServiceList=false;
    this.iseditServiceList=false
    this.MaintenanceID=""
  }
/**
   * ~ addService
   * * show service model 
   * # Method
   */

addService(){
  this.isAddServiceList=false;
this.isAddServiceList=true;
//this.MaintenanceID=value.MaintenanceID
this.sstartdate=""
this.startTime=""
this.endTime=""
this.senddate=""
this.remarks=""
this.scost=null
this.MaintenanceID=""
}
/**
   * @method method
   * @name  cancelRepairEdit()
   * @description 
   */
cancelServiceModel(){
  this.isAddServiceList=false;
  this.isAddServiceList=false;
  this.ADLE.resetForm()
  this.MaintenanceID=""
}
/**
   * ~ addOthersEquipment
   * * submit form value addOthersEquipment
   * # Method POST ApI
   */
addOthersEquipment(){


    var timeTodate = new Date("01/01/2020 " + this.startTime + "");
    console.log(timeTodate);
  
    const stratTime = this.datePipe.transform(timeTodate, "HH:mm");
    
  
    var timeendTodate = new Date("01/01/2020 " + this.endTime + "");
    console.log(timeendTodate);
  
    const endTime = this.datePipe.transform(timeendTodate, "HH:mm");
  
  let newdate=new Date()
  let newdate1=this.datePipe.transform(newdate, "yyyy-MM-dd")
  let newtime=this.datePipe.transform(newdate, "HH:mm")
  let slddate=this.datePipe.transform(this.sstartdate, "yyyy-MM-dd")
  
  
  let Document1=null
  let Document2=null
  let Document3=null
  let Document4=null
  
  if(this.selectedFiles.length==1){
  
    Document1=this.selectedFiles[0].url;
  }
  else if(this.selectedFiles.length==2){
    Document1=this.selectedFiles[0].url;
    Document2=this.selectedFiles[1].url;
  }
  else if(this.selectedFiles.length==3){
    Document1=this.selectedFiles[0].url;
    Document2=this.selectedFiles[1].url;
    Document3=this.selectedFiles[2].url;
  }
  else if(this.selectedFiles.length==4){
    Document1=this.selectedFiles[0].url;
    Document2=this.selectedFiles[1].url;
    Document3=this.selectedFiles[2].url;
    Document4=this.selectedFiles[3].url;
  }
   
     
      if(this.iseditServiceList==true){
        var serviceData = {
          //XBID: this.XBID,
          //XID: this.userID,
          AssetID:this.selecedUIAID,
          MaintenanceID: this.MaintenanceID,
          StartDate:this.sstartdate,
          EndDate:this.senddate,
          StartTime:stratTime,
          EndTime:endTime,
          Cost:this.scost,
          Description:this.remarks,
          Document1: Document1,
          Document2: Document2,
          Document3: Document3,
          Document4: Document4,
          isRemoved :0
          
        };
        var url = this.apiServer + "resource/updateassetmaintenance";
         
     
  
      console.log(serviceData);
      this.apiCall.makePostApiCall(url, serviceData).then((res: any) => {
        console.log(res);
  // -----------------------------------------------
        if (res.status === "Success") { 
         
         // this.myForm.reset(); // Reset the form values after submission
          this.iseditServiceList=false;
          this.MaintenanceID=""
          let value=0
          this.getServiceEquipmentList(value)
          // this._notification.remove()
          // this._notification.create("success", "Successfully Added", {
          //   Position: "top-right",
          //   Style: "flip bar",
          //   Duration: 3000,
          // });
          this.notificationService.showNotification("Success","Successfully Added");
        }
        else{
          // this._notification.remove()
          // this._notification.create("danger", res.error.message, {
          //   Position: "top-right",
          //   Style: "flip bar",
          //   Duration: 3000,
          // });
          this.notificationService.showNotification("Error","Something Went Wrong");
        }
      });
      }
      else{
  
        var serviceData1 = {
          XBID: this.XBID,
          XID: this.userID,
          AssetID:this.selecedUIAID,
          MaintenanceType:"Others",
          StartDate:this.sstartdate,
          EndDate:this.senddate,
          StartTime:stratTime,
          EndTime:endTime,
          Status:"Start",
          Cost:this.scost,
          Description:this.remarks,
          Document1: Document1,
          Document2: Document2,
          Document3: Document3,
          Document4: Document4,
          isRemoved :0
          
        };
        var url = this.apiServer + "resource/scheduleassetmaintenance";
      
     
  
      console.log(serviceData1);
      this.apiCall.makePostApiCall(url, serviceData1).then((res: any) => {
        console.log(res);
  // -----------------------------------------------
        if (res.status === "Success") {
         // this.myForm.reset(); // Reset the form values after submission
          this.isAddServiceList=false;
          this.iseditServiceList=false
          this.MaintenanceID=""
          let value=0
          this.getServiceEquipmentList(value)
          // this._notification.remove()
          this.notificationService.showNotification("Success","Successfully Added");
          // this._notification.create("success", "Successfully Added", {
          //   Position: "top-right",
          //   Style: "flip bar",
          //   Duration: 3000,
          // });
        }
        else{
          this.notificationService.showNotification("Error","Something Went Wrong");
          // this._notification.remove()
          // this._notification.create("danger", res.error.message, {
          //   Position: "top-right",
          //   Style: "flip bar",
          //   Duration: 3000,
          // });
        }
      });
    }
  
}

handleRadioChange(event){
  console.log(this.optionAct);
  if(this.configAct==0){
    this.lateThreshold=null
    this.configLast=0
  }
}
/**
   * ~ addServiceEquipment
   * * submit form value addServiceEquipment
   * # Method POST ApI
   */

addServiceEquipment(){

  var timeTodate = new Date("01/01/2020 " + this.startTime + "");
  console.log(timeTodate);

  const stratTime = this.datePipe.transform(timeTodate, "HH:mm");
  

  var timeendTodate = new Date("01/01/2020 " + this.endTime + "");
  console.log(timeendTodate);

  const endTime = this.datePipe.transform(timeendTodate, "HH:mm");

let newdate=new Date()
let newdate1=this.datePipe.transform(newdate, "yyyy-MM-dd")
let newtime=this.datePipe.transform(newdate, "HH:mm")
let slddate=this.datePipe.transform(this.sstartdate, "yyyy-MM-dd")


let Document1=null
let Document2=null
let Document3=null
let Document4=null

if(this.selectedFiles.length==1){

  Document1=this.selectedFiles[0].url;
}
else if(this.selectedFiles.length==2){
  Document1=this.selectedFiles[0].url;
  Document2=this.selectedFiles[1].url;
}
else if(this.selectedFiles.length==3){
  Document1=this.selectedFiles[0].url;
  Document2=this.selectedFiles[1].url;
  Document3=this.selectedFiles[2].url;
}
else if(this.selectedFiles.length==4){
  Document1=this.selectedFiles[0].url;
  Document2=this.selectedFiles[1].url;
  Document3=this.selectedFiles[2].url;
  Document4=this.selectedFiles[3].url;
}
 
   
    if(this.iseditServiceList==true){
      var serviceData = {
        //XBID: this.XBID,
        //XID: this.userID,
        AssetID:this.selecedUIAID,
        MaintenanceID: this.MaintenanceID,
        StartDate:this.sstartdate,
        EndDate:this.senddate,
        StartTime:stratTime,
        EndTime:endTime,
        Cost:this.scost,
        Description:this.remarks,
        Document1: Document1,
        Document2: Document2,
        Document3: Document3,
        Document4: Document4,
        isRemoved :0
        
      };
      var url = this.apiServer + "resource/updateassetmaintenance";
       
   

    console.log(serviceData);
    this.apiCall.makePostApiCall(url, serviceData).then((res: any) => {
      console.log(res);
// -----------------------------------------------
      if (res.status === "Success") { 
       
       // this.myForm.reset(); // Reset the form values after submission
        this.iseditServiceList=false;
        this.MaintenanceID=""
        let value=0
        this.getServiceEquipmentList(value)
        // this._notification.remove()
        this.notificationService.showNotification("Success","Successfully Added");
        // this._notification.create("success", "Successfully Added", {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      }
      else{
        this.notificationService.showNotification("Error","Something Went Wrong");
        // this._notification.remove()
        // this._notification.create("danger", res.error.message, {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      }
    });
    }
    else{

      var serviceData1 = {
        XBID: this.XBID,
        XID: this.userID,
        AssetID:this.selecedUIAID,
        MaintenanceType:"service",
        StartDate:this.sstartdate,
        EndDate:this.senddate,
        StartTime:stratTime,
        EndTime:endTime,
        Status:"Start",
        Cost:this.scost,
        Description:this.remarks,
        Document1: Document1,
        Document2: Document2,
        Document3: Document3,
        Document4: Document4,
        isRemoved :0
        
      };
      var url = this.apiServer + "resource/scheduleassetmaintenance";
    
   

    console.log(serviceData1);
    this.apiCall.makePostApiCall(url, serviceData1).then((res: any) => {
      console.log(res);
// -----------------------------------------------
      if (res.status === "Success") {
       // this.myForm.reset(); // Reset the form values after submission
        this.isAddServiceList=false;
        this.iseditServiceList=false
        this.MaintenanceID=""
        let value=0
        this.getServiceEquipmentList(value)
        // this._notification.remove()
        this.notificationService.showNotification("Success","Successfully Added");
        // this._notification.create("success", "Successfully Added", {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      }
      else{
        // this._notification.remove()
        this.notificationService.showNotification("Error","Something Went Wrong");
        // this._notification.create("danger", res.error.message, {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      }
    });
  }
}


/**
   * ~ deleteOthers
   * *Delete others List 
   * # Method GET ApI
   */

deleteOthers(){

  const url = this.apiServer + "resource/deleteassetserviceandrepair/" + this.MaintenanceIDForRepair + "/" + this.XBID;
  this.apiCall.makeGetApiCall(url).then((res: any) => {
    console.log(res);
    if (res.Status === "Success") {
    
      let value=0
      this.getOthersEquipmentList(value)
       this.MaintenanceID=""
       this.MaintenanceIDForRepair=""
       this.notificationService.showNotification("Success","Successfully Deleted");
      // this._notification.create("success", "Successfully Deleted", {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
      this.isSEActiveDelete=false;
      this.isSEActiveEdit=false;
      this.isSEActiveAdd=true
    }
    else{
      this.notificationService.showNotification("Error","Something Went Wrong");
      // this._notification.create("danger", "Something Went Wrong", {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
    }

  })
}

   /**
   * ~ deleteService
   * *Delete Repair List 
   * # Method GET ApI
   */

   deleteRepair(){

    const url = this.apiServer + "resource/deleteassetserviceandrepair/" + this.MaintenanceIDForRepair + "/" + this.XBID;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
      if (res.Status === "Success") {
      
        let value=0
      this.getRepairEquipmentList(value)
         this.MaintenanceIDForRepair=""
         this.notificationService.showNotification("Success","Successfully Deleted");
        // this._notification.create("success", "Successfully Deleted", {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
        this.isREActiveDelete=false;
        this.isREActiveEdit=false;
        this.isREActiveAdd=true
      }
      else{
        this.notificationService.showNotification("Error","Something Went Wrong");
        // this._notification.create("danger", "Something Went Wrong", {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      }

    })
  }

  /**
   * ~ deleteService
   * *Delete Service List 
   * # Method GET ApI
   */

  deleteService(){

    const url = this.apiServer + "resource/deleteassetserviceandrepair/" + this.MaintenanceIDForRepair + "/" + this.XBID;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
      if (res.Status === "Success") {
      
        let value=0
        this.getServiceEquipmentList(value)
         this.MaintenanceID=""
         this.MaintenanceIDForRepair=""
         this.notificationService.showNotification("Success","Successfully Deleted");
        // this._notification.create("success", "Successfully Deleted", {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
        this.isSEActiveDelete=false;
        this.isSEActiveEdit=false;
        this.isSEActiveAdd=true
      }
      else{
        this.notificationService.showNotification("Error","Something Went Wrong");
        // this._notification.create("danger", "Something Went Wrong", {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      }

    })
  }
/**
   * @method function
   * @name EndRepairSchedule
   * @HttpMethod Post
   * @description  function is handling the process of ending a repair schedule.
   */
  EndRepairSchedule() {


      console.log(this.sldRepairList)
      var currentdate=new Date();
      var time = currentdate.getHours() + ":" + currentdate.getMinutes();
    
    
      const url = this.apiServer + "resource/assetrepair";
     
      const serviceData = {
        XBID: this.XBID,
        XID: this.userID,
        AssetID:this.selecedUIAID,
        MaintenanceType:"Repair",
        Equipid:this.sldEquipmentId,
        EquipmentCategoryTypeId:this.sldEQCatTypeID,
        StartDate:this.sldRepairList.StartDate,
        EndDate:currentdate,
        StartTime:this.sldRepairList.StartTime,
        EndTime:time,
        Status:"End",
        MaintenanceID:this.sldRepairList.MaintenanceID,
        Description:"End Repair",
        isRemoved :0
      };
    
      console.log(serviceData);
      this.apiCall.makePostApiCall(url, serviceData).then((res: any) => {
        console.log(res);
    // -----------------------------------------------
    if (res.status === "Success") {
    //  this.myForm.reset(); // Reset the form values after submission
    let value=0
      this.getRepairEquipmentList(value)
    this.isREActiveEdit=false;
    this.isREActiveAdd=true;
    this.isREActiveDelete=false;
    this.MaintenanceID=""
    this.MaintenanceIDForRepair=""
    this.notificationService.showNotification("Success","Successfully Repair Ended ");
    // this._notification.create("success", "Successfully Repair Ended ", {
    //   Position: "top-right",
    //   Style: "flip bar",
    //   Duration: 3000,
    // });
    }
    else{
      this.notificationService.showNotification("Error","Something Went Wrong");
    // this._notification.create("danger", "Something Went Wrong", {
    //   Position: "top-right",
    //   Style: "flip bar",
    //   Duration: 3000,
    // });
    }
    });
    
}

/**
   * @method function
   * @name getGroupStatReservations
   * @HttpMethod GET
   * @description Get Reservation by Equipgrpid
   */

getGroupStatReservations(equipgrpid){
let url;
if(this.catype=='gsReservation'){
   url =this.apiServer +"reservation/getreservationforequipmentgroup/" +this.XBID +"/" +equipgrpid + "/" + this.timelineView ;
   }
   else if(this.catype=='gsCancel'){url =this.apiServer +"reservation/getcancelledreservationforequipmentgroup/" +this.XBID +"/" +equipgrpid + "/" + this.timelineView ;}
   else if(this.catype=='gsWalk'){url =this.apiServer +"reservation/getwalkinreservespotforequipmentgroup/" +this.XBID +"/" +equipgrpid + "/" + this.timelineView ;}
  this.apiCall.makeGetApiCall(url).then((res: any) => { 
    console.log(res);
     if (res.length > 0) {
     this.GroupStatMembersList=res
     }
    
  });
}
/**
   * @method function
   * @name getReservations
   * @HttpMethod GET
   * @description Get Reservation by Asset ID
   */

getReservations(AID) {
  this.noReservation = false;
  this.noMachineReservation=true
  this.reservationsList = [];
  
  // --------------------------------------------------------
  // GET API Call getreservation for assets
  const url =
    this.apiServer +
    "reservation/getreservationforassets/" +
    this.XBID +
    "/" +
    AID + "/" + this.timelineView ;
  this.apiCall.makeGetApiCall(url).then((res: any) => {
     // --------------------------------------------------------
    console.log(res);
    if (res.length > 0) {
      this.allreserveitems = res;
      this.reservationsList = res;
      this.noReservation = false;
    } else {
      this.noReservation = true;
    }
  });
}

getCancellation(AID){
  let url;
 if(this.catype=='msCancel'){
  url =this.apiServer +"reservation/getcancelledreservationforassets/"+ this.XBID +
  "/" +
  AID + "/" + this.timelineView ;
 }
 else if(this.catype=='msWalk'){
  url =this.apiServer +"reservation/getwalkinreservespotforassets/"+ this.XBID +
  "/" +
  AID + "/" + this.timelineView ;
 }

  this.apiCall.makeGetApiCall(url).then((res: any) => {
     // --------------------------------------------------------
    console.log(res);
    if(res.length>0){
      this.CancellationList=res
    }
  console.log(this.CancellationList);
  
  });
}
/**
   * @method function
   * @name onRepairUpdateSubmit
  
   * @description update for the form submit and repairs     
   */
onRepairUpdateSubmit(form){
  if (form.valid) {
    console.log('Form submitted:', this.models);
    this.ReapirEdit()

  } else {
    console.log('Form is invalid');
  }

}
/**
   * @method function
   * @name ReapirEdi
   * @HttpMethod Post
   * @description update the asset maintenance
   */
ReapirEdit(){
let Document1=null
let Document2=null
let Document3=null
let Document4=null

if(this.selectedFiles.length==1){

  Document1=this.selectedFiles[0].url;
}
else if(this.selectedFiles.length==2){
  Document1=this.selectedFiles[0].url;
  Document2=this.selectedFiles[1].url;
}
else if(this.selectedFiles.length==3){
  Document1=this.selectedFiles[0].url;
  Document2=this.selectedFiles[1].url;
  Document3=this.selectedFiles[2].url;
}
else if(this.selectedFiles.length==4){
  Document1=this.selectedFiles[0].url;
  Document2=this.selectedFiles[1].url;
  Document3=this.selectedFiles[2].url;
  Document4=this.selectedFiles[3].url;
}
let endtime
if(this.endRepairTime==null){
  endtime=null
}
else{
  endtime=this.endRepairTime
  this.rtartTime=this.startTime
}

  console.log(this.selectedFiles)
  //return false;
  const serviceData = {
    MaintenanceID:this.MaintenanceID,
    AssetID:this.selecedUIAID,
    StartDate:this.datePipe.transform(this.purchaseDate, "yyyy-MM-dd"),
    EndDate:null,
    StartTime:this.rtartTime,  //rtartTime
    EndTime:endtime,
    Status:"Start",
    Description:this.repairremarks,
    XBID:this.XBID,
    Document1:Document1,
    Document2:Document2,
    Document3:Document3,
    Document4:Document4,
    isRemoved:0,
  };

  console.log(serviceData)
  //return false;
  const url = this.apiServer + "resource/updateassetmaintenance";

  //this.datePipe.transform(this.sstartdate, "yyyy-MM-dd"),

  console.log(serviceData);
  this.apiCall.makePostApiCall(url, serviceData).then((res: any) => {
    console.log(res);
// -----------------------------------------------
    if (res.status === "Success") {
      let value=0
      this.getRepairEquipmentList(value)
     // this.myForm.reset(); // Reset the form values after submission
      this.MaintenanceID=""
      this.cancelRepairEdit()
    }
  })

}
// --------------------------------------------------------------------------------------
//  Usage Tracking End Here
// --------------------------------------------------------------------------------------

// --------------------------------------------------------------------------------------
// ----------------- ADD Equipment Start Here--------------------------------------------
/**
   * ~ addEquipment
   * * Add Equipment Window opens
   * # Method
*/  
addEquipmentShow(){

    this.isShowAddEquipment=true
    this.getVarientGenericEquipment("All")

}
/**
   * @method function
   * @name backtoEquipmentView
   
   * @description  It is used to back the view
   */
backtoEquipmentView(){
  this.isShowAddEquipment=false 
  this.showForm = false; // Hide the form
  this.category = null; // Reset selected category
  this.sldModalID = null;
  this.sldQuickAddcategoryID = null;
  this.sldBrandID = null;
  this.sldVarientId = null;
  this.brand = null;
  this.model = null;
  this.ModelImage = null;
  this.quantity = null;
  this.slotDuration = null;
  this.capacity = null;
  this.maximum = null;
  this.optionAct=null;
  this.optionLast=null;
  this.optionPercent = null;
  // this.category=""
}
/**
   * @method function
   * @name goToPrevious
   * @description select capacity,quantity,category,slotduration.
   */
goToPrevious(){
  this.showForm = false;
}
/**
   * @method method
   * @name getVarientGenericEquipment
   * @HttpMethod GET
   * @description Get equipment category type for add
   */
getVarientGenericEquipment(value){
  this.modalList=[]
  console.log(value)
  let categoryList="All"
  const url =
    this.apiServer + "resource/getequipmentcategorytypeforadd/" + categoryList + "/" + this.XBID;
  this.apiCall.makeGetApiCall(url).then((res: any) => {
    console.log(res);
    if (res.length > 0) {
      this.modalList = res;
      
    // this.selectQuickAddProduct(res[0])
    // --------------------------------------------------  
      
      
    } 
    else {
    }
  });

}
/**
   * @method Method
   * @name selectQuickAddProduct
   * @description Select model iD ,brand name and mode; number etc..
   */

selectQuickAddProduct(pData) {
  console.log(pData);
  this.sldEquipmentListForAdd=pData;
  this.category=""
  this.sldModalID=null
  this.sldBrandID=null
  this.sldVarientId=null
  this.sldTag=""
  this.category=pData.Name || null;
  this.sldQuickAddcategoryID=pData.ID;
  this.sldModalID = pData.ModelID;
  this.sldBrandID = pData.BrandID;
  this.sldVarientId=pData.VariantID
  this.brand = pData.BrandName;
  this.model = pData.ModelNumber;
  this.ModelImage=pData.ModelImage;
}

/**
   * @method Method
   * @name triggerAddEuipment
   * @description Form Submit add equipment
   */
triggerAddEuipment(event) {
  console.log("Custom Add Equipment")
  this.addEquipForm.onSubmit(null);
  console.log(this.quantity)
  console.log(this.capacity)
  console.log(this.slotDuration)
  console.log(this.category)
  //this.successAddEquipment.show()
  // const button = (event.srcElement.disabled === undefined) ? event.srcElement.parentElement : event.srcElement;
  // button.setAttribute('disabled', true);
  // setTimeout(function () {
  // button.removeAttribute('disabled');
  // }, 1000);
  // this.deselectborders();

}




showNext() {
  if (this.sldModalID) {
    this.showForm = true;
    this.capacity=""
    this.slotDuration=null
    this.quantity=null
    this.optionAct=null;
    this.optionLast=null;
    this.optionPercent = null;
  }
}


 /**
   * @method Method
   * @name addEquipment
   * @Method POST
   * @description Save Equipment Group
   */
 addEquipment() {
  this.isAddEquipLoading = true;
  var equipData = {};
  
  console.log(this.slotDuration);
  // -----------------------------------------------
  // POST API Call insertassests

  const url = this.apiServer + "resource/insertassests";
  
     equipData = {
      AssetTag: null,
      BID: this.XBID,
      ActivitytypeID: this.addEQactivityTypeID,
      AssetTypeID: 1,
      PssnTypeID: 1,
      EquipCatID: this.sldEquipmentListForAdd.EquipCatTypeID,
      EquipSrlNum: null,
     
      AssetName: null,
      SlotDuration: this.slotDuration,
      SlotCapacity: this.capacity,
      MaxSlotsPerResvn:this.maximum,
      Quantity: this.quantity,
      EquipSlotDuration: this.slotDuration,
      EquipSlotCapacity: this.capacity,
      ActiveCount: this.quantity,
      InActiveCount: 0,
      DeletedCount: 0,
      isResvnAllowed: this.optionAct !== undefined ? +this.optionAct : 0, 
      isLateCheckinAllowed: this.optionLast !== undefined ? +this.optionLast : 0,
      LateCheckinThresholdLimit: this.optionPercent != null ? String(this.optionPercent) : null,
      SessnSlotDurnTypeID:this.slotDuration != null ? this.slotDurationMapping[this.slotDuration] : null,
   
    };
  
  
  // -----------------------------------------------
  console.log(equipData);
  this.apiCall.makePostApiCall(url, equipData).then((res: any) => {
    console.log(res);
// -----------------------------------------------
    if (res.status === "Success") {
      this.notificationService.showNotification("Success","Successfully Added");
      // this._notification.create("success", "Successfully Added", {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
    
      this.capacity=null
      this.slotDuration=null
      this.quantity=null
     this.isViewGroupEquipment=true
      this.clearValue();
      this.showForm = false;
      this.isShowAddEquipment=false 
      this.categoryType ="All"
      this.getEquipmentsByCategory("All");
     // this.myForm.reset(); // Reset the form values after submission
      this.addEquipForm.resetForm()
    } 
 // -----------------------------------------------   
    else {
      this.isAddEquipLoading = false;
      this.notificationService.showNotification("Error","Something Went Wrong");
      // this._notification.create("danger", res.error.message, {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
    }
  });
}
 // --------------------------------------------------------------------------------------
// ----------------- ADD Equipment END  Here--------------------------------------------

// -----------------------------------------------------------------------------------

//  SERVICE SCHEDULE START HERE DEACTIVATE
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
/**
   * @method function
   * @name onDeactivationSubmit
   
   * @description it used to display form in validation
   */

onDeactivationSubmit(form) {
  if (form.valid) {
    console.log('Form submitted:', this.models);
    this.addServiceSchedule()

  } else {
    console.log('Form is invalid');
  }
}
/**
   * @method method
   * @name addServiceSchedule
   * @HttpMethod Post
   * @description Post schedule of asset maintenance
   */
addServiceSchedule(){
let scheduled:number;

if(this.serviceType== 'Scheduled'){
  scheduled=1
}
else{
  scheduled=0
}
  var timeTodate = new Date("01/01/2020 " + this.startTime + "");
  console.log(timeTodate);

  const stratTime = this.datePipe.transform(timeTodate, "HH:mm");
  

  var timeendTodate = new Date("01/01/2020 " + this.endTime + "");
  console.log(timeendTodate);

  const endTime = this.datePipe.transform(timeendTodate, "HH:mm");

let newdate=new Date()
let newdate1=this.datePipe.transform(newdate, "yyyy-MM-dd")
let newtime=this.datePipe.transform(newdate, "HH:mm")
let slddate=this.datePipe.transform(this.sstartdate, "yyyy-MM-dd")
let Document1=null
let Document2=null
let Document3=null
let Document4=null

if(this.selectedFiles.length==1){

  Document1=this.selectedFiles[0].url;
}
else if(this.selectedFiles.length==2){
  Document1=this.selectedFiles[0].url;
  Document2=this.selectedFiles[1].url;
}
else if(this.selectedFiles.length==3){
  Document1=this.selectedFiles[0].url;
  Document2=this.selectedFiles[1].url;
  Document3=this.selectedFiles[2].url;
}
else if(this.selectedFiles.length==4){
  Document1=this.selectedFiles[0].url;
  Document2=this.selectedFiles[1].url;
  Document3=this.selectedFiles[2].url;
  Document4=this.selectedFiles[3].url;
}

  const serviceData = {
    XBID: this.XBID,
    XID: this.userID,
    AssetID:this.sldAssetsForDeactivate,
    MaintenanceType:"service",
    StartDate:this.sstartdate,
    EndDate:this.senddate,
    StartTime:stratTime,
    EndTime:endTime,
    Status:"Start",
    Description:this.remarks,
    Cost:this.serviceCost,
    isScheduled:scheduled, 
    Document1: Document1,
    Document2: Document2,
    Document3: Document3,
    Document4: Document4,
    isRemoved :0
  };
  const url = this.apiServer + "resource/scheduleassetmaintenance";

  console.log(serviceData);
  this.apiCall.makePostApiCall(url, serviceData).then((res: any) => {
    console.log(res);
// -----------------------------------------------
    if (res.status === "Success") {
      this.getEquipmentsByCategory("All");
     this.isOpenDeactivate=false;
      // this._notification.remove()
      this.notificationService.showNotification("Success","Successfully Added");
      // this._notification.create("success", "Successfully Added", {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
      this.bodyClass.remove("slideprofile");
      this.deactivateMachine.resetForm()
      this.deactivateMachine.reset()
    }
    else{
      this.isOpenDeactivate=true;
      // this._notification.remove()
      this.notificationService.showNotification("Error","Something Went Wrong");
      // this._notification.create("danger", res.error.message, {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
    }
  });
}

//  SERVICE SCHEDULE END HERE DEACTIVATE
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
/**
   * @method function
   * @name onDeactivationRepairSubmit
   
   * @description form repairs the submitted models.
   */
onDeactivationRepairSubmit(form) {
  if (form.valid) {
    console.log('Form submitted:', this.models);
    this.addRepairSchedule()

  } else {
    console.log('Form is invalid');
  }
}
/**
   * @method function
   * @name otherDeactivation
   * @HttpMethod POST
   * @description shows the date start and end time in YYYY-MM-DD.
   */
otherDeactivation(){

  let scheduled:number;

  
    var timeTodate = new Date("01/01/2020 " + this.rtartTime + "");
    console.log(timeTodate);
  
    const stratTime = this.datePipe.transform(timeTodate, "HH:mm");
    
  
    var timeendTodate = new Date("01/01/2020 " + this.endTime + "");
    console.log(timeendTodate);
  
    const endTime = this.datePipe.transform(timeendTodate, "HH:mm");
  
  let newdate=new Date()
  let newdate1=this.datePipe.transform(newdate, "yyyy-MM-dd")
  let newtime=this.datePipe.transform(newdate, "HH:mm")
  let slddate=this.datePipe.transform(this.sstartdate, "yyyy-MM-dd")
  
  
    const serviceData = {
      XBID: this.XBID,
      XID: this.userID,
      AssetID:this.sldAssetsForDeactivate,
      MaintenanceType:"Others",
      Equipid:this.sldEquipmentId,
      EquipmentCategoryTypeId:this.sldEQCatTypeID,
      StartDate:this.rstartdate,
      EndDate:this.senddate,
      StartTime:stratTime,
      EndTime:endTime,
      Status:"Start",
      MaintenanceID:null,
      Description:this.repairremarks,
      Cost:null,
      isScheduled:0,
      isRemoved :0
    };
    const url = this.apiServer + "resource/saveothersdeactivation";
  
    console.log(serviceData);
    this.apiCall.makePostApiCall(url, serviceData).then((res: any) => {
      console.log(res);
  // -----------------------------------------------
      if (res.status === "Success") {
        this.getEquipmentsByCategory("All");
       this.isOpenDeactivate=false;
        
        this.bodyClass.remove("slideprofile");
        this.deactivateMachine.resetForm()
        this.deactivateMachine.reset()
      }
      else{
        this.isOpenDeactivate=true;
        
      }
    });

}


/**
   * @method function
   * @name addRepairSchedule
   * @HttpMethod POST
   * @description it schedules the servie date
   */
addRepairSchedule() {
var timeTodate = new Date("01/01/2020 " + this.rtartTime + "");
  console.log(timeTodate);

  const stratTime = this.datePipe.transform(timeTodate, "HH:mm");

  const serviceData = {
    XBID: this.XBID,
    XID: this.userID,
    AssetID:this.sldAssetsForDeactivate,
    MaintenanceType:"Repair",
    Equipid:this.sldEquipmentId,
    EquipmentCategoryTypeId:this.sldEQCatTypeID,
    StartDate:this.rstartdate,
    EndDate:null,
    StartTime:stratTime,
    EndTime:null,
    Status:"Start",
    MaintenanceID:null,
    Description:this.repairremarks,
    Cost:null,
    isScheduled:0,
    isRemoved :0
  };
  const url = this.apiServer + "resource/assetrepair";

  console.log(serviceData);
  this.apiCall.makePostApiCall(url, serviceData).then((res: any) => {
    console.log(res);
// -----------------------------------------------
    if (res.status === "Success") {
      this.getEquipmentsByCategory("All");
      this.getEquipmentListView("All");
     this.isOpenDeactivate=false;
     this.notificationService.showNotification("Success","Successfully Added");
      // this._notification.remove()
      // this._notification.create("success", "Successfully Added", {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
      this.bodyClass.remove("slideprofile");
      this.deactivateRepairMachine.resetForm()
      this.deactivateRepairMachine.reset()
    }
    else{
      this.isOpenDeactivate=true;
      // this._notification.remove()
      this.notificationService.showNotification("Error","Something Went Wrong");
      // this._notification.create("danger", res.error.message, {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
    }
  });

}


//  Repair SCHEDULE Start HERE DEACTIVATE
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------




//  Repair SCHEDULE End HERE DEACTIVATE
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------

/**
   * ~ serviceScheduleCall
   * * his is automatically setting active/inactive state of service that is scheduled
   * # Method
   */

serviceScheduleCall(){
  const url = this.apiServer + "resource/SetAssetServiceStatus/" + this.XBID;
  this.apiCall.makePostApiCall(url,null).then((res: any) => {
    console.log(res)

  });
}


/**
   * ~ chooseStats
   * * choose weekly,Monthly etc... from green card
   * # Method
   */

  chooseStats(val,UID){
    console.log( this.sldAssetsList);
    this.duraion = val;
    console.log(val)
    // this.machineDowntimeCount=""
    // this.repairsCount=""
    // this.machineloadHrs=""
    // this.machinereservation=""
    
    const url = this.apiServer + "resource/getmachinestats/" + this.sldAssetsList.BID + "/" + this.sldAssetsList.AssetID + "/" + this.duraion;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
     console.log(res)
     if(res&&res.error){
      this.machineDowntimeCount=0
      this.machineloadHrs=0
      this.machinereservation=0
      this.machineCancelsCount=0
      this.machineWalksCount=0
     }
     else{
      this.machineDowntimeCount=res.Downtime;
      this.machineloadHrs=res.Load.reservationcount
      this.machinereservation=res.Reservation;
      this.machineCancelsCount=res.Cancellation
      this.machineWalksCount=res.Walkin
     }
    });

  }

 

 /**
   * ~ addRepairModel
   * * add Repair Model  and time Description 
   * # Method POST API
   */

  addRepairModels(){
  // this.addRepairModel.show()

  }

   endRepairModels(){

   // this.addRepairModel.show()

   }


 


  /**
   * ~ updateServiceModel
   * * show service model for update
   * # Method
   */

   updateServiceModel(){
    console.log(this.sldServiceList)
    this.remarks=this.sldServiceList.Description;
    this.endTime=this.sldServiceList.EndTime;
    this.startTime=this.sldServiceList.StartTime;
    this.senddate=this.datePipe.transform(this.sldServiceList.EndDate, "yyyy-MM-dd");
    this.sstartdate=this.datePipe.transform(this.sldServiceList.StartDate, "yyyy-MM-dd");
    // this.senddate=this.sldServiceList.EndDate;
    // this.sstartdate=this.sldServiceList.StartDate;

    //this.addServiceModel.show()
 
  }


 /**
   * ~ cancelRepairModel
   * * hide Repair Model
   * # Method
   */ 

  cancelRepairModel(){
    this.RPADD.resetForm()
    //this.addRepairModel.hide()
  }



/**
   * ~ triggerService
   * * submit form value check validation
   * # Method
   */

  triggerService(event){
    this.ADLE.onSubmit(undefined);
    const button = (event.srcElement.disabled === undefined) ? event.srcElement.parentElement : event.srcElement;
    button.setAttribute('disabled', true);
    setTimeout(function () {
    button.removeAttribute('disabled');
    }, 1000);
  }

  /**
   * ~   triggerRepair()
   * * submit form value check validation
   * # Method
   */

  triggerRepair(){
    this.RPADD.onSubmit(undefined);
  }

 
  
 



  
//-------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------
/**
   * ~ chooseUserType
   * * Choose user type of the Add Equipment Group 
   * # Method
   */
 chooseUserType(userType) {
  console.log(userType);
  //----------------------------------------------------
  if (userType === "Custom") {
    this.sldUserType = "Custom";
   // this.userRedirect(this.sldUserType)
  } else if (userType === "Quick") {
    this.sldUserType = "Quick";
  
  }
//----------------------------------------------------  
}
/**
   * ~ userRedirect
   * * Choose user type and open add equipment model open either custom or quick
   * # Method
   */
userRedirect(value){
console.log(value)

if(value==="Custom"){
  this.isUpdateEQGroup = false;
  
  this.addEQactivityTypeID = this.catactivityTypeID;
  console.log(this.addEQactivityTypeID);
  if (this.addEQactivityTypeID === 1) {
    this.activityType = "Cardio";
  } else if (this.addEQactivityTypeID === 2) {
    this.activityType = "Strength";
  } else {
    this.activityType = "Cardio";
  }

  //this.addMachinesModal.show();
  //this.chooseQuickORCustomModal.hide()
  this.getCategoryByActivityID(this.addEQactivityTypeID, "Add");
}
else{
  this.isUpdateEQGroup = false;
  this.addEQactivityTypeID = this.catactivityTypeID;
  console.log(this.addEQactivityTypeID);
  if (this.addEQactivityTypeID === 1) {
    this.activityType = "Cardio";
  } else if (this.addEQactivityTypeID === 2) {
    this.activityType = "Strength";
  } else {
    this.activityType = "Cardio";
  }
this.getVarientGenericEquipment(this.addEQactivityTypeID)
//this.addQickMachinesModal.show()

//this.chooseQuickORCustomModal.hide()
//this.getCategoryByActivityID(this.addEQactivityTypeID, "Add");
}
    
} 




selectactive()
{
  const selectborder = document.getElementById("selectborder");
  selectborder.classList.add("selectborderactive");
}
deselectactive()
{
  const selectborder = document.getElementById("selectborder");
  selectborder.classList.remove("selectborderactive");

}
activecategory()
{
  this.deactivevariant();
  this.deactivebrand();
  const selectcategory = document.getElementById("selectcategory");
  selectcategory.classList.add("selectcategoryactive");
}
deactivecategory()
{
  const selectcategory = document.getElementById("selectcategory");
  selectcategory.classList.remove("selectcategoryactive");
}
activevariant()
{
  this.deactivecategory();
  this.deactivebrand();
  const selectvariant = document.getElementById("selectvariant");
  selectvariant.classList.add("selectvariantactive");
}
deactivevariant()
{
  const selectvariant = document.getElementById("selectvariant");
  selectvariant.classList.remove("selectvariantactive");
}
activebrand()
{
  this.deactivecategory();
  this.deactivevariant();
  const selectbrand = document.getElementById("selectbrand");
  selectbrand.classList.add("selectbrandactive");
}
deactivebrand()
{
  const selectbrand = document.getElementById("selectbrand");
  selectbrand.classList.remove("selectbrandactive");
}
deselectborders()
{
  this.deactivecategory();
  this.deactivevariant();
  this.deactivebrand();
}
/**
* @method Method
* @name cancel

* @description Model add machine and table hidng
*/
cancel() {
// let currentUrl = this.router.url;
// this.router.routeReuseStrategy.shouldReuseRoute = () => false;
// this.router.onSameUrlNavigation = "reload";
// this.router.navigate([currentUrl]);
this.addQuickEquipForm.resetForm()
  this.addQuickEquipForm.reset()
 //this.addMachinesModal.hide();
 //this.addMachineTablet.hide();
 //this.chooseQuickORCustomModal.show();
 this.deselectborders();

}
/**
* @method Method
* @name cancelQuickAdd

* @description  cancel or deselect resetForm
*/
cancelQuickAdd(){
  this.addQuickEquipForm.resetForm()
  this.addQuickEquipForm.reset()
  //this.addQickMachinesModal.hide()
 // this.chooseQuickORCustomModal.show()
  this.deselectactive()
}


 /**
   * @method Method
   * @name setPagination
   * @description Based On Screen Height Set Items Count
   */
  // setPagination() {
  //   this.isShowScroll=true;
  //   this.isShowPagination=false;
  //  // this.isShowPagination=false;
  //   this.isShowPaginationMachine=false;
  //   this.isShowPaginationResesrve=false

  //   const body = document.getElementsByTagName("body")[0];
  //   body.classList.remove("showall");
  //   body.classList.remove("showallreserve");
  //   body.classList.remove("showallmachine");
  //   this.screenSize.setPagination().then((res: any) => {
  //      console.log(res);

  //          this.cardheight = document.querySelector<HTMLElement>(".items-row").offsetHeight;
  //          this.cardheightreserve = document.querySelector<HTMLElement>(".itemsreserve-row").offsetHeight;
  //          console.log(this.cardheight)
  //          console.log(this.cardheightreserve)
  //          let rowheight=70;
  //          let rowheightsmall=70;
  //          let rowheightreserve=60;
  //          console.log(this.cardheight)
  //          console.log(rowheight)
  //          let result=Math.round(this.cardheight/ rowheight);
  //          let resultsmall=Math.round(this.cardheight/ rowheightsmall);
  //          let resultreserve=Math.round(this.cardheightreserve/ rowheightreserve);
  //          this.machinePerPage=result;
  //          this.machinePerPageListView=result
  //          this.assetPerPage=resultsmall;
  //          this.loginPerPage=resultreserve;

  //     });
  // }

/**
   * @method Method
   * @name showAll
   * @description Show All items using Scrollbar
   */
  // showAll() {
  //   this.equtGRPPage=1
  //   this.isShowPagination=true;
  //   this.isShowScroll=false
   
  //   this.isShowPaginationMachine=false;
  //   this.isShowPaginationResesrve=false
   

  //   const body = document.getElementsByTagName("body")[0];
  //   body.classList.add("showall");
  //   this.screenSize.setPagination().then((res: any) => {
  //      console.log(res);
  //           this.machinePerPage=this.showallitems.length;
  //           this.machinePerPageListView=this.showallitems.length;
  //       }
  //     );
  // }

  /**
   * @method Method
   * @name showAll
   * @description Show All items using Scrollbar
   */
  //  showAllreserve() {
  //   this.resvPage=1
  //   this.isShowPagination=false;
  //   this.isShowScroll=false
   
  //   this.isShowPaginationMachine=false;
  //     this.isShowPaginationResesrve=true
   
  //   const body = document.getElementsByTagName("body")[0];
  //   body.classList.add("showallreserve");
  //   this.screenSize.setPagination().then((res: any) => {
  //      console.log(res);
  //           this.loginPerPage=this.allreserveitems.length;

  //       }
  //     );
  // }

    /**
   * @method Method
   * @name showAll
   * @description Show All machines using Scrollbar
   */
    //  showAllmachines() {
    //   this.assetCurrentpage=1
    //   this.isShowPagination=false;
    //   this.isShowScroll=false
      
    //   this.isShowPaginationMachine=true;
    //     this.isShowPaginationResesrve=false
         
    //   const body = document.getElementsByTagName("body")[0];
    //   body.classList.add("showallmachine");
    //   this.screenSize.setPagination().then((res: any) => {
    //      console.log(res);
    //           this.assetPerPage=this.allAssetsList.length;
  
    //       }
    //     );
    // }
 
  /**
   * @method method
   * @name getSlotDuration
   * @description Get Slot Durations
   */
  getSlotDuration() {
    this.slotDurationList = [];
    const url = this.apiServer + "resource/getslotduration/";
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
      if (res.length > 0) {
        // this.slotDurationList = res;
        const result = res.filter((slt) => slt.ID === 1 || slt.ID === 2);
        // console.log(result);
        this.slotDurationList = result;
      }
    });
  }

  /**
   * @method Method
   * @name addMachinesModalShow
   * @description Show Machine Modal
   */
  addMachinesModalShow() {
    this.sldUserType = "Quick"
   // this.chooseQuickORCustomModal.show()
    
  }

  /**
   * @method Method
   * @name addIncrementGroupModal
   * @description Add Increment Show Modal
   */
  addIncrementGroupModal(equipt) {
    this.isUpdateEquitLoading = false;
    console.log(equipt);
    this.isOpenedInCrementModal = "True";
    this.sldEquipID = equipt.EquipID;
    this.sldEQModalID = equipt.ModelID;
    this.sldEQBrandID = equipt.BrandID;
    this.mGroupquantity = null;
    this.sldEQTotal = equipt.TotalCount;
    this.sldEQActiveCount = equipt.ActiveCount;
    this.sldEQDeActiveCount = equipt.DeActiveCount;
    this.sldEQDeletedCount = equipt.DeletedCount;
    this.sldEQBrandName = equipt.BrandName;
    this.sldEQCatName = equipt.CategoryName;
    this.sldEQCatTypeID = equipt.EquipCatTypeID;
    this.sldEQVariantID = equipt.VariantID;
    this.sldEQActTypeID = equipt.ActivityTypeID;
    this.sldEQslotDuration = equipt.SlotDuration;
    this.sldEQslotCapacity = equipt.SlotCapacity;
    this.sldEQImage = equipt.Image;
    this.sldEQModalName = equipt.ModelNumber;
    this.sldEQVariantName = equipt.VariantName;
   // this.incrementGroupModal.show();
    this.getAssets(this.sldEquipID);
  }

  /**
   * @method Method
   * @name chooseCategory
   * @param {terms}
   * @description Choose Category
   */
  chooseCategoryOld(term,value) {
    console.log(term);
    this.categoryType = term.value;
    this.equtGRPPage = 1;
    this.assetCurrentpage = 1;
    this.isMachineProfile = false;
    this.isMachineTracker = false;
    this.isEQActiveAdd = true;
    this.isEQActiveEdit = false;
    this.isEQActiveDelete = false;
    this.machineViewType = "Stats";
    this.showDropdown=false

    if (!this.selectedFilters.includes(term) && term !== 'All') {
      this.selectedFilters.push(term);
    }
    // --------------------------------------------------
    // check equment category All ,Cardio,Strength,Functional
// Process equipment category based on the selected filter
if (term === "All") {
  this.handleEquipmentCategory("All");
} else if (term === "Cardio") {
  this.catactivityTypeID = 1;
  this.handleEquipmentCategory(this.catactivityTypeID);
} else if (term === "Strength") {
  this.catactivityTypeID = 2;
  this.handleEquipmentCategory(this.catactivityTypeID);
} else if (term === "Functional") {
  this.catactivityTypeID = 3;
  this.handleEquipmentCategory(this.catactivityTypeID);
}
    // if (term === "All") {
      
    //   if(this.isViewGroupEquipment===false){
    //   this.getEquipmentListView("All");
    //   }
    //   else{
    //     this.getEquipmentsByCategory("All");
    //   }
    // } else if (term=== "Cardio") {
    //   this.catactivityTypeID = 1;
      
    //   if(this.isViewGroupEquipment===false){
    //   this.getEquipmentListView(this.catactivityTypeID);
    //   }
    //   else{
    //     this.getEquipmentsByCategory(this.catactivityTypeID);
    //   }
    // } else if (term === "Strength") {
    //   this.catactivityTypeID = 2;
 

    //   if(this.isViewGroupEquipment===false){
    //     this.getEquipmentListView(this.catactivityTypeID);
    //   }
    //   else{
    //     this.getEquipmentsByCategory(this.catactivityTypeID);
    //   }
     
    // } else if (term === "Functional") {
    //   this.catactivityTypeID = 3;
  
    //   if(this.isViewGroupEquipment===false){
    //   this.getEquipmentListView(this.catactivityTypeID);
    //   }
    //   else{
    //     this.getEquipmentsByCategory(this.catactivityTypeID);
    //   }
    // } 
    // --------------------------------------------------
    else {
      return false;
    }
  }

  updateProgressCircle() {
    const active = this.sldEQActiveCount;
    const deactivated = this.sldEQDeActiveCount;
    const removed = this.sldEQDeletedCount;
  
    const total = active + deactivated + removed;
  
    if (total > 0) {
      const activePercentage = (active / total) * 100;
      const deactivatedPercentage = (deactivated / total) * 100;
      const removedPercentage = (removed / total) * 100;
  
      const circleElement = document.querySelector('.ui-widgets') as HTMLElement;
  
      if (circleElement) {
        circleElement.style.setProperty('--active-percentage', `${activePercentage}%`);
        circleElement.style.setProperty('--deactivated-start', `${activePercentage}%`);
        circleElement.style.setProperty('--deactivated-end', `${activePercentage + deactivatedPercentage}%`);
        circleElement.style.setProperty('--removed-start', `${activePercentage + deactivatedPercentage}%`);
        circleElement.style.setProperty('--removed-end', `${activePercentage + deactivatedPercentage + removedPercentage}%`);
        circleElement.style.setProperty('--border-thickness', '6px'); // Adjust thickness if needed
      }
    }
  }
  
 /**
   * @method function
   * @name handleEquipmentCategory
   
   * @description  Helper function to handle equipment category
   */


handleEquipmentCategory(category: string | number) {
  if(this.isViewGroupEquipment) {
    this.getEquipmentsByCategory(category);
  } else {
    this.getEquipmentListView(category);
  }
}
/**
   * @method function
   * @name chooseCategory
   * @param {term}
   
   * @description  // Manage adding "All" option logic
   */
 
chooseCategory(term: string) {
  // Manage adding "All" option logic
  if (term === 'All') {
    if(this.isViewGroupEquipment) {
      this.getEquipmentsByCategory("All");
    } else {
      this.getEquipmentListView("All");
    }
  } else {
    // Remove "All" if another option is selected
    this.selectedFilters = this.selectedFilters.filter(item => item !== 'All');

    if (!this.selectedFilters.includes(term)) {
      this.selectedFilters.push(term);
    }
  }

  // Apply the filter logic
  this.applyFilters();
}
/**
   * @method function
   * @name removeFilte
   * @param {filter}
   
   * @description   Remove the filter from the array
   */
 
removeFilter(filter: string) {
  
  this.selectedFilters = this.selectedFilters.filter(item => item !== filter);

  // If all filters are removed, default to "All"
  if (this.selectedFilters.length === 0) {
    //this.selectedFilters = ['All'];
    if(this.isViewGroupEquipment) {
      this.getEquipmentsByCategory("All");
    } else {
      this.getEquipmentListView("All");
    }
  }

  // Apply the updated filters
  this.applyFilters();
}
/**
   * @method method
   * @name applyFilters
   
   
   * @description   // Display all data
   */
 
applyFilters() {
  if (this.selectedFilters.includes('All')) {
    // Display all data
    if(this.isViewGroupEquipment) {
      this.getEquipmentsByCategory("All");
    } else {
      this.getEquipmentListView("All");
    }
  } else {
    console.log(this.selectedFilters)
    // Combine filters to display specific data
    if(this.isViewGroupEquipment) {
    for (const filter of this.selectedFilters) {
      switch (filter) {
        case 'Cardio':
          this.getEquipmentsByCategory(1);
          break;
        case 'Strength':
          this.getEquipmentsByCategory(2);
          break;
        case 'Functional':
          this.getEquipmentsByCategory(3);
          break;
      }
    }
  }
  else{
    for (const filter of this.selectedFilters) {
      switch (filter) {
        case 'Cardio':
          this.getEquipmentListView(1);
          break;
        case 'Strength':
          this.getEquipmentListView(2);
          break;
        case 'Functional':
          this.getEquipmentListView(3);
          break;
      }
    }
  }
  }
}


  /**
   * @method Method
   * @name getEquipmentsByCategory
   * @param Activity Id
   * @description Get All Equipments List
   */
getEquipmentsByCategory(actvID) {
    this.allequipMents = [];
    const DATETIME = new Date();
    const currentTime = this.datePipe.transform(DATETIME, "HH:mm:ss");

// --------------------------------------------------
// API call

    const url =this.apiServer + "resource/getequipmentgroupview/" + actvID + "/" + this.XBID + "/" + this.userID+ "/" + currentTime;

    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);

       if(actvID=="All"){
        if (res.length > 0) {
          this.listOfAllEquiments = res;
        }
      }

      if (res.length > 0) {
       // this.showallitems=res;
        this.noDataFound = "";
        this.allequipMents = res;
        this.filteredSlots = this.allequipMents;
        this.selectEquipment(res[0]);
        console.log(this.allequipMents)
      } 
      else{
        this.allequipMents = [];
        this.selectEquipment(null);
      }
      // else if(res.success =="false" || res.success ==false){
      //     this.Accessrestriction.show();
      //     this.activityRestrictionMsg=res.message;
      //    // this.getGymRole()
    
      //   }
       

    });
    console.log(this.allequipMents)
  }

/**
   * @method function
   * @name CancelAccessRestriction
   * @description Call getEquiptCategory
*/

CancelAccessRestriction(){

 // this.Accessrestriction.hide();
  //this.isSldMemberReservation=false;
  this.router.navigate(["/dashboard"]);
  const body = document.getElementsByTagName("body")[0];
  body.classList.remove("modal-open");
}
  
  /**
   * @method Method
   * @name oncheckEquipt
   * @param { Selected Equipment }
   * @description Get All Equipments List
   */
  oncheckEquipt(equipt, event) {
    console.log(equipt);
    this.equipGrpid=equipt.EquipID;
    this.GroupMode=equipt.GroupMode
    const checked = event.target.checked;
    // --------------------------------------------------
    if (checked) {
      this.sldEqupiments=equipt;
      this.sldGroupID = equipt.EquipID;
      // this.isEQActiveEdit = true;
      // this.isEQActiveAdd = false;
      // this.isEQActiveDelete = true;
    if(this.GroupMode !="Default" || equipt.GroupTag!="Default"){
        this.isEQActiveEdit = true;
        this.isEQActiveAdd = false;
      this.isEQActiveDelete = true;
     }
     else{
      this.isEQActiveEdit = false;
      this.isEQActiveAdd = false;
      this.isEQActiveDelete = false;
     }
    } 
    
    // --------------------------------------------------
    else {
      this.sldGroupID = null;
      this.sldEqupiments=[]
      // const index = this.sldEqupiments.findIndex(
      //   (eid) => eid.EquipID === equipt.EquipID
      // );
      // this.sldEqupiments.splice(index, 1);
      this.isEQActiveEdit = false;
      this.isEQActiveAdd = true;
      this.isEQActiveDelete = false;
    }
    // --------------------------------------------------
   
    // else if(this.sldEqupiments.length > 1){
    //   this.isEQActiveEdit = false;
    //   this.isEQActiveAdd = false;
    //   this.isEQActiveDelete = true;
    // }
    // else{
    //   this.sldEqupiments=[]
    // }
    console.log(this.sldEqupiments);
    //this.sldCheckboxSelectionRowEquipmentList
   
  }

  /**
   * @method Method
   * @name selectActivityType
   * @param { Activity Type }
   * @description Set Activity Type
   */
  selectActivityType(type) {
    console.log(type);
    this.category = "";
    this.activityType = type;
    // --------------------------------------------------
    if (type === "Cardio") {
      if( this.sldUserType === "Quick"){
        this.addEQactivityTypeID = 1;
        this.clearValue();
        this.getVarientGenericEquipment(this.addEQactivityTypeID)
      }
      else{
        this.addEQactivityTypeID = 1;
        this.clearValue();
        this.getCategoryByActivityID(this.addEQactivityTypeID, "Add");
        
      }
  
    } 
    // --------------------------------------------------
    else if (type === "Strength") {
      if( this.sldUserType === "Quick"){
        this.addEQactivityTypeID = 2;
        this.clearValue();
        this.getVarientGenericEquipment(this.addEQactivityTypeID)
      }
      else{
        this.addEQactivityTypeID = 2;
        this.clearValue();
        this.getCategoryByActivityID(this.addEQactivityTypeID, "Add");
      }
      
    } 
    // --------------------------------------------------
    else if (type === "Functional") {

      if( this.sldUserType === "Quick"){
        this.addEQactivityTypeID = 6;
        this.clearValue();
        this.getVarientGenericEquipment(this.addEQactivityTypeID)
      }
      else{
        this.addEQactivityTypeID = 6;
        this.clearValue();
        this.getCategoryByActivityID(this.addEQactivityTypeID, "Add");
      }
    
    }
    // --------------------------------------------------
  }

  /**
   * @method Method
   * @name clearValue
   * @description Reset The Values
   */
  clearValue() {
    //this.addEquipForm.resetForm();
    // this.duration = "30";
    console.log(this.addEquipForm);
    
    this.variantList = [];
    this.categoryList = [];
    this.modalList = [];
    this.menuType = "";
    this.sldVarType = null;
    this.variantID = null;
    this.sldModalID = null;
    this.sldBrandID = null;
  }

  /**
   * @method Method
   * @name getCategoryByActivityID
   * @description Get All Category List
   */
  getCategoryByActivityID(sldActID, type) {
    this.categoryList = [];
// --------------------------------------------------
// API Call GET 
let activityType="All"
    const url = this.apiServer + "resource/getcategorytype/" + activityType;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
      this.categoryList = res;
      if (res.length > 0) {
        if (type !== "Update") {
          this.selectCategory(res[0]);
        } else {
          for (const CD of res) {
            if (CD.ID === this.sldEqupiments.EquipCatTypeID) {
              this.sldCategoryID = CD.ID;
              this.menuType = CD.Name;
              this.category = CD.Name;
             // this.getVariantByCategoryID(this.sldCategoryID, "Update");
              break;
            }
          }
        }
      }
    });
  }

   /**
   * @method Method
   * @name getQR ode
   * @description Get All QR code List
   */

  generateQRCode(){
    // --------------------------------------------------
    // --------------------------------------------------
    // GEnerate QR code API
    // GET APi

    const url = this.apiServer + "resource/assignqrcodetoasset/" + this.XBID ;
    //this.apiCall.makeGetApiCall(url).then((res: any) => {
     const data ={
       BID: this.XBID,
        } 
      console.log(data);
      this.apiCall.makePostApiCall(url,data).then((res: any) => {

        console.log(res);
// --------------------------------------------------
        if (res.status === "Success") {
          this.notificationService.showNotification("Success","Successfully Ordered QR Code");
          // this._notification.create("success", "Successfully Ordered QR Code", {
          //   Position: "top-right",
          //   Style: "flip bar",
          //   Duration: 3000,
          // });
          this.isAddEquipLoading = false;
        }
// --------------------------------------------------
        else {
          this.isAddEquipLoading = false;
          this.notificationService.showNotification("Error","Something Went Wrong");
          // this._notification.create("danger", res.error.message, {
          //   Position: "top-right",
          //   Style: "flip bar",
          //   Duration: 3000,
          // });
        }

    });
   
  }
  /**
   * @method Method
   * @name selectCategory
   * @description get Variant By Category ID
   */
  selectCategory(category) {
    this.variantList = [];
    console.log(category);

    if(this.isViewGroupEquipment===false) {
      this.sldTag=""
      this.sldTag="Default"
     }
      else{
          this.sldTag=""
       }
    this.menuType = category.Name;
    this.category = category.Name;
    this.sldCategoryID = category.ID;
    //this.getVariantByCategoryID(this.sldCategoryID, "Add");
  }
// -----------------------------------------------------------
  chooseMenu(menu) {
    this.menuType = menu;
  }

  /**
   * @method Method
   * @name getVariantByCategoryID
   * @description Get All Varients By Category ID
   */
  // getVariantByCategoryID(sldcatID, type) {
  //   this.modalList = [];
  //   // -----------------------------------------------------------
  //   // GET API Call

  //   const url = this.apiServer + "resource/getvariant/" + sldcatID;
  //   this.apiCall.makeGetApiCall(url).then((res: any) => {
  //     console.log(res);
  //     if (res.length > 0) {
  //       this.variantList = res;
  //       // this.dgFilters=this.dgFilters.reverse();
  //       let variantListAll=res[res.length-1];
  //      this.variantList.unshift(variantListAll)
  //      this.variantList.pop()

       
  //       this.totalVariant = res.length;
  //       if (type !== "Update") {
  //         this.selectVariant(res[0]);
  //       } else {
  //         for (const VD of res) {
  //           if (VD.ID === this.sldEqupiments.VariantID) {
  //             this.p = 1;
  //             this.sldVarType = VD.Name;
  //             this.variantID = VD.ID;
  //             this.variant = VD.Name;
  //             this.getModalandBrandByVarientID(this.variantID, "Update");
  //             break;
  //           }
  //         }
  //       }
  //     } 
  //  // -----------------------------------------------------------   
  //     else {
  //       this.totalVariant = 0;
  //     }
  //   });
  // }

  /**
   * @method Method
   * @name selectVariant
   * @description Select Variant
   */
  selectVariant(variant) {
    this.p = 1;
    console.log(variant);
    this.sldVarType = variant.Name;
    this.variantID = variant.ID;
    this.variant = variant.Name;
    this.getModalandBrandByVarientID(this.variantID, "Add");
  }

 /**
   * @method Method
   * @name getModalandBrandByVarientID
   * @description GET API getmodel
   */

  getModalandBrandByVarientID(varID, type) {
    this.modalList = [];
    const url =
      this.apiServer + "resource/getmodel/" + varID + "/" + this.sldCategoryID;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
      if (res.length > 0) {
        this.modalList = res;
      // --------------------------------------------------  
        if (type !== "Update") {
          this.selectProduct(res[0]);
        } else {
          for (const MBD of res) {
            if (MBD.ModelID === this.sldEqupiments.ModelID) {
              this.sldModalID = MBD.ModelID;
              this.sldBrandID = MBD.BrandID;
              this.brand = MBD.BrandName;
              this.model = MBD.ModelNumber;
              break;
            }
          }
        }
      } else {
      }
    });
  }

/**
   * @method Method
   * @name selectProduct
   * @description Select model iD ,brand name and mode; number etc..
   */

  selectProduct(pData) {
    console.log(pData);
    this.sldModalID = pData.ModelID;
    this.sldBrandID = pData.BrandID;
    this.brand = pData.BrandName;
    this.model = pData.ModelNumber;
  }

  /**
   * @method Method
   * @name triggerAddQuickEuipment
   * @description Form Submit Quick add equipment
   */
  triggerAddQuickEuipment(event){
    console.log("Quick Add Equipment")
    this.addQuickEquipForm.onSubmit(undefined);
    const button = (event.srcElement.disabled === undefined) ? event.srcElement.parentElement : event.srcElement;
    button.setAttribute('disabled', true);
    setTimeout(function () {
    button.removeAttribute('disabled');
    }, 1000);
    this.deselectactive()
  }
 /**
   * @method Method
   * @name addQuickEquipment
   * @Method POST
   * @description Save Quick Equipment Group
   */
  addQuickEquipment(){
    var equipData = {};
    let assetTag = Math.random().toString(36).substring(7);
    console.log("random", assetTag);
    const url = this.apiServer + "resource/insertassests";

    if(this.isViewGroupEquipment===false){
       equipData = {
        AssetTag: assetTag,
        BID: this.XBID,
        ActivitytypeID: this.addEQactivityTypeID,
        AssetTypeID: 1,
        PssnTypeID: 1,
        EquipCatID:  this.sldQuickAddcategoryID,
        EquipSrlNum: null,
        BrandID: this.sldBrandID,
        ModelID: this.sldModalID,
        VariantID: this.sldVarientId,
        AssetName: null,
        SlotDuration: this.slotDuration,
        SlotCapacity: this.capacity,
        PurchasePrice: null,
        PurchaseDate: null,
        RentalPrice: null,
        RentalStartDate: null,
        RentalEndDate: null,
        LeasePrice: null,
        LeaseStartDate: null,
        LeaseEndDate: null,
        WarrantyDuration: null,
        Quantity: this.quantity,
        EquipSlotDuration: this.slotDuration,
        EquipSlotCapacity: this.capacity,
        ActiveCount: this.quantity,
        InActiveCount: 0,
        DeletedCount: 0,
        GroupMode:"Default",
        GroupTag:"Default",
      };
    }
    else{
       equipData = {
        AssetTag: assetTag,
        BID: this.XBID,
        ActivitytypeID: this.addEQactivityTypeID,
        AssetTypeID: 1,
        PssnTypeID: 1,
        EquipCatID:  this.sldQuickAddcategoryID,
        EquipSrlNum: null,
        BrandID: this.sldBrandID,
        ModelID: this.sldModalID,
        VariantID: this.sldVarientId,
        AssetName: null,
        SlotDuration: this.slotDuration,
        SlotCapacity: this.capacity,
        PurchasePrice: null,
        PurchaseDate: null,
        RentalPrice: null,
        RentalStartDate: null,
        RentalEndDate: null,
        LeasePrice: null,
        LeaseStartDate: null,
        LeaseEndDate: null,
        WarrantyDuration: null,
        Quantity: this.quantity,
        EquipSlotDuration: this.slotDuration,
        EquipSlotCapacity: this.capacity,
        ActiveCount: this.quantity,
        InActiveCount: 0,
        DeletedCount: 0,
        GroupMode:"Manual",
        GroupTag:this.sldTag,
      };
    }
 
    console.log(equipData);
    this.apiCall.makePostApiCall(url, equipData).then((res: any) => {
      console.log(res);
// -----------------------------------------------
      if (res.status === "Success") {
        this.notificationService.showNotification("Success","Successfully Added");
        // this._notification.create("success", "Successfully Added", {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
       // this.addQickMachinesModal.hide();
        //this.addMachineTablet.hide();
        this.isAddEquipLoading = false;
        this.categoryType ="All"
        this.clearValue();
        this.addQuickEquipForm.resetForm()
        this.getEquipmentsByCategory("All");
        this.getEquipmentListView("All")
      } 
   // -----------------------------------------------   
      else {
        this.isAddEquipLoading = false;
        this.notificationService.showNotification("Error","Something Went Wrong");
        // this._notification.create("danger", res.error.message, {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      }
    });
  }


 

  /**
   * @method Method
   * @name getAllEquipmentbyActivityID
   * @Method GET
   * @description Get All Equipments
   */
  getAllEquipmentbyActivityID() {
    const url = this.apiServer + "resource/insertassests";
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
    });
  }



  //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  //
  //  SUB- METHODS
  //
  //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++



//------------------------------------------------------------------------ 
//------------------------------------------------------------------------ 

  /**
   * @method Method
   * @name selectEquipment
   * @description Select Equipments
   */
  selectEquipment(equipt) {
    console.log(equipt);
    this.sldAssetsList={}
    if(equipt===null){
      console.log(equipt);
      this.getAssets(null)
    }
    //-------------------------------------
    else{
      // this.total = this.sldEQDeActiveCount + this.sldEQDeletedCount + this.sldEQActiveCount;
      // this.updatePaths();
      console.log(equipt);
     // this.assetCurrentpage = 1;
      this.sldEquipID = equipt.EquipID;
      this.sldEQModalID = equipt.ModelID;
      this.sldEQBrandID = equipt.BrandID;
      this.mGroupquantity = equipt.TotalCount;
      this.isMachineProfile = true;
      this.isMachineTracker = false;
      this.sldEQTotal = equipt.TotalCount;
      this.sldEQActiveCount = equipt.ActiveCount;
      this.sldEQDeActiveCount = equipt.DeActiveCount;
      this.sldEQDeletedCount = equipt.DeletedCount;
      this.sldEQBrandName = equipt.BrandName;
      this.sldEQCatName = equipt.CategoryName;
      this.sldEQCatTypeID = equipt.EquipCatTypeID;
      this.sldEQVariantID = equipt.VariantID;
      this.sldEQActTypeID = equipt.ActivityTypeID;
      this.sldEQslotDuration = equipt.SlotDuration;
      this.sldEQslotCapacity = equipt.SlotCapacity;
      this.sldEQImage = equipt.Image;
      this.sldEQModalName = equipt.ModelNumber;
      this.sldEQVariantName = equipt.VariantName;
      this.machineViewType = "Stats";
     
      this.getAssets(equipt.EquipID);
    }
  this.showDeatails("commercial")
 
  

  }
  
  /**
   * @method Method
   * @name getAssets
   * @description Get All Assets By Equipment Id
   */
  getAssets(equipID) {
    if(equipID===null){
      this.allAssetsList = [];
      this.selectAssetbyAID("event",null);
    }
    else{
      this.allAssetsList = [];
      this.sldAssetId = null;
      this.isAssetActiveEdit = false;
      this.isActiveDelete = false;
      const url = this.apiServer + "resource/getassets/" + equipID;
      this.apiCall.makeGetApiCall(url).then((res: any) => {
        console.log(res);
        this.totalAssets = res.length;
        if (res.length > 0) {
          this.sldConfigureAssetsList=[]
          this.isMachineTracker = true;
          this.isMachineProfile = true;
          this.allAssetsList = res;
         this.selectAssetbyAID("event",res[0]);
         this.groupStat("Today",res[0]);
        }
        else{
        this.selectAssetbyAID("event",null);
        }
      });
    }
 
  }

  groupStat(durtn,value){
    this.duraion=durtn;

    
    console.log(value);
    let url=this.apiServer+"resource/getmachinegroupstats/" + value.BID +"/"+ value.EquipID +"/"+durtn ;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
      if(res.error&&res.error.success==false){
        this.groupStatCancelation=0
        this.groupStatDownTime=0
        this.groupStatLoad=0
        this.groupStatReservation=0
        this.groupStatWalkin=0 
      }
    else{
      this.groupStatCancelation=res.Cancellation
      this.groupStatDownTime=res.Downtime
      this.groupStatLoad=res.Load.reservationcount
      this.groupStatReservation=res.Reservation
      this.groupStatWalkin=res.Walkin
    }
     
    });  

  }

  /**
   * @method Method
   * @name selectAssetbyAID
   * @description Select Asset ID
   */
  selectAssetbyAID(event,assets) {
    console.log(assets)
     // --------------------------------------------------------
    if(assets!=null){
    this.sldAssetsList=assets
    this.selectedTagNo=""
    this.selectedTagNo=assets.AssetTag
    this.selectedTagSerialNo=""
    this.selectedTagSerialNo=assets.AssetSerailNo
    this.isActiveQRcode1=assets.isActive
    this.maintenanceType=assets.MaintenanceType
    this.selecedUIAID = assets.AssetID;
    this.sldEquipmentId=assets.EquipID;
     console.log(this.sldAssetsList)

     this.manufacturingNo=assets.AssetManufactureNo;
     this.purchaseDate=assets.PurchaseDate;
     this.price=assets.PurchasePrice;
 
    this.fileinfo=assets.AssetInvoice;
  

    this.sldQRCodePic=assets.QrCodePic
    //selecedUIAID
    this.isMachineTracker = true;
     this.getAssetsInfo(assets)
    this.getReservations(assets.AssetID); 
    this.getMachineProfile(assets.AssetID);
    // this.getServiceEquipmentList()
    // this.getRepairEquipmentList()
    this.chooseStats("Today","UID");
    }
     // --------------------------------------------------------
    else{
      this.noReservation = true;
      this.reservationsList = [];
      this.sldMachineProfileDetails = {};
      this.noMachineReservation=false
      this.manufacturingNo=null
      this.purchaseDate=""
      this.price=""
     this.warrantyDate=""
     this.fileinfo=""
      this.servicelast=""
     this.servicenext=""
 
     this.sldQRCodePic=""
    }
  }


   
/**
   * @method Method
   * @name oncheckAssest
   * @description toggle switch on and off
   */
  oncheckAssest(assets, event) {
    console.log(assets);
    this. selectAssetbyAID("event",assets)
    console.log(this.sldAssetsList);
    this.AssetID=assets.AssetID
    this.sldAssetDetails = assets;
    this.sldAssetId = assets.AssetID;
    const checked = event.target.checked;
//--------------------------------------------------------------------
// check assets value

    if (checked) {

      this.sldConfigureAssetsList.push(assets)
      this.sldDeleteAssetsList.push(assets.AssetID)
  //     if (assets.isActive === 1) {
  //       this.isAssetActiveEdit = true;
  //       this.sldAssetId = assets.AssetID;
  //       this.sldAssetSNO = assets.AssetSerailNo;
  //       this.isActiveDelete = false;
  //       return false;
  //     } 
  //  //--------------------------------------------------------------------   
  //     else {
  //       this.isAssetActiveEdit = true;
  //       this.isActiveDelete = true;
  //       this.sldAssetId = assets.AssetID;
  //       this.sldAssetSNO = assets.AssetSerailNo;
  //     }
    } 
  //--------------------------------------------------------------------  
    else {
      const index = this.sldConfigureAssetsList.findIndex(
        (eid) => eid.AssetID === assets.AssetID
        );
        this.sldConfigureAssetsList.splice(index, 1);

        const index1 = this.sldDeleteAssetsList.findIndex(
          (eid) => eid === assets.AssetID
          );
          this.sldDeleteAssetsList.splice(index1, 1);
    }

     console.log(this.sldDeleteAssetsList)

     for (let item of this.sldConfigureAssetsList) {
      if (item.selected) {  // Check if the item is selected
        if(item.isActive==1 && item.isConfigured==0){
          this.isActiveDelete=false;
          this.isAssetActiveEdit=true
        }
        else if(item.isActive==1 && item.isConfigured==1){
          this.isActiveDelete=false;
          this.isAssetActiveEdit=false
        }
        else{
          this.isActiveDelete=true;
          this.isAssetActiveEdit=false
        }
      }
    }






    if(this.sldConfigureAssetsList.length>0){
      for(let i of this.sldConfigureAssetsList){
        if(i.isActive==1 && i.isConfigured==0){
          this.isActiveDelete=false;
          this.isAssetActiveEdit=true
        }
        else if(i.isActive==1 && i.isConfigured==1){
          this.isActiveDelete=false;
          this.isAssetActiveEdit=false
        }
        else{
          this.isActiveDelete=false;
          this.isAssetActiveEdit=true;
        }

      }
    }
    else{
      this.isActiveDelete=false;
      this.isAssetActiveEdit=false
    }

   if(this.sldConfigureAssetsList.length>=1){
    this.isAssetActiveEdit = this.sldConfigureAssetsList.every(ele => ele.isConfigured === 0);
   }

    console.log(this.sldConfigureAssetsList)
  }

/**
   * @method Method
   * @name updateTransferAssetsStatus
   * @description Update transfer Assets
   */

updateTransferAssetsStatus(){

  let sldData={
    BID:this.XBID,
    Assetid: this.sldAssetId,
  }
  const url =
  this.apiServer +
  "resource/transferReservation";
  this.apiCall.makePostApiCall(url,sldData).then((res: any) => {
    console.log(res);

    if (res.status === "Success" && res.untransferredReservations.length==0) {
      this.notificationService.showNotification("Success","Successfully Transferred");
      // this._notification.remove()
      // this._notification.create("success", "Successfully Transferred", {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
      this.getEquipmentListView("All")
      this.updateAssetStatus("InActive");
     // this.ActiveConfirmModal.hide();
    }
    else{
      this.notificationService.showNotification("Error","Sorry we Could't transfer"  + res.untransferredReservations.length +  "Reservations, it will be cancel");
      // this._notification.remove()
      // this._notification.create("danger", "Sorry we Could't transfer"  + res.untransferredReservations.length +  "Reservations, it will be cancel", {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 5000,
      // });
      //this.ActiveConfirmModal.hide();
      this.updateAssetStatus("InActive");
    }
    });
}

getSliceRange(): number {
  return this.sldEQCatName.split('').length > 5 ? 7 : 9;
}

  /**
   * @method Method
   * @name updateAssetStatus
   * @description Update Assets
   */

  updateAssetStatus(value) {
    console.log(value);
    this.isUpdateEquitLoading = true;
    //--------------------------------------------------------------------
    // API Call updateassetstatus
    // GET 
    const url =
      this.apiServer +
      "resource/updateassetstatus/" +
      this.sldEquipID +
      "/" +
      this.sldAssetId +
      "/" +
      value +
      "/" +
      this.XBID +
      "/" +
      this.sldEQCatTypeID;
    //-------------------------------------------------------------------- 
    //-------------------------------------------------------------------- 
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
      if (res.status === "Success") {
        this.isActiveDelete = false;
        this.isActiveQRcode=res.type;
        if (res.type === "Active") {
          this.sldEQActiveCount = this.sldEQActiveCount + 1;
          this.sldEQDeActiveCount = this.sldEQDeActiveCount - 1;

          const newState = this.allequipMents.map((obj) =>
            obj.EquipID === this.sldEquipID
              ? {
                  ...obj,
                  ActiveCount: this.sldEQActiveCount,
                  DeActiveCount: this.sldEQDeActiveCount,
                }
              : obj
          );
          this.allequipMents = newState;

          const asstetState = this.allAssetsList.map((obj) =>
            obj.AssetID === this.sldAssetId ? { ...obj, isActive: 1 } : obj
          );
          this.allAssetsList = asstetState;
        } 
     //--------------------------------------------------------------------
     //--------------------------------------------------------------------   
        else {
          this.sldEQActiveCount = this.sldEQActiveCount - 1;
          this.sldEQDeActiveCount = this.sldEQDeActiveCount + 1;
          const newState = this.allequipMents.map((obj) =>
            obj.EquipID === this.sldEquipID
              ? {
                  ...obj,
                  ActiveCount: this.sldEQActiveCount,
                  DeActiveCount: this.sldEQDeActiveCount,
                  isActive: 0,
                }
              : obj
          );
          this.allequipMents = newState;

          const asstetState = this.allAssetsList.map((obj) =>
            obj.AssetID === this.sldAssetId ? { ...obj, isActive: 0 } : obj
          );
          this.allAssetsList = asstetState;
          console.log(this.allAssetsList);
          //this.ActiveConfirmModal.hide();
        }
//--------------------------------------------------------------------
//--------------------------------------------------------------------
        this.getReservations(this.sldAssetId);
        this.sldAssetId = null;
        if(this.inactiveType=="cancel"){
          this.notificationService.showNotification("Success","Successfully Status Updated");
        // this._notification.create("success", "Successfully Status Updated", {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      }
        this.getEquipmentListView("All")
      } 
    //--------------------------------------------------------------------  
      else {
        this.isUpdateEquitLoading = false;
        this.notificationService.showNotification("Error","Something Went Wrong");
        // this._notification.create("danger", res.error.message, {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      }
    });
  }

  /**
   * @method Method
   * @name incrementEQGroup
   * @description Increment Equipment Group
   */
  incrementEQGroup() {
    this.isUpdateEquitLoading = true;
    let assetTag = Math.random().toString(36).substring(7);
    console.log("random", assetTag);

    //--------------------------------------------------------------------
    // POST  API call updateasset

    const url = this.apiServer + "resource/updateasset/" + this.sldEquipID;
    const equipData = {
      AssetTag: assetTag,
      BID: this.XBID,
      EquipCatID: this.sldEQCatTypeID,
      VariantID: this.sldEQVariantID,
      BrandID: this.sldEQBrandID,
      ModelID: this.sldEQModalID,
      Quantity: this.mGroupquantity,
      EquipSlotDuration: this.sldEQslotDuration,
      EquipSlotCapacity: this.sldEQslotCapacity,
      ActivitytypeID: this.sldEQActTypeID,
      AssetTypeID: 1,
      PssnTypeID: 1,
      EquipSrlNum: null,
      AssetName: null,
      PurchasePrice: null,
      PurchaseDate: null,
      RentalPrice: null,
      RentalStartDate: null,
      RentalEndDate: null,
      LeasePrice: null,
      LeaseStartDate: null,
      LeaseEndDate: null,
      WarrantyDuration: null,
      activationStatus: this.activationStatus,
    };
    //--------------------------------------------------------------------
    console.log(equipData);
    this.apiCall.makePostApiCall(url, equipData).then((res: any) => {
      console.log(res);

      if (res.status === "Success") {
        this.isUpdateEquitLoading = false;
        this.sldEQTotal = this.sldEQTotal + this.mGroupquantity;
        this.sldEQActiveCount = this.sldEQActiveCount + this.mGroupquantity;
        if (this.activationStatus === "deActive") {
          this.sldEQDeActiveCount =
            this.sldEQDeActiveCount + this.mGroupquantity;
          this.sldEQActiveCount = this.sldEQActiveCount - this.mGroupquantity;
        }
        //--------------------------------------------------------------------
        this.notificationService.showNotification("Success","Successfully Added");
        // this._notification.create("success", "Successfully Added", {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
       // this.incrementGroupModal.hide();
        this.INCEQG.resetForm();
        this.getAssets(this.sldEquipID);
        this.getEquipmentsByCategory("All");
      } 
      //--------------------------------------------------------------------
      else {
        this.isUpdateEquitLoading = false;
        this.notificationService.showNotification("Error","Something Went Wrong");
        // this._notification.create("danger", res.error.message, {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      }
    });
  }

  /**
   * @method Method
   * @name cancelIncrement
   * @description resetForm and hide model
   */
  cancelIncrement() {
   // this.incrementGroupModal.hide();
    this.INCEQG.resetForm();
  }

  /**
   * @method Method
   * @name updateIEQ
   * @description activationStatus active and deactive
   */
  updateIEQ(event) {
    console.log(event.target.checked);
    if (event.target.checked === false) {
      this.activationStatus = "deActive";
    } else {
      this.activationStatus = "Active";
    }
  }

  deletewindowModel(){
   this.isModalOpenDelete=true
  }
  closewindowModel(){
    this.isModalOpenDelete=false
   }
  /**
   * @method Method
   * @name deleteAssets
   * @description Delete Assets
   */
  deleteAssets() {
    const url =
      this.apiServer +
      "resource/deleteassets/" +
      this.sldEquipID;
     

   // ---------------------------------------------------
   // GET API call deleteassets
      
    this.apiCall.makePostApiCall(url,this.sldDeleteAssetsList).then((res: any) => {
      console.log(res);
      if (res.status === "Success") {
        this.getAssets(this.sldEquipID);
        this.sldEQDeletedCount = this.sldEQDeletedCount + 1;
        this.sldEQDeActiveCount = this.sldEQDeActiveCount - 1;
// ---------------------------------------------------
// Map obj calling 
        const newState = this.allequipMents.map((obj) =>
          obj.EquipID === this.sldEquipID
            ? {
                ...obj,
                DeletedCount: this.sldEQDeletedCount,
                DeActiveCount: this.sldEQDeActiveCount,
              }
            : obj
        );
        // ---------------------------------------------------

        this.allequipMents = newState;
        this.isActiveDelete = false;
        this.isAssetActiveEdit = false;
        this.sldConfigureAssetsList =[]
        this.sldDeleteAssetsList=[]
        this.closewindowModel()
        this.notificationService.showNotification("Success","Selected" + this.sldAssetsList.CategoryName + "successfully deactivated.");
        // this._notification.create("success", "Successfully Deleted", {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      } else {
        this.notificationService.showNotification("Error","Something Went Wrong");
        // this._notification.create("danger", res.error.message, {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      }
    });
  }


 /**
   * @method Method
   * @name onChangePage
   * @description  assign pages per item
   */
  onChangePage(pageOfItems: Array<any>) {
    // update current page of items
    this.pageOfItems = pageOfItems;
  }
  /**
   * @method Method
   * @name triggerINCEQG
   * @description  Form Sumbit 
   */
  triggerINCEQG() {
    this.INCEQG.onSubmit(undefined);
  }

  /**
   * @method Method
   * @name openActiveModal
   * @description  show active confirmation model 
   */
  openActiveModal() {
    this.getinactiveCount();
   // this.ActiveConfirmModal.show();
  }
  /**
   * @method Method
   * @name cancelInactive
   * @description  map new state assiagn to all assets list
   */

  cancelInactive() {
    const newstate = this.allAssetsList.map((obj) =>
      obj.AssetID === this.sldAssetId ? { ...obj, isActive: 1 } : obj
    );
    this.allAssetsList = newstate;
   // this.ActiveConfirmModal.hide();
    this.getEquipmentListView("All")
  }

  /**
   * @method Method
   * @name getinactiveCount
   * @description  API call GET getreservationcountassets
   */

  getinactiveCount() {
    // --------------------------------------------------------
    // Call GET API getreservationcountassets
    const url =
      this.apiServer +
      "resource/getreservationcountassets/" +
      this.sldAssetId +
      "/" +
      this.XBID +
      "/" +
      this.sldEQCatTypeID;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
      this.reservationCount = res.reservationCount;
    });
     // --------------------------------------------------------
  }

  updateStatusTransfer(value){
  this.inactiveType=value;
  }
/**
   * @method Method
   * @name updateInactiveStatus
   * @description  update assets passing inactive
   */
  updateInactiveStatus() {
    if(this.inactiveType=="cancel"){
      this.updateAssetStatus("InActive");
    }
    else{
      this.updateTransferAssetsStatus();
    }
  }




   /**
   * @method function
   * @name getAssetsInfo
   * @HttpMethod GET
   * @description Get Reservation by Asset ID
   */

   getAssetsInfo(value) {
    

  const DATETIME = new Date();
  let currentDateTime =this.datePipe.transform(DATETIME, 'HH:mm')
 // let currentDateTime =this.datePipe.transform(today, 'HH')
 
  let todayDateForSlot=moment(DATETIME).format("YYYY-MM-DD");
   // this.sldAssetsList={}
    // --------------------------------------------------------
    // GET API Call getreservation for assets
    const url =
      this.apiServer +
      "resource/getassetinfo/" +
      this.selecedUIAID + "/" + value.isConfigured + "/" + todayDateForSlot + "/" + currentDateTime + "/" + this.userID;
  
     
    this.apiCall.makeGetApiCall(url).then((res: any) => {
       // --------------------------------------------------------
      console.log(res);
        this.sldAssetsList=res;
        this.manufacturingNo=res.AssetManufactureNo;
        this.purchaseDate=res.PurchaseDate;
        this.price=res.PurchasePrice;
       this.warrantyDate=res.WarrantyDate;
       this.fileinfo=res.AssetInvoice;
        this.servicelast=res.LastServiceDate;
       this.servicenext=res.NextServiceDate;
       this.priceImage=res.ModelImage
    });
    console.log(this.sldAssetsList)
  }
  
  /**
   * @method function
   * @name getReservations
   * @HttpMethod GET
   * @description Get Reservation by Asset ID
   */

  getMachineProfile(AID) {
    this.noMachineReservation=true
    this.noReservation = false;
    this.sldMachineProfileDetails = {};
    // --------------------------------------------------------
    // GET API call getassersdetails

    const url = this.apiServer + "resource/getassetsdetails" + "/" + AID;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
    
      

      this.sldMachineProfileDetails = res;
      this.isActiveQRcode1=res.isActive
   
    });
  }

  /**
   * @method function
   * @name selectViewType
   * @description seleced Machine View Type
   */
  selectViewType(type) {
    console.log(type);
    this.machineViewType = type;
    if(type=="Profile"){
      const body = document.getElementsByTagName("body")[0];
      body.classList.add("profilemenu");
      body.classList.remove("statmenu");
    }
    else if(type=="Stats"){
      const body = document.getElementsByTagName("body")[0];
      body.classList.add("statmenu");
      body.classList.remove("profilemenu");
    }
    else{
      const body = document.getElementsByTagName("body")[0];
      body.classList.remove("profilemenu");
      body.classList.remove("statmenu");
    }

  }

  /**
   * @method Function
   * @name backToNormal
   * @description back button while expand width of screen 
   */

  backToNormal(){
    const body = document.getElementsByTagName("body")[0];
    body.classList.remove("profilemenu");
    body.classList.remove("statmenu");
    //console.log(this.isscheduleActive==false)
    //if(this.isscheduleActive==false){
    //   this.isscheduleActive=true;
    // this.classViewType=""
   // }
   
  }
  /**
   * @method function
   * @name updateMachine
   * @HttpMethod POST
   * @description Update Machine
   */

  updateMachine() {
    var updateDate = {};

    if(this.isViewGroupEquipment===false){
      console.log(this.sldCheckboxSelectionRowEquipmentList);
      if (this.purchaseType === "Rental") {
        updateDate = {
          AssetTag: this.tagname,
          AssetID: this.sldCheckboxSelectionRowEquipmentList.AssetID,
          AssetSerailNo: this.sldCheckboxSelectionRowEquipmentList.AssetSerailNo,
          AssetManufactureNo: this.SRNumber,
          BID: this.XBID,
          PurchasePrice: null,
          PurchaseDate: null,
          RentalPrice: this.price,
          RentalStartDate: this.datePipe.transform(this.startDate, "yyyy-MM-dd"),
          RentalEndDate: this.datePipe.transform(this.endDate, "yyyy-MM-dd"),
          LeasePrice: null,
          LeaseStartDate: null,
          LeaseEndDate: null,
          PssnTypeID: 2,
        };
         
      } 
      else if (this.purchaseType === "Lease") {
        updateDate = {
          AssetTag: this.tagname,
          AssetID: this.sldCheckboxSelectionRowEquipmentList.AssetID,
          AssetSerailNo:  this.sldCheckboxSelectionRowEquipmentList.AssetSerailNo,
          AssetManufactureNo: this.SRNumber,
          BID: this.XBID,
          PurchasePrice: null,
          PurchaseDate: null,
          RentalPrice: null,
          RentalStartDate: null,
          RentalEndDate: null,
          LeasePrice: this.price,
          LeaseStartDate: this.datePipe.transform(this.startDate, "yyyy-MM-dd"),
          LeaseEndDate: this.datePipe.transform(this.endDate, "yyyy-MM-dd"),
          PssnTypeID: 3,
        };
         
      } 
      else {
        updateDate = {
          AssetTag: this.tagname,
          AssetID: this.sldCheckboxSelectionRowEquipmentList.AssetID,
          AssetSerailNo:  this.sldCheckboxSelectionRowEquipmentList.AssetSerailNo,
          AssetManufactureNo: this.SRNumber,
          BID: this.XBID,
          PurchasePrice: this.price,
          PurchaseDate: this.datePipe.transform(this.startDate, "yyyy-MM-dd"),
          RentalPrice: null,
          RentalStartDate: null,
          RentalEndDate: null,
          LeasePrice: null,
          LeaseStartDate: null,
          LeaseEndDate: null,
          PssnTypeID: 1,
        };
      }
    }

  
    else{
    // ----------------------------------------------
    if (this.purchaseType === "Rental") {
      updateDate = {
        AssetTag: this.tagname,
        AssetID: this.sldAssetId,
        AssetSerailNo: this.sldAssetSNO,
        AssetManufactureNo: this.SRNumber,
        BID: this.XBID,
        PurchasePrice: null,
        PurchaseDate: null,
        RentalPrice: this.price,
        RentalStartDate: this.datePipe.transform(this.startDate, "yyyy-MM-dd"),
        RentalEndDate: this.datePipe.transform(this.endDate, "yyyy-MM-dd"),
        LeasePrice: null,
        LeaseStartDate: null,
        LeaseEndDate: null,
        PssnTypeID: 2,
      };
       
    } 
     // ----------------------------------------------
    else if (this.purchaseType === "Lease") {
      updateDate = {
        AssetTag: this.tagname,
        AssetID: this.sldAssetId,
        AssetSerailNo: this.sldAssetSNO,
        AssetManufactureNo: this.SRNumber,
        BID: this.XBID,
        PurchasePrice: null,
        PurchaseDate: null,
        RentalPrice: null,
        RentalStartDate: null,
        RentalEndDate: null,
        LeasePrice: this.price,
        LeaseStartDate: this.datePipe.transform(this.startDate, "yyyy-MM-dd"),
        LeaseEndDate: this.datePipe.transform(this.endDate, "yyyy-MM-dd"),
        PssnTypeID: 3,
      };
       
    } 
     // ----------------------------------------------
    else {
      updateDate = {
        AssetTag: this.tagname,
        AssetID: this.sldAssetId,
        AssetSerailNo: this.sldAssetSNO,
        AssetManufactureNo: this.SRNumber,
        BID: this.XBID,
        PurchasePrice: this.price,
        PurchaseDate: this.datePipe.transform(this.startDate, "yyyy-MM-dd"),
        RentalPrice: null,
        RentalStartDate: null,
        RentalEndDate: null,
        LeasePrice: null,
        LeaseStartDate: null,
        LeaseEndDate: null,
        PssnTypeID: 1,
      };
    }

  }
     // ----------------------------------------------
    this.isLoading = true;
    console.log(this.sldAssetId);
    const url = this.apiServer + "resource/updateassetsdetails";

    console.log(updateDate);
     // ----------------------------------------------
     // API CAll

    this.apiCall.makePostApiCall(url, updateDate).then((res: any) => {
      console.log(res);
      if (res.status === "Success") {
        this.getEquipmentListView("All");
        this.isMachineTracker = false;
        this.selecedUIAID = null;
        this.sldGroupID=null;
        this.isAssetActiveEdit = false;
        this.machineViewType = "Stats";
        this.getAssets(this.sldEquipID);
       // this.updateMachineModal.hide();
        this.upmForm.resetForm();
        this.sldAssetId = null;
        this.isLoading = false;
      } else {
        this.isLoading = false;
      }
    });
  }
 /**
   * @method function
   * @name openUpdateModal
   * @description seleced AssetDetails
   */
  openUpdateModal() {
   if(this.isViewGroupEquipment===false){
    this.isLoading = false;
    this.endDate=null
   // this.updateMachineModal.show();
    console.log(this.sldCheckboxSelectionRowEquipmentList);
    this.SRNumber = this.sldCheckboxSelectionRowEquipmentList.AssetManufactureNo;
    this.tagname = this.sldCheckboxSelectionRowEquipmentList.AssetTag;
// -----------------------------------------------------------------------
    this.sldCheckboxSelectionRowEquipmentList.PssnTypeID === 1

      ? (((this.purchaseType = "Purchase"),
        (this.price = this.sldCheckboxSelectionRowEquipmentList.PurchasePrice)),
        (this.startDate = new Date(this.sldCheckboxSelectionRowEquipmentList.PurchaseDate)))

      : this.sldCheckboxSelectionRowEquipmentList.PssnTypeID === 2

      // -----------------------------------------------------------------------

      ? (((this.purchaseType = "Rental"),
        (this.price = this.sldCheckboxSelectionRowEquipmentList.RentalPrice)),
        (this.startDate = new Date(this.sldCheckboxSelectionRowEquipmentList.RentalStartDate)),
        (this.endDate = new Date(this.sldCheckboxSelectionRowEquipmentList.RentalEndDate)))

      : this.sldCheckboxSelectionRowEquipmentList.PssnTypeID === 3

      // -----------------------------------------------------------------------
      ? ((this.purchaseType = "Lease"),
        (this.price = this.sldCheckboxSelectionRowEquipmentList.LeasePrice),
        (this.startDate = new Date(this.sldCheckboxSelectionRowEquipmentList.LeaseStartDate)),
        (this.endDate = new Date(this.sldCheckboxSelectionRowEquipmentList.LeaseEndDate)))

      : null;

   }


else{
     this.endDate=null
    console.log(this.sldAssetDetails);
    this.SRNumber = this.sldAssetDetails.AssetManufactureNo;
    this.sldAssetDetails.PssnTypeID === 1
// -----------------------------------------------------------------------
      ? (((this.purchaseType = "Purchase"),
        (this.price = this.sldAssetDetails.PurchasePrice)),
        (this.startDate = new Date(this.sldAssetDetails.PurchaseDate)))
      : this.sldAssetDetails.PssnTypeID === 2
      // -----------------------------------------------------------------------
      ? (((this.purchaseType = "Rental"),
        (this.price = this.sldAssetDetails.RentalPrice)),
        (this.startDate = new Date(this.sldAssetDetails.RentalStartDate)),
        (this.endDate = new Date(this.sldAssetDetails.RentalEndDate)))
      : this.sldAssetDetails.PssnTypeID === 3
      // -----------------------------------------------------------------------
      ? ((this.purchaseType = "Lease"),
        (this.price = this.sldAssetDetails.LeasePrice),
        (this.startDate = new Date(this.sldAssetDetails.LeaseStartDate)),
        (this.endDate = new Date(this.sldAssetDetails.LeaseEndDate)))
      : null;
      // -----------------------------------------------------------------------
    this.isLoading = false;
    // this.purchaseType = "Purchase";
   // this.updateMachineModal.show();
    this.tagname = this.sldAssetDetails.AssetTag;
}
}


  /**
   * @method function
   * @name   closeUpdateModal
   * @description Form Update machine model close
   */
  closeUpdateModal() {
   // this.updateMachineModal.hide();
    this.isLoading = false;
    this.sldGroupID=null;
  }
/**
   * @method function
   * @name   triggerUpdateMachine
   * @description Form Update machine submit
   */
  triggerUpdateMachine() {
    this.upmForm.onSubmit(undefined);
  }
/**
   * @method function
   * @name   onStartDateChange(date) 
   * @description 
   */
  onStartDateChange(date) {
    console.log(date);
  }
/**
   * @method function
   * @name onEndDateChange
  
   * @description 
   */
  onEndDateChange(date) {
    console.log(date);
  }
/**
   * @method function
   * @name selectPurchaseType
  
   * @description Update purchaseType
   */
  selectPurchaseType(type) {
    this.purchaseType = type;
    if (this.purchaseType === "Purchase") {
      this.endDate = null;
    }
  }



 
  /**
   * @method function
   * @name addTabviewMachinesModalShow
   * @description Get add EQactivity Type ID
   */
  addTabviewMachinesModalShow() {
     // ----------------------------------------------
    this.addEQactivityTypeID = this.catactivityTypeID;
    console.log(this.addEQactivityTypeID);
    if (this.addEQactivityTypeID === 1) {
      this.activityType = "Cardio";
    } else if (this.addEQactivityTypeID === 2) {
      this.activityType = "Strength";
    } else {
      this.activityType = "Cardio";
    }
    //this.chooseQuickORCustomModal.show()
    //this.addMachineTablet.show();
    this.getCategoryByActivityID(this.addEQactivityTypeID, "Add");
  }
  /**
   * @method function
   * @name activeView
   * @description isActiveCatList flag set to true
   */
  activeView() {
    this.isActiveCatList = true;
  }
    /**
   * @method function
   * @name confirm
   * @description isActiveCatList flags set to false
   */
  confirm() {
    this.isActiveCatList = false;
  }

  /**
   * @method function
   * @name updateEQShowModal
   * @description Show Equipment Update Modal
   */
  updateEQShowModal() {
    this.isUpdateEQGroup = true;
    console.log(this.sldEqupiments);
    this.quantity = this.sldEqupiments.TotalCount;
    this.addEQactivityTypeID = this.sldEqupiments.ActivityTypeID;
    this.slotDuration = this.sldEqupiments.SlotDuration;
    this.capacity = this.sldEqupiments.SlotCapacity;
    //this.sldTag=""
    this.sldTag=this.sldEqupiments.GroupTag;
    console.log(this.addEQactivityTypeID);
    // ------------------------------------------
    if (this.addEQactivityTypeID === 1) {
      this.activityType = "Cardio";
    } else if (this.addEQactivityTypeID === 2) {
      this.activityType = "Strength";
    } else {
      this.activityType = "Cardio";
    }
// ------------------------------------------
   // this.addMachinesModal.show();
    this.getCategoryByActivityID(this.addEQactivityTypeID, "Update");
    this.sldGroupID = null;
  }

  /**
   * @method function
   * @name getGroupResrvation
   * @description get Group Reservation
   */
  getGroupResrvation() {
    // ------------------------------------------
    // API Call getequipmentgroupreservation
    const url =
      this.apiServer +
      "resource/getequipmentgroupreservation/" +
      this.sldEqupiments.EquipID;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
      res.status === "Success" && res.Count !== 0
        ? null //this.machineGroupWarning.show()
        : this.updateEQGroup();
    });
  }
/**
   * @method function
   * @name applyTypeFun
   
   */
  applyTypeFun(type) {
    this.applyType = type;
  }
  /**
   * @method function
   * @name updateEQGroup
   * @description update Equipment Group
   */
  updateEQGroup() {
    if(this.sldTag==="" || this.capacity==null){
      this.notificationService.showNotification("","Please fill all the details");
      // this._notification.create("danger","Please fill all the details", {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
      return false;
    }
    // ------------------------------------------
    console.log(this.applyType);
    // return false;
    this.isAddEquipLoading = true;
    // ------------------------------------------
    // POST API Call updateequipmentgroup

    const url = this.apiServer + "resource/updateequipmentgroup";
    const UED = {
      EquipGrpID: this.sldEqupiments.EquipID,
      BID: this.XBID,
      EquipCatID: this.sldEqupiments.EquipCatTypeID,
      VariantID: this.variantID,
      BrandID: this.sldBrandID,
      ModelID: this.sldModalID,
      EquipSlotCapacity: this.capacity,
      IsDelete: this.applyType,
      GroupMode:"Manual",
      GroupTag:this.sldTag,
    };
    // ------------------------------------------
    console.log(UED);
    this.apiCall.makePostApiCall(url, UED).then((res: any) => {
      if (res.status === "Success") {
        this.sldEqupiments = [];
      //  this.addMachinesModal.hide();
       // this.addMachineTablet.hide();
       // this.machineGroupWarning.hide();
        this.isAddEquipLoading = false;
        this.isEQActiveEdit = false;
        this.isEQActiveDelete = false;
        this.isEQActiveAdd = true;
        this.clearValue();
        this.getEquipmentsByCategory("All");
        this.notificationService.showNotification("Success","Successfully Updated");
        // this._notification.create("success", "Successfully Updated", {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
      }
    });
  }

  /**
   * @method function
   * @name deleteClassGroup
   * @description Delete Class Groip
   */
  deleteEquipmentGroup() {
    // ------------------------------------------
    // GET API CALl deleteequipmentgroup
    if(this.isViewGroupEquipment===true){
      const url =
      this.apiServer +
      "resource/deleteequipmentgroup/" +
      this.sldEqupiments.EquipID + "/" + this.XBID;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
      res.status === "Success"
        ?((this.refreshCard("EQPG")),
        (this.refreshCard("EQML")),(this.equtGRPPage=1),
          (this.isEQActiveEdit = false),
         // this.warningModel.hide(),
          (this.isEQActiveAdd = true),
          (this.isEQActiveDelete = false),
          (this.sldEqupiments = []))
        : null;
    });
    }
    else{
    //  http://demo.minute.fit/api/resource/deleteassets/3561/39344
      const urlDelete =
      this.apiServer +
      "resource/deleteassets/" +
      this.sldCheckboxSelectionRowEquipmentList.EquipGrpID + "/" + this.sldCheckboxSelectionRowEquipmentList.AssetID ;

      this.apiCall.makeGetApiCall(urlDelete).then((res: any) => {
        console.log(res);
        res.status === "Success"
          ? (this.getEquipmentListView("All"),(this.equtGRPPage=1),
            (this.isEQActiveEdit = false),
           // this.warningModel.hide(),
            (this.isEQActiveAdd = true),
            (this.isEQActiveDelete = false),
            (this.sldCheckboxSelectionRowEquipmentList = []))
          : null;
      });
    }
   
  }
 /**
   * @method function
   * @name activecalenderView
   * @description navigate calander 
   */
  activecalenderView() {
    this.router.navigateByUrl("/resource/machine/calender");
  }
 /**
   * @method function
   * @name checkInQRCode
   * @description CAll API service file  
   */
  checkInQRCode() {
    console.log(this.sldEQslotDuration);
    const DATETIME = new Date();
    console.log(DATETIME);
    const currentTime = this.datePipe.transform(DATETIME, "HH:mm:ss");
    const date = this.datePipe.transform(new Date(), "yyyy-MM-dd");
    //this.resourceSVC
      // .userCheckInOutEquip(this.userID, date, currentTime, this.selecedUIAID)
      // .subscribe((res: any) => {
      //   console.log(res);
      //   this.checkInStatus = res.type;
      //   this.checkResnID = res.resvnID;
      //   this.checkInMsg = res.message;
      //  // this.checkINOut.show();
      //   this.isViewAccessRestricton=false
      // });
      this.getEquipmentListView("All")
  }
 /**
   * @method function
   * @name saveCheckIn
   * @description CAll subscribe file  
   */
  saveCheckIn() {
    console.log(this.checkResnID);
    const DATETIME = new Date();
    console.log(DATETIME);
    const currentTime = this.datePipe.transform(DATETIME, "HH:mm");
    const date = this.datePipe.transform(new Date(), "yyyy-MM-dd");
    var slotD = 1;
    this.sldEQslotDuration == 30 ? (slotD = 2) : null;

    if(this.sldAssetsList.ReservedSpot==0){
      this.checkInStatus="New-Reservation"
      this.checkResnID=null
    }
    else if(this.sldAssetsList.ReservedSpot==1 && this.sldAssetsList.Checkin==0 && this.sldAssetsList.Checkout==0){
      this.checkInStatus="Start-Workout"
      this.checkResnID=this.sldAssetsList.EquipResvnID
    }
    else if(this.sldAssetsList.ReservedSpot==1 && this.sldAssetsList.Checkout==0 && this.sldAssetsList.Checkin !=0 ){
      this.checkInStatus="Stop-Workout"
      this.checkResnID=this.sldAssetsList.EquipResvnID
    }

    const URI =
    this.apiServer +
    "reservation/usercheckinandout/" + this.userID + "/" + date + "/" + currentTime + "/" + this.selecedUIAID + "/" + this.checkInStatus + "/" +
    this.checkResnID + "/" + slotD + "/" + this.XBID;
    this.apiCall.makeGetApiCall(URI).then((res: any) => {
      console.log(res);
    if (res.status === "Success") {
        this.isModalOpen=false;
        this.getAssets(this.sldEquipID)

        if(this.sldAssetsList.ReservedSpot==0){
          this.notificationService.showNotification("Success","InCheck In successfully done forequipment."); // Show error message in notification
        }
        else if(this.sldAssetsList.ReservedSpot==1 && this.sldAssetsList.Checkin==0 && this.sldAssetsList.Checkout==0){
          this.notificationService.showNotification("Success","Checked InCheck In successfully done forequipment.."); // Show error message in notification
        }
        else if(this.sldAssetsList.ReservedSpot==1 && this.sldAssetsList.Checkout==0 && this.sldAssetsList.Checkin !=0 ){
          this.notificationService.showNotification("Success","Checked Out Check Out successfully done for equipment...");
        }

        //  this.isViewAccessRestricton=false
        //  this.isCheckError=false
        //  this.getEquipmentListView("All")
        }
   
      
    });


}

 
  /**
   * @func       closeclassConflictModal
   * @desc   Close Conflict Window Modal
   */


  closeclassConflictModal()
  {
    this.isCheckError=false
    //this.ActiveClassConflictModal.hide();
  }


  
  // ------------------------------------------------
  // Open and close conflict Window
    /**
   * @method function
   * @name openConflictModal
   * @description conflict window open
   */
  openConflictModal() {
    this.isCheckError = true;
   // this.ActiveConflictModal.show();
  }
  /**
   * @method function
   * @name closeConflictModal
   * @description conflict window hide
   */
  closeConflictModal()
  {
    //this.ActiveConflictModal.hide();
  }

 /**
   * @method function
   * @name onEquipmentPage
   * @description Pagination
   */

  onEquipmentPage(page){

      console.log(page)
      this.equtGRPPage=page
      for (const i of this.allequipMents) {
      for (const mc of this.sldEqupiments) {
      i.EquipID == mc.EquipID ? i.checked = true : null ;
      }
    }

  }
// ----------------------------------------------------------------------------------------
// New FEatures Group and List View Equipment Start...........................
//----------------------------------------------------....................
//-----------------------------------------------------......................
//isViewGroupEquipment

/**
   * @method function
   * @name getEquipmentView
   * @description Pagination
   */

getEquipmentView(event,val) {
console.log(val);
console.log(event);
this.sldGroupID=null

if(event==="Group"){
  this.typeList="Group"
this.getEquipmentsByCategory("All")
this.isViewGroupEquipment=true;
this.isViewListEquipment=false;
this.isEQActiveEdit=false;
this.isEQActiveDelete=false;
this.isEQActiveAdd=true;
}
else if(event==="Machine"){
  this.typeList="Machine"
this.machineViewType ='Stats';
 this.getEquipmentListView("All")
 this.getClasViewCount()
this.isViewGroupEquipment=false;
this.isViewListEquipment=true;
this.isEQActiveEdit=false;
this.isEQActiveDelete=false;
this.isEQActiveAdd=true;
}

}

refreshCardForListView(){
  this.sldGroupAssetID=null
    this.sldEqupiments=[]
    this.sldCheckboxSelectionRowEquipmentList = [];
    this.isEQActiveEdit=false;
    this.isEQActiveDelete=false;
    this.isEQActiveAdd=true
  this.getEquipmentListView("All")
}
// ----------------------------------------
// ----------------------------------------
 /**
   * @method Method
   * @name selectEquipmentForListView
   * @description Select Equipments in List View
   */
selectEquipmentForListView(equipt)  {
console.log(equipt)
this.showDeatails("commercial")

this.sldEquiptIDForListView=equipt.AssetID
this.selectedModelImage=""
this.selectedTagNo=""
this.selectedManufactureNo=""
this.selectedTagSerialNo=""
this.selectedModelNo=""
this.selectedQRCode=""
this.selecedUIAID=null
this.sldAssetsList=equipt
this.selecedUIAID=equipt.AssetID
this.selectedModelImage=equipt.ModelImage
this.selectedTagNo=equipt.AssetTag
this.sldEQCatName=equipt.CategoryName;
this.selectedTagSerialNo=equipt.AssetSerailNo
this.selectedManufactureNo=equipt.AssetManufactureNo
this.selectedModelNo=equipt.ModelNumber
this.selectedQRCode=equipt.QrCodePic
this.sldQRCodePic=equipt.QrCodePic
this.sldEQImage=equipt.CategoryImage
this.sldGroupAssetID=null
this.getAssetsInfo(equipt)
this.chooseStats("Today","UID");
this.getReservations(this.sldEquiptIDForListView);
this.getMachineProfile(this.sldEquiptIDForListView);

let value=0
this.getServiceEquipmentList(value)
this.getRepairEquipmentList(value)
}





// Access Restrictions for machine
// checking menu and submenu 
// checking role of the user then stores value of restriction based on value will binding
// into hTml and added style
 // -------------------------------------------------------- 
 getGymRole() {
  const url =this.apiServer +
  "businessacount/getgymroleaccessforuser/" + this.XBID + "/"+ this.userID 

  this.apiCall.makeGetApiCall(url).then((res: any) => {
    console.clear()
    console.log(res)

  for(let i of res){

  //  if(i.Menu=="Dashboard" && i.Submenu =="Dashboard"){
  //   this.DashboardAccess=i.AccessLevel; 
  //  }

// Resource Module
if(i.RoleName==this.userDetails.role){
 if(i.Menu=="Resource" && i.Submenu=="Equipments"){
  this.resourceequipmentAccess=i.AccessLevel;
 }
}
else{

}
  }
   

  });
  
}
// ----------------------------------------------------------------------------------------
// New FEatures Group and List View Equipment End.........................................
//----------------------------------------------------...................
//-----------------------------------------------------....................
oncheckShowModelBrand(event){
  const checked = event.target.checked;
  if(checked){
    this.IsShowModelBrand=true
  }
  else{
    this.IsShowModelBrand=false
  }
}

// getClasViewCount
// checking count of machine view active ,deleted and deactivated 

 // -------------------------------------------------------- 
getClasViewCount(){
  this.sldEQTotal=""
  this.sldEQActiveCount=""
  this.sldEQDeActiveCount=""
  this.sldEQDeletedCount=""

  const url =this.apiServer +
  "resource/getassetcurrentstats/" + this.XBID;

  this.apiCall.makeGetApiCall(url).then((res: any) => {
    // console.clear()
    console.log(res)
  this.sldEQTotal=res[0].TotalCount
  this.sldEQActiveCount=res[0].ActiveCount
  this.sldEQDeActiveCount=res[0].DeactivatedCount
  this.sldEQDeletedCount=res[0].DeletedCount
  });

}

}
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
