import moment from "moment";
import React, { useEffect, useRef, useState } from "react"
import { Alert, Button, Card, Col, ConfigProvider, DatePicker, Form, Input, InputNumber, Modal, Row, Select, Table, Tabs } from "antd";
import Highlighter from 'react-highlight-words';
import { BarcodeOutlined, FormOutlined, SearchOutlined, UndoOutlined } from '@ant-design/icons';
import { CollectionsService } from "@gtpl/shared-services/finance";
import { Link, useHistory } from "react-router-dom";
import { IdRequest } from "@gtpl/shared-models/gtpl";
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
import { PayableFilterRequest, PayableRequest } from "@gtpl/shared-models/finance";
import { render } from "react-dom";
import { CompanyTypeEnum, PlantsDropDown } from "@gtpl/shared-models/masters";
import { UnitcodeService } from "@gtpl/shared-services/masters";

export function Payables(){
    const [page, setPage] = useState(1);
      const [pageSize, setPageSize] = useState<number>(100);
      const [data, setData] = useState([])
      const [searchText, setSearchText] = useState("");
      const [searchedColumn, setSearchedColumn] = useState("");
      const searchInput = useRef(null);
      const { TabPane } = Tabs;  
      const { Option } = Select;
      const [invoices, setInvoices] = useState([])
      const [invoiceType, setInvoiceType] = useState(undefined)
      const [selectedInvoices, setSlectedInvoices] = useState(undefined)
      const [vendors, setVendors] = useState([])

      const createdUser = localStorage.getItem('createdUser')
      const service = new CollectionsService()
      const [totalInvAmt, setTotalInvAmt] = useState<number>(0);
      const [taxAmt, setTaxAmt] = useState<number>(0);
      const [deductionAmt, setDeductionAmt] = useState<number>(0);
      const [totalAmt, setTotalAmt] = useState<number>(0);
      const [totQty, setTotQty] = useState<number>(0);
      const [tds, setTds] = useState<boolean>(false);
      const [paidAmt, setPaidAmt] = useState<number>(0);
      const [isPaymentModal, setIsPaymentModal] = useState<boolean>(false);
      const [itemsData, setItemsData] = useState([])
      const [batches, setBatches] = useState([]);
  const [plantData, setPlantData] = useState<PlantsDropDown[]>([]);
  const unitsService = new UnitcodeService();


  
  useEffect(() => {
    getAllPlants();

  }, []);


 const [form] = Form.useForm();
   let history = useHistory();
 const [paymentForm] = Form.useForm();

 const getRmSuppliers =()=>{
        service.getRmSuppliers().then(res=>{
            if(res.status){
              setVendors(res.data)
            }else{
              setVendors([])
            }
          })
      }
    const getPackingVendors =()=>{
 const req = new PayableFilterRequest()
  if(form.getFieldValue('invoiceId')!=undefined){
        req.supplierId = form.getFieldValue('invoiceId')
            }         
             service.getPackingVendors(req).then(res=>{
            if(res.status){
              setVendors(res.data)
            }else{
              setVendors([])
            }
          })
          
        }

         const getAllPlants = () => {
    unitsService.getAllMainPlants().then((res) => {
        if (res.status) {
            setPlantData(res.data);
        } else {
            setPlantData([]);
        }
    }).catch(err => {
        AlertMessages.getErrorMessage(err.message);
        setPlantData([]);
    })
}
      
      
      const getRMInvoices =  () =>{
        const req = new IdRequest()
        // req.Id = form
 service.getRmInvoices().then(res=>{
            if(res.status){
              setInvoices(res.data)
              
            }else{
              setInvoices([])
            }
          })
        }
      
const getPackingInvoices =  () =>{
 const req = new PayableFilterRequest()
  if(form.getFieldValue('vendorId')!=undefined){
        req.supplierId = form.getFieldValue('vendorId')
    }       
     if(form.getFieldValue('unit')!=undefined){
        req.unit = form.getFieldValue('unit')
            }  
               service.getPackingInvoices(req).then(res=>{
            if(res.status){
              setInvoices(res.data)
            }else{
              setInvoices([])
            }
          })     
         }
        
        
      const getData =  (val) =>{
      const req = new PayableFilterRequest()
      if(form.getFieldValue('invoiceId')!=undefined){
        req.invoiceNumber = form.getFieldValue('invoiceId')
      }
            if(form.getFieldValue('vendorId')!=undefined){
        req.supplierId = form.getFieldValue('vendorId')
            }
             if(form.getFieldValue('unit')!=undefined){
        req.unit = form.getFieldValue('unit')
            }
 {val ==='RM'?
           service.getRmPayableInvoices(req).then(res=>{
            if(res.status){
              setData(res.data)
              // console.log(res.data);
              
//                const totalInvoiceAmount = res.data.reduce((sum, invoice) => {
//                 const inv = Number(invoice.amount)
//                 const deduction = invoice.tdsApplicable && invoice.type == 'GOOD'?(Number(invoice.deduction)*0.001):0
//       return sum + Number((inv-deduction) || 0)
//     }, 0);
//      const totalAmount = res.data.reduce((sum, invoice) => {
//       return sum + Number((Number(invoice.amount)) || 0);
//     }, 0);
//      const totalQuantity = res.data.reduce((sum, invoice) => {
//       return sum + Number(invoice.quantity || 0);
//     }, 0);
//      const totDed = res.data.reduce((sum, invoice) => {
//       return sum + (invoice.tdsApplicable && invoice.type == 'GOOD'?Number(invoice.deduction)*0.001 : 0);
//     }, 0);
//      const payment = res.data[0]?.payment
//     setTotalInvAmt(totalInvoiceAmount)
//     setTotQty(totalQuantity)
//     setTotalAmt(totalAmount)
//     setDeductionAmt(totDed)
//     setPaidAmt(res.data[0]?.payment)
// // console.log(Number(payment>0?0:totDed),'dedddddddddd');
// // console.log(Number(totalInvoiceAmount),payment,'777777777777777777');

// // console.log(Number(totalInvoiceAmount-payment)-Number(payment>0?0:totDed),'000000000');

// console.log(Math.round(Number(totalInvoiceAmount-payment)),'ppppppppppp');


//     form.setFieldsValue({ 'due':(Math.round(Number(totalInvoiceAmount-payment))) });
            }else{
              setData([])
              AlertMessages.getErrorMessage('No Data Found')
            }
          }):
          service.getPackingPayableInvoices(req).then(res=>{
            if(res.status){
              setData(res.data)
//                const totalInvoiceAmount = res.data.reduce((sum, invoice) => {
//                 const inv = Number(invoice.amount)
//                  const taxAmt = Number(Number(invoice.amount)*Number((invoice.taxPer)/100))
//                 const deduction = invoice.tdsApplicable?(Number(invoice.deduction)*0.001):0
//       return sum + Number((inv-deduction) || 0)
//     }, 0);
//     const totalAmount = res.data.reduce((sum, invoice) => {
//       return sum + Number((Number(invoice.quantity)*Number(invoice.unitPrice)) || 0);
//     }, 0);
//      const totalQuantity = res.data.reduce((sum, invoice) => {
//       return sum + Number(invoice.quantity || 0);
//     }, 0);
//      const totDed = res.data.reduce((sum, invoice) => {
//       return sum + Number(invoice.tdsApplicable?Number(invoice.deduction)*0.001: 0);
//     }, 0);
//     const taxAmt = res.data.reduce((sum, invoice) => {
//       return sum + Number(((Number(invoice.quantity)*Number(invoice.unitPrice))-Number(invoice.discount))*Number((invoice.taxPer)/100));
//     }, 0);
//     const payment = res.data[0]?.paidAmount
//     setTotalInvAmt(totalInvoiceAmount)
//     setTotQty(totalQuantity)
//     setTotalAmt(totalAmount)
//     setDeductionAmt(totDed)
//     setTaxAmt(taxAmt)
//     setPaidAmt(res.data[0]?.paidAmount)

// // console.log(res.data.reduce((sum, invoice) => {
// //       return sum + (invoice.amount +(Number(invoice.quantity)*Number(invoice.unitPrice))*(Number(invoice.taxPer)/100)-(Number(invoice.deduction)?(Number(invoice.deduction))*0.001:0) || 0)
// //     }, 0));
// // const due = (totalInvoiceAmount)-form.getFieldValue('payment')
// console.log(totalInvoiceAmount,payment);

//     form.setFieldsValue({ 'due':(Math.round(Number(totalInvoiceAmount-Number(payment)))) });
    // setTotalInvAmt(totalInvoiceAmount)
            }else{
              setData([])
              AlertMessages.getErrorMessage('No Data Found')
            }
          })     
         }
        }
        function handleSearch(selectedKeys, confirm, dataIndex) {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
      };
    
      function handleReset(clearFilters) {
        clearFilters();
        setSearchText('');
      };
// getData(selectedInvoices)
     const getColumnSearchProps = (dataIndex: string) => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={searchInput}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: "block" }}
        />
        <Button
          type="primary"
          onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
          icon={<SearchOutlined />}
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          Search
        </Button>
        <Button
          size="small"
          style={{ width: 90 }}
          onClick={() => {
            handleReset(clearFilters);
            setSearchedColumn(dataIndex);
            confirm({ closeDropdown: true });
          }}
        >
          Reset
        </Button>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined
        type="search"
        style={{ color: filtered ? "#1890ff" : undefined }}
      />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex]
          .toString()
          .toLowerCase()
          .includes(value.toLowerCase())
        : false,
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current.select());
      }
    },
    render: (text) =>
      text ? (
        searchedColumn === dataIndex ? (
          <Highlighter
            highlightStyle={{ backgroundColor: "#ffc069", padding: 0 }}
            searchWords={[searchText]}
            autoEscape
            textToHighlight={text.toString()}
          />
        ) : (
          text
        )
      ) : null,
  })
const packingItemColumns: any[] = [
    {
      title: 'S No', dataIndex: 'sNo', render: (text, object, index) => {
        if (index == data.length) {
          return null;
        } else {
          return index + 1
        }
      },
    
    },
    {
      title: 'PO Number', 
    
     dataIndex: 'poNumber',
     render: (text: any, record: any) => { return record.poNumber ? record.poNumber : '-' } ,
     sorter: (a, b) => a.poNumber.localeCompare(b.poNumber),
     sortDirections: ['descend', 'ascend'],
    ...getColumnSearchProps('poNumber')},
    {
       title: 'Invoice Number', 
    
      dataIndex: 'invoiceNumber',

        render: (text: any, record: any) => { return record.invoiceNumber ? record.invoiceNumber : '-' } ,
        sorter: (a, b) => a.invoiceNumber.localeCompare(b.invoiceNumber),
      sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('invoiceNumber')},
      {
       title: 'Invoice Date', 
    
      dataIndex: 'invoiceDate',

        render: (text: any, record: any) => { 
                    console.log(moment(text.invoiceDate).format('DD-MM-YYYY'),'ppppppppppppppppp');
          return record.invoiceDate ? moment(record.invoiceDate).format('DD-MM-YYYY') : '-' } ,
        sorter: (a, b) => a.invoiceDate.localeCompare(b.invoiceDate),
      sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('invoiceDate')},
   
    {
       title: 'Item', 
    
      dataIndex: 'item',

        sorter: (a, b) => a.item-b.item,
      sortDirections: ['descend', 'ascend'],
     },
     
    {
      title: 'Quantity', 
        align:'right',
     dataIndex: 'quantity',
    },
    {
     title: 'Unit Price', 
        align:'right',
    dataIndex: 'unitPrice',
},
    {
        title: 'Amount', 
        align:'right',
       dataIndex: 'quantity',
 
         render: (text: any, record: any) => { return record.quantity ?((Number(record.quantity)*Number(record.unitPrice))-Number(record.discount) ).toFixed(2): '-' },
       },
       {
     title: 'Discount', 
             align:'right',
    dataIndex: 'discount',
    render: (text: any, record: any) => { return record.discount ?`${record.discount}(${(Number(record.discountPer))}%)` : '-' },

    },
      {
     title: 'Tax', 
    dataIndex: 'taxPer',
    render: (text: any, record: any) => { return record.taxPer ?`${(Number(record.taxPer))}%` : '-' },

    },
{
     title: 'Tax Amount',
             align:'right',
    dataIndex: 'taxPer',
             render: (text: any, record: any) => { return record.taxPer ?(Number(((Number(record.quantity)*Number(record.unitPrice))-Number(record.discount))*(Number(record.taxPer)/100)).toFixed(2)) : '-' },

}, 
    {
       title: 'Tax Deduction', 
               align:'right',
       dataIndex: 'deduction',
        render: (_: any, record: any) => {
   
    const deduction = (Number(record.deduction)    || 0)*0.001;

    return record.deduction
      ? deduction.toFixed(2)
      : '0';
  },
       },
    {
  title: 'Invoice',
          align:'right',
  dataIndex: 'invoiceAmount',
  render: (_: any, record: any) => {
    const qty       = Number(record.quantity)    || 0;
    const price     = Number(record.unitPrice)   || 0;
    const taxRate   = (Number(record.taxPer)      || 0) / 100;
    const deduction = (Number(record.deduction)    || 0)*0.001;
    const discount = Number(record.discount) || 0 
    const amount   = (qty * price)-discount;
    const taxValue = amount * taxRate;
    const invoice  = amount + taxValue - deduction;
    return price
      ? invoice.toFixed(2)
      : '-';
  },
},

// {
//   title: 'Payment',
//   dataIndex: 'payment',
//   render: (_: any, record: any, rowIndex: number) => {
//     // compute due exactly as you do below
//     const qty       = Number(record.quantity)    || 0;
//     const price     = Number(record.unitPrice)   || 0;
//     const taxRate   = (Number(record.taxPer)      || 0) / 100;
//     const deduction = (Number(record.deduction)    || 0) * 0.001;
//     const amount    = qty * price;
//     const taxValue  = amount * taxRate;
//     const invoice   = amount + taxValue - deduction;
//     const due       = invoice; // since payment starts at 0

//     return (
//     <Form.Item
//         name={['data', rowIndex, 'payment']}
//         style={{ margin: 0 }}
//         rules={[
//           {
//             validator: (_, value) => {
//               // If no value entered, skip validation
//               if (value === undefined || value === null || value === '') {
//                 return Promise.resolve();
//               }

//               if (value > due) {
//                 return Promise.reject(new Error(`Cannot exceed due of ${due.toFixed(2)}`));
//               }

//               return Promise.resolve();
//             },
//           },
//         ]}
//       >
//         <InputNumber
//           min={0}
//           step={0.01}
//           onChange={val => {
//             if (val > due) {
//              AlertMessages.getWarningMessage(`Payment cannot exceed due amount of ${due.toFixed(2)}`);
//             }
//             onPaymentChange(val, rowIndex);
//           }}
//           placeholder="Enter payment"
//         />
//       </Form.Item>
//     );
//   },
// },
  
//   {
//   title: 'Payment',
//   dataIndex: 'payment',
//   render: (_: any, record: any, rowIndex: number) => (
//      <Form.Item name={['data', rowIndex, 'payment']} style={{ margin: 0 }}>
//       <Input
//         value={record.payment}
//         onChange={e => onPaymentChange(e.target.value, rowIndex)}
//         placeholder="Enter payment"
//       />
//     </Form.Item>
//   ),
// },

// {
//   title: 'Due Amount',
//   dataIndex: 'due',
//   render: (_: any, record: any) => {
//     const qty       = Number(record.quantity)    || 0;
//     const price     = Number(record.unitPrice)   || 0;
//     const taxRate   = (Number(record.taxPer)      || 0) / 100;
//     const deduction = (Number(record.deduction) || 0)*0.001;
//     const payment   = Number(record.payment)      || 0;
//     // const paidAmount = Number(record.payment)
//     const amount   = qty * price;
//     const taxValue = amount * taxRate;
//     const invoice  = amount + taxValue - deduction;
//     const due      = invoice - payment;
//     return  due
//       ? Number(due).toFixed(2)
//       : 0;
//   },
// },



     
  ]
  const rmItemcolumns: any[] = [
    {
      title: 'S No', dataIndex: 'sNo', render: (text, object, index) => {
        if (index == data.length) {
          return null;
        } else {
          return index + 1
        }
      },
    
    },
    {
      title: 'Indent Number', 
    
     dataIndex: 'indentNumber',
     render: (text: any, record: any) => { return record.indentNumber ? record.indentNumber : '-' } ,
    //  sorter: (a, b) => a.indentNum.localeCompare(b.indentNum),
    //  sortDirections: ['descend', 'ascend'],
    // ...getColumnSearchProps('indentNum')
    },
    {
       title: 'Invoice Number', 
    
      dataIndex: 'invoiceNumber',

        render: (text: any, record: any) => { return record.invoiceNumber ? record.invoiceNumber : '-' } ,
        sorter: (a, b) => a.invoiceNumber.localeCompare(b.invoiceNumber),
      sortDirections: ['descend', 'ascend'],
    //  ...getColumnSearchProps('invoiceNumber')
    },
    {
       title: 'Invoice Date', 
    
      dataIndex: 'invoiceDate',

        render: (text: any, record: any) => { 
          console.log(moment(record.invoiceDate).format('DD-MM-YYYY'),'ppppppppppppppppp');
          
          return record.invoiceDate ? moment(record.invoiceDate).format('DD-MM-YYYY') : '-' } ,
        sorter: (a, b) => a.invoiceDate.localeCompare(b.invoiceDate),
      sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('invoiceDate')},
     {
       title: 'Batch', 
    
      dataIndex: 'batch',

        render: (text: any, record: any) => { return record.batch ? record.batch : '-' } ,
        sorter: (a, b) => a.batch.localeCompare(b.batch),
      sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('batch')
    },
   
    {
       title: 'Item', 
    
      dataIndex: 'item',

        sorter: (a, b) => a.item-b.item,
      sortDirections: ['descend', 'ascend'],
     },
      {
       title: 'Count', 
      dataIndex: 'count',
       render: (text: any, record: any) => { return record.type!='GOOD' ? `${record.count}(${record.deffect})`: record.count },
 },
    {
      title: 'Quantity', 
      align:'right',
     dataIndex: 'quantity',

    },
    {
     title: 'Unit Price', 
     align:'right',
    dataIndex: 'unitPrice',

},

      {
        title: 'Amount', 
        align:'right',
       dataIndex: 'amount',

        //  render: (text: any, record: any) => { return record.quantity ?Number(Number(record.quantity)*Number(record.unitPrice)).toFixed(2) : '-' },
       },
    {
       title: 'Tax Deduction', 
       align:'right',
       dataIndex: 'deduction',
              render: (text: any, record: any) => { return record.type=='GOOD' ? (Number(record.deduction)*0.001).toFixed(2): 0 },
        },
  {
  title: 'Invoice',
          align:'right',
  dataIndex: 'invoiceAmount',
  render: (_: any, record: any) => {
    // const qty       = Number(record.quantity)    || 0;
    // const price     = Number(record.unitPrice)   || 0;
    const taxRate   = (Number(record.taxPer)      || 0) / 100;
    const deduction = record.type=='GOOD'?(Number(record.deduction)    || 0)*0.001:0;

    const amount   =  Number(record.amount) || 0 ;
    const taxValue = amount * taxRate;
    const invoice  = amount + taxValue - deduction;
    return record.unitPrice
      ? invoice.toFixed(2)
      : '-';
  },
},
//   {
//   title: 'Payment',
//   dataIndex: 'payment',
//   render: (_: any, record: any, rowIndex: number) => {
//     // compute due exactly as you do below
//     const qty       = Number(record.quantity)    || 0;
//     const price     = Number(record.unitPrice)   || 0;
//     const taxRate   = (Number(record.taxPer)      || 0) / 100;
//     const deduction = (Number(record.deduction)    || 0) * 0.001;
//     const amount    = qty * price;
//     const taxValue  = amount * taxRate;
//     const invoice   = amount + taxValue - deduction;
//     const due       = invoice; // since payment starts at 0

//     return (
//     <Form.Item
//         name={['data', rowIndex, 'payment']}
//         style={{ margin: 0 }}
//         rules={[
//           {
//             validator: (_, value) => {
//               // If no value entered, skip validation
//               if (value === undefined || value === null || value === '') {
//                 return Promise.resolve();
//               }

//               if (value > due) {
//                 return Promise.reject(new Error(`Cannot exceed due of ${due.toFixed(2)}`));
//               }

//               return Promise.resolve();
//             },
//           },
//         ]}
//       >
//         <InputNumber
//           min={0}
//           step={0.01}
//           onChange={val => {
//             if (val > due) {
//              AlertMessages.getWarningMessage(`Payment cannot exceed due amount of ${due.toFixed(2)}`);
//             }
//             onPaymentChange(val, rowIndex);
//           }}
//           placeholder="Enter payment"
//         />
//       </Form.Item>
//     );
//   },
// },
// {
//   title: 'Due Amount',
//   dataIndex: 'due',
//   render: (_: any, record: any) => {
//     const amount    = Number(record.quantity) * Number(record.unitPrice);
//    const payment   = Number(record.payment)      || 0;
//     const deduction = (Number(record.deduction)    || 0)*0.001;

//     const invoice   = amount  - deduction;
//     const dueAmount = invoice - payment;

//     return record.unitPrice ? dueAmount.toFixed(2) : '0';
//   },
// }

  ]
  const itemColumns = invoiceType === 'PACKING' ? packingItemColumns : rmItemcolumns;

  const packingColumns: any[] = [
    {
      title: 'S No', dataIndex: 'sNo', render: (text, object, index) => {
        if (index == data.length) {
          return null;
        } else {
          return index + 1
        }
      },
    
    },
     {
      title: 'Vendor', 
    
     dataIndex: 'vendor',
     render: (text: any, record: any) => { return record.vendor ? record.vendor : '-' } ,
     sorter: (a, b) => a.vendor.localeCompare(b.vendor),
     sortDirections: ['descend', 'ascend'],
     },
    {
      title: 'PO Number', 
    
     dataIndex: 'poNumber',
     render: (text: any, record: any) => { return record.poNumber ? record.poNumber : '-' } ,
     sorter: (a, b) => a.poNumber.localeCompare(b.poNumber),
     sortDirections: ['descend', 'ascend'],
    ...getColumnSearchProps('poNumber')},
    {
       title: 'Invoice Number', 
    
      dataIndex: 'invoiceNumber',

        render: (text: any, record: any) => { return record.invoiceNumber ? record.invoiceNumber : '-' } ,
        sorter: (a, b) => a.invoiceNumber.localeCompare(b.invoiceNumber),
      sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('invoiceNumber')},
      {
       title: 'Invoice Date', 
    
      dataIndex: 'invoiceDate',

        render: (text: any, record: any) => { 
                    console.log(moment(text.invoiceDate).format('DD-MM-YYYY'),'ppppppppppppppppp');
          return record.invoiceDate ? moment(record.invoiceDate).format('DD-MM-YYYY') : '-' } ,
        sorter: (a, b) => a.invoiceDate.localeCompare(b.invoiceDate),
      sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('invoiceDate')},
   
    // {
    //     title: 'Amount', 
    //     align:'right',
    //    dataIndex: 'quantity',
 
    //      render: (text: any, record: any) => { return record.quantity ?(Number(record.quantity)*Number(record.unitPrice) ).toFixed(2): '-' },
    //    },
//        {
//      title: 'Discount', 
//              align:'right',
//     dataIndex: 'discount',
//     render: (text: any, record: any) => { return record.discount ?`${record.discount}(${(Number(record.discountPer))}%)` : '-' },

//     },
//       {
//      title: 'Tax', 
//     dataIndex: 'taxPer',
//     render: (text: any, record: any) => { return record.taxPer ?`${(Number(record.taxPer))}%` : '-' },

//     },
// {
//      title: 'Tax Amount',
//              align:'right',
//     dataIndex: 'taxPer',
//              render: (text: any, record: any) => { return record.taxPer ?((Number(record.quantity)*Number(record.unitPrice))-Number(record.discount))*(Number(record.taxPer)/100) : '-' },

// }, 
//     {
//        title: 'Tax Deduction', 
//                align:'right',
//        dataIndex: 'deduction',
//         render: (_: any, record: any) => {
   
//     const deduction = (Number(record.deduction)    || 0)*0.001;

//     return record.deduction
//       ? deduction.toFixed(2)
//       : '0';
//   },
//        },
    {
  title: 'Invoice',
          align:'right',
  dataIndex: 'invoiceAmount',
  render: (_: any, record: any) => {
   
    return record.amount
      ? Number((record.amount)-(record.deduction*0.001)).toFixed(2)
      : '-';
  },
},
{
   title: 'Action',
  dataIndex: 'invoiceAmount',
  render:(val,rec)=>{
      return(<FormOutlined title="Payment" onClick={() => payment(rec)}/> )
  }
}
  
  ]
  const rmColumns: any[] = [
    {
      title: 'S No', dataIndex: 'sNo', render: (text, object, index) => {
        if (index == data.length) {
          return null;
        } else {
          return index + 1
        }
      },
    
    },
     {
      title: 'Supplier', 
    
     dataIndex: 'vendor',
     render: (text: any, record: any) => { return record.vendor?record.vendor:'-' } ,
    //  sorter: (a, b) => a.vendor.localeCompare(b.vendor),
    //  sortDirections: ['descend', 'ascend'],
     },
    {
      title: 'Indent Number', 
    
     dataIndex: 'indentNumber',
     render: (text: any, record: any) => { return record.indentNumber ? record.indentNumber : '-' } ,
    //  sorter: (a, b) => a.indentNum.localeCompare(b.indentNum),
    //  sortDirections: ['descend', 'ascend'],
    // ...getColumnSearchProps('indentNum')
    },
    {
       title: 'Invoice Number', 
    
      dataIndex: 'invoiceNumber',

        render: (text: any, record: any) => { return record.invoiceNumber ? record.invoiceNumber : '-' } ,
        sorter: (a, b) => a.invoiceNumber.localeCompare(b.invoiceNumber),
      sortDirections: ['descend', 'ascend'],
    //  ...getColumnSearchProps('invoiceNumber')
    },
    {
       title: 'Invoice Date', 
    
      dataIndex: 'invoiceDate',

        render: (text: any, record: any) => { 
          console.log(moment(record.invoiceDate).format('DD-MM-YYYY'),'ppppppppppppppppp');
          
          return record.invoiceDate ? moment(record.invoiceDate).format('DD-MM-YYYY') : '-' } ,
        sorter: (a, b) => a.invoiceDate.localeCompare(b.invoiceDate),
      sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('invoiceDate')},
     {
       title: 'Batch', 
    
      dataIndex: 'batch',

        render: (text: any, record: any) => { return record.batch ? record.batch : '-' } ,
        sorter: (a, b) => a.batch.localeCompare(b.batch),
      sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('batch')
    },
   
//     {
//        title: 'Item', 
    
//       dataIndex: 'item',

//         sorter: (a, b) => a.item-b.item,
//       sortDirections: ['descend', 'ascend'],
//      },
//       {
//        title: 'Count', 
//       dataIndex: 'count',
//        render: (text: any, record: any) => { return record.type!='GOOD' ? `${record.count}(${record.deffect})`: record.count },
//  },
    {
      title: 'Quantity', 
      align:'right',
     dataIndex: 'quantity',

    },
//     {
//      title: 'Unit Price', 
//      align:'right',
//     dataIndex: 'unitPrice',

// },

    //   {
    //     title: 'Amount', 
    //     align:'right',
    //    dataIndex: 'amount',

    //     //  render: (text: any, record: any) => { return record.quantity ?Number(Number(record.quantity)*Number(record.unitPrice)).toFixed(2) : '-' },
    //    },
    // {
    //    title: 'Tax Deduction', 
    //    align:'right',
    //    dataIndex: 'deduction',
    //           render: (text: any, record: any) => { return record.type=='GOOD' ? (Number(record.deduction)*0.001).toFixed(2): 0 },
    //     },
  {
  title: 'Invoice',
          align:'right',
  dataIndex: 'invoiceAmount',
  render: (_: any, record: any) => {
    // const qty       = Number(record.quantity)    || 0;
    // const price     = Number(record.unitPrice)   || 0;
    const deduction = (Number(record.deduction)|| 0)*0.001;
// console.log(deduction,'tdssssssssss');

    const amount   =  Number(record.amount) || 0 ;
    const payment   =  Number(record.payment) || 0 ;
// console.log(payment,'ppppppppppppppp');

    // const taxValue = amount * taxRate;
    const invoice  = amount- deduction;
    return record.amount
      ? invoice.toFixed(2)
      : '-';
  },
},
{
   title: 'Action',
  dataIndex: 'invoiceAmount',
  render:(val,rec)=>{
      return(<FormOutlined title="Payment" onClick={() => payment(rec)}/> )
  }
}

  ]
  const invoiceColumns = invoiceType === 'PACKING' ? packingColumns : rmColumns;
const payment = (rowData) =>{
  setIsPaymentModal(true)
  getPaymentData(rowData)
}
const getPaymentData=(rowData)=>{
  
  console.log(rowData,invoiceType,'rowwwwww');
  paymentForm.setFieldsValue({invoiceId:rowData.invoiceNumber})
  paymentForm.setFieldsValue({vendorId:rowData.vendorId})
  paymentForm.resetFields(['receivedDate'])
       const rmReq = new PayableFilterRequest()
        rmReq.invoiceNumber = rowData.invoiceNumber
        rmReq.supplierId = rowData.vendorId
{invoiceType ==='RM'?
   
           service.getRmPayables(rmReq).then(res=>{
            if(res.status){
              setItemsData(res.data)
               const totalInvoiceAmount = res.data.reduce((sum, invoice) => {
                console.log(invoice,'lllllllllllll');
                
                const inv = Number(invoice.amount)
                const deduction = invoice.tdsApplicable && invoice.type == 'GOOD'?(Number(invoice.deduction)*0.001):0
      return sum + Number((inv-deduction) || 0)
    }, 0);
    console.log(totalInvoiceAmount,'totalInvoiceAmount');
    
     const totalAmount = res.data.reduce((sum, invoice) => {
      return sum + Number((Number(invoice.amount)) || 0);
    }, 0);
     const totalQuantity = res.data.reduce((sum, invoice) => {
      return sum + Number(invoice.quantity || 0);
    }, 0);
     const totDed = res.data.reduce((sum, invoice) => {
      return sum + (invoice.tdsApplicable && invoice.type == 'GOOD'?Number(invoice.deduction)*0.001 : 0);
    }, 0);
     const payment = res.data[0]?.payment
    setTotalInvAmt(totalInvoiceAmount)
    setTotQty(totalQuantity)
    setTotalAmt(totalAmount)
    setDeductionAmt(totDed)
    setPaidAmt(res.data[0]?.payment)
// console.log(Number(payment>0?0:totDed),'dedddddddddd');
// console.log(Number(totalInvoiceAmount),payment,'777777777777777777');

// console.log(Number(totalInvoiceAmount-payment)-Number(payment>0?0:totDed),'000000000');

console.log(Math.round(Number(totalInvoiceAmount-payment)),'ppppppppppp');


    paymentForm.setFieldsValue({ 'due':(Math.round(Number(totalInvoiceAmount-payment))) });
            }else{
              setItemsData([])
            }
          }):
          service.getPackingPayables(rmReq).then(res=>{
            if(res.status){
              setItemsData(res.data)
               const totalInvoiceAmount = res.data.reduce((sum, invoice) => {
                const inv = Number(invoice.amount)
                 const taxAmt = Number(Number(invoice.amount)*Number((invoice.taxPer)/100))
                const deduction = invoice.tdsApplicable?(Number(invoice.deduction)*0.001):0
      return sum + Number((inv-deduction) || 0)
    }, 0);
    const totalAmount = res.data.reduce((sum, invoice) => {
      return sum + Number((Number(invoice.quantity)*Number(invoice.unitPrice)) || 0);
    }, 0);
     const totalQuantity = res.data.reduce((sum, invoice) => {
      return sum + Number(invoice.quantity || 0);
    }, 0);
     const totDed = res.data.reduce((sum, invoice) => {
      return sum + Number(invoice.tdsApplicable?Number(invoice.deduction)*0.001: 0);
    }, 0);
    const taxAmt = res.data.reduce((sum, invoice) => {
      return sum + Number(((Number(invoice.quantity)*Number(invoice.unitPrice))-Number(invoice.discount))*Number((invoice.taxPer)/100));
    }, 0);
    const payment = res.data[0]?.paidAmount
    setTotalInvAmt(totalInvoiceAmount)
    setTotQty(totalQuantity)
    setTotalAmt(totalAmount)
    setDeductionAmt(totDed)
    setTaxAmt(taxAmt)
    setPaidAmt(res.data[0]?.paidAmount)

// console.log(res.data.reduce((sum, invoice) => {
//       return sum + (invoice.amount +(Number(invoice.quantity)*Number(invoice.unitPrice))*(Number(invoice.taxPer)/100)-(Number(invoice.deduction)?(Number(invoice.deduction))*0.001:0) || 0)
//     }, 0));
// const due = (totalInvoiceAmount)-form.getFieldValue('payment')

    paymentForm.setFieldsValue({ 'due':(Math.round(Number(totalInvoiceAmount-Number(payment)))) });
    // setTotalInvAmt(totalInvoiceAmount)
            }else{
              setItemsData([])
            }
          })     
         }
}
  const invoiceTypeChange=(val) =>{
    form.resetFields(['vendorId','invoiceId'])
setInvoiceType(val)
  paymentForm.resetFields()
  // console.log(val,'valllllllllll');
    getData(val)
    if(val != null|| val!= undefined)
    if(val==='RM'){
      getRmSuppliers()
      getRMInvoices()
    }else{
        getPackingVendors()
        getPackingInvoices()
      }
    }
  
//   const vendorChange=(val) =>{
//      setInvoices([]);
//   setSlectedInvoices(undefined);
//   setData([]);
//   form.resetFields([ 'invoiceId']);
//     form.setFieldsValue({ vendorId: val })
//   console.log(val);
//   // if(invoiceType=='RM'){
//   //   getRMInvoices()
//   // }else{
//   //   getPackingInvoices(val)
//   // }
//  }
  const invoiceChange=(val,rec) =>{
  //  console.log(val);
   setSlectedInvoices(rec.invoiceNum)
  //  getData(invoiceType)
  }
  const save=async (val)=>{
   const values = await paymentForm.validateFields();
    // const { vendorId, invoiceType, receivedDate,payment } = values;
         console.log(values,'pppppppppppppppp');
         
 const req =new PayableRequest(
    1,
    invoiceType,             // from form
    totQty,
    totalAmt,
    Number(deductionAmt)  || 0,
    totalInvAmt,
    values.payment,
    createdUser,         // optional: adjust accordingly
    values.vendorId,                // from form
    values.receivedDate,           // from form
    values.invoiceId,
    '',
    tds,
   Math.round(totalInvAmt-values.payment-paidAmt),
   itemsData[0]?.invoiceDate
  )
    // Filter only those rows with payment entered
//     const filteredRows = data.filter(row => !!row.payment && row.payment !== '');

//     // Map required data
//    const finalPayload: PayableRequest[] = filteredRows.map(row =>
//    { console.log(row,'pppppppppppppppppp')
//     const qty       = Number(row.quantity)  || 0;
//     const price     = Number(row.unitPrice) || 0;
//     const taxRate   = (Number(row.taxPer)    || 0) / 100;
//     const deduction = (Number(row.deduction)*0.001)|| 0;
//     const payment   = Number(row.payment)    || 0;

//     const amount      = qty * price;
//     const taxValue    = amount * taxRate;
//     const invoiceAmt  = amount + taxValue - deduction;
//     const dueAmt      = invoiceAmt - payment;

//     return(
    
//   new PayableRequest(
//     row.invoiceId,
//     invoiceType,             // from form
//     row.quantity,
//     amount,
//     Number(deduction)  || 0,
//     invoiceAmt,
//     row.payment,
//     createdUser,         // optional: adjust accordingly
//     vendorId,                // from form
//     receivedDate,           // from form
//     row.invoiceNumber,
//     row.item,
//     row.tdsApplicable || false,
//     dueAmt,
//     row.invoiceDate
//   )
// )}
// );

// console.log(finalPayload,'savee');

    
    service.savePayables(req).then(res=>{
      if(res.status){
        AlertMessages.getSuccessMessage(res.internalMessage)
        form.resetFields()
        paymentForm.resetFields()
        setData([])
        setInvoices([])
        setInvoiceType(null)
history.push("/payables-view");
      }else{
        AlertMessages.getErrorMessage(res.internalMessage)
      }
    })

  }
 const handlePaymentChange = (val) => {
    const payment = val || 0;
    const due = totalInvAmt - payment-paidAmt;

    // Set "due" field dynamically
    paymentForm.setFieldsValue({ 'due':(Math.round(due)) });
  };
  const resetFilter=() =>{
form.resetFields(['vendorId','invoiceId'])
getData(invoiceType)
  }
  return(
    <>
    <Card
 
  title={<span style={{ color: 'white',fontSize:"20px" }}>Payables</span>}
  style={{ textAlign: 'center', width: '100%' }}
  headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
  extra={
    <Link to="/payables-view">
      <Button className="panel_button">View</Button>
    </Link>
  }
>
  <Form layout={'vertical'} form={form}   onFinish={() => {
    getPackingInvoices();
    getData(invoiceType)
  }}>
    <Row gutter={24}>
      <Col xs={24} sm={24} md={8} lg={6} xl={4}>
        <Form.Item name="invoiceType" label="Invoice Type">
          <Select allowClear showSearch onSelect={invoiceTypeChange} dropdownMatchSelectWidth={false} placeholder="Select Invoice Type">
            <Option value="PACKING" key="PACKING">PACKING</Option>
            <Option value="RM" key="RM">RM</Option>
          </Select>
        </Form.Item>
      </Col>
      {invoiceType != undefined && (
        <>
          {invoiceType == 'PACKING' ? (
            <Col xs={24} sm={24} md={8} lg={6} xl={4}>
              <Form.Item label="Vendor" name="vendorId" >
                <Select
                  allowClear
                  showSearch
                  placeholder="Select Vendor"
                  optionFilterProp="children"
                  // onChange={vendorChange}
                  dropdownMatchSelectWidth={false}
                  showArrow
                >
                  {vendors.map((data) => {
                    return <Option key={data.vendorId} value={data.vendorId}>{data.vendor}</Option>;
                  })}
                </Select>
              </Form.Item>
            </Col>
          ) : (
            <Col xs={24} sm={24} md={8} lg={6} xl={4}>
              <Form.Item label="Supplier" name="vendorId" >
                <Select
                  allowClear
                  showSearch
                  placeholder="Select Supplier"
                  optionFilterProp="children"
                  // onChange={vendorChange}
                  dropdownMatchSelectWidth={false}
                  showArrow
                >
                  {vendors.map((data) => {
                    return (
                      <Option
                        key={data?.type != 'Dealer' ? data?.farmerId : data?.dealerId}
                        value={data?.type != 'Dealer' ? data?.farmerId : data?.dealerId}
                      >
                        {data?.type != 'Dealer' ? data?.farmer : data.dealer}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
          )}
          { invoiceType=='PACKING' &&(
            <><Col xs={24} sm={24} md={5} lg={5} xl={5}>
                    <Form.Item
                      name="invoiceId"
                      label="Invoice Number"
                    >
                      <Select
                        allowClear
                        // mode="multiple"
                        showSearch
                        placeholder="Select Invoice Number"
                        optionFilterProp="children"
                        onChange={invoiceChange}
                        dropdownMatchSelectWidth={false}
                        showArrow
                      >
                        {invoices.map((data) => {
                          return <Option key={data.invoiceNumber} value={data.invoiceNumber} invoiceNumber={data.invoiceNumber}>{data.invoiceNumber}</Option>;
                        })}
                      </Select>
                    </Form.Item>
                  </Col><Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                      <Form.Item
                        name="unit"
                        label="Unit"
                        rules={[
                          {
                            required: false, message: 'Select Unit',
                          },
                        ]}
                      >
                        <Select
                          showSearch
                          optionFilterProp="children"
                          filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                          placeholder="Select Unit"
                          allowClear
                          style={{ width: '100%' }}
                        >
                          {plantData.map(dropData => {
                                return <Option value={dropData.plantId}>{dropData.plantCode}</Option>
                            })}
                        </Select>
                      </Form.Item>
                    </Col></>
          )}
          {invoiceType=='RM' &&(
            <><Col xs={24} sm={24} md={8} lg={8} xl={4}>
                    <Form.Item
                      name="invoiceId"
                      label="Batch"
                    >
                      <Select
                        allowClear
                        // mode="multiple"
                        showSearch
                        placeholder="Select Batch"
                        optionFilterProp="children"
                        onChange={invoiceChange}
                        dropdownMatchSelectWidth={false}
                        showArrow
                      >
                        {invoices.map((data) => {
                          return <Option key={data.invoiceId} value={data.invoiceId} invoiceNumber={data.invoiceNumber}>{data.batch}-{data.year}</Option>;
                        })}
                      </Select>
                    </Form.Item>
                  </Col><Col xs={24} sm={24} md={8} lg={6} xl={4}>
                      <Form.Item name='unit' label='Unit'>
                        <Select showSearch allowClear optionFilterProp='children' placeholder='Select Unit'
                        dropdownMatchSelectWidth={false}

                        >
                          {Object.values(CompanyTypeEnum).map(e => {
                            return (
                              <Option key={e} value={e}>{e}</Option>
                            );
                          })}
                        </Select>
                      </Form.Item>
                    </Col></>
          )}
        
        </>
      )}
                  <Col span={2}>
      <Form.Item>
          {/* {data.length > 0 && ( */}
          <><Button type="primary" htmlType="submit"  style={{ marginTop: '35px'}} size="small">
                    Search
                  </Button></>
          {/* )} */}
        </Form.Item>
                </Col>
         <Col span={2}>
      <Form.Item>
          {/* {data.length > 0 && ( */}
        <Button  style={{ marginTop: '35px' }} size="small" onClick={resetFilter}>
                      Reset
                    </Button>
{/* )} */}
        </Form.Item>
              </Col>
        
    </Row>
       
         {data.length > 0 && (
      <Table
        columns={invoiceColumns} // Use a different set of columns if needed
        dataSource={data}
        // scroll={{ x: 'max-content' }}
        // pagination={false}
       
      />
    )}
          
        
        
</Form>

<Modal visible={isPaymentModal} onCancel={()=>setIsPaymentModal(false)} onOk={()=>setIsPaymentModal(false)} width={'90%'} footer={false}>
  <Card size="small">
     <Form layout={'vertical'} form={paymentForm} onFinish={save}>
    <Row gutter={24}>
      {invoiceType != undefined && (
        <>
          {invoiceType == 'PACKING' ? (
            <Col xs={24} sm={24} md={8} lg={6} xl={4}>
              <Form.Item label="Vendor" name="vendorId" rules={[{ required: true, message: 'Missing Vendor' }]}>
                <Select
                  allowClear
                  showSearch
                  placeholder="Select Vendor"
                  optionFilterProp="children"
                  // onChange={vendorChange}
                  dropdownMatchSelectWidth={false}
                  showArrow
                  disabled={true}
                >
                  {vendors.map((data) => {
                    return <Option key={data.vendorId} value={data.vendorId}>{data.vendor}</Option>;
                  })}
                </Select>
              </Form.Item>
            </Col>
          ) : (
            <>
            <Col xs={24} sm={24} md={8} lg={6} xl={4}>
                          <Form.Item label="Supplier" name="vendorId" rules={[{ required: true, message: 'Missing Supplier' }]}>
                            <Select
                              allowClear
                              showSearch
                              placeholder="Select Supplier"
                              optionFilterProp="children"
                              // onChange={vendorChange}
                              dropdownMatchSelectWidth={false}
                              showArrow
                              disabled={true}

                            >
                              {vendors.map((data) => {
                                return (
                                  <Option
                                    key={data?.type != 'Dealer' ? data?.farmerId : data?.dealerId}
                                    value={data?.type != 'Dealer' ? data?.farmerId : data?.dealerId}
                                  >
                                    {data?.type != 'Dealer' ? data?.farmer : data.dealer}
                                  </Option>
                                );
                              })}
                            </Select>
                          </Form.Item>
            </Col>
            
            </>
          )}
          {invoiceType=='PACKING' && (
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.Item
                name="invoiceId"
                label="Invoice Number"
                rules={[{ required: true, message: 'Invoice Number is required' }]}
              >
                <Select
                  allowClear
                  // mode="multiple"
                  showSearch
                  placeholder="Select Invoice Number"
                  optionFilterProp="children"
                  onChange={invoiceChange}
                  dropdownMatchSelectWidth={false}
                  showArrow
                  disabled={true}
                >
                  {invoices.map((data) => {
                    return <Option key={data.invoiceNumber} value={data.invoiceNumber} invoiceNumber={data.invoiceNumber}>{data.invoiceNumber}</Option>;
                  })}
                </Select>
              </Form.Item>
            </Col>
          )}
          {invoiceType=='RM' &&(
            <>
            <Col xs={24} sm={24} md={8} lg={8} xl={4}>
                        <Form.Item
                          name="invoiceId"
                          label="Batch"
                          rules={[{ required: true, message: 'Batch  is required' }]}
                        >
                          <Select
                            allowClear
                            // mode="multiple"
                            showSearch
                            placeholder="Select Batch"
                            optionFilterProp="children"
                            onChange={invoiceChange}
                            dropdownMatchSelectWidth={false}
                            showArrow
                            disabled={true}

                          >
                            {invoices.map((data) => {
                              return <Option key={data.invoiceId} value={data.invoiceId} invoiceNumber={data.invoiceNumber}>{data.batch}-{data.year}</Option>;
                            })}
                          </Select>
                        </Form.Item>
                      </Col>
                      
                      </>
          )}
          <Col xs={24} sm={24} md={8} lg={6} xl={4}>
            <Form.Item label="Payment Date" name="receivedDate" rules={[{ required: true, message: 'Missing Received Date' }]}>
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </>
      )}
    </Row>
      
    <Row gutter={8} justify="center">
      <Col xs={24} sm={24} md={24} lg={24} xl={24}>
       <Table
        columns={itemColumns}
        dataSource={itemsData}
        scroll={{ x: 'max-content' }}
        pagination={false}
        size="small"
        summary={(pageData) => {
          let totQuantity = 0;
          let totAmount = 0;
          let tax = 0;
          let payment = 0;
          let deductionAmount = 0;

          pageData.forEach(({ quantity,  deduction, discount,amount,type,taxPer,unitPrice,taxAmount }) => {
            //  const amount   = (qty * price)-discount;
            //  const taxValue = amount * taxRate;
            totQuantity += parseFloat(quantity) || 0;
            if(invoiceType=='RM'){
            totAmount += parseFloat(amount) || 0;
              deductionAmount += type=='GOOD'?(deduction*0.001) : 0;
            }else{
              deductionAmount +=Number((deduction*0.001).toFixed(2));
              tax += Number(taxAmount)
              totAmount += (Number(amount)-Number(taxAmount) || 0)
            }

            // invoiceAmount += ((quantity * unitPrice)-deduction )|| 0;
          });

// console.log(totQuantity,'totQuantity');
console.log(totAmount,'totAmount');
// console.log(deductionAmount,'deductionAmount');
console.log(tax,'taxAmount');

          return (
            <Table.Summary.Row>
              <Table.Summary.Cell index={invoiceType=='RM'?7:5} colSpan={invoiceType=='RM'?7:5}>Total</Table.Summary.Cell>
              <Table.Summary.Cell index={invoiceType=='RM'?8:6}>{totQuantity.toFixed(2)}</Table.Summary.Cell>
              <Table.Summary.Cell index={invoiceType=='RM'?9:7}></Table.Summary.Cell>
              {/* {invoiceType != 'RM'?(<Table.Summary.Cell index={10}></Table.Summary.Cell>):<></>} */}
              <Table.Summary.Cell index={invoiceType=='RM'?10:8}>{totAmount.toFixed(2)}</Table.Summary.Cell>
              {invoiceType!='RM'?(
                <><Table.Summary.Cell index={11}></Table.Summary.Cell>
                <Table.Summary.Cell index={12}></Table.Summary.Cell>
                <Table.Summary.Cell index={13}>{tax.toFixed(2)}</Table.Summary.Cell></>

                ):<></>}
              <Table.Summary.Cell index={invoiceType=='RM'?11:14}>{deductionAmount.toFixed(2)}</Table.Summary.Cell>
              <Table.Summary.Cell index={invoiceType=='RM'?12:15}>{((Number((totAmount).toFixed(2) )+ Number((tax).toFixed(2))- Number((deductionAmount).toFixed(2)))).toFixed(2)}</Table.Summary.Cell>
            </Table.Summary.Row>
          );
        }}
      />
      </Col>
    </Row>
    
    <Row style={{justifyContent:'flex-end',marginLeft:'550px'}}>
       <Col span={12} >
      {data.length > 0 && (
          <Form.Item label= 'Payment' name='payment'
      rules={[
              {
                validator: (_, value) => {
                    if (Math.round(value) > Math.round(totalInvAmt-paidAmt)) {
                    return Promise.reject(
                      new Error(`Payment cannot exceed due amount `)
                    );
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <InputNumber
              min={0}
              step={0.01}
              style={{width:'200px'}} 
              onChange={handlePaymentChange}
              placeholder="Enter payment"
            />
      </Form.Item>

          )}
          </Col>
       <Col span={12} >
      {data.length > 0 && (
          <Form.Item label= 'Due Amount' name='due'
        style={{ margin: 0 }}>
        <InputNumber 
style={{width:'200px'}}
         disabled
        />
      </Form.Item>

          )}
          </Col>


    </Row>
        <Form.Item>
          {data.length > 0 && (
          <Button type="primary" htmlType="submit" disabled={invoiceType == undefined ? true : false} style={{marginTop:'15px',display: 'flex',marginLeft:"auto" }}>
            Submit
          </Button>
          )}
        </Form.Item>
</Form>
     
  </Card>
</Modal>
</Card>
    </>
)
} 
export default Payables
