import { Button, Col, DatePicker, Descriptions, Divider, Form, Input, Radio, Row, Select, Table } from "antd";
import React, { useEffect, useState } from "react";
import {ProdlogService,  ProductionInventoryService, WorkstationService } from '@gtpl/shared-services/production'
import { BillNumberRequest, JsonObjectreq, LotAndOperationReq, LotNumberRequest, OperationReportingReq, WorkStationCategoryReq } from "@gtpl/shared-models/production-management";
import { DeheadingPrevOperationEnum, DeheadingReportingTypeEnum, OperationTypeEnum, ProductionProcessTypeEnum, ShiftsEnum, SoakingPrevOperationEnum, TransactionType, ValueAdditionPrevOperationEnum, WorkStationCategoryEnum } from "@gtpl/shared-models/common-models";
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { UndoOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { DeheadingPeelingService, EmployeeService, SkuService, WorkerService } from '@gtpl/shared-services/masters'
import { ContractorIdReq, DeheadingRateBasedEnum, EmployeeRequest, PeelingRateBasedEnum, ScopeGradeReq, SoakTypeRequest } from "@gtpl/shared-models/masters";
import { ForkLiftJobService } from '@gtpl/shared-services/warehouse-management'
import moment from "moment";
import { ContractorService } from '@gtpl/shared-services/hrms'
import { ColumnProps } from "antd/lib/table";
import TextArea from "antd/lib/input/TextArea";
import { ForkLiftJobRequestDTO } from "@gtpl/shared-models/warehouse-management";

const { Option } = Select

export interface ProductionOperationFormProps {
    tabName: OperationTypeEnum
    processType: ProductionProcessTypeEnum
}

export const ProdutionOperationForm = (props: ProductionOperationFormProps) => {
    const prodService = new ProductionInventoryService()
    const [batchNumbers, setBatchNumbers] = useState<any[]>([])
    const [workStations, setWorkStations] = useState<any[]>([]);
    const workstationService = new WorkstationService();
    const [form] = Form.useForm()
    const productService = new SkuService()
    const [products, setProducts] = useState<any[]>([])
    const [type, setType] = useState<string>('')
    const [jobCodeData, setJobCodeData] = useState<any[]>([])
    const forkliftService = new ForkLiftJobService();
    const [contractorsInfo, setContractorsInfo] = useState<any[]>([])
    const contractorService = new ContractorService()
    const [tableData, setTableData] = useState<any[]>([])
    const employeeService = new EmployeeService()
    const [workersData, setWorkersData] = useState<any[]>([])
    const [page, setPage] = React.useState(1);
    const deheadingPeelingService = new DeheadingPeelingService()
    const [scopeOfWorkInfo, setScopeOfWorkInfo] = useState<any[]>([])
    const [peelingRate, setPeelingRate] = useState<number>()
    const employeeIds = []
    const workersService = new WorkerService()
    const [deheadingRate, setDeheadingRate] = useState<number>()
    const prodLogService  = new ProdlogService()
    const [prevBillInfo,setPrevBillInfo] = useState<any[]>([])
    const [contractorDisable,setContractorDisable] = useState<boolean>(false)
    const [workerDisable,setWorkerDisable] = useState<boolean>(false)
    const [totalsInfo,setTotalsInfo] = useState<any[]>([])
    const [billAgainstWorkers,setBillAgainstWorkers] = useState<any[]>([])
    const [countsInfo,setCountsInfo] = useState<any[]>([])
    const [addedInfo,setAddedInfo] = useState<any[]>([])
    const [editIndex,setEditIndex] = useState<number>(undefined)
    const [meatBasedPrice,setMeatBasedPrice] = useState<boolean>(false)
    const [honQty,setHonQty] = useState<number>(0)
    const [availableQty,setAvailableQty] = useState<number>(0)

    const [noOfWorkers,setNoOfWorkers] = useState<number>(0)
    const [totalAmount,setTotalAmount] = useState<number>(0)
    const [totalQty,setTotalQty] = useState<number>(0)
    const [addedInfoQty,setAddedInfoQty] = useState<number>(0)
    const [addedInfoAmount,setAddedInfoAmount] = useState<number>(0)
    const [submitDisable,setSubmitDisable] = useState<boolean>(false)
    const [isRRP,setIsRRP] = useState<boolean>(false)
    // const [rejectionFromProducts,setRejectionFromproducts] = useState<any[]>([])
    const [prevOpProductsInfo,setPrevOpProductsInfo] = useState<any[]>([])


    const plantId = localStorage.getItem('unit_id')
    const role = JSON.parse(localStorage.getItem('username'));
    const [jobCodeGrades, setJobCodeGrades] = useState<any[]>([])
    const [deheadingPriceBasedOn,setDeheadingPriceBasedOn] = useState<DeheadingRateBasedEnum>(DeheadingRateBasedEnum.HL)
    const [reportingTypeDisable,setReportingTypeDisable] = useState<boolean>(false)

    useEffect(() => {
        if(props.tabName != undefined){
            onReset()
        }
    },[props.tabName])

    useEffect(() => {
        getWorkStations()
        getContractorInfo()
        getWorkersInfo()
        if (props.tabName == OperationTypeEnum.VALUE_ADDITION) {
            getScopeOfWorkDropdown()
        }
    }, [])

    useEffect(() => {
        if (props.processType == ProductionProcessTypeEnum.REPROCESS) {
            getJobCodes()
        }
    }, [props.processType])

    const getPrevOperationProductsInfo = () => {
            const req = new LotAndOperationReq(props.processType == ProductionProcessTypeEnum.REPROCESS ? form.getFieldValue('jobCode') : form.getFieldValue('batchNumber'),form.getFieldValue('previousOperation'),form.getFieldValue('count'),Number(plantId),form.getFieldValue('year'))
            prodService.getProductsAgainstLotCount(req).then(res => {
                if(res.status){
                    setPrevOpProductsInfo(res.data)
                }else{
                    setPrevOpProductsInfo([])
                }
            })
        
    }

    const getCountsAgainstBatchNumber = () => {
        setCountsInfo([])
        const req = new LotAndOperationReq(props.processType == ProductionProcessTypeEnum.REPROCESS ? form.getFieldValue('jobCode') : form.getFieldValue('batchNumber'),form.getFieldValue('previousOperation'))
        req.year = form.getFieldValue('year')
        prodService.getCountsAgainstBatchNumber(req).then(res => {
            if(res.status){
                setCountsInfo(res.data)
                if(res.data.length == 1){
                    form.setFieldsValue({'count' : res.data[0].count})
                    onCountChange()
                }
            }else{
                setCountsInfo([])
            }
        })
    }

    const getScopeOfWorkDropdown = () => {
        deheadingPeelingService.getScopeOfWorkDropdown().then(res => {
            if (res.status) {
                setScopeOfWorkInfo(res.data)
            }
        })
    }

    const onDeleteWorker = (record, index) => {
        tableData.splice(index, 1)
        setTableData([...tableData])
        workersData.splice(index, 1)
    }

    useEffect(() => {
        if(tableData){
            form.setFieldsValue({'noOfWorkers' : tableData.length})
            setNoOfWorkers(tableData.length)
        }
    },[tableData])

    const columns: ColumnProps<any>[] = [
        {
            title: 'S No',
            key: 'sno',
            width: '70px',
            render: (text, object, index) => (page - 1) * 10 + (index + 1)
        },
        {
            title: 'Code',
            dataIndex: 'workerCode'
        },
        {
            title: 'Name',
            dataIndex: 'workerName'
        },
        {
            title: 'Contractor',
            dataIndex: 'contractorName'
        },
        {
            title: 'Village',
            dataIndex: 'village'
        },
        {
            title: 'Auto Charges',
            dataIndex: 'transportCost',
            render:(text,record) => {
                return(
                    <>{Number(record.transportCost)}</>
                )
            }
        },
        {
            title: 'Transportation',
            dataIndex: 'transportation',
            render: (text, record) => {
                return (
                    <>{
                        record.transportation ? (<>
                            {record.transportation}
                        </>) : (<>
                        
                        <Form.Item rules={[{ required: true, message: 'Transportation is required' }]}>
                            <Select allowClear showSearch optionFilterProp="children" placeholder='Select Transportation' onChange={(val) => onTransportationChange(record, val)}>
                                <Option key='Auto' value='Auto'>Auto</Option>
                                <Option key='Bus' value='Bus'>Bus</Option>
                            </Select>
                        </Form.Item>
                        </>)
                        
                    }</>
                )
            }
        },
        {
            title: 'Action',
            dataIndex: 'action',
            render: (text, record, index) => {
                return (
                    <DeleteOutlined onClick={() => { onDeleteWorker(record, index) }} />
                )
            }
        }
    ]

    const onTransportationChange = (record, val) => {
        record.transportation = val

    }

    const getWorkersInfo = () => {
        const req = new ContractorIdReq(form.getFieldValue('contractorId'))
        workersService.getWorkersAgainstContractor(req).then(res => {
            if (res.status) {
                setWorkersData(res.data)
            } else {
                setWorkersData([])
            }
        })
    }

    const getContractorAgainstDeheadingRate = () => {
        const req = new OperationReportingReq(null, null, null, null, null, null, form.getFieldValue('count'), null, null, null, null, null)
        req.contractorId = form.getFieldValue('contractorId')
        prodService.getContractAgainstDeheadingRate(req).then(res => {
            if (res.status) {
                form.setFieldsValue({ deheadingRate: Number(res.data[0].rate) })
            } else {
                AlertMessages.getErrorMessage('No deheading rate found against contractor and count')
                form.setFieldsValue({ deheadingRate: undefined })
            }
        })
    }

    const onEmployeeCodeChange = (val, object) => {
        employeeIds.push(form.getFieldValue('employeeId'))
        // getEmployeeInfoAgainstId()
        setTableData([...tableData, object?.record])
        // form.setFieldsValue({'employeeId' : undefined})
        form.resetFields(['employeeId'])
    }

    const getContractorInfo = () => {
        contractorService.getAllActiveContractActions().then(res => {
            if (res.status) {
                setContractorsInfo(res.data)
            } else {
                setContractorsInfo([])
            }
        })
    }

    const getJobCodes = () => {
        let plantId = Number(localStorage.getItem("unit_id"));
        forkliftService.getForkliftJobCodes({ unitId: plantId, transactionType: TransactionType.reprocessing }).then((res) => {
            if (res.status) {
                if (res.data.length > 0) {
                    setJobCodeData(res.data);
                } else {
                    setJobCodeData([]);
                }

            } else {
                if (res.intlCode) {
                    AlertMessages.getErrorMessage(res.internalMessage);
                } else {
                    AlertMessages.getErrorMessage(res.internalMessage);
                }
                setJobCodeData([]);
            }
        }).catch((err) => {
            AlertMessages.getErrorMessage(err.message);
            setJobCodeData([]);
        });
    }

    const getGradesAgainstForkliftJobCodes = () => {
        const req=new ForkLiftJobRequestDTO()
        req.forkliftJobId=form.getFieldValue('jobId')
        console.log(req,"reqqqqqqqqq")
        forkliftService.getGradesAgainstForkliftJobCodes(req).then((res) => {
            console.log(res,"resssssssssssssssss")
            if (res.status) {
                if (res.data.length > 0) {
                    setJobCodeGrades(res.data);
                    if(res.data.length == 1){
                        form.setFieldsValue({'count' : res.data[0].gradeName})
                    }
                } else {
                    setJobCodeGrades([]);
                }

            } else {
                if (res.intlCode) {
                    AlertMessages.getErrorMessage(res.internalMessage);
                } else {
                    AlertMessages.getErrorMessage(res.internalMessage);
                }
                setJobCodeGrades([]);
            }
        }).catch((err) => {
            AlertMessages.getErrorMessage(err.message);
            setJobCodeGrades([]);
        });
    }

    const getProducts = (val) => {
        const req = new SoakTypeRequest(val)
        productService.getSkuCodesBySoakStyle(req).then(res => {
            if (res.status) {
                setProducts(res.data)
            } else {
                setProducts([])
            }
        })
    }

    const getBatchNumbers = () => {
        const req = new LotNumberRequest(Number(plantId), form.getFieldValue('previousOperation'))
        prodService.getBatchNumberDropdown(req).then(res => {
            if (res.status) {
                setBatchNumbers(res.data)
            } else {
                setBatchNumbers([])
            }
        })
    }

    const getWorkStations = () => {
        const catReq = new WorkStationCategoryReq();
        catReq.workstationCategory = WorkStationCategoryEnum.find((res) => res.name === props.tabName).value;
        catReq.unitId = Number(localStorage.getItem('unit_id'));
        workstationService.getWorkStationsForCategory(catReq).then((res) => {
            if (res.status) {
                setWorkStations(res.data);
                // workstation = (res.data[0].workstationId)
            } else {
                setWorkStations([]);
            }
        }).catch((err) => {
            AlertMessages.getErrorMessage(err.message);
            setWorkStations([]);
        });
    }

    const onRadioButtonChange = () => {

    }

    const onReset = () => {
        // form.resetFields()
        console.log(props.tabName,'===')
        if(props.tabName == OperationTypeEnum.SOAKING){
            console.log('okkkkkkkk')
            form.resetFields(['billNo','peelingPriceBasedOn','type','previousOperation','count','grade','contractorId','jobCode','reportedQty','opQty','boxes','shift','workStation','soakTime','soakStyle','reportingType','deheadingRate','product','scpeOfWork','peelingRate','noOfWorkers','amount','reason','employeeId'])
        }else{
            form.resetFields(['billNo','peelingPriceBasedOn','type','previousOperation','batchNumber','count','grade','contractorId','jobCode','reportedQty','opQty','boxes','shift','workStation','soakTime','soakStyle','reportingType','deheadingRate','product','scpeOfWork','peelingRate','noOfWorkers','amount','reason','employeeId'])
        }
        getWorkStations()
        setTableData([])
        setPeelingRate(0)
        setPrevBillInfo([])
        setContractorDisable(false)
        setWorkerDisable(false)
        setAddedInfo([])
        setEditIndex(undefined)
        setHonQty(0)
        setAddedInfoAmount(0)
        setAddedInfoQty(0)
        setTotalAmount(0)
        setTotalQty(0)
        setNoOfWorkers(0)
        setAvailableQty(0)
    }


    const onFinish = () => {
        console.log('okkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk')
        setSubmitDisable(true)
        const val = form.getFieldsValue()
        if (props.processType == ProductionProcessTypeEnum.REPROCESS) {
            val.batchNumber = val.jobCode
        }
        const saveFlag = new Set<boolean>()
        const employees = []
        for (const rec of tableData) {
            if (rec.transportation != undefined) {
                saveFlag.add(true)
            } else {
                saveFlag.add(false)
            }
            employees.push(rec.employeeId)
        }
        const reqArray = []
        let req
        if(addedInfo.length > 0){
            for(const rec of addedInfo){
                console.log(addedInfo,"addedInfo")
                if(props.processType == ProductionProcessTypeEnum.REPROCESS){
                    rec.batchNumber=rec.jobCode
                }
                req = new OperationReportingReq(props.tabName, rec.previousOperation, rec.batchNumber, rec.reportedQty, rec.shift, rec.workStation, rec.count, rec.reportingType, rec.product, Number(plantId), role, rec.grade, props.processType, rec.boxes>0?rec.boxes:0, rec.date, rec.billNo, rec.contractorId, rec.scopeOfWork, rec.peelingRate,
                // meatBasedPrice ? rec.noOfWorkers : tableData.length, 
                rec.noOfWorkers > 0 ? rec.noOfWorkers : tableData.length,
                tableData, rec.soakTime)
                req.deheadingRate = rec.deheadingRate
                req.reason = rec.reason
                req.outputQuantity = rec.opQty
                req.peelingPriceBasedOn = rec.peelingPriceBasedOn
                req.year = rec.year
                req.avgQty = noOfWorkers > 0 ? Number((Number(totalQty) + Number(addedInfoQty))/ (noOfWorkers)).toFixed(2) : 0
                req.avgWage = noOfWorkers > 0 ? Number((Number(totalAmount) + Number(addedInfoAmount))/ Number(noOfWorkers)).toFixed(2) : 0
                req.isRRP = rec.isRRP
                req.rejectionFrom = rec.rejectionFrom
                req.deheadingPriceBasedOn = rec.deheadingPriceBasedOn
                req.honQuantity = rec.honQuantity
                reqArray.push(req)
            }
        }else{
            req = new OperationReportingReq(props.tabName, val.previousOperation, val.batchNumber, val.reportedQty, val.shift, val.workStation, val.count, val.reportingType, val.product, Number(plantId), role, val.grade, props.processType, val.boxes>0?val.boxes:0, val.date, val.billNo, val.contractorId, val.scopeOfWork, peelingRate, tableData.length, tableData, val.soakTime)
            req.year = val.year 
            req.prevOperProduct = val.fromProduct
            req.deheadingPriceBasedOn = val.deheadingPriceBasedOn
            req.honQuantity = val.honQuantity
        }
        if (!(saveFlag.has(false))) {
            if (props.tabName == OperationTypeEnum.BE_HEADING) {
                console.log(reqArray)
                const req = new JsonObjectreq(JSON.stringify(reqArray))
                prodService.createDeheadingReporting(req).then(res => {
                    setSubmitDisable(false)
                    if (res.status) {
                        AlertMessages.getSuccessMessage(res.internalMessage)
                        // getPrevBillInfo()
                        // getworkersInfoAgainstBill()
                        setTableData([])
                        onReset()
                    } else {
                        AlertMessages.getErrorMessage(res.internalMessage)
                    }
                })
            } else if (props.tabName == OperationTypeEnum.VALUE_ADDITION) {
                // if (tableData.length > 0 || prevBillInfo.length > 0 || meatBasedPrice) {
                 const req = new JsonObjectreq(JSON.stringify(reqArray))
                    prodService.createValueAdditionIssuing(req).then(res => {
                        setSubmitDisable(false)
                        if (res.status) {
                            AlertMessages.getSuccessMessage(res.internalMessage)
                            // getPrevBillInfo()
                            // getworkersInfoAgainstBill()
                            setTableData([])
                            onReset()
                        } else {
                            AlertMessages.getErrorMessage(res.internalMessage)
                        }
                    })
                // } else {
                //     AlertMessages.getErrorMessage('Please select workers info')
                // }
            } else if (props.tabName == OperationTypeEnum.SOAKING && type == 'Soaked') {
                console.log(req,"reqqqqqqqqqq soakingggggggggggggggggg")
                prodService.createSoakingReporting(req).then(res => {
                    setSubmitDisable(false)
                    if (res.status) {
                        AlertMessages.getSuccessMessage(res.internalMessage)
                        onReset()
                    } else {
                        AlertMessages.getErrorMessage(res.internalMessage)
                    }
                })
            } else if (props.tabName == OperationTypeEnum.SOAKING && type == 'Non Soaked') {
                prodService.createNonSoakedProductsInfo(req).then(res => {
                    setSubmitDisable(false)
                    if (res.status) {
                        AlertMessages.getSuccessMessage(res.internalMessage)
                        onReset()
                    } else {
                        AlertMessages.getErrorMessage(res.internalMessage)
                    }
                })
            }
        } else {
            setSubmitDisable(false)
            AlertMessages.getErrorMessage('Please fill Transportation mode for all workers.')
        }
    }
    

    const onTypeChange = (val) => {
        setType(val)
        getProducts(form.getFieldValue('type'))
    }

    const onPrevOperationChange = (val) => {
        form.setFieldsValue({'count' : undefined})
        getBatchNumbers()
        if (val == OperationTypeEnum.COOKING) {
            getProducts(form.getFieldValue('previousOperation'))
        }
        if(form.getFieldValue('batchNumber') != undefined || form.getFieldValue('jobCode') != undefined){
            getCountsAgainstBatchNumber()
        }
    }

    const onJobChange = (val, option) => {
        console.log(val,"!!!!!!!!!!!!!!!!!!!!!!")
        form.setFieldsValue({ jobCode: option?.jobCode ,batchNumber: option?.jobCode})
            getGradesAgainstForkliftJobCodes()  
                getPrevOperationProductsInfo()
    }

    const onProductChange = (val, option) => {
        form.setFieldsValue({ grade: option?.grade })
        form.setFieldsValue({ soakTime: option?.soakingTime })
        form.setFieldsValue({ soakStyle: option?.soakStyle })
    }

    const onScopeOfWorkChange = () => {
        const req = new ScopeGradeReq(form.getFieldValue('scopeOfWork'), form.getFieldValue('count'),form.getFieldValue('peelingPriceBasedOn'),form.getFieldValue('isRRP'),form.getFieldValue('previousOperation'))
        deheadingPeelingService.getPellingRateAgainstScopeAndGrade(req).then(res => {
            if (res.status) {
                setPeelingRate(res.data[0].rate)
                const qty = form.getFieldValue('peelingPriceBasedOn') == PeelingRateBasedEnum.KG ? form.getFieldValue('reportedQty')  : form.getFieldValue('opQty')
                form.setFieldsValue({peelingRate:res.data[0].rate,amount: Number(Number(res.data[0].rate).toFixed(2)) * Number(qty)})
            } else {
                setPeelingRate(0)
                form.setFieldsValue({peelingRate:0,amount: 0})
            }
        })
    }

    const onContractorChange = (e,option) => {
        form.setFieldsValue({'contractorName' : option?.name})
        getWorkersInfo()
        if (form.getFieldValue('count') != undefined) {
            getContractorAgainstDeheadingRate()
        }
    }

    const onHLQtyChange = () => {
        if ((form.getFieldValue('deheadingRate') != undefined || form.getFieldValue('peelingRate') != undefined) && Number(form.getFieldValue('reportedQty') != undefined)) {
            const rate = props.tabName == OperationTypeEnum.VALUE_ADDITION ? form.getFieldValue('peelingRate') : form.getFieldValue('deheadingRate')
            if(form.getFieldValue('deheadingPriceBasedOn') == DeheadingRateBasedEnum.HON && props.tabName == OperationTypeEnum.BE_HEADING){
                form.setFieldsValue({ amount: (Number(rate) * Number(form.getFieldValue('honQuantity'))).toFixed(2) })
            }else{
                form.setFieldsValue({ amount: (Number(rate) * Number(form.getFieldValue('reportedQty'))).toFixed(2) })
            }
        }
    }

    const getworkersInfoAgainstBill = () => {
        const req=  new BillNumberRequest(form.getFieldValue('billNo'))
        prodLogService.getWorkersInfoByBillNumber(req).then(res => {
            if(res.status){
                setBillAgainstWorkers(res.data)
                setWorkerDisable(true)
                if(res.data.length > 0 ){
                    form.setFieldsValue({'noOfWorkers' : res.data.length})
                    setNoOfWorkers(res.data.length)
                }
            }else{
                setBillAgainstWorkers([])
                setWorkerDisable(false)
            }
        })
    }

    const getPrevBillInfo = () => {
        const req=  new BillNumberRequest(form.getFieldValue('billNo'))
        prodLogService.getBillInfoByBillNumber(req).then(res => {
            if(res.status){
                setPrevBillInfo(res.data)
                setTotalsInfo(res.data1)
                setTotalAmount(res.data.reduce((sum, item) => sum + parseFloat(item.amount), 0))
                if(res.data[0].peelingPriceBasedOn == PeelingRateBasedEnum.MEAT){
                    setTotalQty(res.data.reduce((sum, item) => sum + parseFloat(item.outputQty), 0))
                    setMeatBasedPrice(true)
                    console.log('okkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk')
                    setNoOfWorkers(res.data[0].noOfWorkers)
                    form.setFieldsValue({peelingPriceBasedOn : PeelingRateBasedEnum.MEAT,noOfWorkers:res.data[0].noOfWorkers})
                }else{
                    if(res.data[0].noOfWorkers > 0){
                        setNoOfWorkers(res.data[0].noOfWorkers)
                        form.setFieldsValue({noOfWorkers:res.data[0].noOfWorkers})
                    }
                    setMeatBasedPrice(false)
                    setTotalQty(res.data.reduce((sum, item) => sum + parseFloat(item.opQty), 0))
                }
                form.setFieldsValue({contractorId : res.data[0].contractorId,contractorName:res.data[0].contractorName})
                setContractorDisable(true)
            }else{
                form.setFieldsValue({contractorId : undefined})
                setPrevBillInfo([])
                setContractorDisable(false)
            }
        })
    }

    const onEdit = (record,index) => {
        form.setFieldsValue(record)
        setEditIndex(index)
    }

    const onDelete = (index) => {
        addedInfo.splice(index,1)
        setAddedInfo([...addedInfo])
        setEditIndex(undefined)
    }

    const PrevBillInfocolumns : ColumnProps<any>[] = [
        {
            title: 'S No',
            key: 'sno',
            width: '70px',
            render: (text, object, index) => (page-1) * 10 +(index+1)
        },
        {
            title:'Date',
            dataIndex:'date',
            render:(text,record) => {
                return(
                    <>{record.date ? moment(record.date).format('YYYY-MM-DD') : '-'}</>
                )
            }
        },
        {
            title:'Operation',
            dataIndex:'operation'
        },
        {
            title:'Bill Number',
            dataIndex:'billNo'
        },
        {
            title:'Batch Number',
            dataIndex:'lotNumber'
        },
        props.tabName == OperationTypeEnum.VALUE_ADDITION ? {
            title:'Product',
            dataIndex:'product'
        } : <></>,
        {
            title:'HON Count',
            dataIndex:'HONcount',
            // render:(text,record) => {
            //     const count=Number(text)

            //     return(
            //         <>{isNaN(count)?"-":count}</>
            //     )
            // }
        },
        props.tabName == OperationTypeEnum.BE_HEADING ?
        {
            title:'HON Quantity',
            dataIndex:'quantity',
            render: (text) => {
                const quantity = Number(text);
                return (
                    <>{isNaN(quantity) ? "-" : quantity}</>
                    // <>{Number(text)}</>
                );
            }
        }:<></>,
        {
            title:'HL Quantity',
            dataIndex:'opQty',
            render:(text,record) => {
                const quantity = Number(text);

                return(
                    <>{isNaN(quantity) ? "-" : quantity}</>
                )
            }
        },
        meatBasedPrice ? {
            title:'Output Quantity',
            dataIndex:'outputQty',
            render:(text,record) => {
                return(
                    <>{Number(record.outputQty)}</>
                )
            }
        } : <></>,
        {
            title:'Rate',
            dataIndex:'unitPrice',
            render:(text,record) => {
                const rate=Number(text)
                return(
                    <>{isNaN(rate) ? "-" : rate}</>
                )
            }
        },
        {
            title:'Amount',
            dataIndex:'amount',
            render:(text,record) => {
                const amount=Number(text)
                return(
                    <>{isNaN(amount)?"-":amount}</>
                )
            }
        },
    ]

    const addedInfoColumns : ColumnProps<any>[] = [
        {
            title: 'S No',
            key: 'sno',
            width: '70px',
            render: (text, object, index) => (page-1) * 10 +(index+1)
        },
        {
            title:'Date',
            dataIndex:'date',
            render:(text,record) => {
                return(
                    <>{record.date ? moment(record.date).format('YYYY-MM-DD') : '-'}</>
                )
            }
        },
        props.tabName == OperationTypeEnum.VALUE_ADDITION ? {
            title: 'Is RRP',
            dataIndex:'isRRP',
            render:(text,record) => {
                return(
                    <>
                    {record.isRRP ? 'YES' : 'NO'}
                    </>
                )
            }
        } : <></>,
        {
            title:'Bill Number',
            dataIndex:'billNo'
        },
        {
            title:'Contractor',
            dataIndex:'contractorName'
        },
        {
            title:'Previous Operation',
            dataIndex:'previousOperation'
        },
        props.processType == ProductionProcessTypeEnum.REPROCESS ? 
        {
            title:'Job Code',
            dataIndex:'jobCode'
        } : 
        {
            title:'Batch Number',
            dataIndex:'batchNumber'
        },
       
        {
            title:`${props.tabName == OperationTypeEnum.BE_HEADING ? 'HON Count' : 'HL Count'}`,
            dataIndex:'count',
            // render:(text,record) => {
            //     const count=Number(text)
            //     return(
            //         <>{isNaN(count)?"-":count}</>
            //     )
            // }
        },
        {
            title:'HL Quantity',
            dataIndex:'reportedQty',
            render:(text,record) => {
                const quantity=Number(text)
                return(
                    <>{isNaN(quantity)?"-":quantity}</>
                )
            }
        },
        meatBasedPrice ? {
            title:'Output Quantity',
            dataIndex:'opQty',
        } : <></>,
        {
            title:'Shift',
            dataIndex:'shift'
        },
        {
            title:'Work Station',
            dataIndex:'workStation'
        },
        {
            title:'Rate',
            dataIndex:`${props.tabName == OperationTypeEnum.BE_HEADING ? 'deheadingRate' : 'peelingRate'}`,
            render:(text,record) => {
                const rate=Number(text)
                return(
                    <>{isNaN(rate)?"-":rate}</>
                )
            }
        },
        {
            title:'Amount',
            dataIndex:'amount',
            render:(text,record) => {
                const amount=Number(text)
                return(
                    <>{isNaN(amount)?"-":Number(amount).toFixed(2)}</>
                )
            }
        },
        props.tabName == OperationTypeEnum.VALUE_ADDITION ? {
            title: 'Rejection From',
            dataIndex:'rejectionFrom',
            render:(text,record) => {
                return(
                    <>
                    {record.rejectionFrom != undefined ? record.rejectionFrom : '-'}
                    </>
                )
            }
        } : <></>,
        props.tabName == OperationTypeEnum.VALUE_ADDITION ? {
            title:'Product',
            dataIndex:'product'
        } : <></>,
        props.tabName == OperationTypeEnum.VALUE_ADDITION ? {
            title:'Scope of Work',
            dataIndex:'scopeOfWork'
        } : <></>,
        {
            title:'Action',
            dataIndex:'action',
            render:(text,record,index) => {
                return(
                    <>
                    <EditOutlined onClick={() => onEdit(record,index)}/>
                        <Divider type="vertical"/>
                    <DeleteOutlined onClick={() => onDelete(index)}/>
                    </>
                )
            }
        }
    ]

    const onBillNoChange = () => {
        if(form.getFieldValue('billNo') != undefined){
            getPrevBillInfo()
            getworkersInfoAgainstBill()
        }
    }

    const onPeelingRateChange = (e) => {
        setPeelingRate(Number(e.target.value))
        if(form.getFieldValue('peelingPriceBasedOn') == PeelingRateBasedEnum.KG){
            form.setFieldsValue({amount : (Number(e.target.value) * Number(form.getFieldValue('reportedQty'))).toFixed(2)    })
        }else{
            form.setFieldsValue({amount :(Number(e.target.value) * Number(form.getFieldValue('opQty'))).toFixed(2)})
        }
    }

    const onBatchNumberChange = (val,option) => {
        form.setFieldsValue({'year':option?.year})
        form.setFieldsValue({'count' : undefined})
        if(form.getFieldValue('previousOperation') != undefined){
            getCountsAgainstBatchNumber()  
            if((form.getFieldValue('batchNumber') != undefined || form.getFieldValue('jobCode') != undefined) && form.getFieldValue('count') != undefined && form.getFieldValue('isRRP') == true){
                getPrevOperationProductsInfo()
            }
        }
    }


    const getQtyAgainstBatchAndCount = () => {
        const req = new LotAndOperationReq(form.getFieldValue('batchNumber'),form.getFieldValue('previousOperation'),form.getFieldValue('count'),Number(localStorage.getItem('unit_id')))
        req.product = form.getFieldValue('fromProduct')
        req.year = form.getFieldValue('year')
        prodService.getQtyAgainstBatchAndCount(req).then(res => {
            if(res.status){
                setHonQty(Number(res.data[0].qty))
                setAvailableQty(Number(res.data[0].remainingQty))
                const rate = form.getFieldValue('deheadingRate') != undefined ? form.getFieldValue('deheadingRate') : 0
                form.setFieldsValue({'honQuantity' : Number(res.data[0].remainingQty),'amount' : (Number(res.data[0].remainingQty) * Number(rate)).toFixed(2)})
            }else{
                setHonQty(0)
                setAvailableQty(0)
            }
        }) 
    }

    const onCountChange = () =>{
        getQtyAgainstBatchAndCount()
        if(props.tabName == OperationTypeEnum.BE_HEADING ){
            getContractorAgainstDeheadingRate()
        }else if( props.tabName == OperationTypeEnum.VALUE_ADDITION){
            onScopeOfWorkChange()
        }
        if((form.getFieldValue('batchNumber') != undefined || form.getFieldValue('jobCode') != undefined) && form.getFieldValue('previousOperation') != undefined && form.getFieldValue('count') != undefined && (form.getFieldValue('isRRP') == true || props.tabName == OperationTypeEnum.SOAKING)){
            getPrevOperationProductsInfo()
        }
        if(form.getFieldValue('deheadingPriceBasedOn') == DeheadingRateBasedEnum.HON){
            const rate = form.getFieldValue('deheadingRate') != undefined ? form.getFieldValue('deheadingRate') : 0
            form.setFieldsValue({'amount' : (Number(form.getFieldValue('honQuantity') * Number(rate)).toFixed(2))})
        }
      
    }

    const onAdd = () =>{
        form.validateFields().then(res => {
            if(props.tabName == OperationTypeEnum.VALUE_ADDITION){
                 const peelingQty = res.prevOperation == PeelingRateBasedEnum.KG ? res.reportedQty : res.opQty
                const amount =  Number(Number(res.peelingRate).toFixed(2)) * Number(peelingQty)
                res.amount = res.amount > 0 ? res.amount : Number(amount).toFixed(2)
            }
            if(editIndex != undefined){
                addedInfo[editIndex] = form.getFieldsValue()
                setAddedInfo([...addedInfo])
                setEditIndex(undefined)
            }else{
                setAddedInfo([...addedInfo,form.getFieldsValue()])
            }
          
        }).catch(e => {
            AlertMessages.getErrorMessage(e)
        })
        
    }

    useEffect(() => {
        setAddedInfoAmount(addedInfo.reduce((sum, item) => sum + parseFloat(item.amount), 0))
        if(!meatBasedPrice){
            setAddedInfoQty(addedInfo.reduce((sum, item) => sum + parseFloat(item.reportedQty), 0))
        }else{
            setAddedInfoQty(addedInfo.reduce((sum, item) => sum + parseFloat(item.opQty), 0))
        }
        if(props.tabName != OperationTypeEnum.SOAKING){
            form.resetFields(['batchNumber','count','reportedQty','boxes','reportingType','deheadingRate','amount','peelingRate','jobCode','jobId'])
        }
    },[addedInfo])

    const onDeheadingPriceBasedOnChange = (val) => {
        setDeheadingPriceBasedOn(val)
        if(val == DeheadingRateBasedEnum.HON){
            setReportingTypeDisable(true)
            const rate = form.getFieldValue('deheadingRate') != undefined ? form.getFieldValue('deheadingRate') : 0
            form.setFieldsValue({'reportingType' : DeheadingReportingTypeEnum.FULL,'honQuantity' : availableQty,amount : (Number(availableQty) * Number(rate)).toFixed(2)})
        }else{
            setReportingTypeDisable(false)
            form.setFieldsValue({'reportingType' : undefined})
        }
    }

    const onPriceBasedOnChange = (val) => {
        if(val == PeelingRateBasedEnum.MEAT){
            setMeatBasedPrice(true)
        }else{
            setMeatBasedPrice(false)
        }
        if(props.tabName == OperationTypeEnum.VALUE_ADDITION){
            onScopeOfWorkChange()
        }
        if(peelingRate > 0){
            const peelingQty = val == PeelingRateBasedEnum.KG ? form.getFieldValue('reportedQty')  : form.getFieldValue('opQty')
            form.setFieldsValue({amount: Number(Number(peelingRate).toFixed(2)) * Number(peelingQty)})
        }
    }

    const onFormReset = () => {
        form.resetFields()
    }

    const onIsRRPChange = (e) => {
        setIsRRP(e.target.value)
        if(e.target.value){
            form.setFieldsValue({'previousOperation' : ValueAdditionPrevOperationEnum.SOAKING})
            onPrevOperationChange(OperationTypeEnum.SOAKING)
            if((form.getFieldValue('batchNumber') != undefined || form.getFieldValue('jobCode') != undefined) && form.getFieldValue('previousOperation') != undefined && form.getFieldValue('count') != undefined && form.getFieldValue('isRRP') == true){
                getPrevOperationProductsInfo()
            }
        }else{
            form.setFieldsValue({'previousOperation' : undefined})
        }
    }

    const onFromproductChange = () => {
        getQtyAgainstBatchAndCount()
    }

    const OnOutputQtyChange = () => {
        if(peelingRate > 0){
            const peelingQty = form.getFieldValue('peelingPriceBasedOn') == PeelingRateBasedEnum.KG ? form.getFieldValue('reportedQty')  : form.getFieldValue('opQty')
            console.log(form.getFieldValue('opQty'),peelingRate)
            form.setFieldsValue({amount: Number(Number(peelingRate).toFixed(2)) * Number(peelingQty)})
        }
    }

    return (
        <>
        {/* {props.tabName == OperationTypeEnum.BE_HEADING ? (<>
        <Descriptions>
        <Descriptions.Item label="HON Qty">{honQty}</Descriptions.Item>
        <Descriptions.Item label="Available Qty">{availableQty}</Descriptions.Item>

        </Descriptions></>):<></>}
        {props.tabName == OperationTypeEnum.VALUE_ADDITION ? (<>
        <Descriptions>
        <Descriptions.Item label="Available Qty">{availableQty}</Descriptions.Item>

        </Descriptions></>):<></>} */}
        {
            props.tabName == OperationTypeEnum.BE_HEADING || props.tabName == OperationTypeEnum.VALUE_ADDITION ? (<>
                <Descriptions>
                <Descriptions.Item label={props.tabName == OperationTypeEnum.BE_HEADING ? 'HON Qty' : 'Physical Qty'}>{honQty}</Descriptions.Item>
                <Descriptions.Item label="Available Qty">{availableQty}</Descriptions.Item>
                </Descriptions>
            
            </>) : (<></>)
        }
        <Form layout="vertical" form={form}>
                <Form.Item name='contractorName' hidden>
                    <Input />
                </Form.Item>
                <Form.Item name='year' hidden><Input /></Form.Item>
                <Row gutter={24}>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                        <Form.Item name='date' label='Date' initialValue={moment(moment().format("YYYY-MM-DD"))} rules={[{ required: true, message: 'Missing Date' }]}>
                            <DatePicker style={{ width: '100%' }} defaultValue={moment(moment().format("YYYY-MM-DD"))} />
                        </Form.Item>
                    </Col>
                    {
                        props.tabName == OperationTypeEnum.VALUE_ADDITION ? (<>
                            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                                <Form.Item name='isRRP' label='Is RRP' rules={[{required:true,message:'Missing is RRP'}]} initialValue={false}>
                                <Radio.Group onChange={onIsRRPChange} defaultValue={false}>
                                    <Radio value={true}>YES</Radio>
                                    <Radio value={false}>NO</Radio>
                                </Radio.Group>

                                </Form.Item>
                            </Col>
                        </>) : (<></>)
                    }
                    {props.tabName != OperationTypeEnum.SOAKING ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item name='billNo' label='Bill Number' rules={[{ required: true, message: 'Missing Bill Number' }]} validateTrigger={["onBlur", "onSubmit"]}>
                                <Input placeholder="Enter Bill No"
                                    onBlur={onBillNoChange} />
                            </Form.Item>
                        </Col>
                    </>) : (<></>)}
                    {props.tabName == OperationTypeEnum.BE_HEADING ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item name='deheadingPriceBasedOn' label='Price Based On' rules={[{ required: true, message: 'Price Based On is required' }]}>
                                <Select allowClear showSearch optionFilterProp="children" placeholder='Select Price Based On' onChange={onDeheadingPriceBasedOnChange}>
                                    {Object.values(DeheadingRateBasedEnum).map(e => {
                                        return (
                                            <Option key={e} value={e}>{e}</Option>
                                        );
                                    })}

                                </Select>
                            </Form.Item>
                        </Col>
                    </>) : (<></>)}
                    {props.tabName == OperationTypeEnum.VALUE_ADDITION ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item name='peelingPriceBasedOn' label='Price Based On' rules={[{ required: true, message: 'Price Based On is required' }]}>
                                <Select allowClear showSearch optionFilterProp="children" placeholder='Select Price Based On' onChange={onPriceBasedOnChange}>
                                    {Object.values(PeelingRateBasedEnum).map(e => {
                                        return (
                                            <Option key={e} value={e}>{e}</Option>
                                        );
                                    })}

                                </Select>
                            </Form.Item>
                        </Col>
                    </>) : (<></>)}
                    {props.tabName == OperationTypeEnum.BE_HEADING || props.tabName == OperationTypeEnum.VALUE_ADDITION ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item name='contractorId' label='Contractor' rules={[{ required: true, message: 'Missing Contractor' }]}>
                                <Select allowClear showSearch optionFilterProp="children" placeholder='Please Select Contractor' onChange={onContractorChange} disabled={contractorDisable}>
                                    {contractorsInfo.map(e => {
                                        return (
                                            <Option key={e.contractorId} value={e.contractorId} name={e.contractorName}>{e.contractorName}</Option>
                                        );
                                    })}
                                </Select>
                            </Form.Item>

                        </Col>

                    </>) : (<></>)}
                    {props.processType == ProductionProcessTypeEnum.REPROCESS ? (<>
                        <Form.Item name='jobCode' hidden>
                            <Input />
                        </Form.Item>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item name='jobId' label='Job Code' rules={[{ required: true, message: 'Job Code is required' }]}>
                                <Select showSearch allowClear optionFilterProp="children" placeholder='Select Job Code' onChange={onJobChange}>
                                    {jobCodeData.map(e => {
                                        return (
                                            <Option value={e.jobId} jobCode={e.jobCode}>{e.jobCode}</Option>
                                        );
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>

                    </>) : (<></>)}
                    {props.tabName == OperationTypeEnum.SOAKING ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item name='type' label='Type' rules={[{ required: true, message: 'Type is required' }]}>
                                <Select showSearch allowClear optionFilterProp="children" placeholder='Select Type' onChange={onTypeChange}>
                                    <Option key='1' value='Soaked'>Soaked</Option>
                                    <Option key='2' value={'Non Soaked'}>Non Soaked</Option>
                                </Select>
                            </Form.Item>
                        </Col>

                    </>) : (<></>)}

                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                        <Form.Item label='Previous Operation' name='previousOperation' rules={[{ required: true, message: 'Previous Operation is required' }]}>
                            <Select allowClear showSearch placeholder='Select Previous Operation' optionFilterProp="children" onChange={onPrevOperationChange}>
                                {Object.values(props.tabName == OperationTypeEnum.BE_HEADING ? DeheadingPrevOperationEnum : props.tabName == OperationTypeEnum.VALUE_ADDITION ? ValueAdditionPrevOperationEnum : SoakingPrevOperationEnum).map(e => {
                                    return (
                                        <Option key={e} value={e}>{e}</Option>
                                    );
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                    {props.processType == ProductionProcessTypeEnum.FRESHPRODUCITON ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item label='Batch Number' name='batchNumber' rules={[{ required: true, message: 'Batch Number is required' }]}>
                                <Select allowClear showSearch placeholder='Select Batch Number' onChange={onBatchNumberChange}>
                                    {batchNumbers.map(e => {
                                        return (
                                            <Option key={e.prodInvId} value={e.lotNumber} year={e.year}>{e.lotNumber}-{e.year}</Option>
                                        );
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                    </>) : (<></>)}

                    {form.getFieldValue('previousOperation') != OperationTypeEnum.COOKING && props.processType != ProductionProcessTypeEnum.REPROCESS ?   (<>
                        {/* {props.tabName == OperationTypeEnum.SOAKING ? (<>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }} >
                <Form.Item label={'Soaking Count(HL)'} name='count' rules={[{ required: true, message: 'Count is required' },
                // {pattern: /^[0-9]*$/,message: `Letters , Spaces and Special charecters are not allowed`}
                { pattern: /^[0-9]*\.?[0-9]*$/, message: `Count should not be allow alphabets and special characters` }
                ]}>
                    <Select allowClear showSearch optionFilterProp="children" placeholder='Select Count'>
                        {
                            countsInfo.map(e => {
                                return(
                                    <Option key={e.count} value={e.count}>{e.count}</Option>
                                )
                            })
                        }
                    </Select>
                </Form.Item>
            </Col>
        </>) : (<>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }} >
                <Form.Item label={`${props.tabName == OperationTypeEnum.BE_HEADING ? 'HON Count' : 'HL Count'}`} name='count' rules={[{ required: true, message: 'Count is required' },
                // {pattern: /^[0-9]*$/,message: `Letters , Spaces and Special charecters are not allowed`}
                { pattern: /^[0-9]*\.?[0-9]*$/, message: `Count should not be allow alphabets and special characters` }
                ]}>
                    <Input placeholder="Enter Count" onBlur={props.tabName == OperationTypeEnum.BE_HEADING ? getContractorAgainstDeheadingRate : props.tabName == OperationTypeEnum.VALUE_ADDITION ? onScopeOfWorkChange : null} />
                </Form.Item>
            </Col>
        
        </>)} */}
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item label={`${props.tabName == OperationTypeEnum.BE_HEADING ? 'HON Count' : props.tabName == OperationTypeEnum.SOAKING ? 'Soaking Count(HL)' : 'HL Count'}`} name='count' rules={[{ required: true, message: 'Count is required' },
                            // {pattern: /^[0-9]*$/,message: `Letters , Spaces and Special charecters are not allowed`}
                            // { pattern: /^[0-9]*\.?[0-9]*$/, message: `Count should not be allow alphabets and special characters` }
                            ]}>
                                {/* <Input placeholder="Enter Count" onBlur={props.tabName == OperationTypeEnum.BE_HEADING ? getContractorAgainstDeheadingRate : props.tabName == OperationTypeEnum.VALUE_ADDITION ? onScopeOfWorkChange : null} /> */}
                                <Select allowClear showSearch optionFilterProp="children" placeholder='Select Count' onChange={onCountChange}>
                                    {countsInfo.map(e => {
                                        return (
                                            <Option key={e.count} value={e.count}>{e.count}</Option>
                                        );
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>

                    </>) : (<></>)}
                    {props.processType == ProductionProcessTypeEnum.REPROCESS ?<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item label={`${props.tabName == OperationTypeEnum.BE_HEADING ? 'HON Count' : props.tabName == OperationTypeEnum.SOAKING ? 'Soaking Count(HL)' : 'HL Count'}`} name='count' rules={[{ required: true, message: 'Count is required' },
                            // {pattern: /^[0-9]*$/,message: `Letters , Spaces and Special charecters are not allowed`}
                            // { pattern: /^[0-9]*\.?[0-9]*$/, message: `Count should not be allow alphabets and special characters` }
                            ]}>
                                {/* <Input placeholder="Enter Count" onBlur={props.tabName == OperationTypeEnum.BE_HEADING ? getContractorAgainstDeheadingRate : props.tabName == OperationTypeEnum.VALUE_ADDITION ? onScopeOfWorkChange : null} /> */}
                                <Select allowClear showSearch optionFilterProp="children" placeholder='Select Count' onChange={onCountChange}>
                                    {jobCodeGrades.map(e => {
                                        return (
                                            <Option key={e.gradeName} value={e.gradeName}>{e.gradeName}</Option>
                                        );
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                    </>:<></>}
                    {
                        props.tabName == OperationTypeEnum.SOAKING && form.getFieldValue('previousOperation') == OperationTypeEnum.VALUE_ADDITION ? (<>
                            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                                <Form.Item name='fromProduct' label='From product' rules={[{required:true,message:'From Product is required'}]}>
                                    <Select showSearch allowClear optionFilterProp="children" placeholder='Select From product' onChange={onFromproductChange}>
                                        {
                                            prevOpProductsInfo.map(e => {
                                                return(
                                                    <Option name={e.product} value={e.product}>{e.product}</Option>
                                                )
                                            })
                                        }
                                    </Select>
                                </Form.Item>
                            </Col>
                        </>) : (<></>)
                    }
                    {
                        deheadingPriceBasedOn == DeheadingRateBasedEnum.HON ? (
                            <>
                                <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                                    <Form.Item name='honQuantity' label='HON Quantity'
                                        rules={[{ required: true, message: 'HON Qty is required' },
                                        // {pattern: /^[0-9]*$/,message: `Letters , Spaces and Special charecters are not allowed`}
                                        { pattern: /^[0-9]*\.?[0-9]*$/, message: `Quantity should not be allow alphabets and special characters` }
                                        ]}
                                    >
                                        <Input placeholder="Enter HON Quantity" disabled/>
                                    </Form.Item>
                                </Col>
                            </>
                        ) : (<></>)
                    }
                    {type == 'Soaked' || props.tabName != OperationTypeEnum.SOAKING ? (<>

                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item label={props.tabName == OperationTypeEnum.BE_HEADING ? `HL Quantity` : props.tabName == OperationTypeEnum.SOAKING ? `Soaking Quantity(HL)  - ${honQty}` : isRRP ? `Quantity` : `HL Quantity`} name='reportedQty'
                                rules={[{ required: true, message: 'Qty is required' },
                                // {pattern: /^[0-9]*$/,message: `Letters , Spaces and Special charecters are not allowed`}
                                { pattern: /^[0-9]*\.?[0-9]*$/, message: `Quantity should not be allow alphabets and special characters` }
                                ]}
                            >
                                <Input placeholder={isRRP ? "Enter Qty" : "Enter HL Qty"} onBlur={onHLQtyChange} />
                            </Form.Item>
                        </Col>
                        {meatBasedPrice ? (<>
                            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                                <Form.Item name='opQty' label='Output Quantity' rules={[{ required: true, message: 'Qty is required' },
                                // {pattern: /^[0-9]*$/,message: `Letters , Spaces and Special charecters are not allowed`}
                                { pattern: /^[0-9]*\.?[0-9]*$/, message: `Quantity should not be allow alphabets and special characters` }
                                ]}>
                                    <Input placeholder="Enter Output Quantity" onBlur={OnOutputQtyChange} />
                                </Form.Item>
                            </Col>
                        </>) : (<></>)}
                        {props.tabName == OperationTypeEnum.VALUE_ADDITION ? (<>
                            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                                <Form.Item label='No of boxes' name='boxes' rules={[{ pattern: /^[0-9]*$/, message: `Letters , Spaces and Special charecters are not allowed` }]}>
                                    <Input placeholder="Enter No of boxes" />
                                </Form.Item>
                            </Col>

                        </>) : (<></>)}
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item label='Shift' name='shift' rules={[{ required: true, message: 'Shift is required' }]}>
                                <Select allowClear showSearch placeholder='Select Shift'>
                                    {Object.values(ShiftsEnum).map(e => {
                                        return (
                                            <Option key={e} value={e}>{e}</Option>
                                        );
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item label='Workstation' name='workStation' rules={[{ required: true, message: 'Work Station is required' }]}>
                                <Select allowClear showSearch placeholder='Select Work Station'>
                                    {workStations.map(e => {
                                        return (
                                            <Option key={e.workstationId} value={e.workstationId}>{e.workstation}</Option>
                                        );
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                    </>) : (<></>)}

                    {props.tabName == OperationTypeEnum.SOAKING || form.getFieldValue('previousOperation') == OperationTypeEnum.COOKING ? (<>
                        {/* <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }} > */}
                        <Form.Item label='Grade' name='grade' hidden>
                            <Input placeholder="Enter Grade" />
                        </Form.Item>
                        <Form.Item name='soakTime' hidden>
                            <Input />
                        </Form.Item>
                        <Form.Item name='soakStyle' hidden>
                            <Input />
                        </Form.Item>
                        {/* </Col> */}

                    </>) : (<></>)}
                    {props.tabName == OperationTypeEnum.BE_HEADING ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item label='Reporting' name='reportingType' rules={[{ required: true, message: 'Reporting Type is required' }]}>
                                <Radio.Group onChange={onRadioButtonChange} disabled={reportingTypeDisable}>
                                    <Radio value={DeheadingReportingTypeEnum.PARTIAL}>Partial</Radio>
                                    <Radio value={DeheadingReportingTypeEnum.FULL}>Full</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </Col>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item label='Deheading Rate Per Kg' name='deheadingRate' rules={[{ required: true, message: 'Deheading Rate is required' }]}>
                                <Input placeholder="Deheding Rate" disabled />
                            </Form.Item>
                        </Col>

                    </>) : (<></>)}
                    { isRRP ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item label='Rejection From' name='rejectionFrom' rules={[{ required: true, message: 'Rejection From Product is required' }]}>
                                {/* <Input placeholder="Enter Rejection From Product" /> */}
                                <Select allowClear showSearch optionFilterProp="children" placeholder='Select Rejection From Product'>
                                    {
                                        prevOpProductsInfo.map(e => {
                                            return(
                                                <Option key={e.product} value={e.product}>{e.product}</Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Form.Item>
                        </Col>
                    </>) : (<></>)
                    }
                   
                    {props.tabName == OperationTypeEnum.SOAKING || form.getFieldValue('previousOperation') == OperationTypeEnum.COOKING ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 6 }}>
                            <Form.Item label='Product' name='product' rules={[{ required: true, message: 'Product is required' }]}>
                                <Select showSearch allowClear dropdownMatchSelectWidth={false} optionFilterProp="children" placeholder='Select Product' onChange={onProductChange}>
                                    {products.map(e => {
                                        return (
                                            <Option key={e.skuCodeId} value={e.shortCode} grade={e.gradeName} soakTime={e.soakingTime} soakStyle={e.soakingStyle}>{e.shortCode}</Option>
                                        );
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                    </>) : (<></>)}
                    {props.tabName == OperationTypeEnum.VALUE_ADDITION && form.getFieldValue('previousOperation') != OperationTypeEnum.COOKING ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item label='Product' name='product' rules={[{ required: true, message: 'Product is required' }]}>
                                <Input placeholder="Enter Product" />
                            </Form.Item>
                        </Col>
                    </>) : (<></>)}
                    {props.tabName == OperationTypeEnum.VALUE_ADDITION ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item name='scopeOfWork' label='Scope Of Work' rules={[{ required: true, message: 'Missing Scope Of Work' }]}>
                                <Select allowClear showSearch optionFilterProp="children" placeholder='Select Scope of work' onChange={onScopeOfWorkChange}>
                                    {scopeOfWorkInfo.map(e => {
                                        return (
                                            <Option key={e.scopeOfWork} value={e.scopeOfWork}>{e.scopeOfWork}</Option>
                                        );
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item label='Peeling Rate Per Kg' name='peelingRate' rules={[{ required: true, message: 'Peeling Rate is requied' }]}>
                                <Input placeholder="Peeling Rate" onChange={onPeelingRateChange} />
                            </Form.Item>
                        </Col>
                        {/* Added no of workers input as of now for making entries faster need to set intial condition */}
                        {/* {meatBasedPrice ? (<> */}
                        {props.tabName == OperationTypeEnum.VALUE_ADDITION ? (<>

                            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                                <Form.Item label='No of workers' name='noOfWorkers' rules={[{ required: true, message: 'No.of workers is required' }]}>
                                    <Input placeholder="No of workers" onChange={(e) => { setNoOfWorkers(Number(e.target.value)); } } />
                                </Form.Item>
                            </Col>
                        </>) : (<></>)}
                        {/* <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item name='transportation' label='Transportation' rules={[{required:true,message:'Missing Transportation'}]}>
                                <Select allowClear showSearch optionFilterProp="children" placeholder='Select transportation'>
                                    <Option key='Bus' value='Bus'>BUS</Option>
                                    <Option key='Auto' value='Auto'>AUTO</Option>
                                </Select>
                            </Form.Item>
                        </Col> */}
                    </>) : (<></>)}
                    {props.tabName == OperationTypeEnum.BE_HEADING || props.tabName == OperationTypeEnum.VALUE_ADDITION ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }} hidden={props.tabName == OperationTypeEnum.VALUE_ADDITION}>
                            <Form.Item label='Total Amount' name='amount' rules={[{ required: true, message: 'Total Amount is required' }]}>
                                <Input placeholder="Total Amount" />
                            </Form.Item>
                        </Col>
                    </>) : (<></>)}
                    {props.tabName == OperationTypeEnum.BE_HEADING ? (<>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item label='Reason' name='reason'>
                                <TextArea placeholder="Enter Reason" />
                            </Form.Item>
                        </Col>
                    </>) : (<></>)}
                    {props.tabName != OperationTypeEnum.SOAKING ? (<>
                        <Col style={{ marginTop: '3%', marginLeft: '6%' }}>
                            <Form.Item>
                                <Button onClick={onAdd} style={{ backgroundColor: 'lightGreen' }}>ADD</Button>
                            </Form.Item>
                        </Col>
                        <Col style={{ marginTop: '3%' }}>
                            <Form.Item>
                                <Button onClick={onFormReset} style={{ backgroundColor: 'tomato' }}>Reset</Button>
                            </Form.Item>
                        </Col>
                    </>) : (<></>)}
                </Row>
                {props.tabName == OperationTypeEnum.VALUE_ADDITION || props.tabName == OperationTypeEnum.BE_HEADING ? (<>
                    <Row gutter={24}>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item name='employeeId'
                            //  label={props.tabName == OperationTypeEnum.BE_HEADING || meatBasedPrice ? <>Worker Code</> : <>{<span style={{ color: 'red' }}>*</span>}<span>Worker Code</span></>}
                            label={<><span>Worker Code</span></>}
                            >
                                <Select allowClear showSearch optionFilterProp="children" placeholder='Select Worker' onChange={onEmployeeCodeChange} disabled={workerDisable}>
                                    {workersData.map(e => {
                                        return (
                                            <Option key={e.workerId} value={e.workerId} record={e}>{e.workerCode}-{e.workerName}</Option>
                                        );
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                        {/* {props.tabName == OperationTypeEnum.VALUE_ADDITION || props.tabName == OperationTypeEnum.BE_HEADING ? (<>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 20 }} style={{marginTop:'2.5%'}}>
            <Descriptions column={5}>
                <Descriptions.Item label='No Of Persons'>{workerDisable ? billAgainstWorkers.length :tableData.length}</Descriptions.Item>
                <Descriptions.Item label='Per Head'>{workerDisable ? (Number(Number(totalsInfo[0]?.amount) / Number(billAgainstWorkers.length)).toFixed(2)) : tableData.length > 0 ? (tableData.reduce((sum, item) => sum + parseFloat(item.amount), 0)) / Number(tableData.length)  : '-' }</Descriptions.Item>
                <Descriptions.Item label='Total Qty'>{workerDisable || prevBillInfo.length > 0 ? Number(totalsInfo[0]?.opQty) : addedInfo.length > 0  && !meatBasedPrice ? addedInfo.reduce((sum, item) => sum + parseFloat(item.reportedQty), 0) : addedInfo.length > 0  && meatBasedPrice ? addedInfo.reduce((sum, item) => sum + parseFloat(item.opQty), 0) : meatBasedPrice ? (form.getFieldValue('opQty')) : (form.getFieldValue('reportedQty'))}</Descriptions.Item>
                <Descriptions.Item label='Average Qty'>{workerDisable ?( Number(Number(totalsInfo[0]?.opQty) / Number(billAgainstWorkers.length)).toFixed(2)) : addedInfo.length > 0 ? addedInfo.reduce((sum, item) => sum + parseFloat(item.amount), 0) :  (form.getFieldValue('reportedQty') != undefined && tableData.length > 0 ? Number(Number(form.getFieldValue('reportedQty'))/Number(tableData.length)) : '')}</Descriptions.Item>
                <Descriptions.Item label='Total Amount'>{workerDisable  || prevBillInfo.length > 0 ? (Number(totalsInfo[0]?.amount)) :addedInfo.length > 0 ? addedInfo.reduce((sum, item) => sum + parseFloat(item.amount), 0): (peelingRate != 0 && tableData.length > 0 ?Number(tableData.length) * Number(peelingRate) :  '')}</Descriptions.Item>
            </Descriptions>
            
            </Col>
        </>) : (<></>)
        } */}
                        {/* {props.tabName == OperationTypeEnum.VALUE_ADDITION || props.tabName == OperationTypeEnum.BE_HEADING ? (<>
           <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 20 }} style={{marginTop:'2.5%'}}>
           <Descriptions column={5}>
               <Descriptions.Item label='No Of Persons'>{workerDisable ? billAgainstWorkers.length : meatBasedPrice ? noOfWorkers  :tableData.length}</Descriptions.Item>

               <Descriptions.Item label='Per Head'>{workerDisable ? (Number(Number(totalsInfo[0]?.amount) / Number(billAgainstWorkers.length)).toFixed(2)) : prevBillInfo.length > 0 && noOfWorkers ? (Number(totalsInfo[0]?.amount) / Number(noOfWorkers)) : tableData.length > 0 && addedInfo.length > 0 && !meatBasedPrice? (addedInfo.reduce((sum, item) => sum + parseFloat(item.amount), 0)) / Number(tableData.length) : meatBasedPrice && addedInfo.length > 0 ? (addedInfo.reduce((sum, item) => sum + parseFloat(item.amount), 0)) / Number(noOfWorkers)  : '-' }</Descriptions.Item>

               <Descriptions.Item label='Total Qty'>{workerDisable || prevBillInfo.length > 0 && !meatBasedPrice ? Number(totalsInfo[0]?.opQty) :  prevBillInfo.length > 0 && meatBasedPrice ? Number(totalsInfo[0]?.meatBasedOpQty) : addedInfo.length > 0  && !meatBasedPrice ? addedInfo.reduce((sum, item) => sum + parseFloat(item.reportedQty), 0) : addedInfo.length > 0  && meatBasedPrice ? addedInfo.reduce((sum, item) => sum + parseFloat(item.opQty), 0) : meatBasedPrice ? (form.getFieldValue('opQty')) :  (form.getFieldValue('reportedQty'))}</Descriptions.Item>

               <Descriptions.Item label='Average Qty'>{workerDisable || billAgainstWorkers.length > 0 ?( Number(Number(totalsInfo[0]?.opQty) / Number(billAgainstWorkers.length)).toFixed(2)) : meatBasedPrice && prevBillInfo.length > 0 && noOfWorkers ? ( Number(Number(totalsInfo[0]?.meatBasedOpQty) / Number(noOfWorkers)).toFixed(2)) : !meatBasedPrice && prevBillInfo.length > 0 && noOfWorkers ? ( Number(Number(totalsInfo[0]?.opQty) / Number(noOfWorkers)).toFixed(2)) : addedInfo.length > 0 && meatBasedPrice ? addedInfo.reduce((sum, item) => sum + parseFloat(item.opQty), 0) / Number(noOfWorkers ) : addedInfo.length > 0 && tableData.length > 0 && !meatBasedPrice ? addedInfo.reduce((sum, item) => sum + parseFloat(item.reportedQty), 0) / tableData.length :  (form.getFieldValue('reportedQty') != undefined && tableData.length > 0 ? Number(Number(form.getFieldValue('reportedQty'))/Number(tableData.length)) : '')}</Descriptions.Item>

               <Descriptions.Item label='Total Amount'>{workerDisable  || prevBillInfo.length > 0 ? (Number(totalsInfo[0]?.amount)) :addedInfo.length > 0 ? addedInfo.reduce((sum, item) => sum + parseFloat(item.amount), 0): (peelingRate != 0 && tableData.length > 0 ?Number(tableData.length) * Number(peelingRate) :  '')}</Descriptions.Item>
           </Descriptions>
           
           </Col>
       </>) : (<></>)
       } */}
                        {props.tabName == OperationTypeEnum.VALUE_ADDITION || props.tabName == OperationTypeEnum.BE_HEADING ? (<>
                            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 20 }} style={{ marginTop: '2.5%' }}>
                                <Descriptions column={5}>
                                    <Descriptions.Item label='No Of Persons'>{noOfWorkers}</Descriptions.Item>

                                    <Descriptions.Item label='Per Head'>{noOfWorkers > 0 ? Number((Number(totalAmount) + Number(addedInfoAmount)) / Number(noOfWorkers)).toFixed(2) : '-'}</Descriptions.Item>

                                    <Descriptions.Item label='Total Qty'>{(Number(totalQty) + Number(addedInfoQty)).toFixed(2)}</Descriptions.Item>

                                    <Descriptions.Item label='Average Qty'>{noOfWorkers > 0 ? Number((Number(totalQty) + Number(addedInfoQty)) / (noOfWorkers)).toFixed(2) : '-'}</Descriptions.Item>

                                    <Descriptions.Item label='Total Amount'>{Number(totalAmount) + Number(addedInfoAmount)}</Descriptions.Item>
                                </Descriptions>

                            </Col>
                        </>) : (<></>)}
                    </Row>
                    {tableData.length > 0 || billAgainstWorkers.length > 0 ? (<>
                        <Table columns={workerDisable ? columns.filter(e => e.dataIndex != 'action') : columns} dataSource={workerDisable ? billAgainstWorkers : tableData} pagination={false} size="small" />
                    </>) : (<></>)}
                </>) : (<></>)}
                {addedInfo.length > 0 ? (<>
                    <Table dataSource={addedInfo} columns={addedInfoColumns} pagination={false} />
                </>) : (<></>)}
                <Row justify="end">
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 2 }}>
                        <Form.Item>
                            <Button type='primary' disabled={props.tabName != OperationTypeEnum.SOAKING ? (addedInfo.length > 0 ? false : true) : submitDisable ? true : false} onClick={onFinish}>Submit</Button>
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 2 }}>
                        <Form.Item>
                            <Button danger icon={<UndoOutlined />} onClick={onReset}>Reset</Button>
                        </Form.Item>
                    </Col>
                </Row>
                {prevBillInfo.length > 0 ? (<>
                    <Row gutter={24}>
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 24 }}>
                            <Table columns={PrevBillInfocolumns} dataSource={prevBillInfo} pagination={false} />
                        </Col>
                    </Row>
                </>) : (<></>)}
            </Form></>
    )

}

export default ProdutionOperationForm