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 React, { useEffect, useRef, useState } from 'react';
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 './purchase-analysis-report.css';
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 { CountRequest } from '@gtpl/shared-models/sale-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 html2pdf from 'html2pdf.js';
import {HLpercentagesService} from 'libs/shared-services/masters/src'
import { HlPercentageRangeRequest } from 'libs/shared-models/masters/src/lib/hl-percentage';
import { IdRequest } from '@gtpl/shared-models/gtpl';
/* eslint-disable-next-line */
export interface PurchaseAnalysisReportProps {}

export function PurchaseAnalysisReport(  props: PurchaseAnalysisReportProps)
 {
 
 
  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 [AvgWeightCount, setAvgWeightCount]=useState(0)
  const [totalCreates, setTotalCreates]=useState(0)
  const [hlPercent, setHlPercent]=useState<any>()
  const [yeildProfit , setYeildProfit]=useState(0)
  const [defectsData, setDeffectsData]=useState([])
  const [qtyForRate,setQtyForRate] = useState([])
  const [amtForRate,setAmtForRate] = useState([])
  const [avgRate,setAvgRate] = useState([])
  const [invRate,setInvRate] = useState(0)
  const [submitDisable, setSubmitDisable] = useState(true)

  const wareHouseService = new WarehouseDashboardService()
  // let totCreate = 0


  const service = new GrnService()
  const hlService = new HLpercentagesService()
  useEffect(() => {
    getBatches();
    // updateRmPurchaseAnalysis()
  }, []);
 
  /**
   * 
   */
  const updateRmPurchaseAnalysis = () =>{
    wareHouseService.updateRmPurchaseAnalysis().then(res =>{
        if(!res.status){
          AlertMessages.getSuccessMessage(res.internalMessage)
        }else{
          getAll(selectedSaleOrder)
          setSubmitDisable(true)
        }
    })
}
 const getBatches =() =>{
  const req = new IdRequest()
   req.Id =  Number(localStorage.getItem('unit_id'));
  service.getAllBatchesForReWeighment(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 totAmt = 0
    let avgWe =0
    let batch 
    let invoiceIncludeIce
    service.getPuchareAnalysisReport(batchReq).then(res => {
      if(res.status){
      setData(res.data)
      batch = res.data[0]?.batch
      // console.log(res.data[0]?.batch,'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy');
      
      const totCreate = res.data.reduce((acc, e) => acc + Number(e.noOfCreate || 0), 0);
      setTotalCreates(totCreate)
      const UnloadingDate = res.data[0]?.loadingDate?moment(res.data[0]?.loadingDate).format('YYYY-MM-DD'):res.data[0]?.loadingDate
      // const totQty = res.data.reduce((acc, e) => acc + Number(e.QTY || 0), 0);
      // setTotalQty(totQty)
      // const totAmt = res.data.reduce((acc, e) => acc +Number(e.price?e.price:0)*Number(e.QTY?e.QTY:0), 0);
      // setTotalAmt (totAmt)
      // 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),'pppppppppppppppp');
    
  // setAvgWeightCount(avgWe)
  const lotReq = new LotNumRequest()
  lotReq.lotNum = res.data1
  
      service.getDeffectsPurchaseAnalysis(batchReq).then(response => {
        if(response.status){
          setDeffectsData(response.data)
          console.log(batch,'batchhhhhhhhhhhhhh');
          
          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)
          const totAvgRate = response.data.reduce((acc, e) => acc + Number(e.type=='GOOD'?e.quantity:0 || 0), 0);
      setQtyForRate(totAvgRate)
      const totAvgRateAmt = response.data.reduce((acc, e) => acc + Number(e.type=='GOOD'?(Number(e.rate)*Number(e.quantity)):0 || 0), 0);
      setAmtForRate(totAvgRateAmt)
         
           totQty = response.data.reduce((acc, e) => acc + Number(e.quantity || 0), 0);
           setTotalQty(totQty)
                     totAmt = response.data.reduce((acc, e) => acc +Number(Number(e.rate)*Number(e.quantity)), 0);
        setTotalAmt (totAmt)
         avgWe = response.data.reduce((acc, e) => acc  + Number(e.count?e.count:0)*Number(e.quantity?e.quantity:0), 0);
        // console.log(response.data.reduce((acc, e) => acc  + Number(e.count?e.count:0)*Number(e.QTY?e.QTY:0), 0),'pppppppppppppppp');
        
        setAvgWeightCount(avgWe)
        }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) 
            const count1= Math.round(avg/totHo)
            const count2 = Math.round(avgWe/totQty)
            getData(count1,count2,UnloadingDate)
            const hlReq = new HlPercentageRangeRequest(Number(Math.round(avgWe/totQty)))
            hlService.getHlPercentageByRange(hlReq).then((res)=>{
              if(res.status){
                setHlPercent(res.data)
              }else{
                setHlPercent([])
              }
              // console.log(Number(totQty),'total qty');
              // Number((Number(totHl/totQty)*100)-Number(res.data?.hlPercentage?res.data?.hlPercentage:'0'))
              const yeildVar = Number(Number(Number(totHl/totQty)*100)-Number(res.data?.hlPercentage?res.data?.hlPercentage:'0')).toFixed(2)
              console.log(Number(yeildVar),'yeild variance');
              // yeilvarience multiply with qty procured at plant weighment
             const yeildPro =Number(Number(Number(totQty)*Number(yeildVar))/100).toFixed(3)
             console.log(Number(totQty),'hon qty');
             console.log(yeildPro,'yeildPro');
             
              const standYeildPro =(Number(Number(yeildPro)*100)/Number(res.data?.hlPercentage?res.data?.hlPercentage:'0')).toFixed(2)
              console.log(standYeildPro,'standYeildPro');
              
              const yeildRate = Number(Number(grade)/Number(totHo)).toFixed(2)
              console.log(yeildRate,'yeildRate');
              
              const yeildValue = Number(standYeildPro)*Number(yeildRate)
              console.log(yeildValue,'ppppppp');
              
              // console.log(yeildPro,'4.048');
              // console.log(standYeildPro,'5.87');
              // console.log(yeildRate,'327.66');
              // console.log(yeildValue,'1923.36');
              
              setYeildProfit(yeildValue)
             //  Number((Number(totalHlWeight/totalQty)*100)-Number(hlPercent?.hlPercentage?hlPercent?.hlPercentage:'0')).toFixed(2)
            })
          }
            })
          }
    })
   
}

const onReset = () => {
  setData([]);
setTotalQty(0);
setTotalAmt(0);
setAvgWeightCount(0);
setData1([]);
setTotalHlWeight(0);
setTotalHonWeight(0);
setAvgCount(0);
setGradeAmt(0);
getAll(0);
}

const getData =(count1,count2,UnloadingDate) =>{
  const req = new RmCountRequest()
  // console.log(Number(AvgCount));
  // console.log(Number(totalHonWeight));
  
  
  req.count1= count1
  req.count2 = count2
  req.date = UnloadingDate
  req.harvestType = HarvestTypes.Re_Weighment
        service.getRmPriceByCount(req).then(res => {
          if(res.status){
            console.log(res.data[0]?.price);
            console.log(res.data[1]?.price);

            console.log(res.data[1]?.price-res.data[0]?.price);

              setPrices(res.data)
          }else{
            setPrices([])
          }
      })
}

const generatePDF = () => {
  const pdfContent = document.createElement('div');

  // Title
  const title = document.createElement('h4');
  title.textContent = 'Purchase Analysis Report';
  title.style.textAlign = 'center';
  title.style.marginBottom = '10px';
  pdfContent.appendChild(title);

  // Clone the table
  const tableElement = document.getElementById("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: 'Purchase Analysis Report.pdf',
    filename: data[0]?.batch 
    ? `${data[0]?.batch} - Purchase Analysis Report.pdf` 
    : '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();
    });
};


    const handleBatch=(value, item)=>{
      // console.log(value);
      setSelectedSaleOrder(value);
      setDisplay('block');
      setSubmitDisable(false)
      
    }
    const submit =()=>{
      // getAll(selectedSaleOrder);
      updateRmPurchaseAnalysis()

    }

  return (
    <>
        <style>
      {
        `.ant-descriptions-item-label {
              font-weight: bold;
            }
        `
      }
    </style>
    <Card title={<span style={{color:'white'}}>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='purchase-analysis-table'
      filename={data[0]?.batch ? `${data[0]?.batch} - Purchase Analysis Report` : 'Purchase Analysis Report'}
      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>
           <table id='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(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/totalQty)*100).toFixed(2)}%</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(totalHlWeight/totalQty)*100)-Number(hlPercent?.hlPercentage?hlPercent?.hlPercentage:'0')).toFixed(2)}%</b></td>
                </tr>
              </table>
                  </Col>
                </Row>
                </div>
                <br></br>
              <Card size='small' title={<span style={{color:'black'}}>Purchase Summary</span>} 
              style={{textAlign:'center',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:'#36BA98'}}><th colSpan={4} className={'ta-b'}>Plant Weighment</th></tr>
  <tr style={{backgroundColor:'#b6a28e'}}>
    <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>
 {defectsData.map((e)=>{

// console.log(totalQty,'ooooooooooooo');
  
  return(
    <tr>
    <td className={'ta-b'}>{e.count ? e.count : ''}{e.type!= 'GOOD'?`(${e.defect})`:''}</td>
    <td className={'ta-b'}>{e.quantity? Number(e.quantity).toFixed(2) : ''}</td>
    <td className={'ta-b'}>{e.rate ? Number(e.rate).toFixed(2) : ''}</td>
    <td className={'ta-b'}>{Number(Number(e.rate?e.rate:0)*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?AvgWeightCount:0)/Number(totalQty?totalQty:0)).toFixed(2)}</b></td>
  </tr>
  <tr>
    <td className={'ta-b'}>Total Qty Procured	</td>
    <td className={'ta-b'}>{Number(totalQty).toFixed(2)}</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>
      </Card>
      {/* <br/><br/> */}
      <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)=>{
              // console.log(totalHlWeight,'oooooooooooo');
              const rateDiff = Number(e.grnRmRate) - Number(invRate)
              console.log(invRate,rateDiff,'iiiiiiiiiiiiiiiiiii');
              
              return(

            <tr>
              <td className={'ta-b'}>{e.hlCount?e.hlCount:'-'}</td>
              <td className={'ta-b'}>{e.hlWeight?Number(e.hlWeight).toFixed(3):'-'}</td>
              <td className={'ta-b'}>{e.honQty?Number(e.honQty).toFixed(3):'-'}</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>{(Number(gradeAmt)/Number(totalHonWeight)).toFixed(2)}</b></th>
              <th className={'ta-b'}><b>{gradeAmt.toFixed(2)}</b></th>
              <th className={'ta-b'}><b></b></th>

            </tr>
          </table>
          ):''}
        </div>
{/* <br/><br/> */}
      <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>
                  <td style={{textAlign:'left',paddingLeft:'10px'}}><b>AVG Count Expected</b></td>
                  <td style={{textAlign:'right',paddingRight:'10px'}}>{Number(Number(AvgCount)/Number(totalHonWeight)).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?AvgWeightCount:0)/Number(totalQty?totalQty:0))-Number(Number(AvgCount?AvgCount:0)/Number(totalHonWeight?totalHonWeight:0))).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'}}>{Number(price[1]?.price?Number(price[0]?.price?price[0]?.price:0)-Number(price[1]?.price?price[1]?.price:0):0).toFixed(2)}</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(price[1]?.price?Number(Number(price[0]?.price?price[0]?.price:0)-Number(price[1]?.price?price[1]?.price:0))*(Number(totalQty?totalQty:0)):0).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'}}>N/A</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))*(Number(totalQty?totalQty:0)):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(gradeAmt-totalAmt).toFixed(2)}</b></td>
                </tr>
                {/* {(Number((Number(totalHlWeight/totalQty)*100)-Number(hlPercent?.hlPercentage?hlPercent?.hlPercentage:'0')))>0?(
                      <> */}
                      <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>
    </>
  );



}

export default PurchaseAnalysisReport;
