import { ExporterDataInput } from "@gtpl/shared-models/logistics";
import { GrnItemIdRequest } from "@gtpl/shared-models/procurement-management";
import { FactoriesInput } from "@gtpl/shared-models/sale-management";
import { GrnService } from "@gtpl/shared-services/procurement";
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
import { Button, Card, Descriptions } from "antd";
import moment from "moment";
import React, { useEffect, useState } from "react";
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
import { getCssFromComponent } from "..";
import { VehicleAssignmentService } from "@gtpl/shared-services/transportation";

export interface RmWeighmentPrintProps{
    grnItemId: number;
}

export function RmWeighmentPrint(props: RmWeighmentPrintProps){
    const service = new GrnService()
    const [data, setData] = useState([])
    const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
    const [vehicles, setVehicles] = useState([])
    const [totalCreates, setTotalCreates]=useState(0)

    const vehicleService = new VehicleAssignmentService()

let total =0
let totalWeight =0
let totalQty =0
let date


    useEffect(()=>{getData()},[])

    // let exporterDetails = ExporterDataInput;
    // const exporterData = exporterDetails.find(
    //   (item) => item.value == data[0]?.plantId
    // );

    const getData=()=>{
        date = new Date ()
        const req =new GrnItemIdRequest(props.grnItemId)
        service.getRmWeighment(req).then((res)=>{
            if(res.status){
                setData(res.data)
               const tot= res.data.reduce((acc, e) => acc + Number(e.noOfCrates || 0), 0);
               setTotalCreates(tot)
                // console.log(total);
                if(res.data[0]?.indentId != null|| res.data[0]?.indentId != undefined || res.data[0]?.indentId != 0){
                    vehicleService.getVehicleAssignDetailsByIndentId({indentId:res.data[0]?.indentId}).then(res=>{
                      if(res.status){
                        setVehicles(res.data[0]?.vechileInfo)
                      }
                    })
                  }
            }
            else{
                AlertMessages.getErrorMessage(res.internalMessage)
            }
        })
    }
    
    let exporterDetails = ExporterDataInput;

    const exporterData = exporterDetails.find(
    (item) => item.value == data[0]?.plantId ? data[0]?.plantId : 0
  );

    // const printOrder = () => {
    //     const printableElements = document.getElementById('printme').innerHTML;
    //     const orderHTML = '<html><head><title></title></head><body>' + printableElements + '</body></html>'
    //     const oldPage = document.body.innerHTML;
    //     document.body.innerHTML = orderHTML;
    //     // document.body.innerHTML = oldPage
    //     window.document.close();
    //     setTimeout(() => {
    //       window.print();
    //       window.close(); // to close window when click on cancel/Save
    //       setIsModalVisible(true); // model should be open
    //     }, 1000);
    //     // window.document.close();
    //     // window.print();
    //     // window.close()    
    //   }
      const printOrder = () => {
        const printableElements = document.getElementById('printme').innerHTML;
        const orderHTML = window.open('<html><head><title></title></head><body>' + printableElements + '</body></html>')
        const oldPage = document.body.innerHTML;
        orderHTML.document.write(printableElements);
      getCssFromComponent(document, orderHTML.document);
      orderHTML.document.close();
        // document.body.innerHTML = oldPage
        orderHTML.print();
        orderHTML.close();
      }
    return(
        <div>
             <Card
                title=' Raw Material Re-WeighMent'  headStyle={{ backgroundColor: '#69c0ff',fontSize:'15px'  }}
        style={{
            textAlign: 'center',
        //   width: '210mm',
        //   height: '297mm',
        //   margin: 'auto',
          padding: '5mm',
          position: 'relative',
        }}
        extra={
            <span style={{alignSelf:'end'}}><Button onClick={printOrder}>Print</Button></span>
  
          }
      >
        
        {/* <span style={{ alignContent: 'left', height:50}}>
        <ReactHTMLTableToExcel
          id="test-table-xls-button"
          className="download-table-xls-button"
          table="table-to-xls"
          filename="RmWeighmentPrint"
          sheet="RmWeighmentPrint"
          buttonText="Get Excel" />

      </span> */}
      {/* <span style={{alignSelf:'end'}}><Button onClick={printOrder}>Print</Button></span> */}
      <br />
      <html>

          <head></head>
          <br />
          <body id='printme'>
          <div style={{ textAlign: 'center' }}>
                  <h2 style={{ margin: '0' }}>{data[0]?.company}</h2>
                  <p>{exporterData?.addressOne} <br/> {exporterData?.addressTwo}</p>
                <h3><u><b>RAW MATERIAL WEIGHMENT</b></u></h3>
                </div>
                <div>
                    <Descriptions column={3}>
                        <Descriptions.Item label='Farmer Name' labelStyle={{fontWeight:'bold'}}>{data?.[0]?.supplier==='Dealer'?data?.[0]?.dealer?data?.[0]?.dealer:'':data?.[0]?.farmer?data?.[0]?.farmer:''}</Descriptions.Item>
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'Date'}>{data?.[0]?.farmer? moment(data?.[0]?.reWeighmentDate).format('DD-MM-YYYY'):''}</Descriptions.Item>
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'PCs'}>{data?.[0]?.pieces?data?.[0]?.pieces:''}</Descriptions.Item>
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'Place'}>{data?.[0]?.supplier==='Dealer'?data?.[0]?.dealerCity?data?.[0]?.dealerCity:'':data?.[0]?.city?data?.[0]?.city:''},{data?.[0]?.supplier==='Dealer'?data?.[0]?.dealerStreet?data?.[0]?.dealerStreet:'':data?.[0]?.street?data?.[0]?.street:''},{data?.[0]?.supplier==='Dealer'?data?.[0]?.dealerPostalCode?data?.[0]?.dealerPostalCode:'':data?.[0]?.postalCode?data?.[0]?.postalCode:''}</Descriptions.Item>
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'S.Code'}>{data?.[0]?.lotNum?data?.[0]?.lotNum:''}</Descriptions.Item>
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'KGs '}>{data?.[0]?.sampleQty?data?.[0]?.sampleQty:''}</Descriptions.Item>
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'Species'}>{''}</Descriptions.Item>
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'Total No Of Crates'}>{totalCreates?totalCreates:'-'}</Descriptions.Item>
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'Count '}>{data?.[0]?.reWeighmentCount?data?.[0]?.reWeighmentCount:''}</Descriptions.Item>
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'Variety'}>{data?.[0]?.product?data?.[0]?.product:''}</Descriptions.Item>
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'Vehicle No'}>{data?.[0]?.vehicle?data?.[0]?.vehicle:''}</Descriptions.Item>
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'G.I & Sof '}>{''}</Descriptions.Item>
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'S.S '}>{data?.[0]?.softPercent?data?.[0]?.softPercent:''}%</Descriptions.Item>
                        {/* <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'Count'}>{data?.[0]?.reWeighmentCount?data?.[0]?.reWeighmentCount:''}</Descriptions.Item> */}
                        <Descriptions.Item labelStyle={{fontWeight:'bold'}} label={'Total Weighment'}>{data?.[0]?.reweighmentQty?data?.[0]?.reweighmentQty:''}</Descriptions.Item>


                    </Descriptions>
                </div>
                <div style={{flexDirection:'row',display:'flex'}}>
                    <div style={{flex:1}}>
                    <Descriptions column={3}>
                       
                        </Descriptions>
                    </div>
                    
                </div>
                <div style={{flex:1}}>
                        {/* <h3>Final Summary</h3> */}
                        <Descriptions column={2} title={'Final Summary'}>

                        </Descriptions>
                    </div>
                <table style={{width:'100%'}}>
                    <tr>
                        <th className="ta-b">S.no</th>
                        <th className="ta-b">{data?.[0]?.reWeighmentCount?data?.[0]?.reWeighmentCount:''}</th>
                        <th className="ta-b"></th>
                    </tr>
                    {data.map((e,index)=>{
                        total = total+Number(e.noOfCrates)
                        totalQty =totalQty+Number(e.quantity)
                        return(
                            <tr>
                                <td className="ta-b">{index+1}</td>
                                <td className="ta-b">{e.quantity}</td>
                                <td className="ta-b">{e.noOfCrates}</td>
                            </tr>
                        )
                    })}
                    <tr>
                        <td className="ta-b"></td>
                        <td className="ta-b">{totalQty}</td>
                        <td className="ta-b"></td>

                    </tr>
                    <tr>
                    <td className="ta-b"></td>
                    <td className="ta-b">(-){Number(totalQty - Number(data?.[0]?.reweighmentQty)).toFixed(3)}</td>
                    <td className="ta-b"></td>
                   </tr>
                    <tr>
                    <td className="ta-b"></td>
                    <td className="ta-b">{data?.[0]?.reweighmentQty?data?.[0]?.reweighmentQty:''}</td>
                    <td className="ta-b"></td>
                   </tr>
                    
                </table>
                <div style={{padding:'20px'}}>
                <Descriptions  column={2}>
                    <Descriptions.Item labelStyle={{fontWeight:'bold'}} label='Remarks'>{''}</Descriptions.Item>
                    <Descriptions.Item labelStyle={{fontWeight:'bold'}} label='Signature'>{''}</Descriptions.Item>

                </Descriptions>
                </div>
</body>
</html>
      </Card>
      </div>
      
    )
}
export default RmWeighmentPrint;
