import { Input, Button, DatePicker, Form, Card, Col, Select, Row } from 'antd';
import Table, { ColumnProps } from 'antd/lib/table';
import React, { useEffect, useRef, useState } from 'react'
import { BarcodeOutlined, DownloadOutlined, SearchOutlined, UndoOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import form from 'antd/lib/form';
import { GrnService } from 'libs/shared-services/procurement/src/lib/grn-service';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { getMonthWisePurchaseRequest } from '@gtpl/shared-models/procurement-management';
import moment from 'moment';
import { WarehouseDashboardService } from '@gtpl/shared-services/analytics';
import { Excel } from "antd-table-saveas-excel";
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import { PlantsDropDown } from '@gtpl/shared-models/masters';
import { UnitcodeService } from '@gtpl/shared-services/masters';



export interface PurchaseAnalysisReportGridProps {
    purchaseAnalysisData?:string
    
}

const MonthWisePurchaseAnalsysisReport = () => {
    const [page, setPage] = React.useState(1); 
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);
    const [form] = Form.useForm(); 
     const service = new GrnService()
     const [data,setdata] = useState([])
     const { RangePicker } = DatePicker;
      const [submitDisable, setSubmitDisable] = useState(true)
     const { Option } = Select;
const [plantData, setPlantData] = useState<PlantsDropDown[]>([]);
  const unitsService = new UnitcodeService();
  const [unitId, setUnitId] = useState<number>(0);
 
  useEffect(()=>{
    if (Number(localStorage.getItem('unit_id')) != 5) {
      form.setFieldsValue({ unitId: Number(localStorage.getItem('unit_id')) })
      setUnitId(Number(localStorage.getItem('unit_id')))
    }
    getAllPlants()
  },[])

     const wareHouseService = new WarehouseDashboardService()

      //  useEffect(() => {
      //        updateRmPurchaseAnalysis()

      //   //  getMonthWisePurchaseAnalysisReport()
      //  }, []);
   


  const getMonthWisePurchaseAnalysisReport = () =>{
    wareHouseService.updateRmPurchaseAnalysis().then(res =>{
        if(!res.status){
         
         AlertMessages.getErrorMessage(res.internalMessage)
              
        }
        else{
          setSubmitDisable(true)
          getData()
        }
    })
}

     const getData = () => {
      // updateRmPurchaseAnalysis()

      const req = new getMonthWisePurchaseRequest()
      console.log(unitId,'uuuuuu');
      
      if(form.getFieldValue('month')!= undefined){
        // console.log(moment(form.getFieldValue('month')[0]).format('YYYY-MM-DD'),'oooo');s
      req.fromDate = moment(form.getFieldValue('month')[0]).format('YYYY-MM-DD')
      req.toDate = moment(form.getFieldValue('month')[1]).format('YYYY-MM-DD')
      }
      req.unit = unitId
      service.getMonthWisePurchaseAnalysisReport(req).then((res) => {
        if (res.status) {
          setdata(res.data);
        } else {
          if (res.intlCode) {
            AlertMessages.getErrorMessage(res.internalMessage);
          } else {
            AlertMessages.getErrorMessage(res.internalMessage);
          }
          setdata([]);
        }
      })
        .catch((err) => {
          AlertMessages.getErrorMessage(err.message);
          setdata([]);
        });
    }


    function handleSearch(selectedKeys, confirm, dataIndex) {
      
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
      };
    
      function handleReset(clearFilters) {
        clearFilters();
        setSearchText('');
      };

    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 onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
              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 columnLine: ColumnProps<any>[] =[
        {
            title: 'S No',
            key: 'id',
            width: '70px',
            responsive: ['md'],
            align: 'left',
            render: (text, object, index) => (page-1) * 10 +(index+1)

        },

        {
            title: 'Batch No',
            key: 'batchNo',
            dataIndex:'batchNo',
            width: '150',
            responsive: ['md'],
            align: 'left',
            ...getColumnSearchProps('batchNo'),
            // sorter: (a, b) => a.batchNo?.localeCompare(b.batchNo),
            // sortDirections: ['descend', 'ascend']
        },
         {
            title: 'Product',
            key: 'product',
            dataIndex:'product',
            width: '150',
            responsive: ['md'],
            align: 'left',
            ...getColumnSearchProps('product'),
            // sorter: (a, b) => a.product?.localeCompare(b.product),
            // sortDirections: ['descend', 'ascend']
        },
        {
          title: 'Year',
          key: 'year',
          dataIndex:'year',
          width: '150',
          responsive: ['md'],
          align: 'left',
          ...getColumnSearchProps('year'),
          // sorter: (a, b) => a.batchNo?.localeCompare(b.batchNo),
          // sortDirections: ['descend', 'ascend']
      },
        {
            title: 'Farmer Name',
            key: 'farmer',
            dataIndex:'farmer',
            width: '150',
            responsive: ['md'],
            align: 'left',
            ...getColumnSearchProps('farmer'),
            // sorter: (a, b) => a.farmer?.localeCompare(b.farmer),
            // sortDirections: ['descend', 'ascend']
        },

        {
          title: 'Invoice Date',
          key: 'invoiceDate',
          dataIndex:'invoiceDate',
          // width: '150',
          responsive: ['md'],
          align: 'left',
          ...getColumnSearchProps('invoiceDate'),
          sorter: (a, b) => a.invoiceDate?.localeCompare(b.invoiceDate),
          sortDirections: ['descend', 'ascend']
      },
        {
          title: 'Harvest Type',
          key: 'harvestType',
          dataIndex:'harvestType',
          // width: '150',
          responsive: ['md'],
          align: 'left',
          ...getColumnSearchProps('harvestType'),
          sorter: (a, b) => a.harvestType?.localeCompare(b.harvestType),
          sortDirections: ['descend', 'ascend']
      },
       {
          title: 'Intake Supervisor',
          key: 'supervisor',
          dataIndex:'supervisor',
          // width: '150',
          responsive: ['md'],
          align: 'left',
          ...getColumnSearchProps('supervisor'),
          sorter: (a, b) => a.supervisor?.localeCompare(b.supervisor),
          sortDirections: ['descend', 'ascend']
      },
        {
        
          title: 'AVG Purchase Count',
          key: 'expected',
          dataIndex: 'expected',
          width: '110px',
          render:(value,record)=>{
            return(record.grnHonProduct?(Number(Number(record.grnHonProduct)/Number(record.totGrnHonQnty)).toFixed(2) ):'-')
          }            

  },
  {
          title: 'AVG Expected Count',
                key: 'purchaseCount',
                dataIndex: 'purchaseCount',
                width: '110px',
                render:(value,record)=>{
                  return(record.honProduct?(Number(Number(record.honProduct)/Number(record.totHonQnty)).toFixed(2) ):'-')
                }            
        },
        {
          title: 'Count Gain/Loss',
          key: 'purchaseCount',
          dataIndex: 'purchaseCount',
          width: '110px',
          render:(value,record)=>{
            return(record.honProduct?((Number(record.grnHonProduct)/Number(record.totGrnHonQnty))-(Number(Number(record.honProduct)/Number(record.totHonQnty))) ).toFixed(2):'-')
          }            
        },
        
        {
            title: 'Total HON Quantity',
            key: 'totHonQnty',
           dataIndex: 'totHonQnty',
            width: '70px',
            responsive: ['md'],
            align: 'left',
            ...getColumnSearchProps('totHonQnty'),
            sorter: (a, b) => a.totHonQnty-b.totHonQnty,
            sortDirections: ['descend', 'ascend'],
            render: (val,text) => (text.totHonQnty ? Number(text.totHonQnty).toFixed(2): '-')
        },
        {
          title: 'Total HL Quantity ',
          key: 'hlQty',
         dataIndex: 'hlQty',
          width: '70px',
          responsive: ['md'],
          align: 'left',
          sorter: (a, b) => a.hlQty.localeCompare(b.hlQty),
          sortDirections: ['descend', 'ascend'],
          render: (val,text) => (text.hlQty ? Number(text.hlQty).toFixed(2): '-')

      },
       {
          title: 'Yeild Variance ',
          key: 'varience',
         dataIndex: 'varience',
          width: '70px',
          responsive: ['md'],
          align: 'left',
          sorter: (a, b) => a.varience.localeCompare(b.varience),
          sortDirections: ['descend', 'ascend'],
          render: (val,text) => (text.varience ? Number(text.varience).toFixed(2): '-')

      },
     
   
        {
            title: 'Purchase Value',
            key: 'purchaseValue',
            dataIndex: 'purchaseValue',
            width: '70px',
            responsive: ['md'],
            align: 'left',
            ...getColumnSearchProps('purchaseValue'),
            sorter: (a, b) => a.purchaseValue.localeCompare(b.purchaseValue),
            sortDirections: ['descend', 'ascend'],
            render: (val,text) => (text.purchaseValue ? Number(text.purchaseValue).toFixed(2): '-')


        },
        {
            title: 'Expected Purchase value',
            key: 'expectedValue',
           dataIndex: 'expectedValue',
            width: '70px',
            responsive: ['md'],
            align: 'left',
            // ...getColumnSearchProps('expectedValue'),
            sorter: (a, b) => a.expectedValue?.localeCompare(b.expectedValue),
            sortDirections: ['descend', 'ascend'],
            render: (val,text) => (text.expectedValue ? Number(text.expectedValue).toFixed(2): '-')

        },
        {
            title: 'Total Profit / loss',
            key: 'expectedValue',
            dataIndex: 'expectedValue',
            width: '70px',
            responsive: ['md'],
            align: 'left',
            // ...getColumnSearchProps('recievedAmt'),
            sorter: (a, b) => a.recievedAmt-b.recievedAmt,
            sortDirections: ['descend', 'ascend'],
            render: (val,text) => (text.expectedValue ? Number(Number(text.expectedValue)-Number(text.purchaseValue)).toFixed(2): '-')

        },
          {
          title: 'As Per Standard Yeild Profit /Loss',
          key: 'varience',
         dataIndex: 'varience',
          width: '70px',
          responsive: ['md'],
          align: 'left',
          sorter: (a, b) => a.varience-b.varience,
          sortDirections: ['descend', 'ascend'],
          render: (val,text) => {
            // excess qty for yeild
            console.log(text.batchNo);
            const yeildPPro = ((Number(Number(text.totHonQnty??0).toFixed(1)  )*Number(Number(text.varience??0).toFixed(2))/100)).toFixed(3)
            console.log(Number(text.totHonQnty).toFixed(1),'hon qtyyyyy');
            console.log(Number(text.varience).toFixed(2),'varienceeeeee');
            console.log(yeildPPro,'yeildPPro');
          //  excess qty for standard yeild
            const standard= (Number(Number(yeildPPro??0)*100)/Number(text.hlPercentage ??0)).toFixed(2)
            console.log(standard,'standard');
            // avg rate for expected amount
            const rate = (Number(text.expectedValue??0)/Number(Number(text.totHonQnty??0).toFixed(1))).toFixed(2)
            console.log(rate,'rate');
            // excess amount 
            const value = Number(Number(standard??0)*Number(rate??0)).toFixed(2)
            console.log(value,'valueeeee');
            return value?(value): '-'
          }

      },
      {
          title: 'As Per Standard Yield Excess Value',
          key: 'varience',
         dataIndex: 'varience',
          width: '70px',
          responsive: ['md'],
          align: 'left',
          sorter: (a, b) => a.varience-b.varience,
          sortDirections: ['descend', 'ascend'],
          render: (val,text) => {
            // console.log(text.batchNo);
            
            const yeildPPro = ((Number(Number(text.totHonQnty??0).toFixed(1)  )*Number(Number(text.varience??0).toFixed(2))/100)).toFixed(3)
            // console.log(Number(text.totHonQnty).toFixed(1),'hon qtyyyyy');
            // console.log(Number(text.varience).toFixed(2),'varienceeeeee');

            // console.log(yeildPPro,'yeildPPro');
            
          //  excess qty for standard yeild
            const standard= (Number(Number(yeildPPro??0)*100)/Number(text.hlPercentage ??0)).toFixed(2)

            // console.log(standard,'standard');
            
            // avg rate for expected amount
            const rate = (Number(text.expectedValue??0)/Number(Number(text.totHonQnty??0).toFixed(1))).toFixed(2)
            console.log(rate,'rate');
            // 
            // excess amount 
            const value = Number(Number(standard??0)*Number(rate??0)).toFixed(2)
            // console.log(value,'valueeeee');  
            return(value?(Number(value??0)+(Number(text.expectedValue??0)-Number(text.purchaseValue??0))).toFixed(2): '-')
          }
      },

    ]
//     const excelColumns:any=[
//       {
//           title: 'S No',
//           render: (text, object, index) => (page-1) * 10 +(index+1)

//       },

//       {
//           title: 'Batch No',
//           dataIndex:'batchNo',
//       },
//       {
//           title: 'Farmer Name',
//           dataIndex:'farmer',
//         },

//       {
//         title: 'Harvest Type',
//         dataIndex:'harvestType',
//        },
//       {
      
//         title: 'AVG Purchase Count',
//         dataIndex: 'expected',
//         render:(value,record)=>{
//           return(record.grnHonProduct?(Number(Number(record.grnHonProduct)/Number(record.totGrnHonQnty)).toFixed(2) ):'-')
//         }            

// },
// {
//         title: 'AVG Expected Count',
//               dataIndex: 'purchaseCount',
//               render:(value,record)=>{
//                 return(record.honProduct?(Number(Number(record.honProduct)/Number(record.totHonQnty)).toFixed(2) ):'-')
//               }            
//       },
//       {
//         title: 'Count Gain/Loss',
//         dataIndex: 'purchaseCount',
//         render:(value,record)=>{
//           return(record.honProduct?((Number(record.grnHonProduct)/Number(record.totGrnHonQnty))-(Number(Number(record.honProduct)/Number(record.totHonQnty))) ).toFixed(2):'-')
//         }            
//       },
      
//       {
//           title: 'Total HON Quantity',
//          dataIndex: 'totHonQnty',
//          render: (val,text) => (text.totHonQnty ? Number(text.totHonQnty).toFixed(2): '-')


//       },
//       {
//         title: 'Total HL Quantity ',
//        dataIndex: 'hlQty',
//         render: (val,text) => (text.hlQty ? Number(text.hlQty).toFixed(2): '-')

//     },
//       {
//           title: 'Purchase Value',
//           dataIndex: 'purchaseValue',
//           render: (val,text) => (text.purchaseValue ? Number(text.purchaseValue).toFixed(2): '-')


//       },
//       {
//           title: 'Expected Purchase value',
//          dataIndex: 'expectedValue',
//           render: (val,text) => (text.expectedValue ? Number(text.expectedValue).toFixed(2): '-')

//       },
//       {
//           title: 'Total Profit / loss',
//           dataIndex: 'expectedValue',
//           render: (val,text) => (text.expectedValue ? Number(Number(text.expectedValue)-Number(text.purchaseValue)).toFixed(2): '-')

//       }

//   ];
//     const exportExcel = () => {
//       const excel = new Excel();
//       excel
//         .addSheet('month-wise-purchase-analysis-table')
//         .addColumns(excelColumns)
//         .addDataSource(data, { str2num: true })
//         .saveAs('MonthWisePurchaseAnalysisReport.xlsx');
//     }


const exportExcel = () => {
  const excel = new Excel();
  
  let totalHonQnty = 0;
  let totalHlQty = 0;
  let totalPurchaseValue = 0;
  let totalExpectedValue = 0;
  let totalProfitLoss = 0;

  const exportData = data.map((record,index) => {
    const profitLoss = (Number(record.expectedValue) || 0) - (Number(record.purchaseValue) || 0);
    
    totalHonQnty += Number(record.totHonQnty) || 0;
    totalHlQty += Number(record.hlQty) || 0;
    totalPurchaseValue += Number(record.purchaseValue) || 0;
    totalExpectedValue += Number(record.expectedValue) || 0;
    totalProfitLoss += profitLoss;

    return {
      ...record,
      sNo: index + 1,
      totalProfitLoss: profitLoss.toFixed(2)
    };
  });

  exportData.push({
    sNo: undefined,
    batchNo: 'Total',
    avgPurchaseCount: undefined,
    avgExpectedCount: undefined,
    countGainLoss: undefined,
    totHonQnty: totalHonQnty.toFixed(2),
    hlQty: totalHlQty.toFixed(2),
    purchaseValue: totalPurchaseValue.toFixed(2),
    expectedValue: totalExpectedValue.toFixed(2),
    totalProfitLoss: totalProfitLoss.toFixed(2)
  });

  excel
    .addSheet('Month-wise Purchase Analysis')
    .addColumns([
      { 
        title: 'S No',
        dataIndex: 'sNo', 
        render: (text, record) => record.batchNo === 'Total' ? '' : text 
      },
      { title: 'Batch No', dataIndex: 'batchNo' },
      { title: 'Year', dataIndex: 'year' },
      { title: 'Invoice Date', dataIndex: 'invoiceDate' },
      { title: 'Farmer Name', dataIndex: 'farmer' },
      { title: 'Harvest Type', dataIndex: 'harvestType' },
      { title: 'Intake Supervisor', dataIndex: 'supervisor' },
      { title: 'AVG Purchase Count', dataIndex: 'avgPurchaseCount', render: (value, record) => record.grnHonProduct ? (Number(record.grnHonProduct) / Number(record.totGrnHonQnty)).toFixed(2) : '-' },
      { title: 'AVG Expected Count', dataIndex: 'avgExpectedCount', render: (value, record) => record.honProduct ? (Number(record.honProduct) / Number(record.totHonQnty)).toFixed(2) : '-' },
      { title: 'Count Gain/Loss', dataIndex: 'countGainLoss', render: (value, record) => record.honProduct ? ((Number(record.grnHonProduct) / Number(record.totGrnHonQnty)) - (Number(record.honProduct) / Number(record.totHonQnty))).toFixed(2) : '-' },
      { title: 'Total HON Quantity', dataIndex: 'totHonQnty' },
      { title: 'Total HL Quantity', dataIndex: 'hlQty' },
       {
          title: 'Yeild Variance ',
         dataIndex: 'varience',
        render: (val,text) => (text.varience ? Number(text.varience).toFixed(2): '-')

      },
      { title: 'Purchase Value', dataIndex: 'purchaseValue' },
      { title: 'Expected Purchase Value', dataIndex: 'expectedValue' },
      { title: 'Total Profit / Loss', dataIndex: 'totalProfitLoss' },
      //     {
      //     title: 'As Per Standard Yeild Profit /Loss',
      //    dataIndex: 'varience',
      //    render: (val,text) => {
      //       // excess qty for yeild
      //       const yeildPPro = ((Number(Number(text.totHonQnty)  )*Number(text.varience)/100))
      //     //  excess qty for standard yeild
      //       const standard= (Number(Number(yeildPPro)*100)/Number(text.hlPercentage ??0))
      //       // avg rate for expected amount
      //       const rate = (Number(text.expectedValue)/Number(text.totHonQnty??0))  
      //       // excess amount 
      //       const value = Number(Number(standard)*Number(rate)).toFixed(2)
      //       return value?(value): '-'
      //     }

      // },
      // {
      //     title: 'As Per Standard Yield Excess Value',
      //    dataIndex: 'varience',
      //     render: (val,text) => {
      //       const yeildPPro = ((Number(Number(text.totHonQnty).toFixed(3))*Number(text.varience??0))/100).toFixed(3)
      //       const standard= (Number(Number(yeildPPro)*100)/Number(text.hlPercentage ??0)).toFixed(2)
      //       const rate = (Number(text.expectedValue)/Number(text.totHonQnty??0)).toFixed(3)
      //       const value = Number(Number(standard)*Number(rate)) .toFixed(3)
      //       return(value?(Number(value)+Number(text.expectedValue)-Number(text.purchaseValue)).toFixed(2): '-')
      //     }
      // },
         {
          title: 'As Per Standard Yeild Profit /Loss',
         dataIndex: 'varience',
render: (val,text) => {
             const yeildPPro = ((Number(Number(text.totHonQnty).toFixed(1)  )*Number(Number(text.varience).toFixed(2))/100)).toFixed(3)
             const standard= (Number(Number(yeildPPro)*100)/Number(text.hlPercentage ??0))
   const rate = (Number(text.expectedValue)/Number(Number(text.totHonQnty).toFixed(1))).toFixed(2)
             const value = Number(Number(standard)*Number(rate)).toFixed(2)
              return value?(value): '-'
          }

      },
      {
          title: 'As Per Standard Yield Excess Value',
         dataIndex: 'varience',
         render: (val,text) => {
            const yeildPPro = ((Number(Number(text.totHonQnty).toFixed(1)  )*Number(Number(text.varience).toFixed(2))/100)).toFixed(3)
             const standard= (Number(Number(yeildPPro)*100)/Number(text.hlPercentage ??0)).toFixed(2)
  const rate = (Number(text.expectedValue)/Number(Number(text.totHonQnty).toFixed(1))).toFixed(2)
           const value = Number(Number(standard)*Number(rate)).toFixed(2)
            return(value?(Number(value)+(Number(text.expectedValue)-Number(text.purchaseValue))).toFixed(2): '-')
          }
      },
    ])
    .addDataSource(exportData, { str2num: true })
    .saveAs('MonthWisePurchaseAnalysisReport.xlsx');
};


const getAllPlants = () => {
    unitsService.getAllMainPlants().then((res) => {
        if (res.status) {
            setPlantData(res.data);
        } else {
            setPlantData([]);
        }
    }).catch(err => {
        AlertMessages.getErrorMessage(err.message);
        setPlantData([]);
    })
}
const handleUnit = (value) => {
  setUnitId(value)
  setSubmitDisable(false)
}

const validateRange = (_: any, value: moment.Moment[]) => {
  if (!value || value.length !== 2) {
    return Promise.resolve();
  }
  const [start, end] = value;
  if (end.diff(start, "day") > 30) {
    return Promise.reject(new Error("Date range should not exceed 30 days"));
  }
  return Promise.resolve();
};
  return (
    <div>
    <Card
      size="small"
      title={<span style={{ color: 'white' }}>Month Wise Purchase Analysis Report</span>}
      style={{ textAlign: 'center' }}
      headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
      extra={
        <div>
          <Button icon={<DownloadOutlined />} onClick={() => { exportExcel(); }} style={{marginRight:30}}>
            GET EXCEL
          </Button>
          {/* <Button icon={<FilePdfOutlined  />} onClick={() => { handleExportPDF(); }}>
            Download PDF
          </Button> */}
        </div>
      }
    >
      <Form form={form} layout="vertical" onFinish={getMonthWisePurchaseAnalysisReport}>
        <Row gutter={24}>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
        <Form.Item name="unitId"   label="Unit" rules={[{ required: false,message: 'Missing Unit' }]} >
               <Select
                    showSearch
                    optionFilterProp="children"
                    filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    placeholder="Select Unit"
                    allowClear
                    style={{ width: '100%' }}
                    onChange={handleUnit}
                    disabled={Number(localStorage.getItem('unit_id')) != 5 ? true : false}
                >
                    {plantData.map(dropData => {
                        return <Option value={dropData.plantId}>{dropData.plantCode}</Option>
                    })}
                </Select>
            </Form.Item>
          
        </Col>
                            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
        
        <Form.Item label="GRN Date" name="month"  rules={[{ validator: validateRange },{ required: true,message: 'Missing grn date'

         }]} >
        <RangePicker onCalendarChange={()=>setSubmitDisable(false)}/>
        </Form.Item>
</Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 5 }} style={{ marginTop: '30px' }}>

        <Form.Item>
          <Button type="primary" onClick={() => form.submit()} disabled={submitDisable}>
            Submit
          </Button>
        </Form.Item>
        </Col></Row>
      </Form>
      {data.length>0?(
        <Table
        size="small"
        dataSource={data}
        columns={columnLine}
        scroll={{x:'max-content'}}
        summary={(pageData) => {
          const totalHonQnty = pageData.reduce((sum, record) => sum + (Number(record.totHonQnty) || 0), 0);
          const totalHlQty = pageData.reduce((sum, record) => sum + (Number(record.hlQty) || 0), 0);
          const totalPurchaseValue = pageData.reduce((sum, record) => sum + (Number(record.purchaseValue) || 0), 0);
          const totalExpectedValue = pageData.reduce((sum, record) => sum + (Number(record.expectedValue) || 0), 0);
          const totalProfitLoss = totalExpectedValue - totalPurchaseValue;
    
          return (
            
            <Table.Summary.Row>
              {/* <Table.Summary.Cell index={0}></Table.Summary.Cell>
              <Table.Summary.Cell index={1}></Table.Summary.Cell>
              <Table.Summary.Cell index={2}></Table.Summary.Cell>
              <Table.Summary.Cell index={3}></Table.Summary.Cell>
              <Table.Summary.Cell index={4} >Total</Table.Summary.Cell>
              <Table.Summary.Cell index={5}></Table.Summary.Cell>
              <Table.Summary.Cell index={6}></Table.Summary.Cell> */}
              <Table.Summary.Cell index={6} colSpan={9} >Total</Table.Summary.Cell>
              <Table.Summary.Cell index={10} >{totalHonQnty.toFixed(2)}</Table.Summary.Cell>
              <Table.Summary.Cell index={11} >{totalHlQty.toFixed(2)}</Table.Summary.Cell>
              <Table.Summary.Cell index={12}></Table.Summary.Cell>
              <Table.Summary.Cell index={13} >{totalPurchaseValue.toFixed(2)}</Table.Summary.Cell>
              <Table.Summary.Cell index={14} >{totalExpectedValue.toFixed(2)}</Table.Summary.Cell>
              <Table.Summary.Cell index={15}>
                <div style={{ fontWeight: 'bold', color: totalProfitLoss >= 0 ? 'green' : 'red' }}>
                  {totalProfitLoss.toFixed(2)}
                </div>
              </Table.Summary.Cell>
            </Table.Summary.Row>
          );
        }}
      />
        ):''}
    </Card>
  </div>
  )}

export default MonthWisePurchaseAnalsysisReport