import React, { useEffect, useState } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { Popconfirm, Tooltip } from 'antd';
import { AiOutlineClose, AiFillDelete } from 'react-icons/ai';
import { PlusOutlined } from '@ant-design/icons';
import {
  SelectedGlobalBillingColorDetail,
  SelectedGlobalBillingFont,
  getTemplateData,
  StoredSessionData,
} from '../../../../../Features/ThemeChange/ThemeChange';
import {
  GlobalOrderCardDetails,
  changeOrderCardDetails,
  GlobalBookingType,
  GlobalPreviousOrderLength,
  GlobalHoldOrderDtl,
  GlobalUnpaidData,
  ChangeSelectedCustDisable,
  changeReorderHoldDetails,
  changeUnpaidData,
  changeSelectedOption,
  changeBookingType,
  GlobalSelProdWiseEst,
  GlobalBookingTypeBoth,
  GlobalOrderType,
  changeothersdata,
  changeReorderProductDetails,
  GlobalReorderHoldDetails,
  getSelectedFavItems,
  getLayoutproductCard,
  getCardDataWithoutSubmodule,
  getCardDataWithoutSub,
  changeOrderType,
  GlobalProductCategorie,
  GlobalProductSubCategorie,
  GlobalReorderProductDetails,
  changeAllProductTokenAvailable,
  changeTokenOnly,
  PreferenceData,
  GlobalEstimateBooking,
  ChangeOverAllDiscSales,
  ChangeOverAllDiscEstimate,
  changeSelProdWiseEst,
  getPreferenceData,
  GlobalOtherSevices,
  GlobalDefaultBookingType,
} from '../../../../../Features/BookingScreen/BookingData/BookingData';
import {
  ChangeFullFreeProductList,
  changeFullOfferAppliedProducts,
  ClearOfferAppliedProducts,
  GlobalFreeProdList,
  GlobalOfferAppliedProducts,
} from '../../../../../Features/Offer/Offernew/BookingOffernew.js';
import {
  ChangeTotalAmount,
  globalExtraTotalAmount,
} from '../../../../../Features/ExteraCharges/ExtraCharges.js';
import BSBillingEditQuantity from '../BSBillingEditQuantity/BSBillingEditQuantity';
import WebFont from 'webfontloader';
import { isMobile } from 'react-device-detect';
import dineInIcon from '../../../../../Images/Dine In.svg';
import TakeAwayIcon from '../../../../../Images/Take away.svg';
import {
  changeholddata,
  gettinghold,
  puttinghold,
} from '../../../../../Features/BookingScreen/HoldOption/HoldOption.js';
import { useApplyOfferto_CardDetail } from '../../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx';
import { getCustomerDisplayWindow } from '../../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
import BSEditTotalAmt from '../BSEditTotalAmount/BSEditTotalAmt.jsx';
import BSImeiDetails from '../BSImeiDetails/BSImeiDetails.jsx';
import { useUtilsComponent } from '../../../../../Services/utils.js';

const BsBill = () => {
  const { removeExtraCharge } = useUtilsComponent();
  const dispatch = useDispatch();
  const applyOffer = useApplyOfferto_CardDetail();
  const preferenceDatas = useSelector(PreferenceData);
  const preferenceOffer =
    preferenceDatas?.[0]?.['SettingDtlDetails']?.find(
      (item) => item.SettingIdName === 'Offer'
    )?.SettingValue === 'Y';
  const SessionData = useSelector(StoredSessionData);
  const BranchId = SessionData?.BranchId;
  const AppId = SessionData?.AppId;
  const CompId = SessionData?.CompId;
  const GlobalOfferAppliedProductsData = useSelector(
    GlobalOfferAppliedProducts
  );
  const OfferFreeProduct = useSelector(GlobalFreeProdList, shallowEqual);
  const ReorderProductData = useSelector(GlobalReorderProductDetails);
  const SelectedBillColor = useSelector(SelectedGlobalBillingColorDetail);
  const SelectedFont = useSelector(SelectedGlobalBillingFont);
  const [shortKeyMethod, setshortKeyMethod] = useState('');
  const preferenceshortcutkey = preferenceDatas?.[0]?.SettingDtlDetails?.find(
    (setting) =>
      setting?.SettingIdName?.toLowerCase() === 'shortcutkeys' &&
      setting?.SettingValue === 'Y'
  );
  const [count, setCount] = useState(1);
  const [EditQuantity, setEditQuantity] = useState(false);
  const [Modaldata, setModaldata] = useState([]);
  const TableData = useSelector(GlobalOrderCardDetails);
  const BookingType = useSelector(GlobalBookingType);
  const defaultBookingType = useSelector(GlobalDefaultBookingType);

  const PreviousOrderLength = useSelector(GlobalPreviousOrderLength);
  const HoldOrderDtl = useSelector(GlobalHoldOrderDtl);
  const UnpaidData = useSelector(GlobalUnpaidData);
  const GlobProdwisedata = useSelector(GlobalSelProdWiseEst);
  const ReportholdData = useSelector(GlobalReorderHoldDetails);
  const prodCat = useSelector(GlobalProductCategorie);
  const ProdSubCat = useSelector(GlobalProductSubCategorie);
  const [PreviousdataLength, setPreviousdataLength] =
    useState(PreviousOrderLength);
  const [triggerAnimation, setTriggerAnimation] = useState(true);
  const templateData = useSelector(getTemplateData);
  const tableOptions = templateData?.BookingBilling?.[1];
  const OfferCheckedInSetup = templateData?.BookingNavbar?.[1].some(
    (item) => item?.OptionName == 'Offer'
  );
  const [editField, setEditField] = useState(false);
  const [Index, setIndex] = useState(null);
  const [allowDecimal, setAllowDecimal] = useState(false);
  const BookingTypeBoth = useSelector(GlobalBookingTypeBoth);
  const OrderType = useSelector(GlobalOrderType);
  const GlobEstBooking = useSelector(GlobalEstimateBooking);
  const GlobalExtraCharge = useSelector(globalExtraTotalAmount);

  const OtherServicesglobal = useSelector(GlobalOtherSevices);

  const tableDataDinein = TableData?.filter(
    (a, b) => a.BookingTypeName === 'Dine In' && !a?.SalesId
  );
  const tableDataTakeAway =
    OrderType === 'Hold'
      ? TableData?.filter((a, b) => a.BookingTypeName === 'TakeAway')
      : TableData?.filter(
          (a, b) => a.BookingTypeName === 'TakeAway' && !a?.SalesId
        );
  const OldtableDataDinein = TableData?.filter(
    (a, b) => a.BookingTypeName === 'Dine In' && a?.SalesId
  );
  const OldtableDataTakeAway =
    OrderType != 'Hold'
      ? TableData?.filter(
          (a, b) => a.BookingTypeName === 'TakeAway' && a?.SalesId
        )
      : [];
  const BillOrderPre = preferenceDatas?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'BillItemsOrder'
  )?.SettingValue;
  const [OpenEditTotalAmt, setOpenEditTotalAmt] = useState(false);
  const [OpenImeiDetail, setOpenImeiDetail] = useState(false);
  const productBasedExtraCharges = GlobalExtraCharge.filter(
    (obj) => 'ProdName' in obj
  );

  const calculateAmounts = (
    OrderQty,
    OrderRate,
    TaxPercentage,
    IsPaid = true
  ) => {
    const total = OrderQty * OrderRate;

    const withoutTax = total - (total * TaxPercentage) / (100 + TaxPercentage);

    return {
      TotalAmt: total,
      ...(IsPaid && { Offer: total }),
      WithoutTaxRate: +withoutTax.toFixed(2),
    };
  };

  const ChangeOrderCardDetailsFn = async ({
    OrderQty,
    InwardDtlId,
    Offer,
    CompleteRemove = false,
    RemoveAndUpdate = false,
    BuyInwardDtlId,
    BuyProdQty,
    UpdateBuyAndFree = false,
    CompleteRemoveBuyAndAddWithPaid = false,
    CompleteRemoveconvertFreetoPaid = false,
    CompleteRemoveconvertFreetoPaidTwoTypes = false,
    CompleteRemoveconvertFreetoPaidNotCompletely = false,
    CompleteRemoveAndPaidToFreeOtherType = false,
    CompleteRemoveAndPaidToFreeOtherTypeWithoutMerge = false,
    RemoveAndUpdateOtherBookingType = false,
    BookingTypeName,
    OrderRate,
  }) => {
    let ModifiedOrderCardDetail = JSON.parse(JSON.stringify(TableData));

    if (RemoveAndUpdate) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === InwardDtlId &&
            e?.Offer === Offer &&
            e?.BookingTypeName === BookingTypeName
          )
      )?.map((e) => {
        if (
          e?.InwardDtlId == InwardDtlId &&
          e?.Offer > 0 &&
          e?.BookingTypeName === BookingTypeName
        ) {
          const newQty = OrderQty;
          return {
            ...e,
            OrderQty: newQty,
            ...calculateAmounts(newQty, e.OrderRate, e.TaxPercentage),
          };
        }

        if (e?.InwardDtlId == BuyInwardDtlId) {
          return {
            ...e,
            OrderQty: BuyProdQty,
            ...calculateAmounts(
              BuyProdQty,
              e.OrderRate,
              e.TaxPercentage,
              false
            ),
          };
        }

        return e;
      });

      return dispatch(changeOrderCardDetails(data));
    }
    if (RemoveAndUpdateOtherBookingType) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === InwardDtlId &&
            e?.Offer === Offer &&
            e?.BookingTypeName === BookingTypeName
          )
      )?.flatMap((e) => {
        if (
          e?.InwardDtlId == InwardDtlId &&
          e?.Offer > 0 &&
          e?.BookingTypeName === BookingTypeName
        ) {
          const newQty = e?.OrderQty - BuyProdQty;

          return {
            ...e,
            OrderQty: newQty,
            ...calculateAmounts(newQty, e.OrderRate, e.TaxPercentage),
          };
        }
        if (
          e?.InwardDtlId == InwardDtlId &&
          e?.Offer == 0 &&
          e?.BookingTypeName !== BookingTypeName
        ) {
          const newQty = e?.OrderQty - BuyProdQty;

          let first = {
            ...e,
            OrderQty: BuyProdQty,
            ...calculateAmounts(BuyProdQty, e.OrderRate, e.TaxPercentage),
          };
          if (newQty > 0) {
            let second = {
              ...e,
              Offer: 0,
              OrderQty: newQty,
              ...calculateAmounts(newQty, e.OrderRate, e.TaxPercentage, false),
            };
            return [first, second];
          }
          return [first];
        }

        if (e?.InwardDtlId == BuyInwardDtlId) {
          return {
            ...e,
            OrderQty: BuyProdQty,
            ...calculateAmounts(
              BuyProdQty,
              e.OrderRate,
              e.TaxPercentage,
              false
            ),
          };
        }

        return e;
      });

      return dispatch(changeOrderCardDetails(data));
    }
    if (CompleteRemove) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === InwardDtlId &&
            e?.Offer === Offer &&
            e?.BookingTypeName === BookingTypeName &&
            e?.OrderRate == OrderRate
          )
      );
      return dispatch(changeOrderCardDetails(data));
    }
    if (CompleteRemoveAndPaidToFreeOtherType) {
      let data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === InwardDtlId &&
            e?.Offer === Offer &&
            e?.BookingTypeName === BookingTypeName
          )
      )?.flatMap((exp) => {
        // Same product but different booking type and not an offer
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer == 0 &&
          exp?.BookingTypeName !== BookingTypeName
        ) {
          const remainingQty = exp.OrderQty - OrderQty;

          if (remainingQty === 0) {
            return {
              ...exp,
              OfferMode: 'B',
              ...calculateAmounts(
                exp.OrderQty,
                exp.OrderRate,
                exp.TaxPercentage,
                true
              ),
            };
          }

          if (remainingQty > 0) {
            return [
              {
                ...exp,
                OrderQty: remainingQty,
                ...calculateAmounts(
                  remainingQty,
                  exp.OrderRate,
                  exp.TaxPercentage,
                  false
                ),
              },
              {
                ...exp,
                OrderQty: OrderQty,
                Offer: 0,
                OfferMode: 'B',
                ...calculateAmounts(
                  OrderQty,
                  exp.OrderRate,
                  exp.TaxPercentage,
                  true
                ),
              },
            ];
          }
        }

        return exp;
      });

      // ===== Merge duplicates for free offers =====
      const mergedData = [];
      data?.forEach((item) => {
        if (item?.OfferMode === 'B') {
          // Check if a free item already exists for this product + booking type
          const existingIndex = mergedData.findIndex(
            (e) =>
              e.InwardDtlId === item.InwardDtlId &&
              e.BookingTypeName === item.BookingTypeName &&
              e.OfferMode === 'B'
          );

          if (existingIndex > -1) {
            // Merge quantities
            const existing = mergedData[existingIndex];
            const newQty = existing.OrderQty + item.OrderQty;
            mergedData[existingIndex] = {
              ...existing,
              OrderQty: newQty,
              ...calculateAmounts(
                newQty,
                item.OrderRate,
                item.TaxPercentage,
                true
              ),
            };
          } else {
            mergedData.push(item);
          }
        } else {
          mergedData.push(item);
        }
      });

      return dispatch(changeOrderCardDetails(mergedData));
    }
    if (CompleteRemoveAndPaidToFreeOtherTypeWithoutMerge) {
      let data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === InwardDtlId &&
            e?.Offer === Offer &&
            e?.BookingTypeName === BookingTypeName
          )
      )?.flatMap((exp) => {
        // Same product but different booking type and not an offer
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer == 0 &&
          exp?.BookingTypeName !== BookingTypeName
        ) {
          const remainingQty = exp.OrderQty - OrderQty;

          if (remainingQty === 0) {
            return {
              ...exp,
              OfferMode: 'B',
              ...calculateAmounts(
                exp.OrderQty,
                exp.OrderRate,
                exp.TaxPercentage,
                true
              ),
            };
          }

          if (remainingQty < 0) {
            return [
              {
                ...exp,
                OrderQty: exp.OrderQty,
                OfferMode: 'B',
                ...calculateAmounts(
                  exp.OrderQty,
                  exp.OrderRate,
                  exp.TaxPercentage,
                  true
                ),
              },
            ];
          }
        }

        return exp;
      });

      return dispatch(changeOrderCardDetails(data));
    }

    if (CompleteRemoveconvertFreetoPaid) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === BuyInwardDtlId &&
            e?.BookingTypeName === BookingTypeName
          )
      )?.map((exp) => {
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer > 0 &&
          exp?.BookingTypeName === BookingTypeName
        ) {
          const { OfferType, OfferMessage, ...exp1 } = exp;
          return {
            ...exp1,
            Offer: 0,
            OrderQty: OrderQty,
            ...calculateAmounts(
              OrderQty,
              exp.OrderRate,
              exp.TaxPercentage,
              false
            ),
          };
        }
        return exp; // keep unchanged item
      });

      return dispatch(changeOrderCardDetails(data));
    }
    if (CompleteRemoveconvertFreetoPaidNotCompletely) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === BuyInwardDtlId &&
            e?.BookingTypeName === BookingTypeName
          )
      )?.flatMap((exp) => {
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer > 0 &&
          exp?.BookingTypeName === BookingTypeName
        ) {
          const { OfferType, OfferMessage, ...exp1 } = exp;
          let first = {
            ...exp1,
            Offer: 0,
            OrderQty: BuyProdQty,
            ...calculateAmounts(
              OrderQty,
              exp.OrderRate,
              exp.TaxPercentage,
              false
            ),
          };
          if (BuyProdQty < OrderQty) {
            let second = {
              ...exp1,
              Offer: 0,
              OrderQty: exp1?.OrderQty - BuyProdQty,
              ...calculateAmounts(
                exp1?.OrderQty - BuyProdQty,
                exp.OrderRate,
                exp.TaxPercentage,
                true
              ),
            };
            return [first, second];
          }
          return [first];
        }
        return exp; // keep unchanged item
      });

      return dispatch(changeOrderCardDetails(data));
    }
    if (CompleteRemoveBuyAndAddWithPaid) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            (e?.InwardDtlId === BuyInwardDtlId &&
              e?.BookingTypeName === BookingTypeName) ||
            (e?.InwardDtlId == InwardDtlId &&
              e?.Offer > 0 &&
              e?.BookingTypeName === BookingTypeName)
          )
      )?.map((exp) => {
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer == 0 &&
          exp?.BookingTypeName === BookingTypeName
        ) {
          return {
            ...exp, // keep existing fields
            OrderQty: OrderQty,
            ...calculateAmounts(
              OrderQty,
              exp.OrderRate,
              exp.TaxPercentage,
              false
            ),
          };
        }
        return exp; // keep unchanged item
      });

      return dispatch(changeOrderCardDetails(data));
    }

    if (UpdateBuyAndFree) {
      const data = ModifiedOrderCardDetail?.map((e) => {
        if (
          e?.InwardDtlId == InwardDtlId &&
          e?.Offer > 0 &&
          e?.BookingTypeName === BookingTypeName
        ) {
          const newQty = e?.OrderQty + OrderQty;
          return {
            ...e,
            OrderQty: newQty,
            ...calculateAmounts(newQty, e.OrderRate, e.TaxPercentage),
          };
        }
        if (e?.InwardDtlId == InwardDtlId && e?.Offer == Offer) {
          const newQty = e?.OrderQty - OrderQty;
          return {
            ...e,
            OrderQty: newQty,

            ...calculateAmounts(newQty, e.OrderRate, e.TaxPercentage, false),
          };
        }

        if (
          e?.InwardDtlId == BuyInwardDtlId &&
          e?.BookingTypeName === BookingTypeName
        ) {
          return {
            ...e,
            OrderQty: BuyProdQty,
            ...calculateAmounts(
              BuyProdQty,
              e.OrderRate,
              e.TaxPercentage,
              false
            ),
          };
        }

        return e;
      });

      return dispatch(changeOrderCardDetails(data));
    }

    if (CompleteRemoveconvertFreetoPaidTwoTypes) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === BuyInwardDtlId &&
            e?.BookingTypeName === BookingTypeName
          )
      )?.flatMap((exp) => {
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer > 0 &&
          exp?.BookingTypeName === BookingTypeName
        ) {
          const { OfferType, OfferMessage, ...exp1 } = exp;
          return {
            ...exp1,
            Offer: 0,
            OrderQty: OrderQty,
            ...calculateAmounts(
              OrderQty,
              exp.OrderRate,
              exp.TaxPercentage,
              false
            ),
          };
        }
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer > 0 &&
          exp?.BookingTypeName !== BookingTypeName
        ) {
          const { ...exp1 } = exp;
          let first = {
            ...exp1,
            // Offer: 0,
            OrderQty: exp1?.OrderQty - BuyProdQty,
            ...calculateAmounts(
              exp1?.OrderQty - BuyProdQty,
              exp.OrderRate,
              exp.TaxPercentage,
              true
            ),
          };

          let second = {
            ...exp1,
            Offer: 0,
            OrderQty: BuyProdQty,
            ...calculateAmounts(
              BuyProdQty,
              exp.OrderRate,
              exp.TaxPercentage,
              false
            ),
          };
          delete second?.OfferMessage;
          delete second?.OfferType;
          return [first, second];
        }
        return exp; // keep unchanged item
      });

      return dispatch(changeOrderCardDetails(data));
    }
    // Update qty for normal case

    const data = ModifiedOrderCardDetail?.map((e) => {
      if (
        e?.InwardDtlId == InwardDtlId &&
        e?.Offer == Offer &&
        e?.BookingTypeName === BookingTypeName
      ) {
        return {
          ...e,
          OrderQty,
          ...calculateAmounts(OrderQty, e.OrderRate, e.TaxPercentage, false),
        };
      }
      return e;
    });

    dispatch(changeOrderCardDetails(data));
  };

  const ChangeFreeprodlistFn = async ({
    FreeProdId,
    OfferId,
    OverAllFreeQty,
    RemainingQty,
    FreeQty,
    CompleteRemove = false,
  }) => {
    const deepCopy = JSON.parse(JSON.stringify(OfferFreeProduct));

    let ModifyedData;

    if (CompleteRemove) {
      // 🔹 Remove the matching FreeProd completely
      ModifyedData = deepCopy?.filter(
        (exp) => !(exp?.OfferId == OfferId && exp?.FreeProdId == FreeProdId)
      );
    } else {
      // 🔹 Update the matching FreeProd
      ModifyedData = deepCopy?.map((exp) => {
        if (exp?.OfferId == OfferId && FreeProdId == exp?.FreeProdId) {
          return {
            ...exp,
            OverAllFreeQty,
            RemainingQty,
            FreeQty,
          };
        }
        return { ...exp };
      });
    }

    dispatch(ChangeFullFreeProductList(ModifyedData));
  };

  const ChangeOfferAppliedProdsFn = async ({
    inwardDtlId,
    OfferAmount,
    FreeQty,
    CompleteRemove = false,
    insideinwardDtlId = false,
  }) => {
    const deepCopy = JSON.parse(JSON.stringify(GlobalOfferAppliedProductsData));

    let ModifyedData;

    if (CompleteRemove) {
      // 🔹 Remove case
      if (!insideinwardDtlId) {
        ModifyedData = deepCopy?.filter(
          (exp) => exp?.InwardDtlId !== inwardDtlId
        );
      } else {
        ModifyedData = deepCopy?.filter(
          (exp) =>
            !(
              Array?.isArray(exp?.FreeProductsList)
                ? exp?.FreeProductsList
                : [exp?.FreeProductsList]
            )?.some((freeProd) =>
              freeProd?.ProdVariantDetails?.some((variant) =>
                variant?.StockDetails?.some(
                  (stock) => stock?.FreeInwardDtlId === inwardDtlId
                )
              )
            )
        );
      }
    } else {
      // 🔹 Update case
      ModifyedData = deepCopy?.map((exp) => {
        let shouldUpdate = false;

        if (!insideinwardDtlId) {
          shouldUpdate = exp?.InwardDtlId == inwardDtlId;
        } else {
          shouldUpdate = (
            Array?.isArray(exp?.FreeProductsList)
              ? exp?.FreeProductsList
              : [exp?.FreeProductsList]
          )?.some((freeProd) =>
            freeProd?.ProdVariantDetails?.some((variant) =>
              variant?.StockDetails?.some(
                (stock) => stock?.FreeInwardDtlId === inwardDtlId
              )
            )
          );
        }

        if (shouldUpdate) {
          return {
            ...exp,
            OfferAmount,
            ActualFreeQty: FreeQty,
            FreeProductsList: (Array?.isArray(exp?.FreeProductsList)
              ? exp?.FreeProductsList
              : [exp?.FreeProductsList]
            )?.map((item, idx) =>
              idx === 0
                ? {
                    ...item,
                    FreeQty,
                  }
                : item
            ),
          };
        }

        return { ...exp };
      });
    }

    dispatch(changeFullOfferAppliedProducts(ModifyedData));
  };

  const removeFromCart = async (item) => {
    removeExtraCharge(item);
    setPreviousdataLength(TableData?.length);

    let ischeckBothBookingType = TableData?.find(
      (e) =>
        e?.InwardDtlId == item?.InwardDtlId &&
        e?.Offer > 0 &&
        e?.BookingTypeName != item?.BookingTypeName
    );

    if (item?.Offer > 0) {
      //check is Buyxgetx Or something
      // let ischeck=  GlobalOfferAppliedProductsData?.some((e)=>e?.FreeProductsList?.[0]??.
      const isBuyAndGetX =
        GlobalOfferAppliedProductsData?.find((data) =>
          (Array?.isArray(data?.FreeProductsList)
            ? data?.FreeProductsList
            : [data?.FreeProductsList]
          )?.some((freeProd) =>
            freeProd?.ProdVariantDetails?.some((variant) =>
              variant?.StockDetails?.some(
                (stock) => stock?.FreeInwardDtlId === item?.InwardDtlId
              )
            )
          )
        )?.OfferMode == 'B';

      const isItemWiseOrQuantityProduct = GlobalOfferAppliedProductsData?.find(
        (data) =>
          data?.ProdId === item?.ProdId &&
          data?.InwardDtlId === item?.InwardDtlId &&
          (data?.OfferMode === 'I' || data?.OfferMode === 'Q') &&
          data?.OfferAmount === item?.Offer
      );

      const isCheckFreeProduct = GlobalOfferAppliedProductsData?.find((off) =>
        (Array.isArray(off?.FreeProductsList)
          ? off?.FreeProductsList
          : [off?.FreeProductsList]
        )?.some((prod) =>
          prod?.ProdVariantDetails?.some((variant) =>
            variant?.StockDetails?.some(
              (stock) => stock.FreeInwardDtlId === item?.InwardDtlId
            )
          )
        )
      );

      if (isBuyAndGetX) {
        let isPaidproduct = TableData?.find(
          (e) =>
            e?.InwardDtlId == item?.InwardDtlId &&
            e?.Offer == 0 &&
            item?.BookingTypeName == e?.BookingTypeName
        );
        const isCheckFreeProduct = OfferFreeProduct?.find((exp) =>
          exp?.ProdVariantDetails?.some((variant) =>
            variant?.StockDetails?.some(
              (stock) => stock?.FreeInwardDtlId === item?.InwardDtlId
            )
          )
        );
        if (isPaidproduct) {
          if (isPaidproduct?.OrderQty == item?.OrderQty) {
            //just remove Paid Qty
            await ChangeOrderCardDetailsFn({
              BookingTypeName: item?.BookingTypeName,
              BuyProdQty: null,
              OrderQty: isPaidproduct?.OrderQty,
              CompleteRemove: true,
              InwardDtlId: isPaidproduct?.InwardDtlId,
              BuyInwardDtlId: null,
              Offer: 0,
            });
          } else if (isPaidproduct?.OrderQty > item?.OrderQty) {
            // Just Decrease Paid Qty
            await ChangeOrderCardDetailsFn({
              BookingTypeName: item?.BookingTypeName,
              BuyProdQty: null,
              OrderQty: isPaidproduct?.OrderQty - item?.OrderQty,
              CompleteRemove: false,
              InwardDtlId: isPaidproduct?.InwardDtlId,
              BuyInwardDtlId: null,
              Offer: 0,
            });
          } else if (isPaidproduct?.OrderQty < item?.OrderQty) {
            //just remove Paid Qty
            //decrease FreeQty

            if (ischeckBothBookingType) {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: -isPaidproduct?.OrderQty,
                RemoveAndUpdate: true,
                InwardDtlId: isPaidproduct?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: 0,
              });

              await ChangeFreeprodlistFn({
                OverAllFreeQty: isCheckFreeProduct?.OverAllFreeQty,
                RemainingQty:
                  isCheckFreeProduct?.OverAllFreeQty -
                  (ischeckBothBookingType?.OrderQty + isPaidproduct?.OrderQty),
                FreeQty:
                  ischeckBothBookingType?.OrderQty + isPaidproduct?.OrderQty,
                FreeProdId: isPaidproduct?.ProdId,
                OfferId: isCheckFreeProduct?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: isPaidproduct?.InwardDtlId,
                OfferAmount: isPaidproduct?.OrderRate * isPaidproduct?.OrderQty,
                FreeQty: isPaidproduct?.OrderQty,
                CompleteRemove: false,
                insideinwardDtlId: true,
              });
            } else {
              let FreeProdcutinPaidModeOtherBookingType = TableData?.find(
                (e) =>
                  e?.InwardDtlId == item?.InwardDtlId &&
                  e?.Offer == 0 &&
                  item?.BookingTypeName != e?.BookingTypeName
              );

              if (FreeProdcutinPaidModeOtherBookingType) {
                await ChangeOrderCardDetailsFn({
                  BookingTypeName: item?.BookingTypeName,
                  BuyProdQty: item?.OrderQty - isPaidproduct?.OrderQty,
                  OrderQty: item.OrderQty,
                  RemoveAndUpdateOtherBookingType: true,
                  InwardDtlId: isPaidproduct?.InwardDtlId,
                  BuyInwardDtlId: null,
                  Offer: 0,
                });

                await ChangeFreeprodlistFn({
                  OverAllFreeQty: item?.OrderQty,
                  RemainingQty:
                    item?.OrderQty -
                    (isPaidproduct?.OrderQty +
                      (FreeProdcutinPaidModeOtherBookingType?.OrderQty -
                        (item?.OrderQty - isPaidproduct?.OrderQty) ||
                        FreeProdcutinPaidModeOtherBookingType?.OrderQty)),
                  FreeQty:
                    isPaidproduct?.OrderQty +
                    (FreeProdcutinPaidModeOtherBookingType?.OrderQty -
                      (item?.OrderQty - isPaidproduct?.OrderQty) ||
                      FreeProdcutinPaidModeOtherBookingType?.OrderQty),
                  FreeProdId: isPaidproduct?.ProdId,
                  OfferId: isCheckFreeProduct?.OfferId,
                });
                // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)

                await ChangeOfferAppliedProdsFn({
                  inwardDtlId: isPaidproduct?.InwardDtlId,
                  OfferAmount:
                    isPaidproduct?.OrderRate *
                    (isPaidproduct?.OrderQty +
                      (FreeProdcutinPaidModeOtherBookingType?.OrderQty -
                        (item?.OrderQty - isPaidproduct?.OrderQty) ||
                        FreeProdcutinPaidModeOtherBookingType?.OrderQty)),
                  FreeQty:
                    isPaidproduct?.OrderQty +
                    (FreeProdcutinPaidModeOtherBookingType?.OrderQty -
                      (item?.OrderQty - isPaidproduct?.OrderQty) ||
                      FreeProdcutinPaidModeOtherBookingType?.OrderQty),
                  insideinwardDtlId: true,
                });
              } else {
                await ChangeOrderCardDetailsFn({
                  BookingTypeName: item?.BookingTypeName,
                  BuyProdQty: null,
                  OrderQty: isPaidproduct?.OrderQty,
                  RemoveAndUpdate: true,
                  InwardDtlId: isPaidproduct?.InwardDtlId,
                  BuyInwardDtlId: null,
                  Offer: 0,
                });

                await ChangeFreeprodlistFn({
                  OverAllFreeQty: item?.OrderQty,
                  RemainingQty: item?.OrderQty - isPaidproduct?.OrderQty,
                  FreeQty: isPaidproduct?.OrderQty,
                  FreeProdId: isPaidproduct?.ProdId,
                  OfferId: isCheckFreeProduct?.OfferId,
                });
                // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)

                await ChangeOfferAppliedProdsFn({
                  inwardDtlId: isPaidproduct?.InwardDtlId,
                  OfferAmount:
                    isPaidproduct?.OrderRate * isPaidproduct?.OrderQty,
                  FreeQty: isPaidproduct?.OrderQty,
                  CompleteRemove: false,
                  insideinwardDtlId: true,
                });
              }
            }
          }
        } else {
          if (ischeckBothBookingType) {
            // //Free Product in Paid Mode
            let FreeProdcutinPaidModeOtherBookingType = TableData?.find(
              (e) =>
                e?.InwardDtlId == item?.InwardDtlId &&
                e?.Offer == 0 &&
                item?.BookingTypeName != e?.BookingTypeName
            );

            //if free product is available in paid mode in other booking type then just decrease the free qty from that product
            if (FreeProdcutinPaidModeOtherBookingType) {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: item?.OrderQty,
                CompleteRemoveAndPaidToFreeOtherType: true,
                InwardDtlId: item?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: item?.Offer,
              });
              await ChangeFreeprodlistFn({
                OverAllFreeQty: isCheckFreeProduct?.OverAllFreeQty,
                RemainingQty: isCheckFreeProduct?.OverAllFreeQty,
                FreeQty: isCheckFreeProduct?.FreeQty,
                FreeProdId: isCheckFreeProduct?.FreeProdId,
                OfferId: isCheckFreeProduct?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * Quantity), Quantity, true,)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount: isCheckFreeProduct?.FreeQty * item?.OrderRate,
                FreeQty: item?.OrderQty,
                CompleteRemove: false,
                insideinwardDtlId: true,
              });
            } else {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: isPaidproduct?.OrderQty,
                CompleteRemove: true,
                InwardDtlId: item?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: item?.Offer,
              });
              await ChangeFreeprodlistFn({
                OverAllFreeQty: isCheckFreeProduct?.OverAllFreeQty,
                RemainingQty:
                  isCheckFreeProduct?.OverAllFreeQty - item?.OrderQty,
                FreeQty: isCheckFreeProduct?.FreeQty - item?.OrderQty,
                FreeProdId: isCheckFreeProduct?.FreeProdId,
                OfferId: isCheckFreeProduct?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * Quantity), Quantity, true,)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount:
                  (isCheckFreeProduct?.FreeQty - item?.OrderQty) *
                  item?.OrderRate,
                FreeQty: item?.OrderQty,
                CompleteRemove: false,
                insideinwardDtlId: true,
              });
            }
          }

          // }
          else {
            let isPaidProductAvailableInCartOtherType = TableData?.find(
              (e) =>
                e?.InwardDtlId == item?.InwardDtlId &&
                e?.Offer == 0 &&
                item?.BookingTypeName != e?.BookingTypeName
            );

            if (isPaidProductAvailableInCartOtherType) {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: item?.OrderQty,
                CompleteRemoveAndPaidToFreeOtherTypeWithoutMerge: true,
                InwardDtlId: item?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: item?.Offer,
              });
              await ChangeFreeprodlistFn({
                OverAllFreeQty: isCheckFreeProduct?.OverAllFreeQty,
                RemainingQty:
                  isCheckFreeProduct?.OverAllFreeQty -
                  (isCheckFreeProduct?.FreeQty -
                    (item?.OrderQty -
                      isPaidProductAvailableInCartOtherType?.OrderQty)),
                FreeQty:
                  isCheckFreeProduct?.FreeQty -
                  (item?.OrderQty -
                    isPaidProductAvailableInCartOtherType?.OrderQty),
                FreeProdId: isCheckFreeProduct?.FreeProdId,
                OfferId: isCheckFreeProduct?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * Quantity), Quantity, true,)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount:
                  item?.OrderRate *
                  (isCheckFreeProduct?.FreeQty -
                    (item?.OrderQty -
                      isPaidProductAvailableInCartOtherType?.OrderQty)),
                FreeQty:
                  isCheckFreeProduct?.FreeQty -
                  (item?.OrderQty -
                    isPaidProductAvailableInCartOtherType?.OrderQty),
                CompleteRemove: false,
                insideinwardDtlId: true,
              });
            } else {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: isPaidproduct?.OrderQty,
                CompleteRemove: true,
                InwardDtlId: item?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: item?.Offer,
              });
              await ChangeFreeprodlistFn({
                OverAllFreeQty: isCheckFreeProduct?.OverAllFreeQty,
                RemainingQty: isCheckFreeProduct?.OverAllFreeQty,
                FreeQty: 0,
                FreeProdId: isCheckFreeProduct?.FreeProdId,
                OfferId: isCheckFreeProduct?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * Quantity), Quantity, true,)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount: item?.OrderRate * item?.OrderQty,
                FreeQty: item?.OrderQty,
                CompleteRemove: true,
                insideinwardDtlId: true,
              });
            }
          }
          //Change Remove OrderCartDetail
          //Remove FreeprodList
          //ChangeOfferApplied Products
        }
      } else {
        ///remove item wise offer
        if (isItemWiseOrQuantityProduct) {
          await ChangeOrderCardDetailsFn({
            BookingTypeName: item?.BookingTypeName,
            BuyProdQty: null,
            OrderQty: item?.OrderQty,
            CompleteRemove: true,
            InwardDtlId: item?.InwardDtlId,
            BuyInwardDtlId: null,
            Offer: item?.Offer,
          });
          await ChangeOfferAppliedProdsFn({
            inwardDtlId: item?.InwardDtlId,
            OfferAmount: item?.OrderRate * item?.OrderQty,
            FreeQty: item?.OrderQty,
            CompleteRemove: true,
          });
        } else if (isCheckFreeProduct) {
          // remove or update loyalty/code based free product which is added in cart
          const freeProdList = Array?.isArray(
            isCheckFreeProduct?.FreeProductsList
          )
            ? isCheckFreeProduct?.FreeProductsList?.[0]
            : isCheckFreeProduct?.FreeProductsList;
          let isPaidProductAvailableInCart = TableData?.find(
            (e) =>
              e?.InwardDtlId == item?.InwardDtlId &&
              e?.Offer == 0 &&
              item?.BookingTypeName == e?.BookingTypeName
          );
          if (isPaidProductAvailableInCart) {
            if (isPaidProductAvailableInCart?.OrderQty === item?.OrderQty) {
              //just remove Paid Qty
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: isPaidProductAvailableInCart?.OrderQty,
                CompleteRemove: true,
                InwardDtlId: isPaidProductAvailableInCart?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: 0,
              });
            } else if (
              isPaidProductAvailableInCart?.OrderQty > item?.OrderQty
            ) {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty:
                  isPaidProductAvailableInCart?.OrderQty - item?.OrderQty,
                CompleteRemove: false,
                InwardDtlId: isPaidProductAvailableInCart?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: 0,
              });
            } else if (
              isPaidProductAvailableInCart?.OrderQty < item?.OrderQty
            ) {
              //just remove Paid Qty
              //decrease FreeQty
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: -isPaidProductAvailableInCart?.OrderQty,
                RemoveAndUpdate: true,
                InwardDtlId: isPaidProductAvailableInCart?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: 0,
              });

              if (ischeckBothBookingType) {
                await ChangeFreeprodlistFn({
                  OverAllFreeQty: freeProdList?.OverAllFreeQty,
                  RemainingQty:
                    freeProdList?.OverAllFreeQty -
                    (ischeckBothBookingType?.OrderQty +
                      isPaidProductAvailableInCart?.OrderQty),
                  FreeQty:
                    ischeckBothBookingType?.OrderQty +
                    isPaidProductAvailableInCart?.OrderQty,
                  FreeProdId: isPaidProductAvailableInCart?.ProdId,
                  OfferId: freeProdList?.OfferId,
                });
                // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)
                await ChangeOfferAppliedProdsFn({
                  inwardDtlId: isPaidProductAvailableInCart?.InwardDtlId,
                  OfferAmount:
                    isPaidProductAvailableInCart?.OrderRate *
                    isPaidProductAvailableInCart?.OrderQty,
                  FreeQty: isPaidProductAvailableInCart?.OrderQty,
                  CompleteRemove: false,
                  insideinwardDtlId: true,
                });
              } else {
                await ChangeFreeprodlistFn({
                  OverAllFreeQty: item?.OrderQty,
                  RemainingQty:
                    item?.OrderQty - isPaidProductAvailableInCart?.OrderQty,
                  FreeQty: isPaidProductAvailableInCart?.OrderQty,
                  FreeProdId: isPaidProductAvailableInCart?.ProdId,
                  OfferId: freeProdList?.OfferId,
                });
                // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)
                await ChangeOfferAppliedProdsFn({
                  inwardDtlId: isPaidProductAvailableInCart?.InwardDtlId,
                  OfferAmount:
                    isPaidProductAvailableInCart?.OrderRate *
                    isPaidProductAvailableInCart?.OrderQty,
                  FreeQty: isPaidProductAvailableInCart?.OrderQty,
                  CompleteRemove: false,
                  insideinwardDtlId: true,
                });
              }
            }
          } else {
            if (ischeckBothBookingType) {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: isPaidProductAvailableInCart?.OrderQty,
                CompleteRemove: true,
                InwardDtlId: item?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: item?.Offer,
              });
              await ChangeFreeprodlistFn({
                OverAllFreeQty: freeProdList?.OverAllFreeQty,
                RemainingQty: freeProdList?.OverAllFreeQty - item?.OrderQty,
                FreeQty: freeProdList?.FreeQty - item?.OrderQty,
                FreeProdId: freeProdList?.FreeProdId,
                OfferId: freeProdList?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * Quantity), Quantity, true,)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount:
                  (freeProdList?.FreeQty - item?.OrderQty) * item?.OrderRate,
                FreeQty: item?.OrderQty,
                CompleteRemove: false,
                insideinwardDtlId: true,
              });
            } else {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: isPaidProductAvailableInCart?.OrderQty,
                CompleteRemove: true,
                InwardDtlId: item?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: item?.Offer,
              });
              await ChangeFreeprodlistFn({
                OverAllFreeQty: freeProdList?.OverAllFreeQty,
                RemainingQty: freeProdList?.OverAllFreeQty,
                FreeQty: 0,
                FreeProdId: freeProdList?.FreeProdId,
                OfferId: freeProdList?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * Quantity), Quantity, true,)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount: item?.OrderRate * item?.OrderQty,
                FreeQty: item?.OrderQty,
                CompleteRemove: true,
                insideinwardDtlId: true,
              });
            }
          }
        }
      }
    } else {
      const isCheckFreeProductOutside = OfferFreeProduct?.find(
        (exp) => exp?.InwardDtlId == item?.InwardDtlId
      );

      if (!isCheckFreeProductOutside) {
        await ChangeOrderCardDetailsFn({
          BookingTypeName: item?.BookingTypeName,
          BuyProdQty: null,
          OrderQty: item?.OrderQty,
          CompleteRemove: true,
          InwardDtlId: item?.InwardDtlId,
          BuyInwardDtlId: null,
          Offer: item?.Offer,
          OrderRate: item?.OrderRate,
        });
      } else {
        const isCheck = GlobalOfferAppliedProductsData?.find(
          (exp) => exp?.InwardDtlId === item?.InwardDtlId
        );
        const FreeProd = OfferFreeProduct?.find(
          (exp) => exp?.InwardDtlId === item?.InwardDtlId
        );

        if (isCheck) {
          let inward =
            isCheck?.FreeProductsList?.[0]?.ProdVariantDetails?.[0]
              ?.StockDetails?.[0]?.FreeInwardDtlId;

          let isPaidproduct = TableData?.find(
            (e) =>
              e?.InwardDtlId == inward &&
              e?.Offer == 0 &&
              e?.BookingTypeName == item?.BookingTypeName
          );
          if (isPaidproduct) {
            let ischeckBothBookingType = TableData?.find(
              (e) =>
                e?.InwardDtlId == inward &&
                e?.Offer > 0 &&
                e?.BookingTypeName != item?.BookingTypeName
            );

            //if any Paid Product is there, we have to Merge With That
            if (ischeckBothBookingType) {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty:
                  isPaidproduct?.OrderQty +
                  isCheck?.ActualFreeQty -
                  ischeckBothBookingType?.OrderQty,
                CompleteRemoveBuyAndAddWithPaid: true,
                InwardDtlId: isPaidproduct?.InwardDtlId,
                BuyInwardDtlId: item?.InwardDtlId,
                Offer: item?.Offer,
              });

              await ChangeFreeprodlistFn({
                OverAllFreeQty: FreeProd?.OverAllFreeQty - item?.OrderQty,
                RemainingQty:
                  FreeProd?.OverAllFreeQty -
                  item?.OrderQty -
                  (FreeProd?.FreeQty - item?.OrderQty),
                FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                FreeProdId: FreeProd?.FreeProdId,
                OfferId: FreeProd?.OfferId,
                CompleteRemove: false,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount:
                  isPaidproduct?.OrderRate *
                  (FreeProd?.FreeQty - item?.OrderQty),
                FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                CompleteRemove: false,
                insideinwardDtlId: false,
              });
            } else {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: isPaidproduct?.OrderQty + isCheck?.ActualFreeQty,
                CompleteRemoveBuyAndAddWithPaid: true,
                InwardDtlId: isPaidproduct?.InwardDtlId,
                BuyInwardDtlId: item?.InwardDtlId,
                Offer: item?.Offer,
              });

              await ChangeFreeprodlistFn({
                OverAllFreeQty: item?.OrderQty,
                RemainingQty: item?.OrderQty - isPaidproduct?.OrderQty,
                FreeQty: isPaidproduct?.OrderQty,
                FreeProdId: FreeProd?.FreeProdId,
                OfferId: FreeProd?.OfferId,
                CompleteRemove: true,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount: isPaidproduct?.OrderRate * isPaidproduct?.OrderQty,
                FreeQty: isPaidproduct?.OrderQty,
                CompleteRemove: true,
                insideinwardDtlId: false,
              });
            }
          } else {
            //have to find if thereis two Booking Type is there
            //Convert That Free Product To Paid Product
            let ischeckBothBookingType = TableData?.find(
              (e) =>
                e?.InwardDtlId == inward &&
                e?.Offer > 0 &&
                e?.BookingTypeName != item?.BookingTypeName
            );

            let FreeProductSameBookingType = TableData?.find(
              (e) =>
                e?.InwardDtlId == inward &&
                e?.Offer > 0 &&
                e?.BookingTypeName == item?.BookingTypeName
            );
            if (ischeckBothBookingType) {
              //Convert That Free Product To Paid Product

              //merge that paid product with same booking type
              //decrease free prod list qty
              //change offer applied product qty
              // await ChangeOrderCardDetailsFn(item?.BookingTypeName, null, ischeckBothBookingType?.OrderQty + FreeProductSameBookingType?.OrderQty, false, ischeckBothBookingType?.InwardDtlId, item?.InwardDtlId, item?.Offer, true)
              if (FreeProductSameBookingType?.OrderQty >= item?.OrderQty) {
                await ChangeFreeprodlistFn({
                  OverAllFreeQty: FreeProd?.OverAllFreeQty - item?.OrderQty,
                  RemainingQty:
                    FreeProd?.OverAllFreeQty -
                    item?.OrderQty -
                    (FreeProd?.FreeQty - item?.OrderQty),
                  FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                  FreeProdId: FreeProd?.FreeProdId,
                  OfferId: FreeProd?.OfferId,
                  CompleteRemove: false,
                });
                await ChangeOrderCardDetailsFn({
                  BookingTypeName: item?.BookingTypeName,
                  BuyProdQty: item?.OrderQty,
                  OrderQty: FreeProductSameBookingType?.OrderQty,
                  CompleteRemoveconvertFreetoPaidNotCompletely: true,
                  InwardDtlId: inward,
                  BuyInwardDtlId: item?.InwardDtlId,
                  Offer: item?.Offer,
                });
                await ChangeOfferAppliedProdsFn({
                  inwardDtlId: item?.InwardDtlId,
                  OfferAmount:
                    (FreeProd?.FreeQty - item?.OrderQty) *
                    ischeckBothBookingType?.OrderRate,
                  FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                  CompleteRemove: false,
                  insideinwardDtlId: false,
                });
              } else {
                let data = isCheckFreeProductOutside?.FreeQty - item?.OrderQty;
                //First i Calculate Another Booking Type Qty
                let anotherBookingType = TableData?.find(
                  (e) =>
                    e?.InwardDtlId == item?.InwardDtlId &&
                    e?.Offer == 0 &&
                    e?.BookingTypeName != item?.BookingTypeName
                );
                let anotherBookingTypeOffer = TableData?.find(
                  (e) =>
                    e?.InwardDtlId == inward &&
                    e?.Offer > 0 &&
                    e?.BookingTypeName != item?.BookingTypeName
                );

                let diff =
                  item?.OrderQty - FreeProductSameBookingType?.OrderQty;

                //SameBookingFreeQty
                //FreeProductSameBookingType?.OrderQty

                //Another BookingType Paid Qty
                //anotherBookingType

                //anotherBookingType?.Free OrderQty
                //ischeckBothBookingType

                //anotherBookingType?.OrderQty-ischeckBothBookingType?.OrderQty
                //convert another Booking Type Qty also Free to Paid

                if (
                  (anotherBookingType?.OrderQty || 0) <
                  anotherBookingTypeOffer?.OrderQty
                ) {
                  //paidproduct                         ischeckBothBookingType?.OrderQty-anotherBookingType?.OrderQty
                  //PaidProdcut Current BookingType    FreeProductSameBookingType?.OrderQty
                  let paidproductAnotherType =
                    ischeckBothBookingType?.OrderQty -
                    anotherBookingType?.OrderQty;
                  let paidproductCurrentType =
                    FreeProductSameBookingType?.OrderQty;

                  await ChangeOrderCardDetailsFn({
                    BookingTypeName: item?.BookingTypeName,
                    BuyProdQty: paidproductAnotherType,
                    OrderQty: paidproductCurrentType,
                    CompleteRemoveconvertFreetoPaidTwoTypes: true,
                    InwardDtlId: inward,
                    BuyInwardDtlId: item?.InwardDtlId,
                    Offer: item?.Offer,
                  });

                  await ChangeFreeprodlistFn({
                    OverAllFreeQty: FreeProd?.OverAllFreeQty - item?.OrderQty,
                    RemainingQty:
                      FreeProd?.OverAllFreeQty -
                      item?.OrderQty -
                      (FreeProd?.FreeQty -
                        (paidproductCurrentType + paidproductCurrentType)),
                    FreeQty:
                      FreeProd?.FreeQty -
                      (paidproductCurrentType + paidproductCurrentType),
                    FreeProdId: FreeProd?.FreeProdId,
                    OfferId: FreeProd?.OfferId,
                    CompleteRemove: false,
                  });
                  await ChangeOfferAppliedProdsFn({
                    inwardDtlId: item?.InwardDtlId,
                    OfferAmount:
                      (FreeProd?.FreeQty - item?.OrderQty) *
                      ischeckBothBookingType?.OrderRate,
                    FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                    CompleteRemove: false,
                    insideinwardDtlId: false,
                  });
                } else {
                  await ChangeFreeprodlistFn({
                    OverAllFreeQty: FreeProd?.OverAllFreeQty - item?.OrderQty,
                    RemainingQty:
                      FreeProd?.OverAllFreeQty -
                      item?.OrderQty -
                      (FreeProd?.FreeQty - item?.OrderQty),
                    FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                    FreeProdId: FreeProd?.FreeProdId,
                    OfferId: FreeProd?.OfferId,
                    CompleteRemove: false,
                  });
                  await ChangeOrderCardDetailsFn({
                    BookingTypeName: item?.BookingTypeName,
                    BuyProdQty: null,
                    OrderQty: FreeProductSameBookingType?.OrderQty,
                    CompleteRemoveconvertFreetoPaid: true,
                    InwardDtlId: inward,
                    BuyInwardDtlId: item?.InwardDtlId,
                    Offer: item?.Offer,
                  });
                  await ChangeOfferAppliedProdsFn({
                    inwardDtlId: item?.InwardDtlId,
                    OfferAmount:
                      (FreeProd?.FreeQty - item?.OrderQty) *
                      ischeckBothBookingType?.OrderRate,
                    FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                    CompleteRemove: false,
                    insideinwardDtlId: false,
                  });
                }
              }
            } else {
              await ChangeFreeprodlistFn({
                OverAllFreeQty: item?.OrderQty,
                RemainingQty: item?.OrderQty - isPaidproduct?.OrderQty,
                FreeQty: isPaidproduct?.OrderQty,
                FreeProdId: FreeProd?.FreeProdId,
                OfferId: FreeProd?.OfferId,
                CompleteRemove: true,
              });
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: FreeProductSameBookingType?.OrderQty,
                CompleteRemoveconvertFreetoPaid: true,
                InwardDtlId: inward,
                BuyInwardDtlId: item?.InwardDtlId,
                Offer: item?.Offer,
              });
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount:
                  (isCheck?.ActualFreeQty -
                    FreeProductSameBookingType?.OrderQty) *
                  isPaidproduct?.OrderQty,
                FreeQty:
                  isCheck?.ActualFreeQty - FreeProductSameBookingType?.OrderQty,
                CompleteRemove: true,
                insideinwardDtlId: false,
              });
            }
          }
        } else {
          let ischeckBothBookingType = TableData?.find(
            (e) =>
              e?.InwardDtlId == item?.InwardDtlId &&
              e?.Offer == 0 &&
              e?.BookingTypeName != item?.BookingTypeName
          );

          if (ischeckBothBookingType) {
            await ChangeOrderCardDetailsFn({
              BookingTypeName: item?.BookingTypeName,
              BuyProdQty: null,
              OrderQty: 0,
              CompleteRemove: true,
              InwardDtlId: item?.InwardDtlId,
              BuyInwardDtlId: item?.InwardDtlId,
              Offer: item?.Offer,
            });
            await ChangeFreeprodlistFn({
              OverAllFreeQty: FreeProd?.OverAllFreeQty - item?.OrderQty,
              RemainingQty: FreeProd?.OverAllFreeQty - item?.OrderQty,
              FreeQty: 0,
              FreeProdId: FreeProd?.FreeProdId,
              OfferId: FreeProd?.OfferId,
              CompleteRemove: false,
            });
          } else {
            await ChangeOrderCardDetailsFn({
              BookingTypeName: item?.BookingTypeName,
              BuyProdQty: null,
              OrderQty: 0,
              CompleteRemove: true,
              InwardDtlId: item?.InwardDtlId,
              BuyInwardDtlId: item?.InwardDtlId,
              Offer: item?.Offer,
            });
            await ChangeFreeprodlistFn({
              OverAllFreeQty: item?.OrderQty,
              RemainingQty: 0,
              FreeQty: 0,
              FreeProdId: FreeProd?.FreeProdId,
              OfferId: FreeProd?.OfferId,
              CompleteRemove: true,
            });
          }
          //Remove From Free ProdList  That Entirely
        }
      }
    }
  };
  // const removeFromCart = async (item) => {
  //   setPreviousdataLength(TableData?.length);
  //   if (item?.BookingTypeName !== 'Dine In' && OrderType !== 'Hold') {
  //     const UpdatedData = TableData?.filter(
  //       (cartItem) =>
  //         !(
  //           cartItem?.ProdId === item?.ProdId &&
  //           cartItem?.InwardDtlId === item?.InwardDtlId &&
  //           cartItem?.OrderRate === item?.OrderRate &&
  //           cartItem?.BookingTypeName === item?.BookingTypeName &&
  //           !cartItem?.SalesId
  //         )
  //     );

  //     if (OfferCheckedInSetup && preferenceOffer) {
  //       await applyOffer(UpdatedData);
  //     } else {
  //       dispatch(changeOrderCardDetails(UpdatedData));
  //     }

  //     await dispatch(
  //       ChangeTotalAmount(
  //         GlobalExtraCharge?.filter((extra) => {
  //           if (BookingType === 'Dine In') {
  //             // Remove extra charges linked to the removed product
  //             return !(extra.ProdId === item?.ProdId && !extra.SalesId);
  //           } else if (BookingType === 'TakeAway') {
  //             // Remove extra charges only if SalesId is not present
  //             return extra.ProdId !== item?.ProdId;
  //           }
  //           return true; // Keep everything else
  //         })
  //       )
  //     );
  //     // if the quantity of the item is 1, remove the item from the cart
  //     if (TableData?.length <= 1) {
  //       await dispatch(changeReorderHoldDetails({}));
  //       await dispatch(changeReorderProductDetails([]));
  //       await dispatch(changeUnpaidData(false));
  //       await dispatch(changeBookingType('TakeAway'));
  //       await dispatch(changeTokenOnly(false));
  //       await dispatch(changeAllProductTokenAvailable(false));
  //       await dispatch(ChangeOverAllDiscSales(null));
  //       await dispatch(ChangeOverAllDiscEstimate(null));
  //       await dispatch(changeSelProdWiseEst([]));
  //       await dispatch(ChangeTotalAmount([]));
  //     }
  //   } else if (item?.BookingTypeName !== 'Dine In' && OrderType === 'Hold') {
  //     const UpdatedData = TableData?.filter(
  //       (cartItem) =>
  //         !(
  //           cartItem?.ProdId === item?.ProdId &&
  //           cartItem?.InwardDtlId === item?.InwardDtlId &&
  //           cartItem?.OrderRate === item?.OrderRate &&
  //           cartItem?.BookingTypeName === item?.BookingTypeName
  //         )
  //     );

  //     if (OfferCheckedInSetup && preferenceOffer) {
  //       await applyOffer(UpdatedData);
  //     } else {
  //       dispatch(changeOrderCardDetails(UpdatedData));
  //     }

  //     await dispatch(
  //       ChangeTotalAmount(
  //         GlobalExtraCharge?.filter((extra) => {
  //           if (BookingType === 'Dine In') {
  //             // Remove extra charges linked to the removed product
  //             return !(extra.ProdId === item?.ProdId && !extra.SalesId);
  //           } else if (BookingType === 'TakeAway') {
  //             // Remove extra charges only if SalesId is not present
  //             return extra.ProdId !== item?.ProdId;
  //           }
  //           return true; // Keep everything else
  //         })
  //       )
  //     );
  //     // if the quantity of the item is 1, remove the item from the cart
  //     if (TableData?.length <= 1) {
  //       await dispatch(changeReorderHoldDetails({}));
  //       await dispatch(changeReorderProductDetails([]));
  //       await dispatch(changeUnpaidData(false));
  //       await dispatch(changeBookingType('TakeAway'));
  //       await dispatch(changeTokenOnly(false));
  //       await dispatch(changeAllProductTokenAvailable(false));
  //       await dispatch(ChangeOverAllDiscSales(null));
  //       await dispatch(ChangeOverAllDiscEstimate(null));
  //       await dispatch(changeSelProdWiseEst([]));
  //       await dispatch(ChangeTotalAmount([]));
  //     }
  //   } else if (item?.BookingTypeName === 'Dine In') {
  //     const UpdatedData = TableData?.filter(
  //       (cartItem) =>
  //         !(
  //           cartItem?.ProdId === item?.ProdId &&
  //           cartItem?.InwardDtlId === item?.InwardDtlId &&
  //           cartItem?.OrderRate === item?.OrderRate &&
  //           cartItem?.BookingTypeName === item?.BookingTypeName &&
  //           !cartItem?.SalesId
  //         )
  //     );

  //     if (OfferCheckedInSetup && preferenceOffer) {
  //       await applyOffer(UpdatedData);
  //     } else {
  //       dispatch(changeOrderCardDetails(UpdatedData));
  //     }
  //     await dispatch(ChangeTotalAmount([]));
  //     await dispatch(
  //       ChangeTotalAmount(
  //         GlobalExtraCharge?.filter((extra) => {
  //           if (BookingType === 'Dine In') {
  //             // Remove extra charges linked to the removed product
  //             return !(extra.ProdId === item?.ProdId && !extra.SalesId);
  //           } else if (BookingType === 'TakeAway') {
  //             // Remove extra charges only if SalesId is not present
  //             return extra.ProdId !== item?.ProdId;
  //           }
  //           return true; // Keep everything else
  //         })
  //       )
  //     ); // if the quantity of the item is 1, remove the item from the cart
  //     if (TableData?.length <= 1) {
  //       await dispatch(changeReorderHoldDetails({}));
  //       await dispatch(changeReorderProductDetails([]));
  //       await dispatch(changeUnpaidData(false));
  //       await dispatch(ChangeSelectedCustDisable(false));
  //       await dispatch(changeSelectedOption(false));
  //       await dispatch(changeBookingType('TakeAway'));
  //       await dispatch(changeTokenOnly(false));
  //       await dispatch(changeAllProductTokenAvailable(false));
  //       await dispatch(ChangeOverAllDiscSales(null));
  //       await dispatch(ChangeOverAllDiscEstimate(null));
  //       await dispatch(changeSelProdWiseEst([]));
  //       await dispatch(ChangeTotalAmount([]));
  //     }
  //   }
  // };
  useEffect(() => {
    getPreference();
  }, []);

  useEffect(() => {
    if (SelectedFont) {
      WebFont.load({
        google: {
          families: [SelectedFont], // Load the selected font
        },
      });
    }
  }, [SelectedFont]);
  useEffect(() => {
    if (TableData?.length === 0) {
      dispatch(ClearOfferAppliedProducts());
    }
    if (!isMobile) {
      const customerDisplayWindow = getCustomerDisplayWindow();
      console.log('customerDisplayWindowtableData', customerDisplayWindow);
      if (customerDisplayWindow && !customerDisplayWindow.closed) {
        const updatedData = {
          userData: TableData,
        };
        customerDisplayWindow.postMessage(updatedData, '*');
      }

      const timer = setTimeout(() => {
        setTriggerAnimation(false);
      }, 400);

      return () => clearTimeout(timer);
    }
  }, [TableData]);

  useEffect(() => {
    setPreviousdataLength(PreviousOrderLength);
  }, [PreviousOrderLength]);

  useEffect(() => {
    if (tableOptions?.length > 0) {
      let editFieldValue = tableOptions?.filter(
        (item) => item.OptionName == 'Edit'
      );
      if (editFieldValue?.length > 0) {
        setEditField(true);
      } else {
        setEditField(false);
      }
    }
  }, [tableOptions]);

  useEffect(() => {
    const getSelectedItem = () => {
      const getItem = (data = []) => {
        if (!data.length) return null;
        return BillOrderPre === 'Y' ? data[0] : data[data.length - 1];
      };

      if (tableDataTakeAway?.length > 0) {
        return getItem(tableDataTakeAway);
      } else if (tableDataDinein?.length > 0) {
        return getItem(tableDataDinein);
      }
      return null;
    };

    const handleShortcut = (method) => {
      const item = getSelectedItem();
      if (!item) return;

      handleEditQuantity(item);
      setshortKeyMethod(method);
    };

    const handleKeyDown = (event) => {
      if (!preferenceshortcutkey) return;
      if (!event.ctrlKey) return;

      const key = event.key.toLowerCase();

      if (key === 'q') {
        event.preventDefault();
        handleShortcut('qty');
      }

      if (key === 'e') {
        event.preventDefault();
        handleShortcut('price');
      }
    };
    window.addEventListener('keydown', handleKeyDown);

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [preferenceshortcutkey, tableDataTakeAway, tableDataDinein, BillOrderPre]);

  const handleImeiDetails = (value) => {
    setOpenImeiDetail(true);
    setModaldata(value);
  };
  const handleImeiDetailClose = () => {
    setOpenImeiDetail(false);
  };
  const getstockbadge = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
    };
    await dispatch(getSelectedFavItems(data)).unwrap();

    let data1 = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      ProdSubCat: ProdSubCat,
    };

    let data2 = {
      compId: CompId,
      branchId: BranchId,
      appId: AppId,
      prodCat: prodCat,
    };

    if (
      templateData?.BookingLayout?.[1]?.some(
        (item) => item?.OptionName === 'SubCategory'
      ) &&
      ProdSubCat
    ) {
      await dispatch(getLayoutproductCard(data1)).unwrap();
    } else if (
      !templateData?.BookingLayout?.[1]?.some(
        (item) => item?.OptionName === 'SubCategory'
      )
    ) {
      await dispatch(getCardDataWithoutSubmodule(data2)).unwrap();
    } else {
      await dispatch(getCardDataWithoutSub(data2)).unwrap();
    }
  };
  const Clearall = async () => {
    if (OrderType === 'Hold') {
      if (OfferCheckedInSetup && preferenceOffer) {
        await applyOffer([]);
      } else {
        await dispatch(changeOrderCardDetails([]));
      }
      let putData = { OrderId: [ReportholdData?.OrderId] };
      console.log(putData, 'putDataputData');
      let response = await dispatch(puttinghold(putData)).unwrap();
      if (response?.data?.statusCode == 1) {
        getstockbadge();
        let holdingData = await dispatch(
          gettinghold({ CompId: CompId, BranchId: BranchId, AppId: AppId })
        ).unwrap();
        if (holdingData?.data?.statusCode === 1) {
          dispatch(changeholddata(holdingData?.data?.data));
        } else {
          dispatch(changeholddata([]));
        }
      }
      await dispatch(ChangeTotalAmount([]));
      await dispatch(changeOrderType(null));
      await dispatch(changeReorderHoldDetails({}));
    } else if (OrderType === 'Reorder') {
      const UpdatedData = TableData?.filter((cartItem) => cartItem?.SalesId);

      if (OfferCheckedInSetup && preferenceOffer) {
        await applyOffer(UpdatedData);
      } else {
        await dispatch(changeOrderCardDetails(UpdatedData));
      }
      await dispatch(changeBookingType('Dine In'));
    } else {
      if (OfferCheckedInSetup && preferenceOffer) {
        await applyOffer([]);
      } else {
        dispatch(changeOrderCardDetails([]));
      }
      await dispatch(ChangeTotalAmount([])); //Shifayath Date:27/12/2023
      await dispatch(changeUnpaidData(false));
      await dispatch(changeReorderHoldDetails({}));
      await dispatch(changeReorderProductDetails([]));
      await dispatch(ChangeSelectedCustDisable(false));
      await dispatch(changeSelectedOption(false));
      await dispatch(changeBookingType(defaultBookingType || 'TakeAway'));
      // await dispatch(changeholddata(null))
      await dispatch(changeOrderType());
    }
    await dispatch(ChangeOverAllDiscSales(null));
    await dispatch(ChangeOverAllDiscEstimate(null));
    await dispatch(changeTokenOnly(false));
    await dispatch(changeAllProductTokenAvailable(false));
    await dispatch(changeSelProdWiseEst([]));
    const customerDisplayWindow = getCustomerDisplayWindow();
    if (customerDisplayWindow && !customerDisplayWindow.closed) {
      const updatedData = {
        type: 'remove',
        keyValue: 'customer',
      };
      customerDisplayWindow.postMessage(updatedData, '*');
    } else {
      console.error(
        'Customer display window is not available or has been closed.'
      );
    }
  };

  const handleEditQuantity = (value) => {
    if (
      OtherServicesglobal &&
      value?.Type == 'OS' &&
      value?.ServiceType == 'I'
    ) {
      setEditQuantity(false);
    } else {
      setEditQuantity(true);
      setModaldata(value);
      setIndex(value?.localId);
    }
  };

  const handleEditQuantityCancel = () => {
    setEditQuantity(false);
  };

  const increase = async (item) => {
    const OtherOrderDatas = TableData?.filter(
      (cartItem) =>
        !(
          cartItem?.ProdId === item?.ProdId &&
          cartItem?.InwardDtlId === item?.InwardDtlId &&
          cartItem?.OrderRate === item?.OrderRate &&
          cartItem?.BookingTypeName === item?.BookingTypeName
        ) && !cartItem?.SalesId
    );
    const OtherOrderDatawithsales = TableData?.filter(
      (cartItem) => cartItem?.SalesId
    );

    const OtherorderDataforNormal = TableData?.filter(
      (cartItem) =>
        !(
          cartItem?.ProdId === item?.ProdId &&
          cartItem?.InwardDtlId === item?.InwardDtlId &&
          cartItem?.OrderRate === item?.OrderRate &&
          cartItem?.BookingTypeName === item?.BookingTypeName &&
          !cartItem?.SalesId
        )
    );
    const isItemInCart = TableData?.find(
      (cartItem) =>
        cartItem?.ProdId === item?.ProdId &&
        cartItem?.InwardDtlId === item?.InwardDtlId &&
        cartItem?.OrderRate === item?.OrderRate &&
        cartItem?.BookingTypeName === item?.BookingTypeName &&
        !cartItem?.SalesId
    ); // check if the item is already in the cart
    const isItemNotInDine = TableData?.find(
      (cartItem) =>
        cartItem?.ProdId === item?.ProdId &&
        cartItem?.InwardDtlId === item?.InwardDtlId &&
        cartItem?.OrderRate === item?.OrderRate &&
        cartItem?.BookingTypeName === item?.BookingTypeName &&
        !cartItem?.SalesId
    ); // check if the item is already in the cart
    const isItemInCartHold = TableData?.find(
      (cartItem) =>
        cartItem?.ProdId === item?.ProdId &&
        cartItem?.InwardDtlId === item?.InwardDtlId &&
        cartItem?.OrderRate === item?.OrderRate &&
        cartItem?.BookingTypeName === item?.BookingTypeName
    ); // check if the item is already in the cart
    const OtherorderDataforNormalWithoutSalesId = TableData?.filter(
      (cartItem) =>
        !(
          cartItem?.ProdId === item?.ProdId &&
          cartItem?.InwardDtlId === item?.InwardDtlId &&
          cartItem?.OrderRate === item?.OrderRate &&
          cartItem?.BookingTypeName === item?.BookingTypeName
        )
    );

    const BookingTypeProd = item?.BookingTypeName;
    if (isItemInCart && BookingTypeProd != 'Dine In' && OrderType != 'Hold') {
      if (BillOrderPre === 'Y') {
        const UpdatedCartItem =
          // if the item is already in the cart, increase the quantity of the item
          {
            ...isItemInCart,
            OrderQty: isItemInCart?.OrderQty + 1,
            TotalAmt: (isItemInCart?.OrderQty + 1) * isItemInCart?.OrderRate,
            TaxAmt: (
              ((isItemInCart?.OrderQty + 1) *
                isItemInCart?.OrderRate *
                isItemInCart?.TaxPercentage) /
              (100 + isItemInCart?.TaxPercentage)
            ).toFixed(2),
            WithoutTaxRate:
              (isItemInCart?.OrderQty + 1) * isItemInCart?.OrderRate -
              (
                ((isItemInCart?.OrderQty + 1) *
                  isItemInCart?.OrderRate *
                  isItemInCart?.TaxPercentage) /
                (100 + isItemInCart?.TaxPercentage)
              ).toFixed(2),
          };

        const UpdatedData = [UpdatedCartItem, ...OtherorderDataforNormal];

        if (OfferCheckedInSetup && preferenceOffer) {
          await applyOffer(UpdatedData);
        } else {
          dispatch(changeOrderCardDetails(UpdatedData));
        }
      } else {
        const UpdatedCartItem =
          // if the item is already in the cart, increase the quantity of the item
          {
            ...isItemInCart,
            OrderQty: isItemInCart?.OrderQty + 1,
            TotalAmt: (isItemInCart?.OrderQty + 1) * isItemInCart?.OrderRate,
            TaxAmt: (
              ((isItemInCart?.OrderQty + 1) *
                isItemInCart?.OrderRate *
                isItemInCart?.TaxPercentage) /
              (100 + isItemInCart?.TaxPercentage)
            ).toFixed(2),
            WithoutTaxRate:
              (isItemInCart?.OrderQty + 1) * isItemInCart?.OrderRate -
              (
                ((isItemInCart?.OrderQty + 1) *
                  isItemInCart?.OrderRate *
                  isItemInCart?.TaxPercentage) /
                (100 + isItemInCart?.TaxPercentage)
              ).toFixed(2),
          };

        const UpdatedData = [...OtherorderDataforNormal, UpdatedCartItem];

        if (OfferCheckedInSetup && preferenceOffer) {
          await applyOffer(UpdatedData);
        } else {
          dispatch(changeOrderCardDetails(UpdatedData));
        }
      }
    }
    //mohan for both
    else if (
      isItemInCart &&
      BookingTypeProd === 'Dine In' &&
      OrderType != 'Hold'
    ) {
      if (BillOrderPre === 'Y') {
        const UpdatedCartItem =
          // if the item is already in the cart, increase the quantity of the item
          {
            ...isItemInCart,
            OrderQty: isItemInCart?.OrderQty + 1,
            TotalAmt: (isItemInCart?.OrderQty + 1) * isItemInCart?.OrderRate,
            TaxAmt: (
              ((isItemInCart?.OrderQty + 1) *
                isItemInCart?.OrderRate *
                isItemInCart?.TaxPercentage) /
              (100 + isItemInCart?.TaxPercentage)
            ).toFixed(2),
            WithoutTaxRate:
              (isItemInCart?.OrderQty + 1) * isItemInCart?.OrderRate -
              (
                ((isItemInCart?.OrderQty + 1) *
                  isItemInCart?.OrderRate *
                  isItemInCart?.TaxPercentage) /
                (100 + isItemInCart?.TaxPercentage)
              ).toFixed(2),
          };

        const UpdatedData = [UpdatedCartItem, ...OtherorderDataforNormal];

        if (OfferCheckedInSetup && preferenceOffer) {
          await applyOffer(UpdatedData);
        } else {
          dispatch(changeOrderCardDetails(UpdatedData));
        }
      } else {
        const UpdatedCartItem =
          // if the item is already in the cart, increase the quantity of the item
          {
            ...isItemInCart,
            OrderQty: isItemInCart?.OrderQty + 1,
            TotalAmt: (isItemInCart?.OrderQty + 1) * isItemInCart?.OrderRate,
            TaxAmt: (
              ((isItemInCart?.OrderQty + 1) *
                isItemInCart?.OrderRate *
                isItemInCart?.TaxPercentage) /
              (100 + isItemInCart?.TaxPercentage)
            ).toFixed(2),
            WithoutTaxRate:
              (isItemInCart?.OrderQty + 1) * isItemInCart?.OrderRate -
              (
                ((isItemInCart?.OrderQty + 1) *
                  isItemInCart?.OrderRate *
                  isItemInCart?.TaxPercentage) /
                (100 + isItemInCart?.TaxPercentage)
              ).toFixed(2),
          };

        const UpdatedData = [...OtherorderDataforNormal, UpdatedCartItem];

        if (OfferCheckedInSetup && preferenceOffer) {
          await applyOffer(UpdatedData);
        } else {
          dispatch(changeOrderCardDetails(UpdatedData));
        }
      }
    } else if (isItemInCartHold && OrderType === 'Hold') {
      if (BillOrderPre === 'Y') {
        const UpdatedCartItem =
          // if the item is already in the cart, increase the quantity of the item
          {
            ...isItemInCartHold,
            OrderQty: isItemInCartHold?.OrderQty + 1,
            TotalAmt:
              (isItemInCartHold?.OrderQty + 1) * isItemInCartHold?.OrderRate,
            TaxAmt: (
              ((isItemInCartHold?.OrderQty + 1) *
                isItemInCartHold?.OrderRate *
                isItemInCartHold?.TaxPercentage) /
              (100 + isItemInCartHold?.TaxPercentage)
            ).toFixed(2),
            WithoutTaxRate:
              (isItemInCartHold?.OrderQty + 1) * isItemInCartHold?.OrderRate -
              (
                ((isItemInCartHold?.OrderQty + 1) *
                  isItemInCartHold?.OrderRate *
                  isItemInCartHold?.TaxPercentage) /
                (100 + isItemInCartHold?.TaxPercentage)
              ).toFixed(2),
          };

        const UpdatedData = [
          UpdatedCartItem,
          ...OtherorderDataforNormalWithoutSalesId,
        ];

        if (OfferCheckedInSetup && preferenceOffer) {
          await applyOffer(UpdatedData);
        } else {
          dispatch(changeOrderCardDetails(UpdatedData));
        }
      } else {
        const UpdatedCartItem =
          // if the item is already in the cart, increase the quantity of the item
          {
            ...isItemInCartHold,
            OrderQty: isItemInCartHold?.OrderQty + 1,
            TotalAmt:
              (isItemInCartHold?.OrderQty + 1) * isItemInCartHold?.OrderRate,
            TaxAmt: (
              ((isItemInCartHold?.OrderQty + 1) *
                isItemInCartHold?.OrderRate *
                isItemInCartHold?.TaxPercentage) /
              (100 + isItemInCartHold?.TaxPercentage)
            ).toFixed(2),
            WithoutTaxRate:
              (isItemInCartHold?.OrderQty + 1) * isItemInCartHold?.OrderRate -
              (
                ((isItemInCartHold?.OrderQty + 1) *
                  isItemInCartHold?.OrderRate *
                  isItemInCartHold?.TaxPercentage) /
                (100 + isItemInCartHold?.TaxPercentage)
              ).toFixed(2),
          };

        const UpdatedData = [
          ...OtherorderDataforNormalWithoutSalesId,
          UpdatedCartItem,
        ];

        if (OfferCheckedInSetup && preferenceOffer) {
          await applyOffer(UpdatedData);
        } else {
          dispatch(changeOrderCardDetails(UpdatedData));
        }
      }
    } else if (
      isItemNotInDine &&
      BookingTypeProd == 'Dine In' &&
      OrderType != 'Hold'
    ) {
      if (BillOrderPre === 'Y') {
        const UpdatedCartItem = {
          ...isItemNotInDine,
          OrderQty: isItemNotInDine?.OrderQty + 1,
          TotalAmt:
            (isItemNotInDine?.OrderQty + 1) * isItemNotInDine?.OrderRate,
          TaxAmt: (
            ((isItemNotInDine?.OrderQty + 1) *
              isItemNotInDine?.OrderRate *
              isItemNotInDine?.TaxPercentage) /
            (100 + isItemNotInDine?.TaxPercentage)
          ).toFixed(2),
          WithoutTaxRate:
            (isItemNotInDine?.OrderQty + 1) * isItemNotInDine?.OrderRate -
            (
              ((isItemNotInDine?.OrderQty + 1) *
                isItemNotInDine?.OrderRate *
                isItemNotInDine?.TaxPercentage) /
              (100 + isItemNotInDine?.TaxPercentage)
            ).toFixed(2),
        };
        // otherwise, return the cart item
        const UpdatedData = [
          UpdatedCartItem,
          ...OtherOrderDatas,
          ...OtherOrderDatawithsales,
        ];

        if (OfferCheckedInSetup && preferenceOffer) {
          await applyOffer(UpdatedData);
        } else {
          dispatch(changeOrderCardDetails(UpdatedData));
        }
      } else {
        const UpdatedCartItem = {
          ...isItemNotInDine,
          OrderQty: isItemNotInDine?.OrderQty + 1,
          TotalAmt:
            (isItemNotInDine?.OrderQty + 1) * isItemNotInDine?.OrderRate,
          TaxAmt: (
            ((isItemNotInDine?.OrderQty + 1) *
              isItemNotInDine?.OrderRate *
              isItemNotInDine?.TaxPercentage) /
            (100 + isItemNotInDine?.TaxPercentage)
          ).toFixed(2),
          WithoutTaxRate:
            (isItemNotInDine?.OrderQty + 1) * isItemNotInDine?.OrderRate -
            (
              ((isItemNotInDine?.OrderQty + 1) *
                isItemNotInDine?.OrderRate *
                isItemNotInDine?.TaxPercentage) /
              (100 + isItemNotInDine?.TaxPercentage)
            ).toFixed(2),
        };
        // otherwise, return the cart item
        const UpdatedData = [
          ...OtherOrderDatawithsales,
          ...OtherOrderDatas,
          UpdatedCartItem,
        ];

        if (OfferCheckedInSetup && preferenceOffer) {
          await applyOffer(UpdatedData);
        } else {
          dispatch(changeOrderCardDetails(UpdatedData));
        }
      }
    }
    await dispatch(changeothersdata({}));

    setCount(count + 1);
  };

  const getPreference = async () => {
    // const data = { AppId: AppId, CompId: CompId, BranchId: BranchId };
    // const { data: res } = await dispatch(getPreferenceData(data)).unwrap()
    const decimalSetting = preferenceDatas?.[0]?.SettingDtlDetails?.find(
      (setting) =>
        setting?.SettingIdName?.toLowerCase() === 'decimal' &&
        setting?.SettingValue === 'Y'
    );
    if (decimalSetting) {
      setAllowDecimal(true);
    }
  };
  function safeRound(amountStr) {
    if (amountStr == null) return allowDecimal ? '0.00' : '0';

    const cleaned = String(amountStr).replace(/[^0-9.-]+/g, '');
    const num = Number(cleaned);

    if (isNaN(num)) return allowDecimal ? '0.00' : '0';

    return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
  }
  const decline = async (item) => {
    setPreviousdataLength(TableData?.length);
    const isItemInCart = TableData?.find(
      (cartItem) =>
        cartItem?.ProdId === item?.ProdId &&
        cartItem?.InwardDtlId === item?.InwardDtlId &&
        cartItem?.OrderRate === item?.OrderRate &&
        cartItem?.BookingTypeName === item?.BookingTypeName
    ); // check if the item is already in the cart
    if (isItemInCart) {
      if (isItemInCart?.OrderQty > 1) {
        const OtherOrderDatas = TableData?.filter(
          (cartItem) =>
            !(
              cartItem?.ProdId === item?.ProdId &&
              cartItem?.InwardDtlId === item?.InwardDtlId &&
              cartItem?.OrderRate === item?.OrderRate &&
              cartItem?.BookingTypeName === item?.BookingTypeName
            ) && !cartItem?.SalesId
        );
        const OtherOrderDatawithsales = TableData?.filter(
          (cartItem) => cartItem?.SalesId
        );

        const OtherorderDataforNormal = TableData?.filter(
          (cartItem) =>
            !(
              cartItem?.ProdId === item?.ProdId &&
              cartItem?.InwardDtlId === item?.InwardDtlId &&
              cartItem?.OrderRate === item?.OrderRate &&
              cartItem?.BookingTypeName === item?.BookingTypeName &&
              !cartItem?.SalesId
            )
        );
        const isItemInCart = TableData?.find(
          (cartItem) =>
            cartItem?.ProdId === item?.ProdId &&
            cartItem?.InwardDtlId === item?.InwardDtlId &&
            cartItem?.OrderRate === item?.OrderRate &&
            cartItem?.BookingTypeName === item?.BookingTypeName &&
            !cartItem?.SalesId
        ); // check if the item is already in the cart
        const isItemNotInDine = TableData?.find(
          (cartItem) =>
            cartItem?.ProdId === item?.ProdId &&
            cartItem?.InwardDtlId === item?.InwardDtlId &&
            cartItem?.OrderRate === item?.OrderRate &&
            cartItem?.BookingTypeName === item?.BookingTypeName &&
            !cartItem?.SalesId
        ); // check if the item is already in the cart
        const isItemInCartHold = TableData?.find(
          (cartItem) =>
            cartItem?.ProdId === item?.ProdId &&
            cartItem?.InwardDtlId === item?.InwardDtlId &&
            cartItem?.OrderRate === item?.OrderRate &&
            cartItem?.BookingTypeName === item?.BookingTypeName
        ); // check if the item is already in the cart
        const OtherorderDataforNormalWithoutSalesId = TableData?.filter(
          (cartItem) =>
            !(
              cartItem?.ProdId === item?.ProdId &&
              cartItem?.InwardDtlId === item?.InwardDtlId &&
              cartItem?.OrderRate === item?.OrderRate &&
              cartItem?.BookingTypeName === item?.BookingTypeName
            )
        );

        const BookingTypeProd = item?.BookingTypeName;
        if (
          isItemInCart &&
          BookingTypeProd != 'Dine In' &&
          OrderType != 'Hold'
        ) {
          if (BillOrderPre === 'Y') {
            const UpdatedCartItem =
              // if the item is already in the cart, increase the quantity of the item
              {
                ...isItemInCart,
                OrderQty: isItemInCart?.OrderQty - 1,
                TotalAmt:
                  (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate,
                TaxAmt: (
                  ((isItemInCart?.OrderQty - 1) *
                    isItemInCart?.OrderRate *
                    isItemInCart?.TaxPercentage) /
                  (100 + isItemInCart?.TaxPercentage)
                ).toFixed(2),
                WithoutTaxRate:
                  (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate -
                  (
                    ((isItemInCart?.OrderQty - 1) *
                      isItemInCart?.OrderRate *
                      isItemInCart?.TaxPercentage) /
                    (100 + isItemInCart?.TaxPercentage)
                  ).toFixed(2),
              };

            const UpdatedData = [UpdatedCartItem, ...OtherorderDataforNormal];

            if (OfferCheckedInSetup && preferenceOffer) {
              await applyOffer(UpdatedData);
            } else {
              dispatch(changeOrderCardDetails(UpdatedData));
            }
          } else {
            const UpdatedCartItem =
              // if the item is already in the cart, increase the quantity of the item
              {
                ...isItemInCart,
                OrderQty: isItemInCart?.OrderQty - 1,
                TotalAmt:
                  (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate,
                TaxAmt: (
                  ((isItemInCart?.OrderQty - 1) *
                    isItemInCart?.OrderRate *
                    isItemInCart?.TaxPercentage) /
                  (100 + isItemInCart?.TaxPercentage)
                ).toFixed(2),
                WithoutTaxRate:
                  (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate -
                  (
                    ((isItemInCart?.OrderQty - 1) *
                      isItemInCart?.OrderRate *
                      isItemInCart?.TaxPercentage) /
                    (100 + isItemInCart?.TaxPercentage)
                  ).toFixed(2),
              };

            const UpdatedData = [...OtherorderDataforNormal, UpdatedCartItem];

            if (OfferCheckedInSetup && preferenceOffer) {
              await applyOffer(UpdatedData);
            } else {
              dispatch(changeOrderCardDetails(UpdatedData));
            }
          }
        }
        //mohan for both
        else if (
          isItemInCart &&
          BookingTypeProd === 'Dine In' &&
          OrderType != 'Hold'
        ) {
          if (BillOrderPre === 'Y') {
            const UpdatedCartItem =
              // if the item is already in the cart, increase the quantity of the item
              {
                ...isItemInCart,
                OrderQty: isItemInCart?.OrderQty - 1,
                TotalAmt:
                  (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate,
                TaxAmt: (
                  ((isItemInCart?.OrderQty - 1) *
                    isItemInCart?.OrderRate *
                    isItemInCart?.TaxPercentage) /
                  (100 + isItemInCart?.TaxPercentage)
                ).toFixed(2),
                WithoutTaxRate:
                  (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate -
                  (
                    ((isItemInCart?.OrderQty - 1) *
                      isItemInCart?.OrderRate *
                      isItemInCart?.TaxPercentage) /
                    (100 + isItemInCart?.TaxPercentage)
                  ).toFixed(2),
              };
            const UpdatedData = [UpdatedCartItem, ...OtherorderDataforNormal];

            if (OfferCheckedInSetup && preferenceOffer) {
              await applyOffer(UpdatedData);
            } else {
              dispatch(changeOrderCardDetails(UpdatedData));
            }
          } else {
            const UpdatedCartItem =
              // if the item is already in the cart, increase the quantity of the item
              {
                ...isItemInCart,
                OrderQty: isItemInCart?.OrderQty - 1,
                TotalAmt:
                  (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate,
                TaxAmt: (
                  ((isItemInCart?.OrderQty - 1) *
                    isItemInCart?.OrderRate *
                    isItemInCart?.TaxPercentage) /
                  (100 + isItemInCart?.TaxPercentage)
                ).toFixed(2),
                WithoutTaxRate:
                  (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate -
                  (
                    ((isItemInCart?.OrderQty - 1) *
                      isItemInCart?.OrderRate *
                      isItemInCart?.TaxPercentage) /
                    (100 + isItemInCart?.TaxPercentage)
                  ).toFixed(2),
              };

            const UpdatedData = [...OtherorderDataforNormal, UpdatedCartItem];

            if (OfferCheckedInSetup && preferenceOffer) {
              await applyOffer(UpdatedData);
            } else {
              dispatch(changeOrderCardDetails(UpdatedData));
            }
          }
        } else if (isItemInCartHold && OrderType === 'Hold') {
          if (BillOrderPre === 'Y') {
            const UpdatedCartItem =
              // if the item is already in the cart, increase the quantity of the item
              {
                ...isItemInCartHold,
                OrderQty: isItemInCartHold?.OrderQty - 1,
                TotalAmt:
                  (isItemInCartHold?.OrderQty - 1) *
                  isItemInCartHold?.OrderRate,
                TaxAmt: (
                  ((isItemInCartHold?.OrderQty - 1) *
                    isItemInCartHold?.OrderRate *
                    isItemInCartHold?.TaxPercentage) /
                  (100 + isItemInCartHold?.TaxPercentage)
                ).toFixed(2),
                WithoutTaxRate:
                  (isItemInCartHold?.OrderQty - 1) *
                    isItemInCartHold?.OrderRate -
                  (
                    ((isItemInCartHold?.OrderQty - 1) *
                      isItemInCartHold?.OrderRate *
                      isItemInCartHold?.TaxPercentage) /
                    (100 + isItemInCartHold?.TaxPercentage)
                  ).toFixed(2),
              };

            const UpdatedData = [
              UpdatedCartItem,
              ...OtherorderDataforNormalWithoutSalesId,
            ];

            if (OfferCheckedInSetup && preferenceOffer) {
              await applyOffer(UpdatedData);
            } else {
              dispatch(changeOrderCardDetails(UpdatedData));
            }
          } else {
            const UpdatedCartItem =
              // if the item is already in the cart, increase the quantity of the item
              {
                ...isItemInCartHold,
                OrderQty: isItemInCartHold?.OrderQty - 1,
                TotalAmt:
                  (isItemInCartHold?.OrderQty - 1) *
                  isItemInCartHold?.OrderRate,
                TaxAmt: (
                  ((isItemInCartHold?.OrderQty - 1) *
                    isItemInCartHold?.OrderRate *
                    isItemInCartHold?.TaxPercentage) /
                  (100 + isItemInCartHold?.TaxPercentage)
                ).toFixed(2),
                WithoutTaxRate:
                  (isItemInCartHold?.OrderQty - 1) *
                    isItemInCartHold?.OrderRate -
                  (
                    ((isItemInCartHold?.OrderQty - 1) *
                      isItemInCartHold?.OrderRate *
                      isItemInCartHold?.TaxPercentage) /
                    (100 + isItemInCartHold?.TaxPercentage)
                  ).toFixed(2),
              };

            const UpdatedData = [
              ...OtherorderDataforNormalWithoutSalesId,
              UpdatedCartItem,
            ];

            if (OfferCheckedInSetup && preferenceOffer) {
              await applyOffer(UpdatedData);
            } else {
              dispatch(changeOrderCardDetails(UpdatedData));
            }
          }
        } else if (
          isItemNotInDine &&
          BookingTypeProd == 'Dine In' &&
          OrderType != 'Hold'
        ) {
          if (BillOrderPre === 'Y') {
            const UpdatedCartItem = {
              ...isItemNotInDine,
              OrderQty: isItemNotInDine?.OrderQty - 1,
              TotalAmt:
                (isItemNotInDine?.OrderQty - 1) * isItemNotInDine?.OrderRate,
              TaxAmt: (
                ((isItemNotInDine?.OrderQty - 1) *
                  isItemNotInDine?.OrderRate *
                  isItemNotInDine?.TaxPercentage) /
                (100 + isItemNotInDine?.TaxPercentage)
              ).toFixed(2),
              WithoutTaxRate:
                (isItemNotInDine?.OrderQty - 1) * isItemNotInDine?.OrderRate -
                (
                  ((isItemNotInDine?.OrderQty - 1) *
                    isItemNotInDine?.OrderRate *
                    isItemNotInDine?.TaxPercentage) /
                  (100 + isItemNotInDine?.TaxPercentage)
                ).toFixed(2),
            };
            // otherwise, return the cart item
            const UpdatedData = [
              UpdatedCartItem,
              ...OtherOrderDatas,
              ...OtherOrderDatawithsales,
            ];

            if (OfferCheckedInSetup && preferenceOffer) {
              await applyOffer(UpdatedData);
            } else {
              dispatch(changeOrderCardDetails(UpdatedData));
            }
          } else {
            const UpdatedCartItem = {
              ...isItemNotInDine,
              OrderQty: isItemNotInDine?.OrderQty - 1,
              TotalAmt:
                (isItemNotInDine?.OrderQty - 1) * isItemNotInDine?.OrderRate,
              TaxAmt: (
                ((isItemNotInDine?.OrderQty - 1) *
                  isItemNotInDine?.OrderRate *
                  isItemNotInDine?.TaxPercentage) /
                (100 + isItemNotInDine?.TaxPercentage)
              ).toFixed(2),
              WithoutTaxRate:
                (isItemNotInDine?.OrderQty - 1) * isItemNotInDine?.OrderRate -
                (
                  ((isItemNotInDine?.OrderQty - 1) *
                    isItemNotInDine?.OrderRate *
                    isItemNotInDine?.TaxPercentage) /
                  (100 + isItemNotInDine?.TaxPercentage)
                ).toFixed(2),
            };
            // otherwise, return the cart item
            const UpdatedData = [
              ...OtherOrderDatawithsales,
              ...OtherOrderDatas,
              UpdatedCartItem,
            ];

            if (OfferCheckedInSetup && preferenceOffer) {
              await applyOffer(UpdatedData);
            } else {
              dispatch(changeOrderCardDetails(UpdatedData));
            }
          }
        }
      } else {
        await dispatch(
          ChangeTotalAmount(
            GlobalExtraCharge?.filter((extra) => {
              if (BookingType === 'Dine In') {
                // Remove extra charges linked to the removed product
                return !(extra.ProdId === item?.ProdId && !extra.SalesId);
              } else if (BookingType === 'TakeAway') {
                // Remove extra charges only if SalesId is not present
                return extra.ProdId !== item?.ProdId;
              }
              return true; // Keep everything else
            })
          )
        ); // if the quantity of the item is 1, remove the item from the cart
        if (item?.BookingTypeName !== 'Dine In' && OrderType !== 'Hold') {
          const UpdatedData = TableData?.filter(
            (cartItem) =>
              !(
                cartItem?.ProdId === item?.ProdId &&
                cartItem?.InwardDtlId === item?.InwardDtlId &&
                cartItem?.OrderRate === item?.OrderRate &&
                cartItem?.BookingTypeName === item?.BookingTypeName &&
                !cartItem?.SalesId
              )
          );

          if (OfferCheckedInSetup && preferenceOffer) {
            await applyOffer(UpdatedData);
          } else {
            dispatch(changeOrderCardDetails(UpdatedData));
          }

          // if the quantity of the item is 1, remove the item from the cart
          if (TableData?.length <= 1) {
            await dispatch(changeReorderHoldDetails({}));
            await dispatch(changeReorderProductDetails([]));
            await dispatch(changeUnpaidData(false));
            await dispatch(changeBookingType('TakeAway'));
            await dispatch(ChangeOverAllDiscSales(null));
            await dispatch(ChangeOverAllDiscEstimate(null));
            await dispatch(changeSelProdWiseEst([]));
            await dispatch(ChangeTotalAmount([]));
          }
        } else if (
          item?.BookingTypeName !== 'Dine In' &&
          OrderType === 'Hold'
        ) {
          const UpdatedData = TableData?.filter(
            (cartItem) =>
              !(
                cartItem?.ProdId === item?.ProdId &&
                cartItem?.InwardDtlId === item?.InwardDtlId &&
                cartItem?.OrderRate === item?.OrderRate &&
                cartItem?.BookingTypeName === item?.BookingTypeName
              )
          );

          if (OfferCheckedInSetup && preferenceOffer) {
            await applyOffer(UpdatedData);
          } else {
            dispatch(changeOrderCardDetails(UpdatedData));
          }

          // if the quantity of the item is 1, remove the item from the cart
          if (TableData?.length <= 1) {
            await dispatch(changeReorderHoldDetails({}));
            await dispatch(changeReorderProductDetails([]));
            await dispatch(changeUnpaidData(false));
            await dispatch(changeBookingType('TakeAway'));
            await dispatch(ChangeOverAllDiscSales(null));
            await dispatch(ChangeOverAllDiscEstimate(null));
            await dispatch(changeSelProdWiseEst([]));
            await dispatch(ChangeTotalAmount([]));
          }
        } else if (item?.BookingTypeName === 'Dine In') {
          const UpdatedData = TableData?.filter(
            (cartItem) =>
              !(
                cartItem?.ProdId === item?.ProdId &&
                cartItem?.InwardDtlId === item?.InwardDtlId &&
                cartItem?.OrderRate === item?.OrderRate &&
                cartItem?.BookingTypeName === item?.BookingTypeName &&
                !cartItem?.SalesId
              )
          );

          if (OfferCheckedInSetup && preferenceOffer) {
            await applyOffer(UpdatedData);
          } else {
            dispatch(changeOrderCardDetails(UpdatedData));
          }
          await dispatch(ChangeTotalAmount([]));
          if (TableData?.length <= 1) {
            await dispatch(changeReorderHoldDetails({}));
            await dispatch(changeReorderProductDetails([]));
            await dispatch(changeUnpaidData(false));
            await dispatch(ChangeSelectedCustDisable(false));
            await dispatch(changeSelectedOption(false));
            await dispatch(changeBookingType('TakeAway'));
            await dispatch(ChangeOverAllDiscSales(null));
            await dispatch(ChangeOverAllDiscEstimate(null));
            await dispatch(changeSelProdWiseEst([]));
            await dispatch(ChangeTotalAmount([]));
          }
        }
      }
    }
  };
  const returnCount = (item) => {
    if (item?.SinglePc === 'Y') {
      let SelectedProduct = ReorderProductData?.filter(
        (a) =>
          a?.ProdId === item?.ProdId && a?.InwardDtlId === item?.InwardDtlId
      );
      let totalSelectedProductQty = SelectedProduct?.reduce(
        (accumulator, card) => {
          return (
            accumulator +
            parseInt(
              card?.StockAvailable === 'Y'
                ? card.SinglePc !== 'Y'
                  ? card.OrderQty * card.NoOfPcs
                  : card.OrderQty
                : 0
            )
          );
        },
        0
      );
      let getCurrentProdDtl = TableData?.filter(
        (a) =>
          a?.ProdId === item?.ProdId && a?.InwardDtlId === item?.InwardDtlId
      );
      let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
        return (
          accumulator +
          parseInt(
            card.SinglePc !== 'Y' ? card.OrderQty * card.NoOfPcs : card.OrderQty
          )
        );
      }, 0);

      let OverallProdQty = totalOrderQty - totalSelectedProductQty;

      if (
        parseInt(item?.OverAllPcs) >
        parseInt(
          Object.keys(ReportholdData)?.length > 0 && totalOrderQty
            ? OverallProdQty
            : getCurrentProdDtl
              ? totalOrderQty
              : 0
        )
      ) {
        let count =
          parseInt(item?.OverAllPcs) -
          parseInt(
            Object.keys(ReportholdData)?.length > 0 && totalOrderQty
              ? OverallProdQty
              : getCurrentProdDtl
                ? totalOrderQty
                : 0
          );
        return parseInt(count);
      } else {
        let count = 0;
        return count;
      }
    } else {
      let getCurrentProdDtl = TableData?.filter(
        (a) =>
          a?.ProdId === item?.ProdId && a?.InwardDtlId === item?.InwardDtlId
      );

      let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
        return (
          accumulator +
          parseInt(
            card.SinglePc !== 'Y'
              ? card.OrderQty
              : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
                ? 0
                : card.OrderQty % card.NoOfPcs === 0
                  ? Math.floor(card.OrderQty / card.NoOfPcs)
                  : Math.floor(card.OrderQty / card.NoOfPcs) + 1
          )
        );
      }, 0);

      if (
        parseInt(item?.BalanceQty) > parseInt(totalOrderQty ? totalOrderQty : 0)
      ) {
        let count =
          parseInt(item?.BalanceQty) -
          parseInt(totalOrderQty ? totalOrderQty : 0);
        return parseInt(count);
      } else {
        let count = 0;
        return count;
      }
    }
  };
  const OpenEditTotalAmount = () => {
    setOpenEditTotalAmt(true);
  };
  const handleEditTotalAmountCancel = () => {
    setOpenEditTotalAmt(false);
  };
  return (
    <div className="BSBillingTable5-billtable">
      <table className="BSBillingTable5-tablediv">
        <thead className="BSBillingTable5-thead">
          <tr
            className="BSBillingTable5-table-tr"
            style={{
              color: SelectedBillColor?.['FontColor'],
              backgroundColor: SelectedBillColor?.['BackgroundColor'],
              fontFamily: SelectedFont,
            }}
          >
            {tableOptions?.map((item) => (
              <>
                {item.OptionName == 'Sl.No' && BookingTypeBoth && (
                  <th
                    className="BSBillingTable5-table-th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                      width: '10px',
                      padding: '1px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Serial Number"></Tooltip>
                    ) : (
                      <div></div>
                    )}
                  </th>
                )}
                {item.OptionName == 'Sl.No' &&
                  (templateData?.BookingLayout?.[0] === 'Combo1' ||
                    templateData?.BookingLayout?.[0] === 'Combo2') && (
                    <th
                      className="BSBillingTable5-table-th"
                      style={{
                        fontFamily: SelectedFont,
                        fontWeight: '600',
                        fontSize: '16px',
                        width: '10px',
                      }}
                    >
                      {!isMobile ? (
                        <Tooltip title="Serial Number">Sl.No</Tooltip>
                      ) : (
                        <div>Sl.No</div>
                      )}
                    </th>
                  )}
                {item.OptionName == 'Item' && (
                  <th
                    className="BSBillingTable5-table-th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Item Name">Item</Tooltip>
                    ) : (
                      <div> Item </div>
                    )}
                  </th>
                )}
                {item.OptionName == 'MRP' && (
                  <th
                    className="BSBillingTable5-table-th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                      width: '20px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="MRP">MRP</Tooltip>
                    ) : (
                      <div>MRP</div>
                    )}
                  </th>
                )}
                {item.OptionName == 'Discount' && (
                  <th
                    className="BSBillingTable5-table-th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                      width: '20px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Discount">₹/%</Tooltip>
                    ) : (
                      <div>₹/% </div>
                    )}
                  </th>
                )}
                {item.OptionName == 'Quantity' && (
                  <th
                    className="BSBillingTable5-table-th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                      width: '20px',
                    }}
                    // onClick={TableData?.length>0? OpenEditTotalAmount :""}
                    onClick={() => {
                      if (TableData?.length > 0) {
                        OpenEditTotalAmount();
                      }
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Quantity">Qty</Tooltip>
                    ) : (
                      <div>Qty</div>
                    )}
                  </th>
                )}
                {item.OptionName == 'Rate' && (
                  <th
                    className="BSBillingTable5-table-th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                      width: '20px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Rate">Rt</Tooltip>
                    ) : (
                      <div> Rt </div>
                    )}
                  </th>
                )}
                {item.OptionName == 'Amount' && (
                  <th
                    className="BSBillingTable5-table-th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                      width: '20px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Amount">Amt</Tooltip>
                    ) : (
                      <div>Amt</div>
                    )}
                  </th>
                )}

                {item.OptionName == 'Delete' && (
                  <th
                    className="BSBillingTable5-table-th"
                    style={{
                      fontFamily: SelectedFont,
                      padding: '0.5rem',
                      borderBottom: '1.9px solid #000',
                      fontWeight: '600',
                      fontSize: '16px',
                      width: '10px',
                    }}
                  >
                    {TableData?.length > 0 ? (
                      <Popconfirm
                        title="Delete the items"
                        description="Are you sure you want to clear these items?"
                        okText="Yes"
                        placement="leftTop"
                        cancelText="No"
                        onConfirm={() => {
                          Clearall();
                        }}
                      >
                        <div className="del-all-btn">
                          {' '}
                          {!isMobile ? (
                            <Tooltip title="Delete All" placement="left">
                              {' '}
                              <AiFillDelete />{' '}
                            </Tooltip>
                          ) : (
                            <div>
                              {' '}
                              <AiFillDelete />{' '}
                            </div>
                          )}{' '}
                        </div>
                      </Popconfirm>
                    ) : (
                      <div className="del-all-btn">
                        {!isMobile ? (
                          <Tooltip title="Delete" placement="left">
                            <AiFillDelete />
                          </Tooltip>
                        ) : (
                          <div>
                            {' '}
                            <AiFillDelete />{' '}
                          </div>
                        )}
                      </div>
                    )}
                  </th>
                )}
              </>
            ))}
          </tr>
        </thead>
        <tbody>
          {OldtableDataTakeAway?.length > 0 &&
            OldtableDataTakeAway?.map((item, index) => (
              <tr
                className={
                  item?.SalesId && OrderType !== 'Hold'
                    ? 'BSBillingTable5-table-tr-disabled'
                    : 'BSBillingTable5-table-tr'
                }
                style={{
                  fontFamily: SelectedFont ? SelectedFont : '',

                  backgroundColor:
                    BillOrderPre === 'Y'
                      ? item?.SalesId && OrderType !== 'Hold'
                        ? 'rgb(243, 248, 213)'
                        : triggerAnimation &&
                            index === 0 &&
                            !item?.SalesId &&
                            tableDataTakeAway?.length >= PreviousdataLength
                          ? 'wheat'
                          : triggerAnimation &&
                              index === 0 &&
                              tableDataTakeAway?.length >= PreviousdataLength &&
                              !HoldOrderDtl &&
                              !UnpaidData
                            ? 'wheat'
                            : 'inherit'
                      : 'none',
                  background:
                    item?.SalesId && OrderType !== 'Hold'
                      ? 'rgb(243, 248, 213)'
                      : GlobEstBooking === 'ParEst' &&
                          GlobProdwisedata?.includes(
                            item?.InwardDtlId + ' ' + item?.BookingTypeName
                          )
                        ? '#b2d1f7'
                        : index % 2 === 0
                          ? 'white'
                          : SelectedBillColor?.['OverallBackgroundColor']
                            ? SelectedBillColor?.['OverallBackgroundColor']
                            : '#d6d6d6',
                  animation:
                    BillOrderPre === 'Y' && !BookingTypeBoth
                      ? triggerAnimation &&
                        index === 0 &&
                        !item?.SalesId &&
                        tableDataTakeAway?.length >= PreviousdataLength &&
                        !HoldOrderDtl &&
                        !UnpaidData
                        ? 'splashAnimation 0.5s ease-in-out'
                        : 'none'
                      : 'none',
                }}
              >
                {tableOptions?.map((tableitem) => (
                  <>
                    {tableitem.OptionName == 'Sl.No' &&
                      BookingTypeBoth &&
                      index == 0 && (
                        <td
                          rowspan={TableData.length}
                          style={{ backgroundColor: '#CFB59D' }}
                        >
                          <img width="30px" alt="" src={TakeAwayIcon} />
                        </td>
                      )}
                    {tableitem.OptionName == 'Sl.No' &&
                      (templateData?.BookingLayout[0] === 'Combo1' ||
                        templateData?.BookingLayout[0] === 'Combo2') && (
                        <td
                          className={
                            templateData?.BookingLayout[0] === 'Combo1' ||
                            templateData?.BookingLayout[0] === 'Combo2'
                              ? 'Table3-Dis-index'
                              : 'Table3-Dis'
                          }
                          style={{ fontFamily: 'Poppins', width: '0px' }}
                          onClick={() => {
                            if (editField) {
                              handleEditQuantity(item);
                            }
                          }}
                        >
                          {index + 1}
                        </td>
                      )}
                    {tableitem.OptionName == 'Item' && (
                      <td
                        className="BSBillingTable5-table-td for-combo"
                        onClick={() =>
                          item.FullProductIdentifierDtls?.length > 0 ||
                          item.ProductIdentifierDtls?.length > 0
                            ? handleImeiDetails(item)
                            : editField && handleEditQuantity(item)
                        }
                      >
                        <div className="BSBillingTable5-table-cont">
                          <p style={{ fontFamily: 'Poppins' }}>
                            {item.ProdName} &nbsp;{' '}
                            {item.BrandName !== null ? item.BrandName : ''}
                            <br></br>
                            <a style={{ fontSize: '12px', fontWeight: '600' }}>
                              {/* <p className='Tbl5-Variant' style={{ fontFamily: "Poppins" }}>
                            ({!item?.ProdVariantName?.toLowerCase()?.includes('variant') && <span>{item?.ProdVariantName}  </span>}{item?.Size} {item?.SinglePc == 'Y' ? 'PCS' : item?.UomName})
                            </p> */}
                              {item?.Type != 'C' && (
                                <>
                                  <p
                                    className="Tbl5-Variant"
                                    style={{ fontFamily: 'Poppins' }}
                                  >
                                    (
                                    {!item?.ProdVariantName?.toLowerCase()?.includes(
                                      'variant'
                                    ) && <span>{item?.ProdVariantName} </span>}
                                    {item?.Size}
                                    {item?.SinglePc == 'Y'
                                      ? 'PCS'
                                      : item?.UomName}
                                    )
                                  </p>
                                  {item?.OfferMessage &&
                                    !Array.isArray(item.OfferMessage) && (
                                      <p
                                        className={`offermessageTag ${!isMobile ? 'desktop' : ''}`}
                                      >
                                        {item.OfferMessage?.split('>')?.[0] +
                                          `> ${item?.OrderQty} Eligible Free`}
                                      </p>
                                    )}
                                </>
                              )}
                              {item?.Type === 'C' && (
                                <div
                                  className="Tbl5-Variant"
                                  style={{ fontFamily: 'Poppins' }}
                                >
                                  {item.ProdDetail?.map((prod, index) => (
                                    <p key={index}>
                                      {prod.ProdName} - {prod.Size}{' '}
                                      {prod.UomName}
                                    </p>
                                  ))}
                                </div>
                              )}
                            </a>
                          </p>
                        </div>
                        {productBasedExtraCharges?.find(
                          (find) => find.ProdId === item.ProdId
                        ) !== undefined && (
                          <div
                            style={{
                              fontSize: '10px',
                              fontWeight: '500',
                              whiteSpace: 'nowrap',
                            }}
                          >
                            Extra Charges :{' '}
                            {
                              productBasedExtraCharges?.find(
                                (find) => find.ProdId === item.ProdId
                              )?.TotalAmt
                            }
                          </div>
                        )}
                      </td>
                    )}
                    {tableitem.OptionName == 'MRP' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.MRP}
                      </td>
                    )}
                    {tableitem.OptionName == 'Discount' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.Type != 'C'
                          ? item.Offer
                            ? item.Offer
                            : '-'
                          : item?.OfferPrice && item?.OfferPrice > 0
                            ? item?.OfferType === 'F'
                              ? `₹${safeRound(item.OfferPrice)}`
                              : `${item.OfferPrice}%`
                            : '-'}
                      </td>
                    )}
                    {tableitem.OptionName == 'Quantity' && (
                      <td className="BSBillingTable5-table-td">
                        <div className="BSBillingTable5-table-count">
                          <button
                            className="BSBillingTable5-table-count-min-btn"
                            onClick={() => decline(item)}
                            icon={<PlusOutlined />}
                          >
                            {' '}
                            -{' '}
                          </button>
                          <div
                            className="BSBillingTable5-table-count-num"
                            style={{ fontFamily: 'Poppins' }}
                            onClick={() => {
                              if (editField) {
                                handleEditQuantity(item);
                              }
                            }}
                          >
                            {item?.OrderQty}
                          </div>
                          {item?.StockAvailable === 'Y' ? (
                            returnCount(item) > 0 && (
                              <button
                                className="BSBillingTable5-table-count-max-btn"
                                onClick={() => increase(item)}
                                icon={<PlusOutlined />}
                              >
                                {' '}
                                +{' '}
                              </button>
                            )
                          ) : (
                            <button
                              className="BSBillingTable5-table-count-max-btn"
                              onClick={() => increase(item)}
                              icon={<PlusOutlined />}
                            >
                              {' '}
                              +{' '}
                            </button>
                          )}
                        </div>
                      </td>
                    )}
                    {tableitem.OptionName == 'Rate' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.OrderRate}
                      </td>
                    )}
                    {tableitem.OptionName == 'Amount' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.TotalAmt}
                      </td>
                    )}

                    {tableitem.OptionName == 'Delete' && (
                      <td
                        className="Table3-editicon"
                        style={{
                          textAlign: 'center',
                          height: '2px',
                          borderBottom: '1.9px dashed #000',
                        }}
                      >
                        <AiOutlineClose
                          onClick={() => removeFromCart(item)}
                          style={{ color: '#FF4D4F', cursor: 'pointer' }}
                        />
                      </td>
                    )}
                  </>
                ))}
              </tr>
            ))}
          {EditQuantity && OldtableDataTakeAway?.length > 0 && (
            <BSBillingEditQuantity
              handleEditQuantityCancel={handleEditQuantityCancel}
              BSBillingEditQuantity={EditQuantity}
              Productdata={Modaldata}
              Index={Index}
              shortKeyMethod={shortKeyMethod}
            />
          )}
        </tbody>
        <tbody>
          {OldtableDataDinein?.length > 0 &&
            OldtableDataDinein?.map((item, index) => (
              <tr
                className={
                  item?.SalesId
                    ? 'BSBillingTable5-table-tr-disabled'
                    : 'BSBillingTable5-table-tr'
                }
                style={{
                  fontFamily: SelectedFont,

                  backgroundColor:
                    BillOrderPre === 'Y'
                      ? item?.SalesId
                        ? 'rgb(243, 248, 213)'
                        : BookingType === 'Dine In' &&
                            triggerAnimation &&
                            OldtableDataTakeAway?.length + index === 0 &&
                            !item?.SalesId &&
                            tableDataDinein?.length >= PreviousdataLength
                          ? 'wheat'
                          : BookingType !== 'Dine In' &&
                              triggerAnimation &&
                              OldtableDataTakeAway?.length + index === 0 &&
                              tableDataDinein?.length >= PreviousdataLength &&
                              !HoldOrderDtl &&
                              !UnpaidData
                            ? 'wheat'
                            : 'inherit'
                      : 'none',
                  background: item?.SalesId
                    ? 'rgb(243, 248, 213)'
                    : GlobEstBooking === 'ParEst' &&
                        GlobProdwisedata?.includes(
                          item?.InwardDtlId + ' ' + item?.BookingTypeName
                        )
                      ? '#b2d1f7'
                      : (OldtableDataTakeAway?.length + index) % 2 === 0
                        ? 'white'
                        : SelectedBillColor?.['OverallBackgroundColor']
                          ? SelectedBillColor?.['OverallBackgroundColor']
                          : '#d6d6d6',
                  animation:
                    BillOrderPre === 'Y' && !BookingTypeBoth
                      ? triggerAnimation &&
                        OldtableDataTakeAway?.length + index === 0 &&
                        !item?.SalesId &&
                        tableDataDinein?.length >= PreviousdataLength &&
                        !HoldOrderDtl &&
                        !UnpaidData
                        ? 'splashAnimation 0.5s ease-in-out'
                        : 'none'
                      : 'none',
                }}
              >
                {tableOptions?.map((tableitem) => (
                  <>
                    {BookingTypeBoth &&
                      index == 0 &&
                      tableitem.OptionName == 'Sl.No' && (
                        <td
                          rowspan={TableData.length}
                          style={{ backgroundColor: '#A2C3CD' }}
                        >
                          <img width="30px" alt="" src={dineInIcon} />
                        </td>
                      )}
                    {tableitem.OptionName == 'Sl.No' &&
                      (templateData?.BookingLayout[0] === 'Combo1' ||
                        templateData?.BookingLayout[0] === 'Combo2') && (
                        <td
                          className={
                            templateData?.BookingLayout[0] === 'Combo1' ||
                            templateData?.BookingLayout[0] === 'Combo2'
                              ? 'Table3-Dis-index'
                              : 'Table3-Dis'
                          }
                          style={{ fontFamily: 'Poppins', width: '0px' }}
                          onClick={() => {
                            if (editField) {
                              handleEditQuantity(item);
                            }
                          }}
                        >
                          {index + 1}
                        </td>
                      )}
                    {tableitem.OptionName == 'Item' && (
                      <td
                        className="BSBillingTable5-table-td for-combo"
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        <div className="BSBillingTable5-table-cont">
                          <p style={{ fontFamily: 'Poppins' }}>
                            {item.ProdName} &nbsp;{' '}
                            {item.BrandName !== null ? item.BrandName : ''}
                            <br></br>
                            <a style={{ fontSize: '12px', fontWeight: '600' }}>
                              {item?.Type != 'C' && (
                                <>
                                  <p
                                    className="Tbl5-Variant"
                                    style={{ fontFamily: 'Poppins' }}
                                  >
                                    (
                                    {!item?.ProdVariantName?.toLowerCase()?.includes(
                                      'variant'
                                    ) && <span>{item?.ProdVariantName} </span>}
                                    {item?.Size}
                                    {item?.SinglePc == 'Y'
                                      ? 'PCS'
                                      : item?.UomName}
                                    )
                                  </p>
                                  {item?.OfferMessage &&
                                    !Array.isArray(item.OfferMessage) && (
                                      <p
                                        className={`offermessageTag ${!isMobile ? 'desktop' : ''}`}
                                      >
                                        {item.OfferMessage?.split('>')?.[0] +
                                          `> ${item?.OrderQty} Eligible Free`}
                                      </p>
                                    )}
                                </>
                              )}
                              {item?.Type === 'C' && (
                                <div
                                  className="Tbl5-Variant"
                                  style={{ fontFamily: 'Poppins' }}
                                >
                                  {item.ProdDetail?.map((prod, index) => (
                                    <p key={index}>
                                      {prod.ProdName} - {prod.Size}{' '}
                                      {prod.UomName}
                                    </p>
                                  ))}
                                </div>
                              )}
                            </a>
                          </p>
                        </div>
                        {productBasedExtraCharges?.find(
                          (find) => find.ProdId === item.ProdId
                        ) !== undefined && (
                          <div
                            style={{
                              fontSize: '10px',
                              fontWeight: '500',
                              whiteSpace: 'nowrap',
                            }}
                          >
                            Extra Charges :{' '}
                            {
                              productBasedExtraCharges?.find(
                                (find) => find.ProdId === item.ProdId
                              )?.TotalAmt
                            }
                          </div>
                        )}
                      </td>
                    )}
                    {tableitem.OptionName == 'MRP' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.MRP}
                      </td>
                    )}
                    {tableitem.OptionName == 'Discount' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.Type != 'C'
                          ? item.Offer
                            ? item.Offer
                            : '-'
                          : item?.OfferPrice && item?.OfferPrice > 0
                            ? item?.OfferType === 'F'
                              ? `₹${safeRound(item.OfferPrice)}`
                              : `${item.OfferPrice}%`
                            : '-'}
                      </td>
                    )}
                    {tableitem.OptionName == 'Quantity' && (
                      <td className="BSBillingTable5-table-td">
                        <div className="BSBillingTable5-table-count">
                          <button
                            className="BSBillingTable5-table-count-min-btn"
                            onClick={() => decline(item)}
                            icon={<PlusOutlined />}
                          >
                            {' '}
                            -{' '}
                          </button>
                          <div
                            className="BSBillingTable5-table-count-num"
                            style={{ fontFamily: 'Poppins' }}
                            onClick={() => {
                              if (editField) {
                                handleEditQuantity(item);
                              }
                            }}
                          >
                            {item?.OrderQty}
                          </div>
                          {item?.StockAvailable === 'Y' ? (
                            returnCount(item) > 0 && (
                              <button
                                className="BSBillingTable5-table-count-max-btn"
                                onClick={() => increase(item)}
                                icon={<PlusOutlined />}
                              >
                                {' '}
                                +{' '}
                              </button>
                            )
                          ) : (
                            <button
                              className="BSBillingTable5-table-count-max-btn"
                              onClick={() => increase(item)}
                              icon={<PlusOutlined />}
                            >
                              {' '}
                              +{' '}
                            </button>
                          )}
                        </div>
                      </td>
                    )}
                    {tableitem.OptionName == 'Rate' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.OrderRate}
                      </td>
                    )}
                    {tableitem.OptionName == 'Amount' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.TotalAmt}
                      </td>
                    )}

                    {tableitem.OptionName == 'Delete' && (
                      <td
                        className="Table3-editicon"
                        style={{
                          textAlign: 'center',
                          height: '2px',
                          borderBottom: '1.9px dashed #000',
                        }}
                      >
                        <AiOutlineClose
                          onClick={() => removeFromCart(item)}
                          style={{ color: '#FF4D4F', cursor: 'pointer' }}
                        />
                      </td>
                    )}
                  </>
                ))}
              </tr>
            ))}
          {OldtableDataDinein?.length > 0 && EditQuantity && (
            <BSBillingEditQuantity
              handleEditQuantityCancel={handleEditQuantityCancel}
              BSBillingEditQuantity={EditQuantity}
              Productdata={Modaldata}
              Index={Index}
              shortKeyMethod={shortKeyMethod}
            />
          )}
        </tbody>
        <tbody>
          {tableDataTakeAway?.length > 0 &&
            tableDataTakeAway?.map((item, index) => (
              <tr
                className={
                  BookingType === 'Dine In' && item?.SalesId
                    ? 'BSBillingTable5-table-tr-disabled'
                    : 'BSBillingTable5-table-tr'
                }
                style={{
                  fontFamily: SelectedFont,

                  backgroundColor:
                    BillOrderPre === 'Y'
                      ? BookingType === 'Dine In' && item?.SalesId
                        ? 'rgb(243, 248, 213)'
                        : BookingType === 'Dine In' &&
                            triggerAnimation &&
                            OldtableDataDinein?.length +
                              OldtableDataTakeAway?.length +
                              index ===
                              0 &&
                            !item?.SalesId &&
                            tableDataTakeAway?.length >= PreviousdataLength
                          ? 'wheat'
                          : BookingType !== 'Dine In' &&
                              triggerAnimation &&
                              OldtableDataDinein?.length +
                                OldtableDataTakeAway?.length +
                                index ===
                                0 &&
                              tableDataTakeAway?.length >= PreviousdataLength &&
                              !HoldOrderDtl &&
                              !UnpaidData
                            ? 'wheat'
                            : (OldtableDataDinein?.length +
                                  OldtableDataTakeAway?.length +
                                  index) %
                                  2 ===
                                0
                              ? 'white'
                              : SelectedBillColor?.['OverallBackgroundColor']
                                ? SelectedBillColor?.['OverallBackgroundColor']
                                : '#d6d6d6'
                      : (OldtableDataDinein?.length +
                            OldtableDataTakeAway?.length +
                            index) %
                            2 ===
                          0
                        ? 'white'
                        : SelectedBillColor?.['OverallBackgroundColor']
                          ? SelectedBillColor?.['OverallBackgroundColor']
                          : '#d6d6d6',
                  background:
                    BookingType === 'Dine In' && item?.SalesId
                      ? 'rgb(243, 248, 213)'
                      : GlobEstBooking === 'ParEst' &&
                          GlobProdwisedata?.includes(
                            item?.InwardDtlId + ' ' + item?.BookingTypeName
                          )
                        ? '#b2d1f7'
                        : (OldtableDataDinein?.length +
                              OldtableDataTakeAway?.length +
                              index) %
                              2 ===
                            0
                          ? 'white'
                          : SelectedBillColor?.['OverallBackgroundColor']
                            ? SelectedBillColor?.['OverallBackgroundColor']
                            : '#d6d6d6',
                  animation:
                    BillOrderPre === 'Y' && !BookingTypeBoth
                      ? triggerAnimation &&
                        OldtableDataDinein?.length +
                          OldtableDataTakeAway?.length +
                          index ===
                          0 &&
                        !item?.SalesId &&
                        tableDataTakeAway?.length >= PreviousdataLength &&
                        !HoldOrderDtl &&
                        !UnpaidData
                        ? 'splashAnimation 0.5s ease-in-out'
                        : 'none'
                      : 'none',
                }}
              >
                {tableOptions?.map((tableitem) => (
                  <>
                    {BookingTypeBoth &&
                      index == 0 &&
                      tableitem.OptionName == 'Sl.No' && (
                        <td
                          rowspan={TableData.length}
                          style={{ backgroundColor: '#CFB59D' }}
                        >
                          <img width="30px" alt="" src={TakeAwayIcon} />
                        </td>
                      )}
                    {tableitem.OptionName == 'Sl.No' &&
                      (templateData?.BookingLayout[0] === 'Combo1' ||
                        templateData?.BookingLayout[0] === 'Combo2') && (
                        <td
                          className={
                            templateData?.BookingLayout[0] === 'Combo1' ||
                            templateData?.BookingLayout[0] === 'Combo2'
                              ? 'Table3-Dis-index'
                              : 'Table3-Dis'
                          }
                          style={{ fontFamily: 'Poppins', width: '0px' }}
                          onClick={() => {
                            if (editField) {
                              handleEditQuantity(item);
                            }
                          }}
                        >
                          {index + 1}
                        </td>
                      )}
                    {tableitem.OptionName == 'Item' && (
                      <td
                        className="BSBillingTable5-table-td for-combo"
                        onClick={() =>
                          item.FullProductIdentifierDtls?.length > 0 ||
                          item.ProductIdentifierDtls?.length > 0
                            ? handleImeiDetails(item)
                            : editField && handleEditQuantity(item)
                        }
                      >
                        <div className="BSBillingTable5-table-cont">
                          <p style={{ fontFamily: 'Poppins' }}>
                            {item?.Type !== 'OS'
                              ? item.ProdName
                              : item.ServiceName}
                            &nbsp;{' '}
                            {item.BrandName !== null ? item.BrandName : ''}
                            <br></br>
                            <a style={{ fontSize: '12px', fontWeight: '600' }}>
                              {item?.Type != 'C' && (
                                <>
                                  <p
                                    className="Tbl5-Variant"
                                    style={{ fontFamily: 'Poppins' }}
                                  >
                                    {item?.Type !== 'OS' && (
                                      <>
                                        {!item?.ProdVariantName?.toLowerCase()?.includes(
                                          'variant'
                                        ) && (
                                          <span>{item?.ProdVariantName} </span>
                                        )}
                                        {item?.Size}
                                        {item?.SinglePc == 'Y'
                                          ? 'PCS'
                                          : item?.UomName}
                                      </>
                                    )}
                                  </p>
                                  {item?.OfferMessage &&
                                    !Array.isArray(item.OfferMessage) && (
                                      <p
                                        className={`offermessageTag ${!isMobile ? 'desktop' : ''}`}
                                      >
                                        {item.OfferMessage?.split('>')?.[0] +
                                          `> ${item?.OrderQty} Eligible Free`}
                                      </p>
                                    )}
                                </>
                              )}
                              {item?.Type === 'C' && (
                                <div
                                  className="Tbl5-Variant"
                                  style={{ fontFamily: 'Poppins' }}
                                >
                                  {item.ProdDetail?.map((prod, index) => (
                                    <p key={index}>
                                      {prod.ProdName} - {prod.Size}{' '}
                                      {prod.UomName}
                                    </p>
                                  ))}
                                </div>
                              )}
                            </a>
                          </p>
                        </div>
                        {productBasedExtraCharges?.find(
                          (find) => find.ProdId === item.ProdId
                        ) !== undefined && (
                          <div
                            style={{
                              fontSize: '10px',
                              fontWeight: '500',
                              whiteSpace: 'nowrap',
                            }}
                          >
                            Extra Charges :{' '}
                            {
                              productBasedExtraCharges?.find(
                                (find) => find.ProdId === item.ProdId
                              )?.TotalAmt
                            }
                          </div>
                        )}
                      </td>
                    )}
                    {tableitem.OptionName == 'MRP' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.MRP}
                      </td>
                    )}
                    {tableitem.OptionName == 'Discount' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.Type != 'C'
                          ? item.Offer
                            ? item.Offer
                            : '-'
                          : item?.OfferPrice && item?.OfferPrice > 0
                            ? item?.OfferType === 'F'
                              ? `₹${safeRound(item.OfferPrice)}`
                              : `${item.OfferPrice}%`
                            : '-'}
                      </td>
                    )}
                    {tableitem.OptionName == 'Quantity' && (
                      <td className="BSBillingTable5-table-td">
                        <div className="BSBillingTable5-table-count">
                          <button
                            className="BSBillingTable5-table-count-min-btn"
                            onClick={() => decline(item)}
                            icon={<PlusOutlined />}
                          >
                            {' '}
                            -{' '}
                          </button>
                          <div
                            className="BSBillingTable5-table-count-num"
                            style={{ fontFamily: 'Poppins' }}
                            onClick={() => {
                              if (editField) {
                                handleEditQuantity(item);
                              }
                            }}
                          >
                            {item?.OrderQty}
                          </div>
                          {item?.StockAvailable === 'Y' ? (
                            returnCount(item) > 0 && (
                              <button
                                className="BSBillingTable5-table-count-max-btn"
                                onClick={() =>
                                  item.Type == 'P' || item.Type == 'C'
                                    ? increase(item)
                                    : item.ServiceType == 'G'
                                      ? increase(item)
                                      : ''
                                }
                                icon={<PlusOutlined />}
                              >
                                {' '}
                                +{' '}
                              </button>
                            )
                          ) : (
                            <button
                              className="BSBillingTable5-table-count-max-btn"
                              onClick={() =>
                                item.Type == 'P' || item.Type == 'C'
                                  ? increase(item)
                                  : item.ServiceType == 'G'
                                    ? increase(item)
                                    : ''
                              }
                              icon={<PlusOutlined />}
                            >
                              {' '}
                              +{' '}
                            </button>
                          )}
                        </div>
                      </td>
                    )}
                    {tableitem.OptionName == 'Rate' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.OrderRate}
                      </td>
                    )}
                    {tableitem.OptionName == 'Amount' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.TotalAmt}
                      </td>
                    )}

                    {tableitem.OptionName == 'Delete' && (
                      <td
                        className="Table3-editicon"
                        style={{
                          textAlign: 'center',
                          height: '2px',
                          borderBottom: '1.9px dashed #000',
                        }}
                      >
                        <AiOutlineClose
                          onClick={() => removeFromCart(item)}
                          style={{ color: '#FF4D4F', cursor: 'pointer' }}
                        />
                      </td>
                    )}
                  </>
                ))}
              </tr>
            ))}
          {tableDataTakeAway?.length > 0 && EditQuantity && (
            <BSBillingEditQuantity
              handleEditQuantityCancel={handleEditQuantityCancel}
              BSBillingEditQuantity={EditQuantity}
              Productdata={Modaldata}
              Index={Index}
              shortKeyMethod={shortKeyMethod}
            />
          )}
        </tbody>
        <tbody>
          {tableDataDinein?.length > 0 &&
            tableDataDinein?.map((item, index) => (
              <tr
                className={
                  BookingType === 'Dine In' && item?.SalesId
                    ? 'BSBillingTable5-table-tr-disabled'
                    : 'BSBillingTable5-table-tr'
                }
                style={{
                  fontFamily: SelectedFont,

                  backgroundColor:
                    BillOrderPre === 'Y' && !BookingTypeBoth
                      ? BookingType === 'Dine In' &&
                        item?.SalesId &&
                        !BookingTypeBoth
                        ? 'rgb(243, 248, 213)'
                        : BookingType === 'Dine In' &&
                            triggerAnimation &&
                            OldtableDataTakeAway?.length +
                              OldtableDataDinein?.length +
                              tableDataTakeAway?.length +
                              index ===
                              0 &&
                            !item?.SalesId &&
                            tableDataDinein?.length >= PreviousdataLength
                          ? 'wheat'
                          : BookingType !== 'Dine In' &&
                              triggerAnimation &&
                              OldtableDataTakeAway?.length +
                                OldtableDataDinein?.length +
                                tableDataTakeAway?.length +
                                index ===
                                0 &&
                              tableDataDinein?.length >= PreviousdataLength &&
                              !HoldOrderDtl &&
                              !UnpaidData
                            ? 'wheat'
                            : 'inherit'
                      : 'none',
                  background:
                    BookingType === 'Dine In' &&
                    item?.SalesId &&
                    !BookingTypeBoth
                      ? 'rgb(243, 248, 213)'
                      : GlobEstBooking === 'ParEst' &&
                          GlobProdwisedata?.includes(
                            item?.InwardDtlId + ' ' + item?.BookingTypeName
                          )
                        ? '#b2d1f7'
                        : (OldtableDataTakeAway?.length +
                              OldtableDataDinein?.length +
                              tableDataTakeAway?.length +
                              index) %
                              2 ===
                            0
                          ? 'white'
                          : SelectedBillColor?.['OverallBackgroundColor']
                            ? SelectedBillColor?.['OverallBackgroundColor']
                            : '#d6d6d6',
                  animation:
                    BillOrderPre === 'Y' && !BookingTypeBoth
                      ? triggerAnimation &&
                        OldtableDataTakeAway?.length +
                          OldtableDataDinein?.length +
                          tableDataTakeAway?.length +
                          index ===
                          0 &&
                        !item?.SalesId &&
                        tableDataDinein?.length >= PreviousdataLength &&
                        !HoldOrderDtl &&
                        !UnpaidData
                        ? 'splashAnimation 0.5s ease-in-out'
                        : 'none'
                      : 'none',
                }}
              >
                {tableOptions?.map((tableitem) => (
                  <>
                    {BookingTypeBoth &&
                      index == 0 &&
                      tableitem.OptionName == 'Sl.No' && (
                        <td
                          rowspan={TableData.length}
                          style={{ backgroundColor: '#A2C3CD' }}
                        >
                          <img width="30px" alt="" src={dineInIcon} />
                        </td>
                      )}
                    {tableitem.OptionName == 'Sl.No' &&
                      (templateData?.BookingLayout[0] === 'Combo1' ||
                        templateData?.BookingLayout[0] === 'Combo2') && (
                        <td
                          className={
                            templateData?.BookingLayout[0] === 'Combo1' ||
                            templateData?.BookingLayout[0] === 'Combo2'
                              ? 'Table3-Dis-index'
                              : 'Table3-Dis'
                          }
                          style={{ fontFamily: 'Poppins', width: '0px' }}
                          onClick={() => {
                            if (editField) {
                              handleEditQuantity(item);
                            }
                          }}
                        >
                          {index + 1}
                        </td>
                      )}
                    {tableitem.OptionName == 'Item' && (
                      <td
                        className="BSBillingTable5-table-td for-combo"
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        <div className="BSBillingTable5-table-cont">
                          <p style={{ fontFamily: 'Poppins' }}>
                            {item.ProdName} &nbsp;{' '}
                            {item.BrandName !== null ? item.BrandName : ''}
                            <br></br>
                            <a style={{ fontSize: '12px', fontWeight: '600' }}>
                              {item?.Type != 'C' && (
                                <>
                                  <p
                                    className="Tbl5-Variant"
                                    style={{ fontFamily: 'Poppins' }}
                                  >
                                    (
                                    {!item?.ProdVariantName?.toLowerCase()?.includes(
                                      'variant'
                                    ) && <span>{item?.ProdVariantName} </span>}
                                    {item?.Size}
                                    {item?.SinglePc == 'Y'
                                      ? 'PCS'
                                      : item?.UomName}
                                    )
                                  </p>
                                  {item?.OfferMessage &&
                                    !Array.isArray(item.OfferMessage) && (
                                      <p
                                        className={`offermessageTag ${!isMobile ? 'desktop' : ''}`}
                                      >
                                        {item.OfferMessage?.split('>')?.[0] +
                                          `> ${item?.OrderQty} Eligible Free`}
                                      </p>
                                    )}
                                </>
                              )}
                              {item?.Type === 'C' && (
                                <div
                                  className="Tbl5-Variant"
                                  style={{ fontFamily: 'Poppins' }}
                                >
                                  {item.ProdDetail?.map((prod, index) => (
                                    <p key={index}>
                                      {prod.ProdName} - {prod.Size}{' '}
                                      {prod.UomName}
                                    </p>
                                  ))}
                                </div>
                              )}
                            </a>
                          </p>
                        </div>
                        {productBasedExtraCharges?.find(
                          (find) => find.ProdId === item.ProdId
                        ) !== undefined && (
                          <div
                            style={{
                              fontSize: '10px',
                              fontWeight: '500',
                              whiteSpace: 'nowrap',
                            }}
                          >
                            Extra Charges :{' '}
                            {
                              productBasedExtraCharges?.find(
                                (find) => find.ProdId === item.ProdId
                              )?.TotalAmt
                            }
                          </div>
                        )}
                      </td>
                    )}
                    {tableitem.OptionName == 'MRP' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.MRP}
                      </td>
                    )}
                    {tableitem.OptionName == 'Discount' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.Type != 'C'
                          ? item.Offer
                            ? item.Offer
                            : '-'
                          : item?.OfferPrice && item?.OfferPrice > 0
                            ? item?.OfferType === 'F'
                              ? `₹${safeRound(item.OfferPrice)}`
                              : `${item.OfferPrice}%`
                            : '-'}
                      </td>
                    )}
                    {tableitem.OptionName == 'Quantity' && (
                      <td className="BSBillingTable5-table-td">
                        <div className="BSBillingTable5-table-count">
                          <button
                            className="BSBillingTable5-table-count-min-btn"
                            onClick={() => decline(item)}
                            icon={<PlusOutlined />}
                          >
                            {' '}
                            -{' '}
                          </button>
                          <div
                            className="BSBillingTable5-table-count-num"
                            style={{ fontFamily: 'Poppins' }}
                            onClick={() => {
                              if (editField) {
                                handleEditQuantity(item);
                              }
                            }}
                          >
                            {item?.OrderQty}
                          </div>
                          {item?.StockAvailable === 'Y' ? (
                            returnCount(item) > 0 && (
                              <button
                                className="BSBillingTable5-table-count-max-btn"
                                onClick={() => increase(item)}
                                icon={<PlusOutlined />}
                              >
                                {' '}
                                +{' '}
                              </button>
                            )
                          ) : (
                            <button
                              className="BSBillingTable5-table-count-max-btn"
                              onClick={() => increase(item)}
                              icon={<PlusOutlined />}
                            >
                              {' '}
                              +{' '}
                            </button>
                          )}
                        </div>
                      </td>
                    )}
                    {tableitem.OptionName == 'Rate' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.OrderRate}
                      </td>
                    )}
                    {tableitem.OptionName == 'Amount' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          fontFamily: 'Poppins',
                          borderBottom: '1.9px dashed #000',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.TotalAmt}
                      </td>
                    )}

                    {tableitem.OptionName == 'Delete' && (
                      <td
                        className="Table3-editicon"
                        style={{
                          textAlign: 'center',
                          height: '2px',
                          borderBottom: '1.9px dashed #000',
                        }}
                      >
                        <AiOutlineClose
                          onClick={() => removeFromCart(item)}
                          style={{ color: '#FF4D4F', cursor: 'pointer' }}
                        />
                      </td>
                    )}
                  </>
                ))}
              </tr>
            ))}
          {tableDataDinein?.length > 0 && EditQuantity && (
            <BSBillingEditQuantity
              handleEditQuantityCancel={handleEditQuantityCancel}
              BSBillingEditQuantity={EditQuantity}
              Productdata={Modaldata}
              Index={Index}
              shortKeyMethod={shortKeyMethod}
            />
          )}
        </tbody>
      </table>

      {OpenEditTotalAmt && (
        <BSEditTotalAmt
          EditTotalOpen={OpenEditTotalAmt}
          EditTotalClose={handleEditTotalAmountCancel}
        />
      )}
      {OpenImeiDetail && (
        <BSImeiDetails
          DeviceDetails={OpenImeiDetail}
          handleDeviceDetailClose={handleImeiDetailClose}
          ProductDetail={Modaldata}
        />
      )}
    </div>
  );
};

export default BsBill;
