import React, { useEffect, useRef, useState } from 'react';

import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Input, Button, Tag, Divider, Popconfirm, Switch, Card, Row, Table, Drawer, Col, Descriptions, Form, Select } from 'antd';
import { ColumnProps } from 'antd/lib/table';
import { Link } from 'react-router-dom';
import {CheckCircleOutlined,CloseCircleOutlined,RightSquareOutlined,EyeOutlined,EditOutlined,SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { EnquiriesService } from "libs/shared-services/enquiry-management/src/lib/enquiries-service"
import { RmCountPriceListService } from "libs/shared-services/raw-material-procurement/src/lib/rm-count-pricelist"
import { CompanyCategoryEnum } from '@gtpl/shared-models/raw-material-procurement';
import moment from 'moment';
import {GrnService} from 'libs/shared-services/procurement/src/lib/grn-service'
import form from 'antd/lib/form';
import { BatchNumRequest, LotNumRequest, RmCountRequest } from '@gtpl/shared-models/procurement-management';
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
import { HarvestTypes, SupplierTypeEnum } from '@gtpl/shared-models/common-models';
import {WarehouseDashboardService} from '@gtpl/shared-services/analytics'
import {HLpercentagesService} from 'libs/shared-services/masters/src'
import { HlPercentageRangeRequest } from 'libs/shared-models/masters/src/lib/hl-percentage';

import html2pdf from 'html2pdf.js';
import { IdRequest } from '@gtpl/shared-models/gtpl';
/* eslint-disable-next-line */
export interface LivePurchaseAnalysisReportProps {}

export function LivePurchaseAnalysisReport(
  props: LivePurchaseAnalysisReportProps
) { 
 
  const searchInput = useRef(null);
  const [page, setPage] = React.useState(1);
  const [searchText, setSearchText] = useState(''); 
  const [searchedColumn, setSearchedColumn] = useState('');
  const [data, setData]=useState([])
  const [data1, setData1]=useState([])
  const [batches, setBatches]=useState([])
  const [selectedSaleOrder,setSelectedSaleOrder] = useState<number>(null);
  const [display, setDisplay] = useState<string>('none');
  const [form] = Form.useForm();
  const { Option } = Select;
  const [price, setPrices]=useState([])
  const [totalAmt, setTotalAmt]=useState(0)
  const [totalQty, setTotalQty]=useState(0)
  const [totalHonWeight, setTotalHonWeight]=useState(0)
  const [totalHlWeight, setTotalHlWeight]=useState(0)
  const [AvgCount, setAvgCount]=useState(0)
  const [gradeAmt, setGradeAmt]=useState(0)
  const [totalVal, setTotalVal]=useState(0)
  const [pondCount, setPondCount]=useState(0)
  const [pondQty, setPondQty]=useState(0)
  const [defectsData, setDeffectsData]=useState([])
  const [qtyForRate,setQtyForRate] = useState([])
  const [amtForRate,setAmtForRate] = useState([])

  const [AvgWeightCount, setAvgWeightCount]=useState(0)
  const [totalCreates, setTotalCreates]=useState(0)

  const [pondData, setPondData]=useState([])
  const [hlPercent, setHlPercent]=useState<any>()
  const [invRate,setInvRate] = useState(0)
  const [submitDisable, setSubmitDisable] = useState(true)
  const [yeildProfit , setYeildProfit]=useState(0)

  const hlService = new HLpercentagesService()

  const wareHouseService = new WarehouseDashboardService()
let count1 = 0
let count2 = 0

  const service = new GrnService()
  // let totCreate = 0
  useEffect(() => {
    getBatches();
    // updateRmPurchaseAnalysis()
  }, []);
 
  /**
   * 
   */
  const updateRmPurchaseAnalysis = () =>{
    wareHouseService.updateRmPurchaseAnalysis().then(res =>{
        if(!res.status){
        
         AlertMessages.getErrorMessage(res.internalMessage)
              
        }else{
          setSubmitDisable(true)
          getAll(selectedSaleOrder)
        }
    })
}

 const getBatches =() =>{
    const req = new IdRequest()
   req.Id =  Number(localStorage.getItem('unit_id'));
  service.getAllBatchesForLive(req).then(res => {
    if(res.status){
      setBatches(res.data)
    }
})
 }
  const getAll= (val) => {
    console.log(localStorage.getItem('createdUser'))
    const batchReq=new BatchNumRequest()
    batchReq.batchNum = val
    let expCount = 0
    let totQty =0 
    let avgWe =0
    let UnloadingDate
    let batch 
    let invoiceIncludeIce
  
         service.getPuchareAnalysisReport(batchReq).then(res => {
      if(res.status){
          setData(res.data)
          batch = res.data[0]?.batch
         const totCreate = res.data.reduce((acc, e) => acc + Number(e.noOfCreate || 0), 0);
         setTotalCreates(totCreate)
          UnloadingDate = res.data[0]?.loadingDate?moment(res.data[0]?.loadingDate).format('YYYY-MM-DD'):res.data[0]?.loadingDate

  // const avgWe = res.data.reduce((acc, e) => acc  + Number(e.count?e.count:0)*Number(e.QTY?e.QTY:0), 0);
  // setAvgWeightCount(avgWe)
         
        const lotReq = new LotNumRequest()
        lotReq.lotNum = res.data1
        service.getDeffectsLivePurchaseAnalysis(batchReq).then(response => {
          if(response.status){
            setDeffectsData(response.data)
            const invoiceRate = response.data.filter(e=>e.type=='GOOD' && e.batch == res.data[0]?.batch)
            console.log(invoiceRate,'ppppppppppppppppppppp');
             invoiceIncludeIce =Number(Number(invoiceRate?.[0]?.unitPrice))
            setInvRate(invoiceIncludeIce)
            
             totQty = response.data.reduce((acc, e) => acc +Number(e.reWequantity? Number(e.reWequantity).toFixed(2) : Number(e.quantity)), 0);
             console.log(response.data.map((e)=>e.reWequantity ));
             
              setPondQty(totQty)
               avgWe = response.data.reduce((acc, e) => acc  + Number(e.count?e.count:0)*Number(e.reWequantity? Number(e.reWequantity).toFixed(2) : Number(e.quantity)), 0);
               setPondCount(avgWe)
               const totAvgRate = response.data.reduce((acc, e) => acc + Number(e.type=='GOOD'?Number(e.reWequantity? Number(e.reWequantity).toFixed(2) : Number(e.quantity)):0 || 0), 0);
    setQtyForRate(totAvgRate)
    const totAvgRateAmt = response.data.reduce((acc, e) => acc + Number(e.type=='GOOD'?(Number(e.rate)*Number(e.reWequantity? Number(e.reWequantity).toFixed(2) : Number(e.quantity))):0 || 0), 0);
    setAmtForRate(totAvgRateAmt)
          }else{
            setDeffectsData([])
          }})
        service.getPuchareAnalysisData(batchReq).then(res => {
          if(res.status){
              setData1(res.data)
              const totHl=res.data.reduce((acc, e) => acc  +Number(e.hlWeight?e.hlWeight:0), 0);
    setTotalHlWeight(totHl) 

    const totHo = res.data.reduce((acc, e) => acc  + Number(e.honQty), 0);
    // console.log(res.data.reduce((acc, e) => acc  + Number(e.honQty), 0),'tot hon weight');
    
    setTotalHonWeight(totHo) 
    const avg = res.data.reduce((acc, e) => acc  + Number(e.honQty*e.honCount), 0)
    // console.log(res.data.reduce((acc, e) => acc + Number(e.honQty*e.honCount), 0),'77777777777777 tot avgcount');
    
    setAvgCount(avg)
    const grade = res.data.reduce((acc, e) => acc + Number(Number(e.honQty)*(Number(e.price)-(Number(e.grnRmRate) - Number(invoiceIncludeIce?invoiceIncludeIce:e.grnRmRate)))), 0);    
    setGradeAmt(grade) 
    expCount=Math.round(Number(avg)/Number(totHo))
    // count1= Math.round(Number(avg)/Number(totHo))
    // console.log(Math.round(Number(avg)/Number(totHo)),'oooooooo');
     service.getAllBatchesAgainstMainLot(batchReq).then(res =>{
        if(res.status){
          
          const lotsReq = new LotNumRequest()
          lotsReq.lotNum = res.data
          service.getLivePurchase(batchReq).then(res => {
            if(res.status){
              setPondData(res.data)
              
      const avgeWe = res.data.reduce((acc, e) => acc  + Number(e.grnCount?e.grnCount:0)*Number(e.quantity?e.quantity:0), 0);
      // console.log(avgeWe,'avgeWeavgeWeavgeWe');
      
      setAvgWeightCount(avgeWe)
              const totalQty = res.data.reduce((acc, e) => acc + Number(e.quantity || 0), 0);
                  setTotalQty(totalQty)
                  
      const totAmt = res.data.reduce((acc, e) => acc +Number(e.price?e.price:0)*Number(e.quantity?e.quantity:0), 0);
      setTotalAmt (totAmt)
              // const totQty = res.data.reduce((acc, e) => acc + Number(e.qty || 0), 0);
              // setPondQty(totQty)
              // const avgWe = res.data.reduce((acc, e) => acc  + Number(e.count?e.count:0)*Number(e.qty?e.qty:0), 0);
              // console.log(res.data.reduce((acc, e) => acc  + Number(e.count?e.count:0)*Number(e.qty?e.qty:0), 0),'ppppppppppppppppppp');
              
              // setPondCount(avgWe)
              // count1= Math.round(Number(AvgCount)/Number(totalHonWeight))
              count2 = Math.round(Number(avgeWe)/Number(totalQty))
              console.log(expCount,'count1');
              console.log(avgeWe/totalQty,'count2');
              getData(expCount,count2,UnloadingDate)
              const hlReq = new HlPercentageRangeRequest(Number( Math.round(Number(avgeWe)/Number(totalQty))))
              hlService.getHlPercentageByRange(hlReq).then((res)=>{
                if(res.status){
                  setHlPercent(res.data)
                                const yeildVar = Number(Number(Number(totHl/totQty)*100)-Number(res.data?.hlPercentage?res.data?.hlPercentage:'0')).toFixed(2)
 const yeildPro =Number(Number(Number(totQty)*Number(yeildVar))/100).toFixed(3)
              const standYeildPro =(Number(Number(yeildPro)*100)/Number(res.data?.hlPercentage?res.data?.hlPercentage:'0')).toFixed(2)
              const yeildRate = Number(Number(grade)/Number(totHo)).toFixed(2)
              const yeildValue = Number(standYeildPro)*Number(yeildRate)
                            setYeildProfit(yeildValue)

                }else{
                  setHlPercent([])
                }
              })
            }
          })
        }
      })
          }
      })
      
      }
    
  })
}



const getData =(count1,count2,UnloadingDate) =>{
  console.log(count1,count2,'ooooooooooo');
  
  const req = new RmCountRequest()
  // console.log(Number(Number(Number(AvgCount?AvgCount:0)/Number(totalHonWeight?totalHonWeight:0))));
  // console.log(Number(Number(AvgWeightCount?AvgWeightCount:0)/Number(totalQty?totalQty:0)));
  
  
  req.count1= Math.round(count1)
  req.count2 = Math.round(count2)
  req.date = UnloadingDate
  req.harvestType = HarvestTypes.Live_Harvest

        service.getRmPriceByCount(req).then(res => {
          if(res.status){
              setPrices(res.data)
          }
      })
}
   
    const handleBatch=(value, item)=>{
      console.log(value);
      setSelectedSaleOrder(value);
      setDisplay('block');
      setSubmitDisable(false)
      
    }
    const submit =()=>{
      // getAll(selectedSaleOrder);
      updateRmPurchaseAnalysis()

    }
    const onReset = () => {
      setData([]);
    setTotalQty(0);
    setTotalAmt(0);
    setAvgWeightCount(0);
    setData1([]);
    setTotalHlWeight(0);
    setTotalHonWeight(0);
    setAvgCount(0);
    setGradeAmt(0);
    setPondData([]);
    setPondQty(0);
    setPondCount(0);
    getAll(0);
    }
    console.log(AvgWeightCount,'ooooooooooo');
    
    console.log(Number(AvgWeightCount?AvgWeightCount:0/totalQty?totalQty:0),'ppppppppppp');
    // const generatePDF = () => {
    //   const pdfContent = document.createElement('div');
    //   const title = document.createElement('h4');
    //   title.textContent = 'Live Purchase Analysis Report';
    //   title.style.textAlign = 'center';
    //   title.style.marginBottom = '10px';
    //   pdfContent.appendChild(title);
    //   const tableElement = document.getElementById("live-purchase-analysis-table");
    //   if (!tableElement) {
    //       console.error("Table element not found!");
    //       return;
    //   }
    //   const clonedTable = tableElement.cloneNode(true);
    //   pdfContent.appendChild(clonedTable);
  
    //   const options = {
    //     filename: 'Live Purchase Analysis Report.pdf',
    //     image: { type: 'jpeg', quality: 0.98 },
    //     html2canvas: { scale: 2 },
    //     jsPDF: { unit: 'mm', format: 'a4', orientation: 'landscape' },
    //   };
    //   html2pdf()
    //     .from(pdfContent)
    //     .set(options)
    //     .save()
    //           .then(() => {
    //           pdfContent.remove();
    //       });
    // };
    
    
    
    const generatePDF = () => {
      const pdfContent = document.createElement('div');
    
      // Title
      const title = document.createElement('h4');
      title.textContent = 'Live Purchase Analysis Report';
      title.style.textAlign = 'center';
      title.style.marginBottom = '10px';
      pdfContent.appendChild(title);
    
      // Clone the table
      const tableElement = document.getElementById("live-purchase-analysis-table");
      if (!tableElement) {
          console.error("Table element not found!");
          return;
      }
      
      // Clone the table properly
      const clonedTable = tableElement.cloneNode(true) as HTMLElement;
      pdfContent.appendChild(clonedTable);
    
      // Add styles for proper page breaks
      const style = document.createElement('style');
      style.textContent = `
        table {
          width: 100%;
          border-collapse: collapse;
        }
        tr, td, th {
          page-break-inside: avoid;  /* Prevent row split */
          break-inside: avoid;  /* Ensures full rows stay together */
        }
        .page-break {
          page-break-before: auto;  /* Only break if necessary */
        }
      `;
      pdfContent.appendChild(style);
    
      // PDF Options
      const options = {
        // filename: 'Live Purchase Analysis Report.pdf',
        filename: data[0]?.batch 
    ? `${data[0]?.batch} - Live Purchase Analysis Report.pdf` 
    : 'Live Purchase Analysis Report.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2 },
        jsPDF: { unit: 'mm', format: 'a3', orientation: 'landscape' },
      };
    
      html2pdf()
        .from(pdfContent)
        .set(options)
        .save()
        .then(() => {
          pdfContent.remove();
        });
    };
   
   
    return (
    <>
    <style>
      {
        `.ant-descriptions-item-label {
              font-weight: bold;
            }

        
        `
      }
    </style>
    <Card title={<span style={{color:'white'}}> Live Purchase Analysis Report</span>}
    style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }} extra={data.length == 0 || (<><ReactHTMLTableToExcel
      id='excel-button'
      // className='download-table-xls-button'
      table='live-purchase-analysis-table'
      filename='LivePrchaseAnalysisReportxls'
      sheet="Sheet 1"
      buttonText='Get Excel'
      className="ant-btn ant-btn" /><Button
        type="primary"
        onClick={generatePDF}
        style={{ marginLeft: 10 }}
      >
        Download PDF
      </Button></>)}>
  <Form form={form} layout={'vertical'} >
          <Row gutter={24}>
            <Col xs={{span:24}} sm={{span:24}} md={{span:5}} lg={{span:6}} xl={{span:6}}>
              <Form.Item
                name="batchNo"
                label="Batch Number"
                // rules={[
                //   {
                //     required: true,
                //     message: 'Sale Order is required'
                //   },
                // ]}
    
              >
                <Select
                      showSearch
                      // style={{ width: 260 }}
                      placeholder="Select Batch Number"
                      optionFilterProp="children"
                      onSelect={handleBatch}
                    //   onFocus={onFocus}
                    //   onBlur={onBlur}
                    //   onSearch={onSearch}
                      // filterOption={(input, option) =>
                      //   option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      // }
                    >
                      {/* <Option key={0} value={null}>Select Batch Number</Option> */}
                      {batches.filter((data) => data.batchNo).map((data)=>{
                        return <Option key={data.yearBatch} value={data.yearBatch}>{data.yearBatch}</Option>
                      })}
                    </Select>
                </Form.Item>
            </Col>
            <Col style={{paddingLeft:'45px',marginTop:'30px'}}>
            <Form.Item>
                      <Button type="primary" onClick={submit} disabled={submitDisable}>
                        Submit
                      </Button>
                    </Form.Item>
                    </Col>
            <Col style={{paddingLeft:'45px',marginTop:'30px'}}>
            <Form.Item>
              <Button type="primary" htmlType="reset" onClick={() => onReset()}>
                Reset
              </Button>
            </Form.Item>
          </Col>
           
            </Row>

           </Form>
           <Card>
              <table id='live-purchase-analysis-table' width='100%' >

                {data.length>0?(
                <div >
                  <div style={{border:'1px solid black'}}>
                  <Descriptions style={{padding:10}} column={4}>
                      <Descriptions.Item label={'Batch No'}>{data[0]?.batch}</Descriptions.Item>
                      <Descriptions.Item label={'Vehicle No'}>{data[0]?.vehicleNum}</Descriptions.Item>
                      <Descriptions.Item label={'Harvest Date'}>{data[0]?.harvestDate?moment(data[0]?.harvestDate).format('DD-MM-YYYY'):''}</Descriptions.Item>
                      <Descriptions.Item label={'Product'}>{data[0]?.product}</Descriptions.Item>
                      <Descriptions.Item label={'No.of Creates'}>{totalCreates?Number(totalCreates):0}</Descriptions.Item>
                      <Descriptions.Item label={'Plant Unloading Date'}>{data[0]?.loadingDate?moment(data[0]?.loadingDate).format('DD-MM-YYYY'):''}</Descriptions.Item>
                      <Descriptions.Item label={'Vehicle Type'}>{data[0]?.vehicleType}</Descriptions.Item>
                      </Descriptions>
                      {/* <br/><br/> */}
                      <div style={{ backgroundColor:'#B6A28E',textAlign:'start',paddingLeft:'10px' }}><b>Farmer Info</b></div>
                      <Row gutter={[16,16]}>
                      <Col xs={24} sm={24} md={14} lg={14} xl={14} >
                      <Descriptions column={2} style={{width:'100%',padding:10}}>
                      <Descriptions.Item label={'Farmer Name'}>{data?.[0]?.supplierType === SupplierTypeEnum.DEALER?data[0]?.dealerName:data[0]?.farmerName}</Descriptions.Item>
                      <Descriptions.Item label={'Farmer Category'}>{data?.[0]?.supplierType === SupplierTypeEnum.DEALER?data[0]?.dealerCategory:data[0]?.category}</Descriptions.Item>
                      <Descriptions.Item label={'Area'}>{data?.[0]?.supplierType === SupplierTypeEnum.DEALER?data[0]?.dealerCity:data[0]?.city}</Descriptions.Item>
                      <Descriptions.Item label={'Harvest Supervisor'}>{data[0]?.supervisor1}</Descriptions.Item>
                      <Descriptions.Item label={'Intake Supervisor'}>{data[0]?.supervisor2}</Descriptions.Item>
                      <Descriptions.Item label={'Harvest Type'}>{data[0]?.harvestType}</Descriptions.Item>
                    </Descriptions>
                        </Col>
                        <Col xs={24} sm={12} md={10} lg={10} xl={10} style={{padding:'10px',}}>
                        <table style={{width:'97%',marginTop:7}}>
                      <tr >
                        <td style={{textAlign:'left'}}><b>HON Qty Received</b></td>
                        <td style={{textAlign:'right'}}>{Number(pondQty?pondQty:totalQty).toFixed(2)}</td>
                      </tr>
                      <tr >
                        <td style={{textAlign:'left'}}><b>HL Qty Graded</b></td>
                        <td style={{textAlign:'right'}}>{Number(totalHlWeight).toFixed(2)}</td>
                      </tr> 
                      <tr >
                        <td style={{textAlign:'left'}}><b>HL Yield</b></td>
                        <td style={{textAlign:'right'}}>{Number(Number(totalHlWeight/(pondQty?pondQty:totalQty))*100).toFixed(3)}%</td>
                      </tr> 
                      <tr style={{borderBottom:'1px solid black'}}>
                        <td style={{textAlign:'left'}}><b>HL Standard Yield</b></td>
                        <td style={{textAlign:'right'}}>{hlPercent?.hlPercentage?hlPercent?.hlPercentage:'-'}%</td>
                        </tr>
                      <tr style={{borderBottom:'1px solid black'}}>
                        <td style={{textAlign:'left'}}><b>Yield Variance</b></td>
                        <td style={{textAlign:'right'}}><b>{Number(Number(Number(totalHlWeight/(pondQty?pondQty:totalQty))*100)-Number(hlPercent?.hlPercentage?hlPercent?.hlPercentage:'0')).toFixed(3)}%</b></td>
                      </tr>
                    </table>
                        </Col>
                      </Row>
                  </div>
                  <br></br>
                    <Card size='small' title={<span style={{color:'black'}}><b>Purchase Analysis Report</b></span>} 
                    style={{textAlign:'center',marginTop:'10px',border:'1px solid #36BA98'}} headStyle={{backgroundColor: '#36BA98', border: 0 }}>
                <Row gutter={[50,50]}>
                <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 12 }}>
                <table className={'ta-b'} style={{ tableLayout: 'fixed',width:'100%' }}>
                <tr style={{backgroundColor:'#b6a28e'}}><th colSpan={4} className={'ta-b'}>Pond Weighment</th></tr>

                <tr >
                <th className={'ta-b'}>Count</th>
                <th className={'ta-b'}>Quantity</th>
                <th className={'ta-b'}>Rate</th>
                <th className={'ta-b'}>Amount</th>

                </tr>
                {pondData.map((e)=>{


                return(
                <tr>
                <td className={'ta-b'}>{e.grnCount ? e.grnCount : ''}</td>
                <td className={'ta-b'}>{e.quantity?Number( e.quantity).toFixed(2) : ''}</td>
                {/* <td className={'ta-b'}>{e.price ?(Number(e.price)-Number(e.commission??0)).toFixed(2) : ''}</td>
                <td className={'ta-b'}>{((Number(e.price)-Number(e.commission??0))*Number(e.quantity?e.quantity:0)).toFixed(2)}</td> */}
                <td className={'ta-b'}>{e.price ?(Number(e.price)).toFixed(2) : ''}</td>
                <td className={'ta-b'}>{((Number(e.price))*Number(e.quantity?e.quantity:0)).toFixed(2)}</td>
                </tr>
                )
                })

 }
  
</table>
        </Col>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 12 }}>
        <table style={{width:'100%'}}>
  <tr>
    <td className={'ta-b'}>Weighted Avg. Count	</td>
    <td className={'ta-b'}><b>{Number(Number(AvgWeightCount)/Number(totalQty)).toFixed(2)}</b></td>
  </tr>
  <tr>
    <td className={'ta-b'}>Total Qty Procured	</td>
    <td className={'ta-b'}>{totalQty}</td>
  </tr> <tr>
    <td className={'ta-b'}>Total Amount in Rs	</td>
    <td className={'ta-b'}><b>{Number(totalAmt).toFixed(2)}</b></td>
  </tr> <tr>
    <td className={'ta-b'}>Purchase Rate	</td>
<td className={'ta-b'}>{Number(Number(amtForRate?amtForRate:0)/Number(qtyForRate?qtyForRate:0)).toFixed(2)}</td>  </tr>
</table>
        </Col>
      </Row>
      <br/><br/>
      <Row gutter={[50,50]}>
     {/* {pondData.length > 0 && pondData.every((e) => e.qty !== null) ? ( */}

                <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 12 }}>
                <table className={'ta-b'} style={{ tableLayout: 'fixed',width:'100%' }}>
                <tr style={{backgroundColor:'#b6a28e'}}><th colSpan={2} className={'ta-b'}>Plant Weighment</th></tr>
                <tr>
                <th className={'ta-b'}>Count</th>
                <th className={'ta-b'}>Quantity</th>

                </tr>
                {defectsData.map((e)=>{


                return(
                <tr>
    <td className={'ta-b'}>{e.reWeigCount ?e.reWeigCount: e.count}{e.type!= 'GOOD'?`(${e.defect})`:''}</td>
    <td className={'ta-b'}>{e.reWequantity? Number(e.reWequantity).toFixed(2) : Number(e.quantity)}</td>
                </tr>
                )
                })

                }
                </table>
                </Col>
                {/* ):''} */}
                <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 12 }}>
                <table style={{width:'100%'}}>
                <tr>
                <td className={'ta-b'}>Weighted Avg. Count	</td>
                <td className={'ta-b'}><b>{Number(Number(pondCount?pondCount:0)/Number(pondQty?pondQty:0)).toFixed(2)}</b></td>
                </tr>
                <tr>
                <td className={'ta-b'}>Total Qty Procured	</td>
                <td className={'ta-b'}>{Number(pondQty).toFixed(2)}</td>
                </tr>
                <br/>
                <tr style={{backgroundColor:'beige'}}>
                <td style={{color:'red'}}>Qty Gain / Loss in kgs</td>
                <td style={{color:'red'}}><b>{Number(pondQty-totalQty).toFixed(2)}</b></td>
                </tr> 
                <tr style={{backgroundColor:'beige'}}>
                <td style={{color:'red'}}>% gain</td>
                <td style={{color:'red'}}>{(Number(Number(pondQty-totalQty)/Number(totalQty))*100).toFixed(3)}%</td>
                </tr>
                </table>
                </Col>
                </Row>
                </Card>
                <div style={{ display: "flex", justifyContent: "center", marginTop: "15px" }}>
                  <div style={{ width: "50%", marginRight: "10px" }}>
                {data1.length>0 ?(
                <table style={{marginTop:'15px'}} >
                <tr><th colSpan={7} style={{color:'black',textAlign:'center',backgroundColor: '#36BA98',border:'1px solid black'}}>HEAD LESS TO HEAD ON CONVERSION (GRADING ANALYSIS)</th></tr>
                <tr>
                <th className={'ta-b'}> HL COUNT/LB </th>
                <th className={'ta-b'}> HL WEIGHT </th>
                <th className={'ta-b'}>HON WEIGHT IN KGS</th>
                <th className={'ta-b'}> HON COUNT PER KG </th>
                <th className={'ta-b'}> RM RATE </th>
                <th className={'ta-b'}> AMOUNT </th>
                <th className={'ta-b'}> % OF GRADING </th>

                </tr>
                {data1.map((e)=>{
              const rateDiff = Number(e.grnRmRate) - Number(invRate)

                return(

                <tr>
                <td className={'ta-b'}>{e.hlCount?e.hlCount:'-'}</td>
                <td className={'ta-b'}>{e.hlWeight?e.hlWeight:'-'}</td>
                <td className={'ta-b'}>{e.honQty?Number(e.honQty).toFixed(2):'-'}</td>
                <td className={'ta-b'}>{e.honCount?Number(e.honCount):'-'}</td>
                <td className={'ta-b'}>{(Number(e.price)-Number(rateDiff)).toFixed(2)}</td>
                <td className={'ta-b'}>{Number(Number(e.honQty)*Number(Number(e.price)-Number(rateDiff))).toFixed(2)}</td>
                <td className={'ta-b'}>{Number(e.hlWeight?e.hlWeight:0/totalHlWeight)?(Number(Number(e.hlWeight?e.hlWeight:0)/Number(totalHlWeight))*100).toFixed(1):0}%</td>

                </tr>
                )
                })}
                <tr>
                <th className={'ta-b'}><b>Total</b></th>
                <th className={'ta-b'}><b>{totalHlWeight.toFixed(2)}</b></th>
                <th className={'ta-b'}><b>{totalHonWeight.toFixed(2)}</b></th>
                <th className={'ta-b'}><b></b></th>
                <th className={'ta-b'}><b></b></th>
                <th className={'ta-b'}><b>{gradeAmt.toFixed(2)}</b></th>
                <th className={'ta-b'}><b></b></th>

                </tr>
                </table>
                ):''}
                  </div>
  
                  <div style={{ width: "50%" }}>
                <table style={{width:'100%',border:'1px solid black',marginTop:'15px'}}>
                <tr><th colSpan={2} style={{color:'black',textAlign:'center',backgroundColor: '#36BA98',border:'1px solid black'}}>ANALYSIS</th></tr>
                      <tr style={{padding:'10px'}}>
                        <td style={{textAlign:'left',paddingLeft:'10px'}}><b>AVG Count Expected</b></td>
                        <td style={{textAlign:'right',paddingRight:'10px'}}>{Number(Number(AvgCount?AvgCount:0)/Number(totalHonWeight?totalHonWeight:0)).toFixed(2)}</td>
                      </tr>
                      <tr>
                        <td style={{textAlign:'left',paddingLeft:'10px'}}><b>Weighted AVG Purchase Count </b></td>
                        <td style={{textAlign:'right',paddingRight:'10px'}}>{Number(Number(AvgWeightCount?AvgWeightCount:0)/Number(totalQty?totalQty:0)).toFixed(2)}</td>
                      </tr> 
                      <tr>
                        <td style={{textAlign:'left',paddingLeft:'10px'}}><b>Count Gain / Loss</b></td>
                        <td style={{textAlign:'right',paddingRight:'10px'}}>{Number(Number(Number(AvgWeightCount)/Number(totalQty))-Number(AvgCount/totalHonWeight)).toFixed(2)}</td>
                      </tr> 
                      <tr style={{borderBottom:'black'}}>
                        <td style={{textAlign:'left',paddingLeft:'10px'}}><b>Rate Difference based on Count Variation</b></td>
                        <td style={{textAlign:'right',paddingRight:'10px'}}>{price[1]?.price?Number(price[0]?.price?price[0]?.price:0)-Number(price[1]?.price?price[1]?.price:0):0}</td>
                      </tr>
                      <tr style={{borderBottom:'1px solid black'}}>
                        <td style={{textAlign:'left',paddingLeft:'10px'}}><b>Amount Gain/Loss Based on Count</b></td>
                        <td style={{textAlign:'right',paddingRight:'10px'}}>{Number(Number(price[1]?.price?Number(price[0]?.price?price[0]?.price:0)-Number(price[1]?.price?price[1]?.price:0):0)*Number(totalQty)).toFixed(2)}</td>
                      </tr>
                      <tr style={{borderBottom:'1px solid black'}}>
                        <td style={{textAlign:'left',paddingLeft:'10px'}}><b>Amount Gain/Loss Based on Qty</b></td>
                        <td style={{textAlign:'right',paddingRight:'10px'}}>{(Number(pondQty-totalQty)*Number(totalAmt?totalAmt:0)/Number(totalQty?totalQty:0)).toFixed(2)}</td> 
                      </tr> 
                      <tr style={{borderBottom:'1px solid black'}}>
                        <td style={{textAlign:'left',paddingLeft:'10px'}}><b>Total Profit /Loss</b></td>
                        <td style={{textAlign:'right',paddingRight:'10px'}}><b>{(Number(price[1]?.price?Number(Number(price[0]?.price?price[0]?.price:0)-Number(price[1]?.price?price[1]?.price:0)):0*Number(totalQty))+Number(Number(Number(pondQty)-Number(totalQty))*Number(totalAmt?totalAmt:0)/Number(totalQty?totalQty:0))).toFixed(2)}</b></td>
                      </tr>
                      <br></br>
                      <tr>
                        <td style={{textAlign:'left',paddingLeft:'10px'}}><b>Purchse Value </b></td>
                        <td style={{textAlign:'right',paddingRight:'10px'}}>{Number(totalAmt).toFixed(2)}</td>
                      </tr><tr style={{borderBottom:'1px solid black'}}>
                        <td style={{textAlign:'left',paddingLeft:'10px'}}><b>Expected Purchase Value</b></td>
                        <td style={{textAlign:'right',paddingRight:'10px'}}>{gradeAmt.toFixed(2)}</td>
                      </tr><tr style={{borderBottom:'1px solid black'}}>
                        <td style={{textAlign:'left',paddingLeft:'10px'}}><b>Total Profit /Loss	</b></td>
                        <td style={{textAlign:'right',paddingRight:'10px'}}><b>{Number(Number(gradeAmt)-Number(totalAmt)).toFixed(2)}</b></td>
                      </tr>
                       <tr style={{ borderBottom: '1px solid black' }}>
                        <td style={{ textAlign: 'left', paddingLeft: '10px' }}><b>As Per Standard Yeild Profit /Loss</b></td>
                        <td style={{ textAlign: 'right', paddingRight: '10px' }}><b>{Number(yeildProfit).toFixed(2)}</b></td>
                      </tr><tr style={{ borderBottom: '1px solid black' }}>
                          <td style={{ textAlign: 'left', paddingLeft: '10px' }}><b>As Per Standard Yield Excess Value</b></td>
                          <td style={{ textAlign: 'right', paddingRight: '10px' }}><b>{(Number(gradeAmt - totalAmt) + Number(yeildProfit)).toFixed(2)}</b></td>
                        </tr>
                    </table>
                </div>
                </div>

           </div>):<span>No data found</span>}
              </table>     
           </Card>

       
     </Card>
    </>
  );



}

export default LivePurchaseAnalysisReport;
