import { RodtepStatus } from "@gtpl/shared-models/common-models";
import { PaymentTypeReq, SaleReceiveReq } from "@gtpl/shared-models/finance";
import { CollectionsService, PurchasesProductService } from "@gtpl/shared-services/finance";
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
import { Button, Checkbox, Col, Form, Row, Select, Space, Switch, Table } from "antd"
import moment from "moment";
import {  SaleOrderService } from '@gtpl/shared-services/sale-management';
import React, { useEffect, useState } from "react"
import { CheckCircleOutlined, CloseCircleOutlined, RightSquareOutlined, EyeOutlined, EditOutlined, FormOutlined,SearchOutlined ,IssuesCloseOutlined} from '@ant-design/icons';
export interface ReceiveSaleProps {
  tab:string
  }
export const ReceiveSale =(props:ReceiveSaleProps) =>{
    const [data, setData] = useState([])
    const service = new CollectionsService()
        const [form] = Form.useForm();
      const [years,setYears] = useState<any[]>([])
      const invoiceDataService = new SaleOrderService;
      const [factoriesData, setFactoriesData] = useState([]);
       const purchaseService = new PurchasesProductService()
       const { Option } = Select;
useEffect(() => {
      getData(props.tab)
      getAllFinancialYear()
      getAllCompanyNames()
  }, [props.tab])

    const getData = (val) =>{
      const req = new PaymentTypeReq(props.tab)
                     
                      if(form.getFieldValue('financialYear') !== undefined){
                        req.financeYear = form.getFieldValue('financialYear')
                      }
                        if(form.getFieldValue('unit') !== undefined){
                  req.unitId = form.getFieldValue('unit')
                }
      service.getReceivePoData(req).then((res)=>{
        if(res.status){
         setData(res.data)
        }else{
          setData([])
          AlertMessages.getSuccessMessage(res.internalMessage)
        }
      })
    }

    
    const getAllCompanyNames = () => {
    purchaseService.getAllCompanys().then((res) => {
        if (res.status) {
            setFactoriesData(res.data)
        }
    })
}
    const getAllFinancialYear  = () => {
        invoiceDataService.getAllFinancialYear().then(res => {
          if (res.status) {
            setYears(res.data);
          } else {
            if (res.intlCode) {
              setYears([]);
              AlertMessages.getErrorMessage(res.internalMessage);
            } else {
              AlertMessages.getErrorMessage(res.internalMessage);
            }
          }
        }).catch(err => {
          setYears([]);
          AlertMessages.getErrorMessage(err.message);
        })
      }
    const handlePaymentChange =(rec)=>{
      // console.log(rec.invoiceNumber,'tttttttttt');
      let invNum = rec.invoiceNumber
      // console.log(invNum);
      const req = new SaleReceiveReq(invNum,rec.soId)
      req.invoiceNumber= invNum
      // console.log(req,'ooooooooooo');
      service.updateSaleReceived(req).then((res)=>{
        if(res.status){
          getData(props.tab)
          AlertMessages.getSuccessMessage(res.internalMessage)
        }else{
          AlertMessages.getErrorMessage(res.internalMessage)
        }
      })
    }
    const columns: any[] = [
        {
          title: 'S No', dataIndex: 'sNo', render: (text, object, index) => {
            if (index == data.length) {
              return null;
            } else {
              return index + 1
            }
          },
          width: 60,
        },
        {
          title: 'Invoice Number', 
          dataIndex: 'invoiceNumber',
          render: (text: any, record: any) => { return record.invoiceNumber ? record.invoiceNumber : '-' } ,
          sorter: (a, b) => a.invoiceNumber.localeCompare(b.invoiceNumber),
          sortDirections: ['descend', 'ascend'],
        },
         {
        title: 'Invoice Date', 
        dataIndex: 'invoiceDate',
        render: (text: any, record: any) => { return record.invoiceDate ? moment(record.invoiceDate).format('DD-MM-YYYY') : '-' },
        sorter: (a, b) => a.invoiceDate.localeCompare(b.invoiceDate),
        sortDirections: ['descend', 'ascend'],
        },
        {
        title: 'Customer', 
        dataIndex: 'customer',
        render: (text: any, record: any) => { return record.customer ?  record.customer : '-' },
        sorter: (a, b) => a.customer.localeCompare(b.customer),
        sortDirections: ['descend', 'ascend'],
        },
        {
        title: 'Sale Amount', 
        dataIndex: 'saleAmount',
        render: (text: any, record: any) => { return record.saleAmount ?  record.saleAmount : '-' },
        sorter: (a, b) => a.saleAmount.localeCompare(b.saleAmount),
        sortDirections: ['descend', 'ascend'],
        },
        {
        title: 'Final Sale Amount', 
        dataIndex: 'finalSaleAmount',
        render: (text: any, record: any) => { return record.finalSaleAmount ?  record.finalSaleAmount : '-' },
        sorter: (a, b) => a.finalSaleAmount.localeCompare(b.finalSaleAmount),
        sortDirections: ['descend', 'ascend'],
        },
        {
        title: 'Discount Rate', 
        dataIndex: 'discountRate',
        render: (text: any, record: any) => { return record.discountRate ?  record.discountRate : '-' },
        sorter: (a, b) => a.discountRate.localeCompare(b.discountRate),
        sortDirections: ['descend', 'ascend'],
        },
        {
        title: 'Payment Recieved', 
        dataIndex: 'paymentRecieved',
        render: (text, rowData) => {
          return(
              <>
                <Switch 
                size="default"
                checkedChildren={<RightSquareOutlined />}
                unCheckedChildren={<RightSquareOutlined />}
                checked={rowData.rodtepStatus === RodtepStatus.RECEIVED}
                disabled={rowData.rodtepStatus === RodtepStatus.RECEIVED}
                onChange={e =>{handlePaymentChange(rowData);}}
                />
                
                </> )
         }      
          },
      ]
      const search =() =>{
        getData(props.tab)
       }
       const onReset = () => {
        form.resetFields();
      }
return(
   <><Form form={form} onFinish={search}>
    <Row gutter={24}>
       <Col xs={{span:24}} sm={{span:24}} md={{span:6}} lg={{span:6}} xl={{span:6}}>
          <Form.Item name="unit" label="Unit" rules={[{ required: false }]}>
                <Select
                    showSearch
                    optionFilterProp="children"
                    filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    placeholder=" Select Unit"
                    allowClear
                    dropdownMatchSelectWidth={false}
                >
                   {factoriesData.map(dropData => {
                   return <Option value={dropData.companyId}>{dropData.company}</Option>
                     })}
                      
                </Select>
                </Form.Item>
              </Col >
      <Col xs={24} sm={12} md={6} lg={6} xl={6}>
        <Form.Item name="financialYear" label="Financial Year">
          <Select
            showSearch
            placeholder="Select Financial Year"
            optionFilterProp="children"
            allowClear
          >
            {years.filter(year => year.financialYear !== null).map((y: any) => (
              <Select.Option key={y.financialYear} value={y.financialYear}>
                {y.financialYear}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
      </Col>
      <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              Search
            </Button>
            <Button type="primary" htmlType="reset" onClick={() => onReset()}>
              Reset
            </Button>
          </Space>
        </Form.Item>
      </Col>
    </Row>
  </Form><Table columns={columns} dataSource={data} size="small" /></>
)
}
export default ReceiveSale