import {Button, Card, Col, DatePicker, Descriptions, Form, Row, Select} from 'antd'
import Table, { ColumnProps } from 'antd/lib/table'
import React, { useEffect, useState } from 'react'
import {WarehouseDashboardService} from '@gtpl/shared-services/analytics'
import { ProductReq } from '@gtpl/shared-models/analytics-data'
import { Excel } from 'antd-table-saveas-excel';
import { StockValuationReportModel } from '@gtpl/shared-models/warehouse-management'
import moment from 'moment'
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';

const {Option} = Select
const {RangePicker} = DatePicker
export const StockValuationReport = () => {
    const [page,setPage] = useState<number>(1)
    const service = new WarehouseDashboardService()
    const [data,setData] = useState<StockValuationReportModel>()
    const [products,setProducts] = useState<any[]>([])
    const [form] = Form.useForm()
    const [pageSize, setPageSize] = useState<number>(1);
    const [productsInfo,setProductsInfo] = useState<any[]>([])
    const [abstractInfo,setAbstractInfo] = useState<any[]>([])
    const [htmlTableDisplay,setHtmlTableDisplay] = useState<boolean>(false)


    useEffect(() => {
        // getReport()
        getProductDropdowns()
    },[])

    const getProductDropdowns = () => {
        service.getVarientCodeDropdown().then(res => {
            if(res.status){
                setProducts(res.data)
            }
        })
    }

    const updateProductionCostAnalysis = () =>{
        service.updateProductionCostAnalysis().then(res =>{
            if(res.status){
            //  AlertMessages.getSuccessMessage(res.internalMessage)
            getReport()
            } else {
             AlertMessages.getErrorMessage(res.internalMessage)
                  
            }
        })
    }

    const getReport = () => {
        const req = new ProductReq(null)
        if(form.getFieldValue('product') != undefined){
            req.varientCode = form.getFieldValue('product')
        }
        if(form.getFieldValue('dateRange') != undefined){
            req.fromDate = moment(form.getFieldValue('dateRange')[0]).format('YYYY-MM-DD')
            req.toDate = moment(form.getFieldValue('dateRange')[1]).format('YYYY-MM-DD')
        }
        service.getStockValuationReport(req).then(res => {
            if(res.status){
                setData(res.data)
                setProductsInfo(res.data.productInfo)
                setAbstractInfo(res.data.abstractInfo)
            }else{
                setData(null)
                AlertMessages.getErrorMessage(res.internalMessage)
            }
        })
    }

    const columns : ColumnProps<any>[] = [
        {
            title: 'S No',
            key: 'sno',
            width: '70px',
            responsive: ['sm'],
            render: (text, object, index) => (page - 1) * 10 + (index + 1)
        },
        {
            title:'Grade',
            dataIndex:'grade'
        },
        {
            title:'Product',
            dataIndex:'variety'
        },
        {
            title:'M/C',
            dataIndex:'masterCartons',
            // sorter: (a, b) =>  a.noOfcartons - b.noOfcartons,
            //  sortDirections: ['descend', 'ascend'],
        },
        // {
        //     title:'Pack Style',
        //     dataIndex:'packStyle'
        // },
        // {
        //     title:'Quantity(Kgs)',
        //     dataIndex:'qtyInKgs',
        //     // sorter: (a, b) =>  a.qtyInKgs - b.qtyInKgs,
        //     //  sortDirections: ['descend', 'ascend'],
        //     render:(text,record) => {
        //         return(
        //             <>
        //             {record.qtyInKgs ? Number(record.qtyInKgs) : '-'}
        //             </>
        //         )
        //     }
        // },
        // {
        //     title:'Quantity(Lbs)',
        //     dataIndex:'qtyInLbs',
        //     // sorter: (a, b) =>  a.qtyInLbs - b.qtyInLbs,
        //     //  sortDirections: ['descend', 'ascend'],
        //     render:(text,record) => {
        //         return(
        //             <>
        //             {record.qtyInLbs ? Number(record.qtyInLbs) : '-'}
        //             </>
        //         )
        //     }
        // },
        {
            title:'Loose',
            dataIndex:'loosePouches',
        },
        // {
        //     title:'Cost Per Kg',
        //     dataIndex:'costPerKg',
        //     // sorter: (a, b) =>  a.costPerKg - b.costPerKg,
        //     //  sortDirections: ['descend', 'ascend'],
        //     render:(text,record) => {
        //         return(
        //             <>
        //             {record.costPerKg ? Number(record.costPerKg) : '-'}
        //             </>
        //         )
        //     }
        // },
        {
            title:'FG Qty in kgs',
            dataIndex:'fgQtyInKgs',
            sorter: (a, b) =>  a.fgQtyInKgs - b.fgQtyInKgs,
             sortDirections: ['descend', 'ascend'],
            render:(text,record) => {
                return(
                    <>
                    {record.fgQtyInKgs ? Number(record.fgQtyInKgs) : '-'}
                    </>
                )
            }
        },
        {
            title:'Yield',
            dataIndex:'productYield',
        },
        {
            title:'Pack Count',
            dataIndex:'packCount',
        },
        {
            title:'RM Count',
            dataIndex:'rmCount',
        },
        {
            title:'RM Rate',
            dataIndex:'rmRate',
        },
        {
            title:'CAL RM Quantity',
            dataIndex:'calRmQty',
        },
        {
            title:'RM Value',
            dataIndex:'rmValue',
        },
        {
            title:'MFG Cost',
            dataIndex:'mfgCost',
        },
        {
            title:'Net COP',
            dataIndex:'netCop',
        },
        {
            title:'Realisation Price Per KG',
            dataIndex:'realisationPricePerKg',
            render:(text,record) => {
                return(
                    <>
                    {text}
                    </>
                )
            }
        },
        {
            title:'Realisation Value',
            dataIndex:'realisationValue',
            render:(text,record) => {
                return(
                    <>
                    {text}
                    </>
                )
            }
        },
        {
            title:'Basis',
            dataIndex:'basis',
        },
    ]

    const abstractColumns  : ColumnProps<any>[] = [
        {
            title:'Particulars',
            dataIndex:'particulars'
        },
        {
            title:'Quantity',
            dataIndex:'qty',
            render:(text,record) => {
                return(
                    <>
                    {text}
                    </>
                )
            }
        },
        {
            title:'COP',
            dataIndex:'cop',
            render:(text,record) => {
                return(
                    <>
                    {text}
                    </>
                )
            }
        },
        {
            title:'COP/KG',
            dataIndex:'copPerKg',
            render:(text,record) => {
                return(
                    <>
                    {text}
                    </>
                )
            }
        },
        {
            title:'Realisation',
            dataIndex:'realisation',
            render:(text,record) => {
                return(
                    <>
                    {text}
                    </>
                )
            }
        },
        {
            title:'Realisation/KG',
            dataIndex:'realisationPerKg',
            render:(text,record) => {
                return(
                    <>
                    {text}
                    </>
                )
            }
        }

    ]

    const onFinish = () => {
        // getReport()
        updateProductionCostAnalysis()
    }

    const onReset = () => {
        form.resetFields()
        setData(null)
        // getReport()
    }

    let x = 1
    const excelData = [
        { title: 'S No', dataIndex: 'sNo', render: (text, object,index) => { return x++; } },
        { title: 'Grade', dataIndex: 'grade', render: (text, record) => { return record.grade ? record.grade : '-' } },
        { title: 'Product', dataIndex: 'variety', render: (text, record) => { return record.variety ? record.variety : '-' } },
        { title: 'M/C', dataIndex: 'masterCartons', render: (text, record) => { return record.masterCartons ? record.masterCartons : '-' } },
        { title: 'Loose', dataIndex: 'loosePouches', render: (text, record) => { return record.loosePouches ? record.loosePouches : '-' } },
        { title: 'FG Qty in kgs', dataIndex: 'fgQtyInKgs', render: (text, record) => { return record.fgQtyInKgs ? Number(record.fgQtyInKgs) : '-' } },
        { title: 'Yield', dataIndex: 'productYield', render: (text, record) => { return record.productYield ? record.productYield : '-' } },
        { title: 'Pack Count', dataIndex: 'packCount', render: (text, record) => { return record.packCount ? record.packCount : '-' } },
        { title: 'RM Count', dataIndex: 'rmCount', render: (text, record) => { return record.rmCount ? record.rmCount : '-' } },
        { title: 'RM Rate', dataIndex: 'rmRate', render: (text, record) => { return record.rmRate ? record.rmRate : '-' } },
        { title: 'CAL RM Quantity', dataIndex: 'calRmQty', render: (text, record) => { return record.calRmQty ? record.calRmQty : '-' } },
        { title: 'RM Value', dataIndex: 'rmValue', render: (text, record) => { return record.rmValue ? record.rmValue : '-' } },
        { title: 'MFG Cost', dataIndex: 'mfgCost', render: (text, record) => { return record.mfgCost ? record.mfgCost : '-' } },
        { title: 'Net COP', dataIndex: 'netCop', render: (text, record) => { return record.netCop ? record.netCop : '-' } },
        { title: 'Realisation Price Per KG', dataIndex: 'realisationPricePerKg', render: (text, record) => { return record.realisationPricePerKg ? record.realisationPricePerKg : '-' } },
        { title: 'Realisation Value', dataIndex: 'realisationValue', render: (text, record) => { return record.realisationValue ? record.realisationValue : '-' } },
        { title: 'Basis', dataIndex: 'basis', render: (text, record) => { return record.basis ? record.basis : '-' } },
    ]

    const abstractData = [
        { title: 'Particulars', dataIndex: 'particulars', render: (text, record) => { return record.particulars ? record.particulars : '-' } },
        { title: 'Quantity', dataIndex: 'qty', render: (text, record) => { return record.qty ? record.qty : '-' } },
        { title: 'COP', dataIndex: 'cop', render: (text, record) => { return record.cop ? record.cop : '-' } },
        { title: 'COP/KG', dataIndex: 'copPerKg', render: (text, record) => { return record.copPerKg ? record.copPerKg : '-' } },
        { title: 'Realisation', dataIndex: 'realisation', render: (text, record) => { return record.realisation ? record.realisation : '-' } },
        { title: 'Realisation/KG', dataIndex: 'realisationPerKg', render: (text, record) => { return record.realisationPerKg ? record.realisationPerKg : '-' } },

    ]

    const exportExcel = () => {
        const excel = new Excel();
        excel
          .addSheet('Stock-Valuation-Report')
          .addColumns(excelData)
        //   .addDataSource(data.productInfo, { str2num: true })
        data.productInfo.forEach(row => {
            excel.addDataSource([row], { str2num: true });
        });
          excel.addColumns(abstractData)
        //   .addDataSource(data.abstractInfo, { str2num: true })
        data.abstractInfo.forEach(row => {
            excel.addDataSource([row], { str2num: true });
        });
          excel.saveAs('StockValuationReport.xlsx');
      }
    return(
        <Card size='small' title={<span style={{color:'white'}}>Stock Valuation Report</span>} 
        style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }} extra={abstractInfo.length==0||(<ReactHTMLTableToExcel
            id='excel-button'
            // className='download-table-xls-button'
            table='stock-valuation'
            filename='stockValuationxls'
            sheet="Sheet 1"
            buttonText='Get Excel'
            className="ant-btn ant-btn"
/>)} >
            <Form form={form} onFinish={onFinish} >
                <Row gutter={24}>
                    {/* <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 8 }}>
                    <Form.Item name='product' label='Product'>
                        <Select allowClear showSearch optionFilterProp='children' placeholder='Select Product'>
                            {
                                products.map(e => {
                                    return(
                                        <Option key={e.varientCode} value={e.varientCode}>{e.varientCode}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>
                    </Col> */}
                     <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 8 }} style={{paddingLeft:"6px",paddingRight:'77px'
    }}>
                    <Form.Item name='dateRange' label='Range' rules={[
                  {
                    required: true,
                    message: 'Range is required'
                  },
                ]}>
                       <RangePicker/>
                    </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 2 }}>
                    <Form.Item >
                       <Button type='primary' htmlType='submit'>Get Report</Button>
                    </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 2 }}>
                    <Form.Item>
                       <Button type='primary' onClick={onReset}>Reset</Button>
                    </Form.Item>
                    </Col>
                </Row>
            </Form>
            {data ? (<>
            <Row>
                <Descriptions>
                  <Descriptions.Item label='MFG Cost On RM For JB'>{data.mfgCostOnRmForJob ? data.mfgCostOnRmForJob.toFixed(2) : '-'}</Descriptions.Item>
                  <Descriptions.Item label='MFG Cost On RM'>{data.mfgCostOnRm ? Number(data.mfgCostOnRm).toFixed(2) : '-'}</Descriptions.Item>
                  <Descriptions.Item label='Exchange Rate'>{data.exchangeRate ? Number(data.exchangeRate) : '-'}</Descriptions.Item>
                </Descriptions>
            </Row>
            <Table columns={columns} dataSource={productsInfo} 
            bordered
            pagination={{
                pageSize:100,
                onChange(current,pageSize) {
                  setPage(current);
                  setPageSize(pageSize);
                }
              }}
              size='small'
            //   scroll={{x:true,y:1200}}
            scroll={{x:'max-content'}}
              />

              <br/>
              <Table columns={abstractColumns} dataSource={abstractInfo} size='small' pagination={false}/>
            
            </>) : (<></>)}

                
            { data ? (<>
                <table id='stock-valuation' hidden>
                <Row>
                <Descriptions>
                  <Descriptions.Item label='MFG Cost On RM For JB'>{data.mfgCostOnRmForJob ? data.mfgCostOnRmForJob : '-'}</Descriptions.Item>
                  <Descriptions.Item label='MFG Cost On RM'>{data.mfgCostOnRm ? Number(data.mfgCostOnRm) : '-'}</Descriptions.Item>
                  <Descriptions.Item label='Exchange Rate'>{data.exchangeRate ? Number(data.exchangeRate) : '-'}</Descriptions.Item>
                </Descriptions>
                </Row>
                <table style={{borderCollapse:'collapse',borderBlockColor:'black',overflow:'scroll',width:'100%'}}>
                    <tr>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Grade</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'150px'}}>Product</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80x'}}>M/C</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Loose</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'150px'}}>FG Quantity In Kgs</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Yield</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Pack Count</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>RM Count</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>RM Rate</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'150px'}}>Cal RM Quantity</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'150px'}}>RM Value</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'150px'}}>MFG Cost</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'150px'}}>Net COP</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'150px'}}>Realisation Price Per KG</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'150px'}}>Realisation Value</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'150px'}}>Basis</th>
                    </tr>
                    {
                        productsInfo.map(rec => {
                            return(
                                <tr>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.grade}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.variety}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.masterCartons}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.loosePouches}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.fgQtyInKgs? Number(rec.fgQtyInKgs) : '-'}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.productYield}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.packCount}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.rmCount}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.rmRate}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.calRmQty}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.rmValue}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.mfgCost}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.netCop}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.realisationPricePerKg ? rec.realisationPricePerKg : '-'}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.realisationValue}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.basis}</td>
                                </tr>
                            )
                        })
                    }
                </table>
                <br/>
                <table style={{borderCollapse:'collapse',borderBlockColor:'black',width:'100%'}}>
                    <tr>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>Particulars</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>Quantity</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>COP</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>COP/KG</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>Realisation</th>
                        <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>Realisation/KG</th>
                    </tr>
                    {
                        abstractInfo.map(rec => {
                            return(
                                <tr>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.particulars}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.qty ? rec.qty :' -'}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.cop ? rec.cop :'-'}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.copPerKg ? rec.copPerKg : '-'}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.realisation ? rec.realisation :'-'}</td>
                                    <td style={{textAlign:'center',fontSize:'15px',border:'2px solid black'}}>{rec.realisationPerKg ? rec.realisationPerKg : '-'}</td>
                                </tr>
                            )
                        })
                    }
                </table>
                </table>
            </>) : (<></>)

            }

        </Card>
    )

}

export default StockValuationReport