import React, { useEffect, useRef, useState } from 'react';
import { IndentService } from '@gtpl/shared-services/raw-material-procurement';
import { HarvestIdRequest, HarvestingTime, HarvestModel, IndentDetailsModel, IndentHarvestingDateRangeReq, IndentHarvestingDateReq, IndentModel, IndentRequest, SupplierType } from '@gtpl/shared-models/raw-material-procurement';
import { IndentForm } from '@gtpl/pages/raw-material-procurement/raw-material-procurement-components/indent-form';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Divider, Popconfirm, Card, Tooltip, Switch, Input, Button, Tag, Row, Col, Drawer, Tabs, ConfigProvider, Modal, Layout, Popover, Form, Select, DatePicker } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined, RightSquareOutlined, EyeOutlined, EditOutlined, SearchOutlined, ExclamationCircleOutlined, PrinterOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import Table, { ColumnProps } from 'antd/lib/table';
import { Link, Redirect } from 'react-router-dom';
import moment from 'moment';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import enUSIntl from 'antd/lib/locale/en_US';
import './indent-grid.css';
import { RawMaterialGrnForm } from '@gtpl/pages/raw-material-procurement/raw-material-procurement-components/raw-material-grn-form';
import { HarvestReport } from '@gtpl/pages/raw-material-procurement/raw-material-procurement-components/harvest-report';
import { render } from 'react-dom';
import { ReasonsService, UnitcodeService } from '@gtpl/shared-services/masters';
import { CompanyTypeEnum, PlantIdRequest, ReasonCategoryDto, UnitTypeEnum } from '@gtpl/shared-models/masters';
import {  FarmTypesEnum, indentstatusenum, PassOrFail, ReasonCategoryEnum, SupplierTypeEnum, VehicleTypeEnum } from '@gtpl/shared-models/common-models';


/* eslint-disable-next-line */
export interface IndentGridProps { }

export function IndentGrid(
  props: IndentGridProps
) {
  const searchInput = useRef(null);
  const [page, setPage] = React.useState(1);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const [totalQuantity, setTotalQuantity] = useState(0);
  const detailedData = []; 
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [indentData, setIndentData] = useState<IndentModel[]>([]);
  const [completedIndentData, setCompletedIndentData] = useState<IndentModel[]>([]);
  // const [updateState, setUpdateState] = useState(false);
  const [plantId, setPlantIdState] = useState(0);
  // const [object, setObject] = useState(null);
  const indentService = new IndentService();

  const [selectedIndentData, setSelectedIndentData] = useState<any>(undefined);
  const [allData, setAllData] = useState<IndentModel[]>([]);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [cancelledIndentData, setCancelledIndentData] = useState<IndentModel[]>([]);
  const [form] = Form.useForm();
const [formCompletedIndents]=Form.useForm();
const [formCancelledIndents]=Form.useForm();
  const [indentId, setIndentIdState] = useState(0);
  const { TabPane } = Tabs;
  const unitId = localStorage.getItem("unit_id");
  const role = localStorage.getItem("role");
  const [cancelModal,setCancelModal] = useState<boolean>(false)
  const reasonService = new ReasonsService()
  const [cancelReasons,setCancelReasons] = useState<any[]>([])
  const [cancelForm] = Form.useForm()
  const [cancelReasonName,setCancelReasonName] = useState<string>('')
  const [record,setRecord] = useState<any>()
  const [index,setIndex] = useState<number>()
  const { RangePicker } = DatePicker;

  const content = (
    <div>
      <p>Assign a Vehicle to raise a GRN </p>
    </div>
  );

  useEffect(() => {
    // Calculate total quantity whenever detailedData changes
    calculateTotalQuantity();
  }, [completedIndentData]);

  useEffect(() => {
    // getHarvestingDateDropdown();
    getAllIndentDetails();
    getCompletedIndents();
    getCancelledIndents()
  }, []);

  const calculateTotalQuantity = () => {
    console.log("Detailed Data:", detailedData);
    let sum = 0;
    completedIndentData.forEach(item => {
      console.log("Item Quantity:", item.expectedQty); // Ensure this logs the correct quantity
      sum += item.expectedQty; // Assuming 'expectedQty' is the key for quantity in detailed data
    });
    console.log("Total Quantity:", sum);
    setTotalQuantity(sum);
  };


  const getAllIndentDetails = () => {
    const req = new IndentHarvestingDateRangeReq()
    if (form.getFieldValue('harvestingDate') !== undefined) {
      req.fromDate = moment(form.getFieldValue('harvestingDate')[0]).format("YYYY-MM-DD")
      req.toDate = moment(form.getFieldValue('harvestingDate')[1]).format("YYYY-MM-DD")

    }
    // console.log(moment());
    // console.log(new Date().toISOString());
    // console.log(new Date(Date.now() - 1 * 86400000 - new Date().getTimezoneOffset() * 60000).toISOString())
    // console.log(new Date(Date.now() - 2 * 86400000 - new Date().getTimezoneOffset() * 60000).toISOString())
    indentService.getAllIndents(req).then(res => {
      if (res.status) {
        if (role === '"ADMIN"' || role === '"INDENT PERSON"' || role === '"REWEIGHTMENT PERSON"') {
          console.log(role);
          setIndentData(res.data);
        }
        else {
          setIndentData(res.data.filter(rec => rec.plantId === null || rec.plantId === 0 || rec.plantId === Number(unitId)));
        }

        setAllData(res.data);
      } else {
        setAllData([]);
        if (res.intlCode) {
          setIndentData([]);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      setAllData([]);
      setIndentData([]);
      AlertMessages.getErrorMessage(err.message);
    })
  }
console.log(indentData)
  // const updateIndent = (indentData:IndentDetailsModel) => {
  //   indentService.updateIndent(indentData).then(res => {
  //     if (res.status) {
  //       AlertMessages.getSuccessMessage('Indent Updated Successfully');
  //       getAllIndentDetails();
  //       setDrawerVisible(false);
  //     } else {
  //       if (res.intlCode) {
  //         // AlertMessages.getErrorMessage(res.internalMessage);
  //       } else {
  //         AlertMessages.getErrorMessage(res.internalMessage);
  //       }
  //     }
  //   }).catch(err => {
  //     AlertMessages.getErrorMessage(err.message);
  //   })
  // }

  const deleteIndent = (indentData: IndentModel) => {
    indentData.isActive = indentData.isActive ? false : true;
    indentService.activateOrDeactivateIndent(indentData).then(res => {
      if (res.status) {
        getAllIndentDetails();
        AlertMessages.getSuccessMessage('Success');
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }

  const setPlantId = (rowdata: { plantId: number; }) => {
    setPlantIdState(rowdata.plantId)

  }


  const getColumnSearchProps = (dataIndex: string) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={searchInput}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
          icon={<SearchOutlined />}
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          Search
        </Button>
        <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          Reset
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <SearchOutlined type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex]
          .toString()
          .toLowerCase()
          .includes(value.toLowerCase())
        : false,
    onFilterDropdownVisibleChange: visible => {
      if (visible) { setTimeout(() => searchInput.current.select()); }
    },
    render: text =>
      text ? (
        searchedColumn === dataIndex ? (
          <Highlighter
            highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
            searchWords={[searchText]}
            autoEscape
            textToHighlight={text.toString()}
          />
        ) : text
      )
        : null

  });

  /**
   * 
   * @param selectedKeys 
   * @param confirm 
   * @param dataIndex 
   */
  function handleSearch(selectedKeys, confirm, dataIndex) {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  function handleReset(clearFilters) {
    clearFilters();
    setSearchText('');
  };
  const closeDrawer = () => {
    setDrawerVisible(false);
    getAllIndentDetails();
  }


  const openFormWithData = (viewData: IndentModel) => {
    setDrawerVisible(true);
    setSelectedIndentData(viewData);
  }
  const getCancelReasons = () => {
    const req = new ReasonCategoryDto(ReasonCategoryEnum.GENERAL)
    reasonService.getReasonsAgainstCategory(req).then(res => {
        if(res.status){
            setCancelReasons(res.data)
        }
    })
}
  const cancel = (viewData,index) => {
    setCancelModal(true)
    getCancelReasons()
    setRecord(viewData.indentId)
        setIndex(index)
  // console.log(viewData,'ppppppppppp');
  // const req = new IndentRequest()
  // req.indentId = viewData.indentId
  // indentService.CancelIndent(req).then((res)=>{
  //   if(res.status){
  //     AlertMessages.getSuccessMessage(res.internalMessage)
  //     getAllIndentDetails();
  //     getCompletedIndents();
  //     getCancelledIndents()
  //   }
  // })
  }
  const onCancelModalClose = () => {
    cancelForm.resetFields()
    setCancelModal(false)
}



const onCancelReasonModalOk = () => {
  if(cancelForm.getFieldValue('cancelReason')  != undefined) {
      setCancelModal(false)
        const req = new IndentRequest()
  req.indentId = record
  req.cancelReason = cancelForm.getFieldValue('cancelReason')
  // console.log(req,'----------');
  
  indentService.CancelIndent(req).then((res)=>{
    if(res.status){
      AlertMessages.getSuccessMessage(res.internalMessage)
      getAllIndentDetails();
      getCompletedIndents();
      getCancelledIndents()
    }
  })
  } else{
      AlertMessages.getErrorMessage('Cancel Reason is mandatory!')
  }
}

const onCancelReasonChange = (key,obj) => {
  setCancelReasonName(obj?.reasonName)
}

  const columnsSkelton: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      responsive: ['md'],
      align: 'left',
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title: 'Indent Code',
      key: 'indentCode',
      dataIndex: 'indentCode',
      // responsive: ['sm'],
      width: 180,
      align: 'left',
      ...getColumnSearchProps('indentCode'),
      sorter: (a, b) => a.indentCode.localeCompare(b.indentCode),
      sortDirections: ['descend', 'ascend'],
      render: (text, record) => { return  record.indentCode ? record.indentCode : "-" }

    },
    {
      title: 'Indent Date',
      dataIndex: 'indentDate',
      key: 'indentDate',
      width: "130px",
      // responsive: ['sm'],
      align: 'left',
      sorter: (a, b) => moment(a.indentDate).unix() - moment(b.indentDate).unix(),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('indentDate'),
      render: (text, record) => { return  record.indentDate ? moment(record.indentDate).format('YYYY-MM-DD') : "-" },
    },
    {
      title: 'Indent By',
      dataIndex: 'indentByName',
      key: 'indentByName',
      width: 180,
      // responsive: ['sm'],
      align: 'left',
      sorter: (a, b) => a.indentByName.localeCompare(b.indentByName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('indentByName'),
      // render: (text, record) => { return moment(record.indentDate).format('YYYY-MM-DD') },
      render: (text, record) => { return  record.indentByName ? record.indentByName : "-" }

    },
    {
      title: 'Count',
      dataIndex: 'expectedCount',
      key: 'expectedCount',
      width: 90,
      sorter: (a, b) => a.expectedCount - b.expectedCount,
        sortDirections: ['descend', 'ascend'],
      // responsive: ['sm'],
      align: 'left',
      render: (text, record) => { return  record.expectedCount ? record.expectedCount : "-" }

      // render: (text, record) => { return moment(record.indentDate).format('YYYY-MM-DD') },
    },
    {
      title: 'Quantity',
      dataIndex: 'expectedQty',
      key: 'expectedQty',
      sorter: (a, b) => a.expectedQty - b.expectedQty,
      sortDirections: ['descend', 'ascend'],
      width: 90,
      align: 'left',
      render: (text, record) => { return  record.expectedQty ? record.expectedQty : "-" }

      // render: (text, record) => groupedData[record.plantId].totalQuantity,
  },
    {
      title: 'Unit',
      dataIndex: 'plant',
      key: 'plant',
      width:"180px",
      // responsive: ['sm'],
      align: 'left',
      render: (text, record) => { return  record.plant ? record.plant : "-" },
      filters: [
        {
          text: "BMR INDUSTRIES-IND",
          value: "BMR INDUSTRIES-IND",
        },

        {
          text: "SNOW WORLD",
          value: "SNOW WORLD",
        },
        {
          text: "BMRINDUSTRIES-EXP",
          value: "BMRINDUSTRIES-EXP",
        },

      ],
      filterMultiple: false,
      onFilter: (value, record) => {
        // === is not work
        return record.plant === value;
      },

      
    },
    {
      title: 'Supplier Type',
      dataIndex: 'supplierType',
      key: 'SupplierType',
      responsive: ['md'],
      width: 180,
      align: 'left',
      sorter: (a, b) => a.supplierType.localeCompare(b.supplierType),
      sortDirections: ['descend', 'ascend'],
      filters: [
        {
          text: SupplierType.Agent,
          value: SupplierType.Agent,
        },

        {
          text: SupplierType.Dealer,
          value: SupplierType.Dealer,
        },
        {
          text: SupplierType.Farmer,
          value: SupplierType.Farmer,
        },
      ],
      filterMultiple: false,
      onFilter: (value, record) => {
        // === is not work
        return record.supplierType === value;
      },


    },
    {
      title: 'Supplier Name',
      dataIndex: 'supplier',
      key: 'supplier',
      width: 180,
      // responsive: ['sm'],
      align: 'left',
      sorter: (a, b) => a.supplier.localeCompare(b.supplier),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('supplier'),
      render: (text, record) => {
        return <>{record.supplierType == SupplierTypeEnum.DEALER ? record.brokerName : text}</>
      },
    },
  
    {
      title: 'Harvest Date',
      dataIndex: 'harvestingDate',
      key: 'harvestingDate',
      responsive: ['md'],
      width: 180,
      align: 'left',
      sorter: (a, b) => moment(a.harvestingDate).unix() - moment(b.harvestingDate).unix(),
      sortDirections: ['descend', 'ascend'],
      render: (text, record) => { return moment(record.harvestingDate).format('YYYY-MM-DD') },
    },
    {
      title: 'Harvest Time',
      dataIndex: 'harvestingTime',
      key: 'harvestingTime',
      responsive: ['sm'],
      width: 180,
      align: 'left',
      // sorter: (a, b) => a.harvestingTime.localeCompare(b.harvestingTime),
      // sortDirections: ['descend', 'ascend'],
      filters: [
        {
          text: HarvestingTime.MORNING,
          value: HarvestingTime.MORNING,
        },

        {
          text: HarvestingTime.EVENING,
          value: HarvestingTime.EVENING,
        },
      ],
      filterMultiple: false,
      onFilter: (value, record) => {
        // === is not work
        return record.harvestingTime === value;
      },
      // ...getColumnSearchProps('status')
    },
    
    {
      title: 'Status',
      dataIndex: 'grnCompleted',
      key: 'grnCompleted',
      // responsive: ['sm'],
      width: 180,
      align: 'left',
      render: (grnCompleted, rowData) => {
        console.log(rowData);
        return(
        
        <>
          {((rowData.vehicleAssigned === 1 && rowData.isVehicleRequired === 1) || rowData.isVehicleRequired === 0) && rowData.plantId != 0 && grnCompleted === 0 ?
            <span>
              {/* <Button size={'small'} title={'Click to add GRN'} icon={<ExclamationCircleOutlined />} onClick={() => {
                console.log(rowData)
                if (rowData.isActive) {
                  return <Link
                    to={{
                      pathname: "/rm-grn-form",
                      state: { id: rowData.indentId }
                    }}
                  />
                } else {
                  AlertMessages.getErrorMessage("You can't Create Grn For Deactivated Indent");
                }
              }}
                style={{ backgroundColor: '#e8e21e', color: "black", fontWeight: 'bold', fontSize: 'small' }}
              >
                Add GRN
              </Button> */}
              {/* <Tooltip
              title={
                rowData.testStatus == 'NOTCOMPLETED' ? 'Antibiotic Test Is not completed for all indent items' :
                rowData?.antibioticsTestResult?.toUpperCase() === 'FAIL'
                  ? 'Antibiotics test result was FAIL'
                  : null
              }
            > */}
         <Link to={`/rm-grn-form/${rowData.indentId}`}>
            <Button
              size="small"
              title={'Click to Add GRN'}
              icon={<ExclamationCircleOutlined />}
              style={{
                // backgroundColor: rowData.testStatus == 'NOTCOMPLETED' || rowData?.antibioticsTestResult?.toUpperCase() === 'FAIL' ? '#d3d3d3' : '#e8e21e',
                backgroundColor:'#e8e21e',
                color: 'black',
                fontWeight: 'bold',
                fontSize: 'small',
              }}
              // disabled={rowData.testStatus == 'NOTCOMPLETED' || rowData?.antibioticsTestResult == PassOrFail.FAIL ? true : false}

            >
              Add GRN
            </Button>
          </Link>
          {/* </Tooltip> */}
            </span>

            : rowData.vehicleAssigned === 1 && rowData.plantId != 0 && grnCompleted === 1 ?
              <Tag
                icon={<CheckCircleOutlined />}
                style={{ backgroundColor: '#52c41a', color: "black", fontWeight: 'bold' }}
              >
                COMPLETED
              </Tag>
              : rowData.plantId === 0 ?
                <Button
                  size={'small'}
                  title={'Click to Assign Vehicle'}
                  icon={<ExclamationCircleOutlined />}
                  style={{ backgroundColor: '#08979c', color: "white", fontWeight: 'bold', fontSize: 'small' }}
                  onClick={() => {
                    if (rowData.isActive) {
                      openFormWithData(rowData);
                    } else {
                      AlertMessages.getErrorMessage('You Cannot Edit Deactivated Indent');
                    }
                  }}
                >
                  Assign Plant
                </Button>
                : rowData.vehicleAssigned === 0 && rowData.isVehicleRequired === 1 ?
                  <Link to="/vehicle-assignment">
                    <Button
                      size={'small'}
                      title={'Click to Assign Vehicle'}
                      icon={<ExclamationCircleOutlined />}
                      style={{ backgroundColor: '#faad14', color: "black", fontWeight: 'bold', fontSize: 'small' }}
                    >
                      Assign Vehicle
                    </Button>
                  </Link>
                  //  <Popover content={(rowData.isActive) ? content : 'Activate indent to create grn'} title={(rowData.isActive) ? "Vehicle is Not Assigned" : "You Can't Perform action on Deactivated Indent"} trigger="click">
                  //   <Tag icon={<ExclamationCircleOutlined />} style={{ backgroundColor: '#fa8c16', color: "black", fontWeight: 'bold' }}>PENDING</Tag>
                  //    </Popover>
                  : "-"}
        </>
      )},
    },
    {
      title: 'Aging',
      key: 'age',
      width: 90,
      // responsive: ['sm'],
      sorter: (a, b) => (Math.floor((new Date(moment(a.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) - Math.floor((new Date(b.harvestingDate).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))),
      sortDirections: ['descend', 'ascend'],
      // ...getColumnSearchProps('aging'),
      render(text, record) {
        const obj: any = {
          children: (<div style={{ textAlign: 'right' }}>{Math.floor((new Date(moment(record.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) + 1}</div>),
          props: {
            style: {
              background: Math.floor((new Date(moment(record.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) + 1 >= 0 ? "#38f438" : '#f4646c',
              color: Math.floor((new Date(moment(record.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) + 1 >= 0 ? "black" : 'white'
            }
          },
        };
        return obj;
      }
    },
    {
      title: `Action`,
      dataIndex: 'action',
      width: 180,
      // responsive: ['sm'],
      render: (text, rowData,index) => (
        <span>
{rowData.grnCompleted !==1?(
          <><Tooltip placement="top" title='Update/Edit'>
              <EditOutlined className={'editSamplTypeIcon'} type="edit"
                onClick={() => {
                  if (rowData.isActive) {
                    openFormWithData(rowData);
                  } else {
                    AlertMessages.getErrorMessage('You Cannot Edit Deactivated Indent');
                  }
                } }
                style={{ color: '#1890ff', fontSize: '14px' }} />
            </Tooltip><Divider type="vertical" /></>
        ):''}

          <Popconfirm onConfirm={e => { deleteIndent(rowData); }}
            title={
              rowData.isActive
                ? 'Are you sure to Deactivate Indent ?'
                : 'Are you sure to Activate Indent ?'
            }
          >
            <Switch size="default"
              className={rowData.isActive ? 'toggle-activated' : 'toggle-deactivated'}
              checkedChildren={<RightSquareOutlined type="check" />}
              unCheckedChildren={<RightSquareOutlined type="close" />}
              checked={rowData.isActive}
            />

          </Popconfirm>
          <Divider type="vertical" />
          <Link
            to={{
              pathname: "/indent-detail-view",
              state: rowData.indentId
            }}
          >
            <Tooltip placement="top" title='Detail View'>
              <EyeOutlined type="view" name="detail view"
                onClick={() => {

                  // if (rowData.isActive) {
                  setPlantId(rowData);
                  // } else { 
                  //   AlertMessages.getErrorMessage('You Cannot Edit Deactivated Item -Variant');
                  // }
                }}
                style={{ color: '#1890ff', fontSize: '14px' }}
              />
            </Tooltip>
          </Link>
          <Divider type="vertical" />
          <Tooltip placement="top" title='cancel Indent'>
<CloseCircleOutlined type="danger" name="Cancel Indent"
              onClick={() => {

                // if (rowData.isActive) {
                cancel(rowData,index);
                // } else { 
                //  AlertMessages.getErrorMessage('You Cannot Edit Deactivated Indent');
                // }
              }}
              style={{ color: 'red', fontSize: '14px' }}/>
</Tooltip>
        </span>
      )
    },
    {
      title: 'Farm Type',
      dataIndex: 'farmType',
      // key: 'farmType',
      // responsive: ['md'],
      width: 130,
      align: 'left',
      sorter: (a, b) => a.farmType - b.farmType,

      // sorter: (a, b) => a.farmType.localeCompare(b.farmType),
      sortDirections: ['descend', 'ascend'],
      // filters: [
      //   {
      //     text: FarmTypesEnum.OTHERS,
      //     value: FarmTypesEnum.OTHERS,
      //   },

      //   {
      //     text: FarmTypesEnum.OWN,
      //     value: FarmTypesEnum.OWN,
      //   }
      // ],
      filterMultiple: false,
      onFilter: (value, record) => {
        // === is not work
        return record.farmType === value;
      },
      render: (text, record) => { return  record.farmType ? record.farmType : "-" }



    },
  ];

  const columnsSkelton1: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      align: 'left',
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title: 'Indent Code',
      key: 'indentCode',
      dataIndex: 'indentCode',
      width: 180,
      align: 'left',
      ...getColumnSearchProps('indentCode'),
      sorter: (a, b) => a.indentCode.localeCompare(b.indentCode),
      sortDirections: ['descend', 'ascend'],
      render: (text, record) => { return  record.indentCode ? record.indentCode : "-" }

    },
    {
      title: 'Indent Date',
      dataIndex: 'indentDate',
      key: 'indentDate',
      width: 180,
      align: 'left',
      sorter: (a, b) => moment(a.indentDate).unix() - moment(b.indentDate).unix(),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('indentDate'),
      render: (text, record) => { return  record.indentDate ? moment(record.indentDate).format('YYYY-MM-DD') : "-" },
    },
    {
      title: 'Indent By',
      dataIndex: 'indentPerson',
      key: 'indentPerson',
      width: 180,
      // responsive: ['sm'],
      align: 'left',
      sorter: (a, b) => a.indentPerson.localeCompare(b.indentPerson),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('indentPerson'),
      render: (text, record) => { return  record.indentPerson ? record.indentPerson : "-" }

    },
   
    {
      title: 'Supplier Type',
      dataIndex: 'supplierType',
      key: 'supplierType',
      width: 180,
      align: 'left',
      sorter: (a, b) => a.supplierType.localeCompare(b.supplierType),
      sortDirections: ['descend', 'ascend'],
      // ...getColumnSearchProps('supplierType')
      filters: [
        {
          text: SupplierType.Agent,
          value: SupplierType.Agent,
        },

        {
          text: SupplierType.Dealer,
          value: SupplierType.Dealer,
        },
        {
          text: SupplierType.Farmer,
          value: SupplierType.Farmer,
        },
      ],
      filterMultiple: false,
      onFilter: (value, record) => {
        // === is not work
        return record.supplierType === value;
      },
    },
    {
      title: 'Supplier Name',
      dataIndex: 'farmerName',
      key: 'farmerName',
      width: 180,
      // responsive: ['sm'],
      align: 'left',
      sorter: (a, b) => a.farmerName.localeCompare(b.farmerName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('farmerName'),
      render: (text, record) => {
        return <>{record.supplierType == SupplierTypeEnum.DEALER ? record.brokerName : text}</>
      },
      // render: (text, record) => { return moment(record.indentDate).format('YYYY-MM-DD') },
    },
    {
      title: 'Count',
      dataIndex: 'expectedCount',
      key: 'expectedCount',
      width: 90,
      // responsive: ['sm'],
      align: 'left',
      render: (text, record) => { return  record.expectedCount ? record.expectedCount : "-" }

    },
    {
      title: 'Quantity',
      dataIndex: 'expectedQty',
      key: 'expectedQty',
      width: 90,
      // responsive: ['sm'],
      align: 'left',
      // render: () => totalQuantity,
      // render: (text, record) => { return moment(record.indentDate).format('YYYY-MM-DD') },
      render: (text, record) => { return  record.expectedQty ? record.expectedQty : "-" }

    },
    {
      title: 'Unit',
      dataIndex: 'plant',
      key: 'plant',
      width:"180px",
      // responsive: ['sm'],
      align: 'left',
      render: (text, record) => { return  record.plant ? record.plant : "-" },
      filters: [
        {
          text: "BMR INDUSTRIES-IND",
          value: "BMR INDUSTRIES-IND",
        },

        {
          text: "SNOW WORLD",
          value: "SNOW WORLD",
        },
        {
          text: "BMRINDUSTRIES-EXP",
          value: "BMRINDUSTRIES-EXP",
        }

      ],
      filterMultiple: false,
      onFilter: (value, record) => {
        // === is not work
        return record.plant === value;
      },

    },
    // {
    //   title: 'Farmer Name',
    //   key: 'supplierName',      
    //   dataIndex: 'supplierName',
    //   responsive: ['sm'],
    //   hideInSearch: true,
    //   hideInForm: true,
    //   width: 180,
    //   align: 'left',
    //   ...getColumnSearchProps('supplierName'),
    //   // sorter: (a, b) => a.supplierName.localeCompare(b.supplierName),
    //   // sortDirections: ['descend', 'ascend'],
    // },
    // {
    //   title: 'Product Code',
    //   dataIndex:'productCode',
    //   key: 'productCode',
    //   hideInSearch: true,
    //   hideInForm: true,
    //   width: 200,
    //   align: 'left',
    //   // render: (rowData) => {return rowData.product},
    //   sorter: (a, b) => a.productCode.localeCompare(b.productCode),
    //   // sortDirections: ['descend', 'ascend'],
    //   // ...getColumnSearchProps('productCode')
    // },
    // {
    //   title: 'Expected Quantity',
    //   dataIndex:'expectedQty',
    //   key: 'expectedQty',      
    //   hideInSearch: true,
    //   hideInForm: true,
    //   width: 200,
    //   align: 'right',
    //   sorter: (a, b) => a.expectedQty - b.expectedQty,
    //   sortDirections: ['descend', 'ascend'],

    // },
    {
      title: 'Harvest Date',
      dataIndex: 'harvestingDate',
      key: 'harvestingDate',
      width: 180,
      align: 'left',
      sorter: (a, b) => moment(a.harvestingDate).unix() - moment(b.harvestingDate).unix(),
      sortDirections: ['descend', 'ascend'],
      render: (text, record) => { console.log(record); return moment(record.harvestingDate).format('YYYY-MM-DD') },

    },
    {
      title: 'Harvest Time',
      dataIndex: 'harvestingTime',
      key: 'harvestingTime',
      width: 180,
      align: 'left',
      render: (text, record) => { return  record.harvestingTime ? record.harvestingTime : "-" }

      
      // sorter: (a, b) => a.harvestingTime.localeCompare(b.harvestingTime),
      // sortDirections: ['descend', 'ascend'],

    },
    // {
    //   title: 'Address',
    //   dataIndex:'address',
    //   key: 'address',
    //   hideInSearch: true,
    //   hideInForm: true,
    //   width: 180,
    //   // align: 'left',
    // },
    // {
    //   title: 'Mobile No',
    //   dataIndex:'mobileNumber',
    //   key: 'mobileNumber',
    //   hideInSearch: true,
    //   hideInForm: true,
    //   // width: 180,
    //   // align: 'left',
    //   sorter: (a, b) => a.mobileNumber.localeCompare(b.mobileNumber),
    //   sortDirections: ['descend', 'ascend'],
    //   // filters: true,
    //   // onFilter: true,
    //   // valueEnum: {
    //   //   Morning: { text: 'Morning', status: 'Default' },
    //   //   Evening: { text: 'Evening', status: 'Default' }
    //   // } 
    // },
    {
      title: 'GRN',
      dataIndex: 'grnCompleted',
      key: 'grnCompleted',
      width: 180,
      align: 'left',
      // sorter: (a, b) => a.grnCompleted.localeCompare(b.grnCompleted),
      // sortDirections: ['descend', 'ascend'],
      // filters: true,
      // onFilter: true,
      // filters: [
      //   {
      //     text: 'CLOSED',
      //     value: true,
      //   },
      //   {
      //     text: 'OPEN',
      //     value: false,
      //   },
      // ],
      // filterMultiple: false,
      // onFilter: (value, record) => {
      //   // === is not work
      //   return record.grnCompleted === value;
      // },
      render: (grnCompleted, rowData: IndentModel) => (
        <>
          {(rowData.isVehicleRequired == true && rowData.vehicleAssigned == true) ? grnCompleted == false ?
            <span>
              <Tag icon={<ExclamationCircleOutlined />} onClick={() => { setIndentId(rowData.indentId); }}
                style={{ backgroundColor: '#e8e21e', color: "black", fontWeight: 'bold' }}>PENDING</Tag>
            </span>
            : <Tag icon={<CheckCircleOutlined />} style={{ backgroundColor: '#52c41a', color: "black", fontWeight: 'bold' }}>COMPLETED</Tag>
            : <Popover content={content} title="Vehicle is Not Assigned" trigger="click">
              <Tag icon={<ExclamationCircleOutlined />} style={{ backgroundColor: '#fa8c16', color: "black", fontWeight: 'bold' }}>PENDING</Tag>
            </Popover>
          }
        </>
      ),
    },

    // {
    //   title: 'Aging',
    //   key: 'age',
    //   // responsive: ['sm'],
    //   sorter: (a, b) => (Math.floor((new Date(moment(a.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) - Math.floor((new Date(b.harvestingDate).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))),
    //   sortDirections: ['descend', 'ascend'],
    //   // ...getColumnSearchProps('aging'),
    //   render(text, record) {
    //     {return "-"}
    //   }
    // },'
    {
      title: 'Farm Type',
      dataIndex: 'farmType',
      // key: 'farmType',
      // responsive: ['md'],
      width: 130,
      align: 'left',
      sorter: (a, b) => a.farmType - b.farmType,

      // sorter: (a, b) => a.farmType.localeCompare(b.farmType),
      sortDirections: ['descend', 'ascend'],
      // filters: [
      //   {
      //     text: FarmTypesEnum.OTHERS,
      //     value: FarmTypesEnum.OTHERS,
      //   },

      //   {
      //     text: FarmTypesEnum.OWN,
      //     value: FarmTypesEnum.OWN,
      //   }
      // ],
      filterMultiple: false,
      onFilter: (value, record) => {
        // === is not work
        return record.farmType === value;
      },
      render: (text, record) => { return  record.farmType ? record.farmType : "-" }



    },
    {
      title: `Action`,
      dataIndex: 'action',
      width: 180,
      render: (text, rowData) => (
        <span>
{rowData.grnCompleted !==1?(
          <><EditOutlined className={'editSamplTypeIcon'} type="edit"
              onClick={() => {
                if (rowData.isActive) {
                  openFormWithData(rowData);
                } else {
                  AlertMessages.getErrorMessage('You Cannot Edit Deactivated Indent');
                }
              } }
              style={{ color: '#1890ff', fontSize: '14px' }} /><Divider type="vertical" /></>
          ):''}
          <Popconfirm onConfirm={e => { deleteIndent(rowData); }}
            title={
              rowData.isActive
                ? 'Are you sure to Deactivate Indent ?'
                : 'Are you sure to Activate Indent ?'
            }
          >
            <Switch size="default"
              className={rowData.isActive ? 'toggle-activated' : 'toggle-deactivated'}
              checkedChildren={<RightSquareOutlined type="check" />}
              unCheckedChildren={<RightSquareOutlined type="close" />}
              checked={rowData.isActive}
            />
          </Popconfirm>
          <Divider type="vertical" />
          <Link
            to={{
              pathname: "/indent-detail-view",
              state: rowData.indentId
            }}
          >
            <EyeOutlined type="view" name="detail view"
              onClick={() => {

                // if (rowData.isActive) {
                setPlantId(rowData);
                // } else { 
                //  AlertMessages.getErrorMessage('You Cannot Edit Deactivated Indent');
                // }
              }}
              style={{ color: '#1890ff', fontSize: '14px' }}
            />
          </Link>
          
        </span>
      )
    },
    {

    }
  ];

  const columnsSkelton2: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      responsive: ['md'],
      align: 'left',
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title: 'Indent Code',
      key: 'indentCode',
      dataIndex: 'indentCode',
      // responsive: ['sm'],
      width: 180,
      align: 'left',
      ...getColumnSearchProps('indentCode'),
      sorter: (a, b) => a.indentCode.localeCompare(b.indentCode),
      sortDirections: ['descend', 'ascend'],
      render: (text, record) => { return  record.indentCode ? record.indentCode : "-" }

    },
    {
      title: 'Indent Date',
      dataIndex: 'indentDate',
      key: 'indentDate',
      width: "200px",
      // responsive: ['sm'],
      align: 'left',
      sorter: (a, b) => moment(a.indentDate).unix() - moment(b.indentDate).unix(),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('indentDate'),
      render: (text, record) => { return  record.indentDate ? moment(record.indentDate).format('YYYY-MM-DD') : "-" },

    },
    {
      title: 'Indent By',
      dataIndex: 'indentByName',
      key: 'indentByName',
      width: 180,
      // responsive: ['sm'],
      align: 'left',
      sorter: (a, b) => a.indentByName.localeCompare(b.indentByName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('indentByName'),
      render: (text, record) => { return  record.indentByName ? record.indentByName : "-" }

    },
    {
      title: 'Count',
      dataIndex: 'expectedCount',
      key: 'expectedCount',
      width: 90,
      sorter: (a, b) => a.expectedCount - b.expectedCount,
        sortDirections: ['descend', 'ascend'],
      // responsive: ['sm'],
      align: 'left',
      render: (text, record) => { return  record.expectedCount ? record.expectedCount : "-" }
      
    },
    {
      title: 'Quantity',
      dataIndex: 'expectedQty',
      key: 'expectedQty',
      sorter: (a, b) => a.expectedQty - b.expectedQty,
        sortDirections: ['descend', 'ascend'],
      width: 90,
      // responsive: ['sm'],
      align: 'left',
      render: (text, record) => { return  record.expectedQty ? record.expectedQty : "-" }

    },
    {
      title: 'Unit',
      dataIndex: 'plant',
      key: 'plant',
      width:"180px",
      // responsive: ['sm'],
      align: 'left',
      render: (text, record) => { return  record.plant ? record.plant : "-" },
      filters: [
        {
          text: "BMR INDUSTRIES-IND",
          value: "BMR INDUSTRIES-IND",
        },

        {
          text: "SNOW WORLD",
          value: "SNOW WORLD",
        },
        {
          text: "BMRINDUSTRIES-EXP",
          value: "BMRINDUSTRIES-EXP",
        },

      ],
      filterMultiple: false,
      onFilter: (value, record) => {
        // === is not work
        return record.plant === value;
      },

    },
    {
      title: 'Supplier Type',
      dataIndex: 'supplierType',
      key: 'SupplierType',
      responsive: ['md'],
      width: 180,
      align: 'left',
      sorter: (a, b) => a.supplierType.localeCompare(b.supplierType),
      sortDirections: ['descend', 'ascend'],
      filters: [
        {
          text: SupplierType.Agent,
          value: SupplierType.Agent,
        },

        {
          text: SupplierType.Dealer,
          value: SupplierType.Dealer,
        },
        {
          text: SupplierType.Farmer,
          value: SupplierType.Farmer,
        },
      ],
      filterMultiple: false,
      onFilter: (value, record) => {
        // === is not work
        return record.supplierType === value;
      },


    },
    {
      title: 'Supplier Name',
      dataIndex: 'farmerName',
      key: 'farmerName',
      width: 180,
      align: 'left',
      sorter: (a, b) => {
        const aName = a.supplierType === SupplierTypeEnum.DEALER ? a.brokerName : a.farmerName;
        const bName = b.supplierType === SupplierTypeEnum.DEALER ? b.brokerName : b.farmerName;
        return aName.localeCompare(bName);
      },
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('farmerName'),
      render: (text, record) => {
        return <>{record.supplierType === SupplierTypeEnum.DEALER ? record.brokerName : text}</>
      },
    },
  
    {
      title: 'Harvest Date',
      dataIndex: 'harvestingDate',
      key: 'harvestingDate',
      responsive: ['md'],
      width: 180,
      align: 'left',
      sorter: (a, b) => moment(a.harvestingDate).unix() - moment(b.harvestingDate).unix(),
      sortDirections: ['descend', 'ascend'],
      render: (text, record) => { return moment(record.harvestingDate).format('YYYY-MM-DD') },
    },
    {
      title: 'Harvest Time',
      dataIndex: 'harvestingTime',
      key: 'harvestingTime',
      responsive: ['sm'],
      width: 180,
      align: 'left',
      // sorter: (a, b) => a.harvestingTime.localeCompare(b.harvestingTime),
      // sortDirections: ['descend', 'ascend'],
      filters: [
        {
          text: HarvestingTime.MORNING,
          value: HarvestingTime.MORNING,
        },

        {
          text: HarvestingTime.EVENING,
          value: HarvestingTime.EVENING,
        },
      ],
      filterMultiple: false,
      onFilter: (value, record) => {
        // === is not work
        return record.harvestingTime === value;
      },
      // ...getColumnSearchProps('status')
    },
    {
      title: 'Cancel Reason',
      dataIndex: 'reasonName',
      key: 'reasonName',
      width: 180,
      // responsive: ['sm'],
      align: 'left',
      sorter: (a, b) => a.reasonName.localeCompare(b.reasonName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('reasonName'),
      render: (text, record) => { return  record.reasonName ? record.reasonName : "-" },
    },
    {
      title: 'Status',
      dataIndex: 'grnCompleted',
      key: 'grnCompleted',
      // responsive: ['sm'],
      width: 180,
      align: 'left',
      render: (grnCompleted, rowData) => (
        <>
          {((rowData.vehicleAssigned === 1 && rowData.isVehicleRequired === 1) || rowData.isVehicleRequired === 0) && rowData.plantId != 0 && grnCompleted === 0 ?
            <span>
              {/* <Button size={'small'} title={'Click to add GRN'} icon={<ExclamationCircleOutlined />} onClick={() => {
                console.log(rowData)
                if (rowData.isActive) {
                  return <Link
                    to={{
                      pathname: "/rm-grn-form",
                      state: { id: rowData.indentId }
                    }}
                  />
                } else {
                  AlertMessages.getErrorMessage("You can't Create Grn For Deactivated Indent");
                }
              }}
                style={{ backgroundColor: '#e8e21e', color: "black", fontWeight: 'bold', fontSize: 'small' }}
              >
                Add GRN
              </Button> */}
              <Link
                to={`/rm-grn-form/${rowData.indentId}`}
              >
                <Button
                  size={'small'}
                  title={'Click to Add GRN'}
                  icon={<ExclamationCircleOutlined />}
                  style={{ backgroundColor: '#e8e21e', color: "black", fontWeight: 'bold', fontSize: 'small' }}
                >
                  Add GRN
                </Button>
              </Link>
            </span>

            : rowData.vehicleAssigned === 1 && rowData.plantId != 0 && grnCompleted === 1 ?
              <Tag
                icon={<CheckCircleOutlined />}
                style={{ backgroundColor: '#52c41a', color: "black", fontWeight: 'bold' }}
              >
                COMPLETED
              </Tag>
              : rowData.plantId === 0 ?
                <Button
                  size={'small'}
                  title={'Click to Assign Vehicle'}
                  icon={<ExclamationCircleOutlined />}
                  style={{ backgroundColor: '#08979c', color: "white", fontWeight: 'bold', fontSize: 'small' }}
                  onClick={() => {
                    if (rowData.isActive) {
                      openFormWithData(rowData);
                    } else {
                      AlertMessages.getErrorMessage('You Cannot Edit Deactivated Indent');
                    }
                  }}
                >
                  Assign Plant
                </Button>
                : rowData.vehicleAssigned === 0 && rowData.isVehicleRequired === 1 ?
                  <Link to="/vehicle-assignment">
                    <Button
                      size={'small'}
                      title={'Click to Assign Vehicle'}
                      icon={<ExclamationCircleOutlined />}
                      style={{ backgroundColor: '#faad14', color: "black", fontWeight: 'bold', fontSize: 'small' }}
                    >
                      Assign Vehicle
                    </Button>
                  </Link>
                  //  <Popover content={(rowData.isActive) ? content : 'Activate indent to create grn'} title={(rowData.isActive) ? "Vehicle is Not Assigned" : "You Can't Perform action on Deactivated Indent"} trigger="click">
                  //   <Tag icon={<ExclamationCircleOutlined />} style={{ backgroundColor: '#fa8c16', color: "black", fontWeight: 'bold' }}>PENDING</Tag>
                  //    </Popover>
                  : "-"}
        </>
      ),
    },
    // {
    //   title: 'Aging',
    //   key: 'age',
    //   // responsive: ['sm'],
    //   sorter: (a, b) => (Math.floor((new Date(moment(a.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) - Math.floor((new Date(b.harvestingDate).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))),
    //   sortDirections: ['descend', 'ascend'],
    //   // ...getColumnSearchProps('aging'),
    //   render(text, record) {
    //     const obj: any = {
    //       children: (<div style={{ textAlign: 'right' }}>{Math.floor((new Date(moment(record.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) + 1}</div>),
    //       props: {
    //         style: {
    //           background: Math.floor((new Date(moment(record.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) + 1 >= 0 ? "#38f438" : '#f4646c',
    //           color: Math.floor((new Date(moment(record.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) + 1 >= 0 ? "black" : 'white'
    //         }
    //       },
    //     };
    //     return obj;
    //   }
    // },
   
    {
      title: 'Farm Type',
      dataIndex: 'farmType',
      // key: 'farmType',
      // responsive: ['md'],
      width: 130,
      align: 'left',
      sorter: (a, b) => a.farmType - b.farmType,

      // sorter: (a, b) => a.farmType.localeCompare(b.farmType),
      sortDirections: ['descend', 'ascend'],
      // filters: [
      //   {
      //     text: FarmTypesEnum.OTHERS,
      //     value: FarmTypesEnum.OTHERS,
      //   },

      //   {
      //     text: FarmTypesEnum.OWN,
      //     value: FarmTypesEnum.OWN,
      //   }
      // ],
      filterMultiple: false,
      onFilter: (value, record) => {
        // === is not work
        return record.farmType === value;
      },
      render: (text, record) => { return  record.farmType ? record.farmType : "-" }



    },
  ];

  /**
   * 
   * @param pagination 
   * @param filters 
   * @param sorter 
   * @param extra 
   */
  const onChange = (pagination, filters, sorter, extra) => {
    console.log('params', pagination, filters, sorter, extra);
  }

  const setIndentId = (indentId: number) => {
    setIndentIdState(indentId);
    setIsModalVisible(true);
    // setCompName(compName);  
  }

  const openModal = () => {
    setIsModalVisible(true);
  }
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  // const tabOnchange = (value) => {
  //   console.log(value)
  //   if (value == 4) {
  //     getCompletedIndents();
  //   }
  // }
  const getCompletedIndents = () => {
    const req = new IndentHarvestingDateRangeReq()
    if (formCompletedIndents.getFieldValue('harvestingDate') !== undefined) {
      req.fromDate = moment(formCompletedIndents.getFieldValue('harvestingDate')[0]).format("YYYY-MM-DD")
      req.toDate = moment(formCompletedIndents.getFieldValue('harvestingDate')[1]).format("YYYY-MM-DD")

    }
    indentService.getCompletedIndents(req).then(res => {
      if (res.status) {
        if (role === '"ADMIN"' || role === '"INDENT PERSON"' || role === '"REWEIGHTMENT PERSON"') {
          console.log(role);
          console.log(res.data);
          setCompletedIndentData(res.data);
        }
        else {
          setCompletedIndentData(res.data.filter(rec => rec.plantId === null || rec.plantId === 0 || rec.plantId === Number(unitId)));
        }

        setAllData(res.data);
      } else {
        setAllData([]);
        if (res.intlCode) {
          setCompletedIndentData([]);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      setAllData([]);
      setIndentData([]);
      AlertMessages.getErrorMessage(err.message);
    })
  }
  const getCancelledIndents = () => {
    const req = new IndentHarvestingDateRangeReq()
    if (formCancelledIndents.getFieldValue('harvestingDate') !== undefined) {
      req.fromDate = moment(formCancelledIndents.getFieldValue('harvestingDate')[0]).format("YYYY-MM-DD")
      req.toDate = moment(formCancelledIndents.getFieldValue('harvestingDate')[1]).format("YYYY-MM-DD")

    }
    indentService.getCancelledIndents(req).then(res => {
      if (res.status) {
        if (role === '"ADMIN"' || role === '"INDENT PERSON"' || role === '"REWEIGHTMENT PERSON"') {
          console.log(role);
          console.log(res.data);
          setCancelledIndentData(res.data);
        }
        else {
          setCancelledIndentData(res.data.filter(rec => rec.plantId === null || rec.plantId === 0 || rec.plantId === Number(unitId)));
        }

        setAllData(res.data);
      } else {
        setCancelledIndentData([]);
        setAllData([]);
        if (res.intlCode) {
          setCompletedIndentData([]);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      setAllData([]);
      setIndentData([]);
      AlertMessages.getErrorMessage(err.message);
    })
  }
// const sum = (indentData && completedIndentData) ? [...indentData,...completedIndentData] : [0]
// console.log(sum)
// console.log(sum.length)
const sum = new Set([...(indentData || []), ...(completedIndentData || [])]);
const totalIndentsCount = sum.size;

const {Option}=Select;
// const [harvestDate,setHarvestDate]=useState<any[]>([])




// const getHarvestingDateDropdown = () => {
//    indentService.getAllIndents().then((res) => {
//      if (res.status) {
//        setHarvestDate(res.data);
//      } else {
//        setHarvestDate([]);
//      }
//    }).catch((err) => {
//      AlertMessages.getErrorMessage(err.message);
//      setHarvestDate([]);
//    });
//  }

const onReset = () => {
  form.resetFields();
  getAllIndentDetails();
};

const onResetClosedIndents = () => {
  formCompletedIndents.resetFields();
  getCompletedIndents();
};

const onResetCancelledIndents = () => {
  formCancelledIndents.resetFields();
  getCancelledIndents();
};

  return (
    <Layout style={{ padding: 10, backgroundColor: 'white', border: 10 }}>
      <Card title={<span style={{ color: 'white' }}>Indents</span>}
        style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }} extra={<Link to='/indent-form' ><span style={{ color: 'white' }} ><Button className='panel_button' >Create </Button> </span></Link>} >
        <br></br>
   <Row>        <Col>
  <Card title={'Total Indents: ' + totalIndentsCount} style={{ textAlign: 'left', width: 200, height: 41, backgroundColor: '#bfbfbf' }}></Card>
</Col></Row>
        <br></br>
        <ConfigProvider locale={enUSIntl}>
          <Tabs type={'card'} tabPosition={'top'} >
            <TabPane
              key="1"
              tab={<span style={{ color: "#f5222d" }}>Pending: {indentData?.length}</span>}
            >
                   <Form form={form} onFinish={getAllIndentDetails} >
        <Row gutter={24}>

<Col>
<Form.Item label="Harvest Date" name="harvestingDate">
                <RangePicker />
              </Form.Item>
</Col>
<Col >
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                style={{ background: "green", width: "100%" }}
              >
                Search
              </Button>
            </Form.Item>
          </Col>
          <Col >
            <Form.Item>
              <Button
                danger
                // icon={<UndoOutlined />}
                onClick={onReset}
                style={{ width: "100%" }}
              >
                Reset
              </Button>
            </Form.Item>
          </Col>
        </Row>
        </Form>
              <Table<IndentModel>
                rowKey={record => record.indentId}
                columns={columnsSkelton}
                dataSource={indentData}
                pagination={{
                  onChange(current) {
                    setPage(current);
                  }
                }}
                // request={(params, sorter, filter) => {
                //   return Promise.resolve({
                //     data: indentData,
                //     success: true,
                //   });
                // }}

                // dateFormatter='string'
                // search={{
                //   searchText: 'Filter',
                // }}
                // onSubmit={(params) => {
                //   if (Object.keys(params).length) {
                //     let filteredData = [];
                //     if (params.indentDate && params.harvestingDate && params.indentCode && params.age) {
                //       filteredData = indentData.filter((record) => {
                //         if (moment(record.indentDate).format('YYYY-MM-DD') === params.indentDate && (moment(record.harvestingDate).format('YYYY-MM-DD') >= params.harvestingDate[0]) && (moment(record.harvestingDate).format('YYYY-MM-DD') <= params.harvestingDate[1]) && (record.indentCode.includes(params.indentCode)) && (Math.floor((new Date(moment(record.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) + 1 === params.age)) {
                //           return record;
                //         }
                //       });
                //     } else if (params.indentDate) {
                //       filteredData = indentData.filter((record) => {
                //         if ((moment(record.indentDate).format('YYYY-MM-DD') >= params.indentDate[0]) && (moment(record.indentDate).format('YYYY-MM-DD') <= params.indentDate[1])) {
                //           return record;
                //         }
                //       });
                //       // filteredData = indentData.filter(record => moment(record.indentDate).format('YYYY-MM-DD') === params.indentDate);
                //     } else if (params.harvestingDate) {
                //       filteredData = indentData.filter((record) => {
                //         if ((moment(record.harvestingDate).format('YYYY-MM-DD') >= params.harvestingDate[0]) && (moment(record.harvestingDate).format('YYYY-MM-DD') <= params.harvestingDate[1])) {
                //           return record;
                //         }
                //       });
                //     } else if (params.indentCode) {
                //       filteredData = indentData.filter(record => record.indentCode.includes(params.indentCode))
                //     } else if (params.age) {
                //       filteredData = indentData.filter(record => {
                //         const age = Math.floor((new Date(moment(record.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) + 1;
                //         if (age.toString() === params.age) {
                //           return record;
                //         }
                //       })
                //     }
                //     setIndentData(filteredData);
                //   }
                // }}
                // onReset={() => {
                //   setIndentData(allData);
                // }}
                scroll={{ x: 1200, y: 500 }} />
            </TabPane>
            <TabPane
              key="4"
              tab={<span style={{ color: "green" }}>Completed: {completedIndentData.length}</span>}
            >
                              <Form form={formCompletedIndents} onFinish={getCompletedIndents} >
        <Row gutter={24}>

<Col>
<Form.Item label="Harvest Date" name="harvestingDate">
                <RangePicker />
              </Form.Item>
</Col>
<Col >
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                style={{ background: "green", width: "100%" }}
              >
                Search
              </Button>
            </Form.Item>
          </Col>
          <Col >
            <Form.Item>
              <Button
                danger
                // icon={<UndoOutlined />}
                onClick={onResetClosedIndents}
                style={{ width: "100%" }}
              >
                Reset
              </Button>
            </Form.Item>
          </Col>
        </Row>
        </Form>
              <Table<IndentModel>
                rowKey={record => record.indentId}
                columns={columnsSkelton1}
                dataSource={completedIndentData}
                pagination={{
                  onChange(current) {
                    setPage(current);
                  }
                }}
                // onSubmit={(params) => {
                //   if (Object.keys(params).length) {
                //     let filteredData = [];
                //     if (params.indentDate && params.harvestingDate && params.indentCode && params.age) {
                //       filteredData = indentData.filter((record) => {
                //         if (moment(record.indentDate).format('YYYY-MM-DD') === params.indentDate && (moment(record.harvestingDate).format('YYYY-MM-DD') >= params.harvestingDate[0]) && (moment(record.harvestingDate).format('YYYY-MM-DD') <= params.harvestingDate[1]) && (record.indentCode.includes(params.indentCode)) && (Math.floor((new Date(moment(record.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) + 1 === params.age)) {
                //           return record;
                //         }
                //       });
                //     } else if (params.indentDate) {
                //       filteredData = indentData.filter((record) => {
                //         if ((moment(record.indentDate).format('YYYY-MM-DD') >= params.indentDate[0]) && (moment(record.indentDate).format('YYYY-MM-DD') <= params.indentDate[1])) {
                //           return record;
                //         }
                //       });
                //       // filteredData = indentData.filter(record => moment(record.indentDate).format('YYYY-MM-DD') === params.indentDate);
                //     } else if (params.harvestingDate) {
                //       filteredData = indentData.filter((record) => {
                //         if ((moment(record.harvestingDate).format('YYYY-MM-DD') >= params.harvestingDate[0]) && (moment(record.harvestingDate).format('YYYY-MM-DD') <= params.harvestingDate[1])) {
                //           return record;
                //         }
                //       });
                //     } else if (params.indentCode) {
                //       filteredData = indentData.filter(record => record.indentCode.includes(params.indentCode))
                //     } else if (params.age) {
                //       filteredData = indentData.filter(record => {
                //         const age = Math.floor((new Date(moment(record.harvestingDate).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) + 1;
                //         if (age.toString() === params.age) {
                //           return record;
                //         }
                //       })
                //     }
                //     setIndentData(filteredData);
                //   }
                // }}
                // onReset={() => {
                //   setIndentData(allData);
                // }}
                scroll={{ x: 1200, y: 500 }} />
            </TabPane>
            <TabPane
              key="5"
              tab={<span style={{ color: "orange" }}>Cancelled: {cancelledIndentData.length}</span>}
            >
                                        <Form form={formCancelledIndents} onFinish={getCancelledIndents} >
        <Row gutter={24}>

<Col>
<Form.Item label="Harvest Date" name="harvestingDate">
                <RangePicker />
              </Form.Item>
</Col>
<Col >
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                style={{ background: "green", width: "100%" }}
              >
                Search
              </Button>
            </Form.Item>
          </Col>
          <Col >
            <Form.Item>
              <Button
                danger
                // icon={<UndoOutlined />}
                onClick={onResetCancelledIndents}
                style={{ width: "100%" }}
              >
                Reset
              </Button>
            </Form.Item>
          </Col>
        </Row>
        </Form>
              <Table<IndentModel>
                rowKey={record => record.indentId}
                columns={columnsSkelton2}
                dataSource={cancelledIndentData}
                pagination={{
                  onChange(current) {
                    setPage(current);
                  }
                }}
                scroll={{ x: 1200, y: 500 }}/>
            </TabPane>
          </Tabs>
        </ConfigProvider>
        <Drawer bodyStyle={{ paddingBottom: 80 }} title='Update' width={window.innerWidth > 768 ? '65%' : '100%'}
          onClose={closeDrawer} visible={drawerVisible} closable={true}>
          <Card headStyle={{ textAlign: 'center', fontWeight: 500, fontSize: 16 }} size='small'>
            <IndentForm key={Date.now()}
              isUpdate={true}
              indentData={selectedIndentData}
              // updateIndent={updateIndent}
              closeDrawer={closeDrawer}
            />

          </Card>
        </Drawer>
      </Card>
      {isModalVisible ?
        <Modal
          key={'modal' + Date.now()}
          width={'80%'}
          style={{ top: 30, alignContent: 'right' }}
          visible={isModalVisible}
          title={<React.Fragment>
          </React.Fragment>}
          onCancel={handleCancel}
          footer={[

          ]}
        >
          <RawMaterialGrnForm key={Date.now()}
            updateItem={undefined}
            isUpdate={false}
            grnData={undefined}
            closeForm={closeDrawer}
            indentId={indentId} />
        </Modal> : ""}
        <Modal key={1} width={'60%'} visible={cancelModal} title={'Cancel Reason'} onCancel={onCancelModalClose} footer={null}>
            <Form form={cancelForm} onFinish={onCancelReasonModalOk}>
                <Row gutter={24}>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 12 }}>
                        <Form.Item name='cancelReason' label='Cancel Reason' rules={[{required:true,message:'Cancel Reason is mandatory'}]}>
                            {/* <TextArea rows={4}/> */}
                            <Select showSearch allowClear placeholder="Select Cancel Reason" onChange={onCancelReasonChange}>
                                {cancelReasons.map(e => {
                                    return(
                                        <Option key={e.reasonId} value={e.reasonId} reasonName={e.reasonName}>{e.reasonName} </Option>
                                    )
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                        <Form.Item >
                            <Button type='primary' htmlType='submit'>Save</Button>
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
            
        </Modal>
    </Layout>
  );
}

export default IndentGrid;
