import { extractLastNumber, getSession } from '../../../../Services/Others';
import moment from 'moment';

const IndividualTokenMobilePrint = async (PrintDetails, UpiId, Mode) => {
  console.log(PrintDetails, Mode, 'PrintDetailsPrintDetails');
  let PrintDetail;
  let PaymentDetail;
  if (Mode === 'Reprint') {
    PrintDetail = PrintDetails;
    PaymentDetail = PrintDetails?.[0]?.OrderPaymentDtl?.filter(
      (ps) => ps.PaymentStatus === 'S'
    );
  } else {
    PrintDetail = PrintDetails?.[0]?.OrderDetails;
    PaymentDetail = PrintDetails?.[0]?.PaymentOrderDtl?.filter(
      (ps) => ps.PaymentStatus === 'S'
    );
  }

  let receiptText = '';
  let textEncodedest = '';
  let LogoImage = '';
  let TokenDataSales = '';
  let TokenDataEstimate = '';
  let OrderIdSales;
  let OrderIdEst;
  let FooterPrint = 'No';
  let OrderId;
  OrderIdSales = PrintDetail?.find((a) => a.OrderType === 'S')?.OrderId
    ? extractLastNumber(PrintDetail?.find((a) => a.OrderType === 'S')?.OrderId)
    : '';
  OrderIdEst = PrintDetail?.find((a) => a.OrderType === 'E')?.OrderId
    ? extractLastNumber(PrintDetail?.find((a) => a.OrderType === 'E')?.OrderId)
    : '';

  let tokenDatasales = PrintDetail?.find(
    (a) => a.OrderType === 'S'
  )?.productDetails;
  let tokenDataestimate = PrintDetail?.find(
    (a) => a.OrderType === 'E'
  )?.productDetails;

  let tokenavailablesles = tokenDatasales?.filter(
    (item) => item?.TokenAvailable === 'Y'
  );
  let tokenavailableEst = tokenDataestimate?.filter(
    (item) => item?.TokenAvailable === 'Y'
  );
  if (Mode !== 'TableBooking') {
    let TokenData1 = []; // Array to store final grouped data
    let groups = {}; // Temporary object to group products by their counter
    let noCounterGroup = []; // To store products with no counter

    tokenavailablesles?.forEach((data, index) => {
      // Normalize the counter: treat empty or null as 'EMPTY'
      let currentCounter = data?.CounterName || 'EMPTY'; // Use 'EMPTY' for null or empty counters

      // Group products based on their counter
      if (currentCounter === 'EMPTY') {
        // If the counter is empty, push to the noCounterGroup
        noCounterGroup.push(
          `${noCounterGroup.length + 1}  ` + // Sequential index within group
            (data?.ProdNameQty.replace(/\s/g, '') + ' '.repeat(24)).substring(
              0,
              24
            ) + // Product name padded to 24 characters
            data?.SalesQty.toString().padStart(6) +
            '   ' + // Sales quantity, right-aligned
            data?.Rate.toString().padStart(6) +
            '   ' + // Rate, right-aligned
            data?.TotalAmt.toString().padStart(6) // Total amount, right-aligned
        );
      } else {
        // If counter exists, group by the counter
        if (!groups[currentCounter]) {
          groups[currentCounter] = [];
        }
        groups[currentCounter].push(
          `${groups[currentCounter].length + 1}  ` + // Sequential index within group
            (data?.ProdNameQty.replace(/\s/g, '') + ' '.repeat(24)).substring(
              0,
              24
            ) + // Product name padded to 24 characters
            data?.SalesQty.toString().padStart(6) +
            '   ' + // Sales quantity, right-aligned
            data?.Rate.toString().padStart(6) +
            '   ' + // Rate, right-aligned
            data?.TotalAmt.toString().padStart(6)
          // +"-" // Total amount, right-aligned
        );
      }
    });

    // Add each group (with counters) to the final result
    Object.keys(groups).forEach((counter) => {
      TokenData1.push(groups[counter].join('-')); // Join all products in the group
    });

    // If there are any products with no counter, add them as a separate group
    if (noCounterGroup.length > 0) {
      TokenData1.push(noCounterGroup.join(','));
    }

    // Join all the groups (with or without counters) with commas
    TokenDataSales = TokenData1.join(', ');
  } else {
    TokenDataSales = [false];
  }
  if (Mode !== 'TableBooking') {
    let TokenData2 = []; // Array to store final grouped data
    let groups = {}; // Temporary object to group products by their counter
    let noCounterGroup = []; // To store products with no counter

    tokenavailableEst?.forEach((data, index) => {
      // Normalize the counter: treat empty or null as 'EMPTY'
      let currentCounter = data?.CounterName || 'EMPTY'; // Use 'EMPTY' for null or empty counters

      // Group products based on their counter
      if (currentCounter === 'EMPTY') {
        // If the counter is empty, push to the noCounterGroup
        noCounterGroup.push(
          `${noCounterGroup.length + 1}  ` + // Sequential index within group
            (data?.ProdNameQty.replace(/\s/g, '') + ' '.repeat(24)).substring(
              0,
              24
            ) + // Product name padded to 24 characters
            data?.SalesQty.toString().padStart(6) +
            '   ' + // Sales quantity, right-aligned
            data?.Rate.toString().padStart(6) +
            '   ' + // Rate, right-aligned
            data?.TotalAmt.toString().padStart(6) // Total amount, right-aligned
        );
      } else {
        // If counter exists, group by the counter
        if (!groups[currentCounter]) {
          groups[currentCounter] = [];
        }
        groups[currentCounter].push(
          `${groups[currentCounter].length + 1}  ` + // Sequential index within group
            (data?.ProdNameQty.replace(/\s/g, '') + ' '.repeat(24)).substring(
              0,
              24
            ) + // Product name padded to 24 characters
            data?.SalesQty.toString().padStart(6) +
            '   ' + // Sales quantity, right-aligned
            data?.Rate.toString().padStart(6) +
            '   ' + // Rate, right-aligned
            data?.TotalAmt.toString().padStart(6)
          // +"-" // Total amount, right-aligned
        );
      }
    });

    // Add each group (with counters) to the final result
    Object.keys(groups).forEach((counter) => {
      TokenData2.push(groups[counter].join('-')); // Join all products in the group
    });

    // If there are any products with no counter, add them as a separate group
    if (noCounterGroup.length > 0) {
      TokenData2.push(noCounterGroup.join(','));
    }
    // Join all the groups (with or without counters) with commas
    TokenDataEstimate = TokenData2.join(', ');
  } else {
    TokenDataEstimate = [false];
  }

  var textEncoded = encodeURI(receiptText);

  var TypeCheck = 'PrintReceipt';
  var scheme = 'pozoprinter';
  var packageName = 'com.example.pozoprinter';

  window.location.href =
    scheme +
    '://' +
    textEncoded +
    '#Intent;scheme=' +
    scheme +
    ';package=' +
    packageName +
    TypeCheck +
    'ImgS' +
    LogoImage +
    'ImgE' +
    'TokenS' +
    TokenDataSales +
    'TokenE' +
    'OrderS' +
    OrderIdSales +
    'OrderE' +
    'EstimateS' +
    textEncodedest +
    'EstimateE' +
    'TokenEstimateS' +
    TokenDataEstimate +
    'TokenEstimateE' +
    'EstimateOrderIdS' +
    OrderIdEst +
    'EstimateOrderIdE' +
    'HasFooterTextS' +
    FooterPrint +
    'HasFooterTextE' +
    ';end;';
};
export default IndividualTokenMobilePrint;
