import React, { useState, useEffect, useRef } from 'react';
import { Divider, Popconfirm, Card, Tooltip, Switch, Input, Button, Tag, Row, Col, Drawer, Space, Tabs, Form, DatePicker, Select, Spin, Modal } from 'antd';
import Highlighter from 'react-highlight-words';
import { ColumnProps } from 'antd/lib/table';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { useIntl } from 'react-intl';
import { CheckCircleOutlined, CheckOutlined, CloseCircleOutlined, RightSquareOutlined, EyeOutlined, EditOutlined, CheckCircleTwoTone, SearchOutlined, RollbackOutlined, UndoOutlined } from '@ant-design/icons';
import { CSVLink } from 'react-csv';
// import { AiOutlineProfile } from 'react-icons/ai';

import { Redirect, useHistory, useLocation } from 'react-router-dom';
import { Table } from "ant-table-extensions";
import { FormattedMessage } from 'react-intl';
import { DestinationService, EndCustomersService, UnitcodeService } from '@gtpl/shared-services/masters';
import { DestinationDto, EndCustomerDto, EndCustomersDropDownData } from '@gtpl/shared-models/masters';
import moment from 'moment';
import { ContainerStatusEnum, ContainerLoadingStatus, EmployeeRolesEnum, GlobalStatus, UnitRequest } from '@gtpl/shared-models/common-models';
import { ContaierRegisterRequest, ContainerStatusInfo, FilenameDto } from '@gtpl/shared-models/logistics';
import { ContainerRegisterService } from '@gtpl/shared-services/logistics';
import { SaleOrderService } from '@gtpl/shared-services/sale-management';
import { SaleOrderDropDownDto, SODto } from '@gtpl/shared-models/sale-management';
import { CaptureGrossWeightForm } from '@gtpl/pages/logistics/logistics-components/capture-gross-weight-form'
import Link from 'antd/lib/typography/Link';
import { SoInfoViewPages } from '@gtpl/pages/sale-management/sale-pages/so-info-view-pages'
import './container-register-grid.css';
import appSettings from 'apps/services/config';
import { FoodTypesDto, PlantsDropDown, ProductDto } from '@gtpl/shared-models/masters';
import ArrowDownOutlined from '@ant-design/icons/lib/icons/ArrowDownOutlined';
// import{saleOrderIdRequest} from "@gtpl/shared-models/logistics"
/* eslint-disable-next-line */
import { SaleOrderIdRequest as saleOrderIdRequest } from 'libs/shared-models/logistics/src/lib/container-register/container.request';
import { PurchasesProductService } from '@gtpl/shared-services/finance';

export interface ContainerRegisterGridProps { }

export function ContainerRegisterGrid(props: ContainerRegisterGridProps) {

  const [defaultTab, setDefaultTab] = useState<string>('0');
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const [object, setObject] = useState(null);

  const searchInput = useRef(null);
  const [page, setPage] = React.useState(1);
  const { TabPane } = Tabs;
  const [updateState, setUpdateState] = useState(false);
  const [coId1, setCoIdState1] = useState<number>(null);
  const [coId2, setCoIdState2] = useState<number>(null);
  const [coId3, setCoIdState3] = useState<number>(null);
  const [coId4, setCoIdState4] = useState<number>(null);
  const [coId5, setCoIdState5] = useState<number>(null);
  const [coId6, setCoIdState6] = useState<number>(null);
  const [coId7, setCoIdState7] = useState<number>(null);
  const [coId8, setCoIdState8] = useState<number>(null);
  const [coId9, setCoIdState9] = useState<number>(null);
  const [disable, setDisable] = useState<boolean>(false);
  const [open, setOpen] = useState(false);
  let location = useLocation();
  const { RangePicker } = DatePicker;
  const role = JSON.parse(localStorage.getItem('role'))
  const unitId = JSON.parse(localStorage.getItem('unit_id'))
  const [selectedUnitName, setSelectedUnitName] = useState<any | undefined>(undefined);
  const [unitIdToSend, setUnitIdToSend] = useState<any | undefined>(unitId!=1?unitId:undefined);
  // setDefaultTab("3");
  const [etdFromDate, setEtdFromDate] = useState(undefined);
  const [etdToDate, setEtdToDate] = useState(undefined);
  const [destination, setDestination] = useState(undefined);
  const [saleOrderId, setSaleOrderId] = useState(undefined)
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [isModalVisible1, setIsModalVisible1] = useState<boolean>(false);
  const [containerData, setContainerData] = useState<ContainerStatusInfo[]>([]);
  const [filtersData, setFiltersData] = useState<ContainerStatusInfo[]>([]);
  const [destinationData, setDestinationData] = useState<DestinationDto[]>([]);
  const [destinationDetails, setDestinationDetails] = useState<string[]>([]);
  const [etdData, setEtdData] = useState<string[]>([]);
  const destinationservice = new DestinationService();
  // const  containerStatusInfo = new ContainerStatusInfo();
  const history = useHistory();
  const text = <span>Set Previous Status</span>
  const [saleId, setSaleId] = useState(0);
  const [modelType, setModelType] = useState<string>('');
  const [plantData, setPlantData] = useState<PlantsDropDown[]>([]);
  const [check, setCheck] = useState<any>([])
  const [years,setYears] = useState<any[]>([])
  const [form] = Form.useForm();
  const { Option } = Select;
  const [selectedFromDate, setSelectedFromDate] = useState(undefined);
  const [selectedToDate, setSelectedToDate] = useState(undefined);
  const [dateKey, setDateKey] = useState(0);
  const service = new ContainerRegisterService();
  const saleService = new SaleOrderService();
  const unitService = new UnitcodeService();
  const [factoriesData, setFactoriesData] = useState([]);
  const purchaseService = new PurchasesProductService()
  const [selectedStatus, setSelectedStatus] = useState(ContainerStatusEnum.READY_TO_BOOK); // default tab
  const [containerStatusCount,setContainerStatusCount] = useState<any>([]);

  const tabKeyToStatus = {
  "1": ContainerStatusEnum.NOT_READY,
  "2": ContainerStatusEnum.READY_TO_BOOK,
  "3": ContainerStatusEnum.BOOKED,
  "5": ContainerStatusEnum.LOADING,
  "6": ContainerStatusEnum.LOADED_AND_SEALED,
  "7": ContainerStatusEnum.SHIPPED
};


  const showModal = (val) => {
    setOpen(true)
    setIsModalVisible1(true);
    getActiveCheckList(val);
    console.log(val, ']]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]');
    // service.checkListInfo().then((res)=>{
    //   if(res.status){
    //    setCheck(res.data);
    //   }else{
    //     if(res.intlCode){
    //     AlertMessages.getErrorMessage(res.internalMessage);

    //   }else{
    //     AlertMessages.getErrorMessage(res.internalMessage);
    //   }
    //   setCheck([]);
    // }})
    // .catch(err) =>{
    //   AlertMessages.getErrorMessage(err.message);
    //   setCheck ([]);
    // }

  };

  useEffect(() => {
    getContainerStatusCount();
  },[])

   const getContainerStatusCount = () => {
     const companyId = form.getFieldValue("companyId") || null;
    const destinationId = form.getFieldValue("destination") || null;
    const financialYear = form.getFieldValue('financialYear')
    const unitReq = new UnitRequest(unitIdToSend,role, null, null, null, companyId, destinationId,selectedFromDate, selectedToDate,financialYear);
    service.getContainerStatusCount(unitReq).then((res) => {
      if (res.status) {
        setContainerStatusCount(res.data);
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);

        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
        setContainerStatusCount([]);
      }
    })


  }
  const getActiveCheckList = (val) => {
    const req = new saleOrderIdRequest(val)
    service.checkListInfo(req).then((res) => {
      if (res.status) {
        setCheck(res.data);
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);

        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
        setCheck([]);
      }
    })


  }

  const handleUnit = (value) => {
    if (unitId ===1) {
        setUnitIdToSend(value === 'all' ? undefined : Number(value));
    } else {
        setUnitIdToSend(Number(unitId));
    }
};

  const handleOk = () => {
    setIsModalVisible1(false);
    setOpen(false);
  };

  const handleCancel1 = () => {
    setIsModalVisible1(null);
  };

  // const download = (filePath) => {
  //   console.log(filePath);

  //   if (filePath) {
  //     filePath = filePath.split(",");
  //     for (const res of filePath) {
  //       if (res) {
  //         console.log(res);
  //         setTimeout(() => {
  //           const response = {
  //             file: appSettings.logistics_doc_upload_path + `${res}`,
  //           };

  //           window.open(response.file);

  //         }, 100);
  //       }
  //     }
  //   }
  //   else {
  //     AlertMessages.getErrorMessage("Please upload file. ");

  //   }
  // }
  

  const download = (filePath) => {
    console.log(filePath);
  
    if (filePath) {
      // Ensure filePath is an array
      if (typeof filePath === "string") {
        filePath = filePath.split(",");
      }
  
      for (const res of filePath) {
        if (res) {
          console.log(res);
          setTimeout(() => {
            const response = {
              file: appSettings.logistics_doc_upload_path + `${res}`,
            };
  
            window.open(response.file);
          }, 100);
        }
      }
    } else {
      AlertMessages.getErrorMessage("Please upload file.");
    }
  };
  


  // const download = (filePath) => {
  //   console.log(filePath);
  //   // : FilenameDto[]

  //   if (filePath) {
  //     filePath = filePath.split(",");
  //     for (const res of filePath) {
  //       if (res) {
  //         console.log(res);
  //         setTimeout(() => {
  //           const response = {
  //             file: appSettings.logistics_doc_upload_path + `${res}`,
  //           };

  //           window.open(response.file);

  //         }, 100);
  //       }
  //     }
  //   }
  //   else {
  //     AlertMessages.getErrorMessage("Please upload file. ");

  //   }
  // }


  const getColumnSearchProps = (dataIndex: string) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={searchInput}
          placeholder={`Sea ${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);
    console.log(dataIndex);
  };

  function handleReset(clearFilters) {
    clearFilters();
    setSearchText('');
  };


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


  // const searchData = () => {
  //   console.log("hai....")
  //   const selectedEtdFromDate = moment(form.getFieldValue('etdDateRange')[0]).format("YYYY-MM-DD");
  //   const selectedEtdToDate = moment(form.getFieldValue('etdDateRange')[1]).format("YYYY-MM-DD");
  //   const destination = form.getFieldValue('destination');
  //   const plantName = form.getFieldValue('plantName');
  //   console.log(selectedEtdToDate, selectedEtdFromDate, destination,plantName);
  //   let selectedData = filtersData;
  //   if (selectedEtdFromDate && selectedEtdToDate) {
  //     selectedData = filtersData.filter(item => moment(item.etd).format("YYYY-MM-DD") > selectedEtdFromDate && moment(item.etd).format("YYYY-MM-DD") <= selectedEtdToDate)
  //   }
  //   if (destination) {
  //     selectedData = selectedData.filter(item => item.destination === destination)
  //   }
  //   if (plantName) {
  //     selectedData = selectedData.filter(item => item.plant === plantName)
  //   }

  //   setContainerData(selectedData);
  // }
  // const searchData = () => {
  // console.log("hai....")
  
  // Retrieve form values
//   const etdDateRange = form.getFieldValue('etdDateRange') || [];
//   const destinations = form.getFieldValue('destination');
//   const plantName = form.getFieldValue('plantName');
//   const companyId = form.getFieldValue("companyId");
//   // Make sure both dates are available before formatting
//   const selectedEtdFromDate = etdDateRange[0] ? moment(etdDateRange[0]) : null;
//   const selectedEtdToDate = etdDateRange[1] ? moment(etdDateRange[1]) : null;

//   console.log(selectedEtdFromDate, selectedEtdToDate, destinations, plantName,companyId);

//   // Initialize selectedData with the full dataset
//   let selectedData = filtersData;

//   // Date filtering (ensure both dates are available before applying filter)
//   if (selectedEtdFromDate && selectedEtdToDate) {
//     selectedData = selectedData.filter(item => {
//       const itemEtd = moment(item.etd); // Ensure `item.etd` is parsed as a moment object
//       return itemEtd.isAfter(selectedEtdFromDate, 'day') && itemEtd.isSameOrBefore(selectedEtdToDate, 'day');
//     });
//   }

//   // Destination filtering
//   if (destinations) {

//     // selectedData = selectedData.filter(item => item.destination === destination);
//     selectedData = selectedData.filter(item => {
//       const itemDestination = item.destination.split(',')[0].trim().toLowerCase(); // Extract city and normalize
//       const normalizedDestination = destination.trim().toLowerCase(); // Normalize the form value
//       return itemDestination === normalizedDestination;
//     });
//   }

//   // Plant name filtering
//   if (plantName) {
//     // selectedData = selectedData.filter(item => item.plant === plantName);
//     selectedData = selectedData.filter(item => {
//       const itemPlant = item.plant ? item.plant.trim().toLowerCase() : ''; // Normalize the plant value
//       const normalizedPlantName = plantName.trim().toLowerCase(); // Normalize the form value
//       return itemPlant === normalizedPlantName;
//     });
//   }
//   if (companyId) {
//     selectedData = selectedData.filter((item) => item.companyId === companyId);
//   }
//   // Update the state with filtered data
//   setContainerData(selectedData);
// };


  // useEffect(() => {
  //   getFiltersDropdownData(filtersData);
  // }, [filtersData])

  const getFiltersDropdownData = (filtersData) => {
    let etdData: any[] = [];
    let destinationData: any[] = [];
    filtersData.forEach(element => {
      if (element.etd > etdFromDate && element.etd < etdToDate) {
        etdData.push(element.etd)
      }
      if (element.destination) {
        destinationData.push(element.destination)
      }
    });
    setDestinationDetails(destinationData)
    setEtdData(etdData)
  }


  useEffect(() => {
    let state = location.state != undefined ? location.state : "Ready to Book";
    const locationDefaultState = state;
    if (locationDefaultState != undefined) {
      if (locationDefaultState === "BOOKED") {
        setDefaultTab("3");
      } else if (locationDefaultState === "Containers in Plant") {
        setDefaultTab("4");
      } else if (locationDefaultState === "Ready to Book") {
        setDefaultTab("2");
      } else if (locationDefaultState === "Loading") {
        setDefaultTab("5");
      } else {
        setDefaultTab("2");
      }
    }
    getFinalDestinationData();
    getAllPlants();
    form.setFieldsValue({ unit: 'all' });
    handleUnit('all');
    getAllCompanyNames()
    getAllFinancialYear()
  }, [])
//   useEffect(() => {
//     if (unitIdToSend === undefined) { 
//         getAllContainerStatus();
//     }
// }, [unitIdToSend]);

  useEffect(() => {
        getAllContainerStatus();
}, []);
  const getAllContainerStatus = (statusParam?: any) => {
    const statusToSend = statusParam || selectedStatus; 
    const companyId = form.getFieldValue("companyId") || null;
    const destinationId = form.getFieldValue("destination") || null;
    const financialYear = form.getFieldValue('financialYear')
    const unitReq = new UnitRequest(unitIdToSend,role, null, null, null, companyId, destinationId,selectedFromDate, selectedToDate,financialYear,statusToSend);

    service.getAllContainerStatusInfo(unitReq).then(res => {
      console.log(unitIdToSend,role,'0000000000000000')
      if (res.status) {
        for (const containerData of res.data) {
          const destinationPlace = `${containerData.destination}, ${containerData.country}`;
          containerData.destination = destinationPlace
          
        }
        setContainerData(res.data);
        // setFiltersData(res.data);
        console.log(res.data);
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.message);
        } else {
          AlertMessages.getErrorMessage(res.message);
        }
        setContainerData([]);
        setFiltersData([]);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
      setContainerData([]);
      setFiltersData([]);
    })
  }
  const getAllFinancialYear  = () => {
    saleService.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 getAllPlants = () => {
    unitService.getAllMainPlants().then((res) => {
      if (res.status) {
        setPlantData(res.data);
      } else {
        setPlantData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setPlantData([]);
    });
  }
  const getAllCompanyNames = () => {
    purchaseService.getAllCompanys().then((res) => {
        if (res.status) {
            setFactoriesData(res.data)
        }
    })
}
  const [activeTab, setActiveTab] = useState('1');

  const handleRollback = (rowData) => {
    setContainerData(prevData =>
      prevData.map(row =>
        row.saleOrderNumber === rowData.saleOrderNumber
          ? { ...row, containerStatus: ContainerStatusEnum.NOT_READY }
          : row
      )
    );
    setActiveTab('1'); // Ensure the active tab is set to "Open" tab
  };

  const revertContainerStatus = (rowData) => {
    setContainerData(containerData.map(item => item.saleOrderNumber === rowData.saleOrderNumber ? { ...item, containerStatus: ContainerStatusEnum.NOT_READY } : item));
  };

  const updateToReadyToBook = (values) => {
    service.updateToReadyToBook(values).then(res => {
      if (!res.status) {
        throw new Error(res.internalMessage);
      } else {
        getAllContainerStatus();
        getContainerStatusCount()
        AlertMessages.getSuccessMessage(res.internalMessage);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }

  const updateToOpenStatus = (values) => {
    saleService.updateToOpenStatus(values).then(res => {
      if (!res.status) {
        throw new Error(res.internalMessage);
      } else {
        getAllContainerStatus();
        getContainerStatusCount()
        AlertMessages.getSuccessMessage(res.internalMessage);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }

  const updateContainerStatusReadyToBook = (values) => {
    // if(	Number(values.fgQty) < (Number(values.poQty) / 2 ))
    // if(Number(values.percent)>70)
    //  {

    saleService.updateContainerStatusReadyToBook(values).then(res => {
      if (!res.status) {
        throw new Error(res.internalMessage);
      } else {
        getAllContainerStatus();
        getContainerStatusCount()
        AlertMessages.getSuccessMessage(res.internalMessage);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }
  // else{
  //   return AlertMessages.getInfoMessage('FG Qty should be grater than 70% of PO qty')
  // }


  const updateToBooked = (values) => {
    service.updateToBooked(values).then(res => {
      if (!res.status) {
        throw new Error(res.internalMessage);
      } else {
        getAllContainerStatus()
        getContainerStatusCount()
        AlertMessages.getSuccessMessage(res.internalMessage);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }
  const updateStatusToLoading = (values) => {
    service.updateStatusToLoading(values).then(res => {
      if (!res.status) {
        throw new Error(res.internalMessage);
      } else {
        getAllContainerStatus()
        getContainerStatusCount()
        AlertMessages.getSuccessMessage(res.internalMessage);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }

  const updateStatusToDispatchedToPlant = (values) => {
    service.updateToDispatchedToPlant(values).then(res => {
      if (!res.status) {
        throw new Error(res.internalMessage);
      } else {
        getAllContainerStatus()
        getContainerStatusCount()
        AlertMessages.getSuccessMessage(res.internalMessage);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }

  const updateToLoading = (values) => {

    service.updateToLoading(values).then(res => {
      if (!res.status) {
        throw new Error(res.internalMessage);
      } else {
        getAllContainerStatus()
        getContainerStatusCount()
        AlertMessages.getSuccessMessage(res.internalMessage);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })

  }

  const updateToLoadedAndSealed = (values) => {
    service.updateToLoadedAndSealed(values).then(res => {
      if (!res.status) {
        throw new Error(res.internalMessage);
      } else {
        getAllContainerStatus()
        getContainerStatusCount()
        AlertMessages.getSuccessMessage(res.internalMessage);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }

  const getFinalDestinationData = () => {
    destinationservice.getAllActiveDestination().then((res) => {
      if (res.status) {
        setDestinationData(res.data);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setDestinationData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setDestinationData([]);
    });
  }

  const setUpdatevalue = (rowdata) => {
    setUpdateState(true);
    setObject(rowdata)
  }

  const setCoId1 = (rowdata) => {
    setUpdateState(true);
    setCoIdState1(rowdata)
  }
  const captureGrossWeight = (saleOrderId) => {
    console.log(saleOrderId)
    setIsModalVisible(true);
    // setBookSlot(true);
    setSaleOrderId(saleOrderId);
    setModelType('gross-weight-form')
  }
  const setCoId2 = (rowdata) => {
    setUpdateState(true);
    setCoIdState2(rowdata)
  }
  const setCoId3 = (rowdata) => {
    setCoIdState3(rowdata)
  }
  const setCoId4 = (rowdata) => {
    setUpdateState(true);
    setCoIdState4(rowdata)
    service.initiateDispatch(rowdata).then(res => {
      if (!res.status) {
        throw new Error(res.internalMessage);
      } else {
        getAllContainerStatus()
        getContainerStatusCount()

        AlertMessages.getSuccessMessage(res.internalMessage);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }
  const setCoId5 = (rowdata) => {
    setUpdateState(true);
    setCoIdState5(rowdata)
  }
  // const setCoId7 = (rowdata) => {
  //   setUpdateState(true);
  //   setCoIdState7(rowdata)
  // }
  const setCoId7 = (rowdata) => {
    setDisable(true);
    if (rowdata.isInvoiced == GlobalStatus.YES) {
      setUpdateState(true);
    setCoIdState7(rowdata)
      //     service.checkListInfo(rowdata).then(res => {
      //   if (!res.status) {
      //     throw new Error(res.internalMessage);
      //   } else {
      //     setDisable(false);
      //     // getAllContainerStatus()

      //     AlertMessages.getSuccessMessage(res.internalMessage);
      //   }
      // }).catch(err => {
      //   AlertMessages.getErrorMessage(err.message);
      // })
    } else {
      AlertMessages.getErrorMessage('Invoice should be done to check list');
    }
  }
  const setCoId8 = (rowdata) => {
    setDisable(true);
    if (rowdata.isInvoiced == GlobalStatus.YES) {
    setUpdateState(true);
    setCoIdState8(rowdata)
    }else {
      AlertMessages.getErrorMessage('Invoice should be done to Update Shippment Details');
    }
  }
  const setCoId9 = (rowdata) => {
    setUpdateState(true);
    setCoIdState9(rowdata)
  }
  const setCoId6 = (rowdata) => {
    setDisable(true);
    console.log(rowdata)
    if (rowdata.isInvoiced == GlobalStatus.YES) {
      setUpdateState(true);
      setCoIdState6(rowdata)
      service.shipContainer(rowdata).then(res => {
        if (!res.status) {
          throw new Error(res.internalMessage);
        } else {
          setDisable(false);
          getAllContainerStatus()
          getContainerStatusCount()

          AlertMessages.getSuccessMessage(res.internalMessage);
        }
      }).catch(err => {
        AlertMessages.getErrorMessage(err.message);
      })
    } else {
      AlertMessages.getErrorMessage('Invoice should be done to ship the container');
    }
  }

  const handleDestination = (value) => {
    console.log(value)
    setDestination(value)
  }

  const EstimatedDate = (value) => {
    if (value) {
      const fromDate = new Date(value[0].format('YYYY-MM-DD'));
      const toDate = new Date(value[1].format('YYYY-MM-DD'));
      setSelectedFromDate(fromDate);
      setSelectedToDate(toDate);
    } else {
      setSelectedFromDate(null);
      setSelectedToDate(null);
    }
  }

  const tableColumns = (key) => {
    const readyToBookColumns: ColumnProps<any>[] = [
      {
        title: 'S No',
        key: 'saleId',
        width: '60px',
        fixed:'left',
        render: (text, object, index) => (page - 1) * 10 + (index + 1)
      },

      {
        title: 'Customer PO',
        dataIndex: 'poNo',
        key: 'poNo',
        width: 150,
        // align:'left',
        fixed:'left',
        sorter: (a, b) => a.poNo?.localeCompare(b.poNo),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('poNo'),
        render:(text, data, index)=>{
          console.log(data)
          return <span>{text ? text :"-"}</span>
        }

      },
      {
        title: 'Buyer PO',
        dataIndex: 'buyerPoNo',
        key: 'buyerPoNo',
        width: 150,
        // align:'left',
        sorter: (a, b) => a.buyerPoNo?.localeCompare(b.buyerPoNo),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('buyerPoNo'),
        render:(text, data, index)=>{
          console.log(data)
          return <span>{text ? text :"-"}</span>
        }
      },
      {
        title: 'Invoice Number',
        dataIndex: 'invoiceNumber',
        key: 'invoiceNumber',
        width: 150,
        // align:'left',
        sorter: (a, b) => a.invoiceNumber?.localeCompare(b.invoiceNumber),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('invoiceNumber'),
        render:(text, data, index)=>{
          console.log(data)
          return <span>{text ? text :"-"}</span>
        }
      },
      {
        title: 'ETD',
        dataIndex: 'etd',
        key: 'etd',
        width: 180,
        align: 'left',
        sorter: (a, b) => moment(a.etd).unix() - moment(b.etd).unix(),
        sortDirections: ['descend', 'ascend'],
        render: (value, record: ContainerStatusInfo, index) => {
          return (record.etd) ? moment(record.etd).format("YYYY-MM-DD") : ' - ';
        },
      },


      {
        title: 'Destination',
        dataIndex: 'destination',
        key: 'destination',
        width: 150,
        ...getColumnSearchProps('destination'),
        sorter: (a, b) => a.destination?.localeCompare(b.destination),
        sortDirections: ['descend', 'ascend'],
        render: (text, data, index) => {
          return <span>{text}</span>
        }

      },

      {
        title: 'End Customer',
        dataIndex: 'endCustomer',
        key: 'endCustomer',
        width: 150,
        ...getColumnSearchProps('endCustomer'),
        sorter: (a, b) => a.endCustomer?.localeCompare(b.endCustomer),
        sortDirections: ['descend', 'ascend'],

      },
    ]
    const bookedColumns: ColumnProps<any>[] = [
      {
        title: 'Reference No',
        dataIndex: 'referenceNumber',
        width: 150,
        sorter: (a, b) => a.referenceNumber?.localeCompare(b.referenceNumber),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('referenceNumber'),
        render: (value, record: ContainerStatusInfo, index) => {
          return (record.referenceNumber) ? record.referenceNumber : ' - ';
        },
      },
      {
        title: 'SCAC',
        dataIndex: 'scac',
        width: 150,
        sorter: (a, b) => a.scac?.localeCompare(b.scac),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('scac'),
        render: (value, record: ContainerStatusInfo, index) => {
          return (record.scac) ? record.scac : ' - ';
        },
      },
      {
        title:'Mode of Export',
        dataIndex:'modeOfExport',
        width: 170,
        sorter: (a, b) => a.modeOfExport?.localeCompare(b.modeOfExport),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('modeOfExport'),
        render: (value, record: ContainerStatusInfo, index) => {
          return (record.modeOfExport) ? record.modeOfExport : ' - ';
        },
      },
      {
        title: 'Container/Filght No',
        dataIndex: 'containerNo',
        width: 150,
        sorter: (a, b) => a.containerNo?.localeCompare(b.containerNo),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('containerNo'),
        render: (value, record: ContainerStatusInfo, index) => {
          return (record.containerNo) ? record.containerNo : ' - ';
        },
      },
      // {
      //   title: 'Vessel No',
      //   dataIndex: 'vesselNumber',
      //   width: 150,
      //   sorter: (a, b) => a.vesselNumber?.localeCompare(b.vesselNumber),
      //   sortDirections: ['descend', 'ascend'],
      //   ...getColumnSearchProps('vesselNumber'),
      //   // render: (value, record: ContainerStatusInfo, index) => {
      //   //   return (record.vesselNumber) ? record.vesselNumber : ' - ';
      //   // },
      // },
      {
        title: 'CHA',
        dataIndex: 'cha',
        width: 150,
        sorter: (a, b) => a.cha?.localeCompare(b.cha),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('cha'),
        // render: (value, record: ContainerStatusInfo, index) => {
        //   return (record.vesselNumber) ? record.vesselNumber : ' - ';
        // },
      }
    ]
    const plantColumn: ColumnProps<any>[] = [
      {
        title: 'Prod Unit',
        dataIndex: 'plant',
        width: 150,
        sorter: (a, b) => a.plant?.localeCompare(b.plant),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('plant'),
      },
      {
        title: "Company",
        dataIndex: "company",
        width: 150,
        sorter: (a, b) => a.company?.localeCompare(b.company),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('company')
    
    },
    ]
    const containerColumn: ColumnProps<any>[] = [
      {
        title: 'Container Number',
        dataIndex: 'containerNo',
        width: 150,
        align: 'left',
        sorter: (a, b) => a.containerNo?.localeCompare(b.containerNo),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('containerNo'),
        render: (value, record: ContainerStatusInfo, index) => {
          return (record.containerNo) ? record.containerNo : ' - ';
        },
      }
    ]
    const shippmentModeColumn: ColumnProps<any>[] = [
      // {
      //   title: 'Mode Of Export',
      //   dataIndex: 'modeOfExport',
      //   width: 150,
      //   align: 'left',
      //   sorter: (a, b) => a.modeOfExport?.localeCompare(b.modeOfExport),
      //   sortDirections: ['descend', 'ascend'],
      //   ...getColumnSearchProps('modeOfExport'),
      //   render: (value, record: ContainerStatusInfo, index) => {
      //     return (record.modeOfExport) ? record.modeOfExport : ' - ';
      //   },
      // },
      {
        title: 'Marks And No',
        dataIndex: 'marksAndNo',
        width: 150,
        align: 'left',
        sorter: (a, b) => a.marksAndNo?.localeCompare(b.marksAndNo),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('marksAndNo'),
        render: (value, record: ContainerStatusInfo, index) => {
          return (record.marksAndNo) ? record.marksAndNo : ' - ';
        },
      }
    ]
    const fgQtyColumns: ColumnProps<any>[] = [
      {
        title: 'PO Qty',
        dataIndex: 'poQty',
        width: 100,
        render: (value, record, index) => {
          return (record.poQty) ? record.poQty : ' - ';
        },
      },
      {
        title: 'FG Qty',
        dataIndex: 'fgQty',
        width: 100,
        render: (value, record, index) => {
          return (record.fgQty) ? record.fgQty : ' - ';
        },
      },
      {
        title: 'FG%',
        dataIndex: 'fgQty',
        width: 100,
        render: (value, record, index) => {
          return (record.fgQty) ? ((record.fgQty * 100) / record.poQty).toFixed(2) : ' - ';
        },
        filters: [
          {
            text: 'Above 70%',
            value: true,
          },
          {
            text: 'Below 70%',
            value: false,
          },
        ],
        filterMultiple: false,
        onFilter: (value, record) => {
          // === is not work
          if (value == true) {
            return ((record.fgQty * 100) / record.poQty) > 70;
          } else {
            return ((record.fgQty * 100) / record.poQty) < 70;
          }
        },
      },
      {
        title: 'Production Status',
        dataIndex: 'productionStatus',
        key: 'productionStatus',
        width: 150,
        ...getColumnSearchProps('productionStatus'),
        sorter: (a, b) => a.productionStatus?.localeCompare(b.productionStatus),
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: 'Inspection Status',
        dataIndex: 'inspectionStatus',
        key: 'inspectionStatus',
        width: 150,
        ...getColumnSearchProps('inspectionStatus'),
        sorter: (a, b) => a.inspectionStatus?.localeCompare(b.inspectionStatus),
        sortDirections: ['descend', 'ascend'],

      },
    ]

    const actionColumns: ColumnProps<any>[] = [
      {
        title: 'Action',
        dataIndex: 'containerStatus',
        width: 200,
        // responsive: ['lg'],
        fixed:'right',

        render: (containerStatus, rowData: ContainerStatusInfo, record) => 
          {
            console.log(Number(rowData.checkListStatus),Number(rowData.shippmentDetailsStatus),rowData.poNo,'');
            return(
          <>
            {containerStatus == ContainerStatusEnum.NOT_READY ? <span>{(coId1) ?
              <Redirect to={{ pathname: "/container-booking", state: coId1 }}
              /> : null}<Button style={{ backgroundColor: '#8fec79', color: "black", fontWeight: 'bold' }}
                onClick={() => { updateContainerStatusReadyToBook(rowData); }}>READY TO BOOK</Button>
            </span> :
              containerStatus == ContainerStatusEnum.READY_TO_BOOK ?
                <span>{(coId1) ?
                  <Redirect to={{ pathname: "/container-booking", state: coId1 }}
                  /> : null}
                  {((JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_PLANT_HEAD) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_PLANT_EXECUTIVE) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_AND_WAREHOUSE_MANAGER) || ((JSON.parse(localStorage.getItem('role'))) === EmployeeRolesEnum.ADMIN) || ((JSON.parse(localStorage.getItem('role'))) === EmployeeRolesEnum.DOCUMENTATION_MANAGER) || ((JSON.parse(localStorage.getItem('role'))) === EmployeeRolesEnum.LOGISTICS_EXECUTIVE) || ((JSON.parse(localStorage.getItem('role'))) === EmployeeRolesEnum.LOGISTICS_HEAD))
                    //&&
                    // <><Tooltip placement="top" title={rowData.grossWeight?"Gross Weight Captured":"Need to Capture Gross Weight"}><Button style={{ backgroundColor: '#7ec1ff', color: "black", fontWeight: 'bold' }} onClick={() => { captureGrossWeight(rowData.saleOrderId); } }>{rowData.grossWeight?<CheckCircleTwoTone twoToneColor="#52c41a" />:""}GROSS WEIGHT</Button></Tooltip></>
                  }
                  {/* {(rowData.grossWeight) ? <Button style={{ backgroundColor: '#722ed1', color: "black", fontWeight: 'bold' }}
                    onClick={() => { setCoId1(rowData); }}>BOOK A SLOT</Button> : ""} */}

                  <Button style={{ backgroundColor: '#b3e897', color: "black", fontWeight: 'bold' }}
                    onClick={() => { setCoId1(rowData); }}>BOOK A SLOT</Button>

                  <Divider type="vertical" /><Tooltip placement="top" title={text}><Button onClick={() => updateToOpenStatus(rowData)}><UndoOutlined style={{ fontSize: '20px', marginLeft: '5px' }}  /></Button></Tooltip>
                </span> :
                containerStatus == ContainerStatusEnum.BOOKED ?
                  <span>{(coId2) ? <Redirect to={{ pathname: "/container-dispatch-to-plant", state: coId2 }}
                  /> : null}
                    <Button style={{ backgroundColor: '#7ec1ff', color: "black", fontWeight: 'bold' }}
                      onClick={() => { setCoId4(rowData); }}>INITIATE DISPATCH</Button><Divider type="vertical" /><Tooltip placement="top" title={text}>
                      <UndoOutlined style={{ fontSize: '20px', marginLeft: '5px' }} onClick={() => { updateToReadyToBook(rowData); }} />
                      {/* <Button onClick={() => { updateToReadyToBook(rowData); } }><RollbackOutlined /></Button> */}
                    </Tooltip></span> :
                  containerStatus == ContainerStatusEnum.LOADING ?
                    <span>{(coId3) ? <Redirect to={{ pathname: "/assign-so", state: coId3 }}
                    /> : null}{((JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_PLANT_HEAD) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_AND_WAREHOUSE_MANAGER) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_EXECUTIVE)) && <><Tooltip placement="topLeft" title={rowData.loadingStatus == ContainerLoadingStatus.LOADED ? "SO Assigned" : " Need to Assign SO"}><Button style={{ backgroundColor: '#f2d18f', color: "black", fontWeight: 'bold' }}
                      onClick={() => { setCoId3(rowData); }}>{rowData.loadingStatus == ContainerLoadingStatus.LOADED ?
                        <CheckCircleTwoTone style={{ color: 'green' }} />
                        : ""}ASSIGN SO</Button></Tooltip></>
                      }
                      {((JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.DOCUMENTATION_MANAGER) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_AND_WAREHOUSE_MANAGER)) &&
                        <Button style={{ backgroundColor: '#a2ee7c', color: "black", fontWeight: 'bold' }} onClick={() => { updateStatusToLoading(rowData) }}>CONFIRM</Button>}
                      {/* {rowData.loadingStatus == ContainerLoadingStatus.LOADED ? ((JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.DOCUMENTATION_MANAGER) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_AND_WAREHOUSE_MANAGER)) && <Button style={{ backgroundColor: '#7ec1ff', color: "black", fontWeight: 'bold' }}
                        onClick={() => { setCoId9(rowData); }}>Loading Chart</Button> : ''}<span>{(coId9) ? <Redirect to={{ pathname: "/loadingSheet", state: coId9 }}
                        /> : null}</span> */}
                      <Button style={{ backgroundColor: '#7ec1ff', color: "black", fontWeight: 'bold' }}
                        onClick={() => { setCoId5(rowData); }}>FILL SEAL INFORMATION</Button> <span>{(coId5) ? <Redirect to={{ pathname: "/fill-seal-info", state: coId5 }}
                        /> : null}</span>
                      <Divider type="vertical" />
                      <Tooltip placement="top" title={text}>
                        <UndoOutlined style={{ fontSize: '20px', marginLeft: '5px' }} onClick={() => { updateToBooked(rowData) }} />

                        {/* <Button onClick={() => { updateStatusToDispatchedToPlant(rowData) }}><RollbackOutlined /></Button> */}
                      </Tooltip></span> :
                    containerStatus == ContainerStatusEnum.DISPATCHED_TO_PLANT ?
                      <span>
                        {((JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.DOCUMENTATION_MANAGER) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_AND_WAREHOUSE_MANAGER) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_HEAD)) &&
                          <Button style={{ backgroundColor: '#d4b106', color: "black", fontWeight: 'bold' }}
                            onClick={() => { setCoId4(rowData); }}>INITIATE DISPATCH</Button>}
                        <Divider type="vertical" />
                        {((JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_AND_WAREHOUSE_MANAGER)) &&
                          <span>
                          </span>
                        }
                        {((JSON.parse(localStorage.getItem('role')) != EmployeeRolesEnum.LOGISTICS_PLANT_EXECUTIVE)) &&
                          <><Divider type="vertical" /><Tooltip placement="top" title={text}>
                            <UndoOutlined style={{ fontSize: '20px', marginLeft: '5px' }} onClick={() => { updateToBooked(rowData); }} />

                            {/* <Button onClick={() => { updateToBooked(rowData); } }><RollbackOutlined /></Button> */}
                          </Tooltip></>}
                      </span> :
                      containerStatus == ContainerStatusEnum.LOADED_AND_SEALED ?
                        <span>
                          <Popconfirm title={rowData.stockId != null ? "Are you sure to ship Sub job also & move stock to bulk ?" : "Are you sure？"} okText="Yes" cancelText="No" disabled={disable} onConfirm={() => {
                            setCoId6(rowData);
                          }}>
                          </Popconfirm>
                          <Button style={{ backgroundColor: rowData.checkListStatus>0?'#F6FB7A':'#14DB7A', color: "black", fontWeight: 'bold' }}
                            onClick={() => { setCoId7(rowData); }}>CHECK LIST
                          </Button>
                          <span>{(coId7) ? <Redirect to={{ pathname: "/check-list", state: coId7 }}
                          /> : null}</span>

                          <Button
                            type="primary"
                            onClick={() => showModal(
                              rowData.saleOrderId
                            )}
                          >
                            {/* <AiOutlineProfile size={24} /> */}
                          </Button>





                          <Button style={{ backgroundColor: rowData.shippmentDetailsStatus>0?'#F6FB7A':'#14DB7A', color: "black", fontWeight: 'bold' }}
                            onClick={() => { setCoId8(rowData); }}>Update Shipment Details</Button> <span>{(coId8) ?
                               <Redirect to={{ pathname: "/post-shipment-details", state: coId8 }}
                            /> : null}</span>
                          <Button style={{ backgroundColor: '#72b7f0', color: "black", fontWeight: 'bold' }}  onClick={() => { setCoId6(rowData); }}>SHIP THE CONTAINER</Button>
                          {/* </Popconfirm> */}
                          <Divider type="vertical" /><Tooltip placement="top" title={text}>
                            <UndoOutlined style={{ fontSize: '20px', marginLeft: '5px' }} onClick={() => { updateToLoading(rowData) }} />


                            {/* <Button onClick={() => { updateToLoading(rowData) }}><RollbackOutlined /></Button> */}
                          </Tooltip><br /><Tooltip placement="top" title={'Download Seal Info'}><Button style={{ marginLeft: 20 }} onClick={() => { download(rowData.filePath); }}> <ArrowDownOutlined />Download</Button></Tooltip></span> :
                        containerStatus == ContainerStatusEnum.SHIPPED ?
                          <span>
                            <Divider type="vertical" /><Tooltip placement="top" title={text}>
                              <UndoOutlined style={{ fontSize: '20px', marginLeft: '5px' }} onClick={() => { updateToLoadedAndSealed(rowData) }} />

                              {/* <Button onClick={() => { updateToLoadedAndSealed(rowData) }}><RollbackOutlined /></Button> */}
                            </Tooltip></span> : ""}
            {/* <Divider type="vertical" /> */}

            {/* {containerStatus=="NOT_READY"?
  <span>
          {(object) ?<Redirect
            to={{
              pathname: "/container-register-form",
              state: object
            }}
          />:null}<EditOutlined className={'editSamplTypeIcon'} type="edit" name="edit"
            onClick={() => {
              
                setUpdatevalue(rowData);
              
            }}
            style={{ color: '#1890ff', fontSize: '14px' }}
          />
        </span>:""} */}

          </>)}

      
      },
    ]


    if (key === "2") {
      return [...readyToBookColumns, ...bookedColumns, ...plantColumn, ...fgQtyColumns,...shippmentModeColumn, ...actionColumns,];
    }
    else if (key === "3") {
      return [...readyToBookColumns, ...bookedColumns, ...plantColumn, ...fgQtyColumns,...shippmentModeColumn, ...actionColumns,];
    }
    else if (key === "4") {
      return [...readyToBookColumns, ...bookedColumns, ...containerColumn, ...plantColumn, ...fgQtyColumns, ...actionColumns,]
    }
    else {
      return [...readyToBookColumns, ...plantColumn, ...fgQtyColumns, ...actionColumns,];
    }
  }

  const onReset = () => {
    // form.resetFields();
    form.resetFields();
    setSearchText('');
    handleUnit('all');
    setDateKey(prev => prev + 1);
    EstimatedDate(undefined);
    setContainerData([]);
    getAllContainerStatus();
    getContainerStatusCount()
    // getFiltersDropdownData(filtersData);
  };
  const handleCancel = () => {
    setIsModalVisible(false);
    getAllContainerStatus();
    getContainerStatusCount()
    setOpen(false);
  };

  const onFilterSearch = () => {
    getAllContainerStatus();
    getContainerStatusCount()
  }
  return (
    <>
      {/* {(saleOrderId)? <Redirect to={{ pathname: "/so-info-view", state: saleOrderId }} /> : null} */}


      <Card title={<span style={{ color: 'white' }}>Container Register</span>}
        style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}>

        <br></br>
        <div className="card-container">
          <Tabs  
          
          key={defaultTab} type={'card'} tabPosition={'top'} defaultActiveKey={defaultTab}  onChange={(tabKey) => {
  const status = tabKeyToStatus[tabKey];
  setSelectedStatus(status);          
  getAllContainerStatus(status);      // send status directly
}}
>
            {
              <TabPane
        
                // tab="Open Orders"
                key="1"
                tab={<span style={{ color: "#f5222d" }}>{'Open: ' + (containerStatusCount?.find(el => el.containerStatus === ContainerStatusEnum.NOT_READY)?.containerStatusCount || 0)}</span>}
              >
                <Table
                  key={defaultTab}
                  rowKey={record => record.saleOrderNumber}
                  columns={tableColumns("1")}
                  dataSource={containerData.filter(rec => rec.containerStatus == ContainerStatusEnum.NOT_READY)}
                  pagination={{
                    onChange(current) {
                      setPage(current);
                    }
                  }}
                  onChange={onChange}
                  scroll={{ y: 500 }}
                  size="middle"
                  bordered />
                {/* } */}
              </TabPane>
            }
            {
              <TabPane
                // tab="In-Procurement" 
                key="2"
                tab={<span style={{ color: "#52c41a" }}>{'Ready to Book: ' + (containerStatusCount?.find(el => el.containerStatus === ContainerStatusEnum.READY_TO_BOOK)?.containerStatusCount || 0)}</span>}
              >
                <Form form={form} layout={'vertical'} style={{ padding: '0px' }} >

                  <Form.Item style={{ display: "none" }} name="plantId" initialValue={Number(localStorage.getItem('unit_id'))}>
                    <Input hidden />
                  </Form.Item>
                  <Row gutter={[24, 24]} style={{rowGap:'0px'}}>
                    <Col span={6}>
                      <Form.Item name="etdDateRange" label="ETD Date" rules={[{
                        required: false,
                        message: "ETD From Date"
                      },
                      ]}>
                        <RangePicker  onChange={EstimatedDate}/>
                      </Form.Item>
                    </Col>
                    {/* <Col span={3}>
                      <Form.Item name="etdFromDate" label="ETD From Date"rules={[  {
                        required: false,
                        message: "ETD From Date"
                      },
                      ]}>
                        <DatePicker placeholder={"select from date"}  onChange={EstimatedFromDate} picker="date" />
                      </Form.Item>
                    </Col>
                    
                    <Col span={3} >
                      <Form.Item name="etdToDate"  label="ETD To Date"  rules={[    {
                        required: false,
                        message: "ETD To Date"
                      },
                      ]}>
                        <DatePicker placeholder={"select to date"} onChange={EstimatedToDate} picker="date" />
                      </Form.Item>
                    </Col> */}
  <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
  <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"
                        onChange={handleUnit}
                          allowClear
                    >
                      <Option key="all" value="all">All</Option>
                      {plantData.map(plant => {
                      return <Option key={plant.plantId}  value={plant.plantId}>{plant.plantCode}</Option>
                           })}
                        </Select>
                      </Form.Item>

                    </Col>
  <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
<Form.Item name="companyId" label="Company" >


  <Select
      placeholder="Select Company"
      showSearch
      optionFilterProp="children"
      filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
      allowClear
      dropdownMatchSelectWidth={false}

  >
      {factoriesData.map(dropData => {
          return <Option value={dropData.companyId}>{dropData.company}</Option>
      })}
  </Select>
</Form.Item>
          </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                      <Form.Item
                        name="destination"
                        label="Destination"
                        rules={[
                          {
                            required: false, message: 'Select Destination',
                          },
                        ]}
                      >
                        <Select
                          showSearch
                          optionFilterProp="children"
                          filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                          placeholder="Select Destination"
                          onChange={handleDestination}
                          allowClear
                          style={{ width: '100%' }}
                        >
                          {destinationData.map(dropData => {
                           return <Option value={dropData.destinationId}>{dropData.destinationName}</Option>
                          })}
                        </Select>

                      </Form.Item>
                    </Col>

                    <Col  span={5}>
                      <Button
                        type="primary"
                        icon={<SearchOutlined />}
                        // size="small"
                        block onClick={onFilterSearch}
                        style={{ marginRight: 2, width: 100 }}
                      >
                        Search
                      </Button>
                      {/* <Button type='primary' block onClick={()=>searchData()}>Get</Button> */}
                      <Button type="primary" htmlType="submit" onClick={onReset}>
                        Reset
                      </Button>
                    </Col>
                  </Row>
                </Form>

                <Table
                  key={defaultTab}
                  rowKey={record => record.saleOrderNumber}
                  columns={tableColumns("1")}
                  dataSource={containerData.filter(rec => rec.containerStatus == ContainerStatusEnum.READY_TO_BOOK)}
                  pagination={{
                    onChange(current) {
                      setPage(current);
                    }
                  }}
                  onChange={onChange}
                  scroll={{ y: 500 }}
                  size="small"
                  bordered />

              </TabPane>
            }
            {((JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_PLANT_EXECUTIVE) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_AND_WAREHOUSE_MANAGER) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.PLANT_SALES_MANAGER) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.SUPER_ADMIN)) &&
              <TabPane
                // tab="Work in Progress"
                key="3"
                tab={<span style={{ color: "#722ed1" }}>{((JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_AND_WAREHOUSE_MANAGER)  || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.SUPER_ADMIN) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.PLANT_SALES_MANAGER)) ? 'Booked: ' + (containerStatusCount?.find(el => el.containerStatus === ContainerStatusEnum.BOOKED)?.containerStatusCount || 0) : 'Booked: ' + (containerStatusCount?.find(el => el.containerStatus === ContainerStatusEnum.BOOKED)?.containerStatusCount || 0)}</span>}
              >
                <Table
                  key={defaultTab}
                  rowKey={record => record.containerId}
                  columns={tableColumns("2")}
                  dataSource={((JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_AND_WAREHOUSE_MANAGER)|| (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.PLANT_SALES_MANAGER) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.SUPER_ADMIN)) ? containerData.filter(rec => rec.containerStatus == ContainerStatusEnum.BOOKED) : containerData.filter(rec => rec.containerStatus == ContainerStatusEnum.BOOKED && rec.plantId === Number(localStorage.getItem("unit_id")))}
                  pagination={{
                    onChange(current) {
                      setPage(current);
                    }
                  }}
                  onChange={onChange}
                  scroll={{ y: 500 }}
                  size="small"
                  bordered />
              </TabPane>
            }
            {/* {
              <TabPane
                // tab="Work in Progress"
                key="4"
                tab={<span style={{ color: "#faad14" }}>{((JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.DOCUMENTATION_MANAGER)  || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_AND_WAREHOUSE_MANAGER) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_HEAD) ) ? 'Containers in Plant: ' + (containerData.filter(el => el.containerStatus == ContainerStatusEnum.DISPATCHED_TO_PLANT).length):'Containers in Plant: ' + (containerData.filter(el => el.containerStatus == ContainerStatusEnum.DISPATCHED_TO_PLANT && el.plantId === Number(localStorage.getItem("unit_id"))).length)}</span>}
              >
                <Table
                  key={defaultTab}
                  rowKey={record => record.containerId}
                  columns={tableColumns("3")}
                  dataSource={((JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.DOCUMENTATION_MANAGER)  || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_AND_WAREHOUSE_MANAGER) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_HEAD) )?containerData.filter(rec => rec.containerStatus == ContainerStatusEnum.DISPATCHED_TO_PLANT):containerData.filter(rec => rec.containerStatus == ContainerStatusEnum.DISPATCHED_TO_PLANT && rec.plantId === Number(localStorage.getItem("unit_id")))}
                  pagination={{
                    onChange(current) {
                      setPage(current);
                    }
                  }}
                  onChange={onChange}
                  scroll={{ y: 500 }}
                  size="small"
                  bordered />
              </TabPane>
            } */}
            {
              <TabPane

                // tab="Work in Progress"
                key="5"
                tab={<span style={{ color: "#d4b106" }}>{(JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN || JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_EXECUTIVE) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.PLANT_SALES_MANAGER)  || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.SUPER_ADMIN) ? 'Loading: ' + (containerStatusCount?.find(el => el.containerStatus === ContainerStatusEnum.LOADING)?.containerStatusCount || 0) : 'Loading: ' + (containerStatusCount?.find(el => el.containerStatus === ContainerStatusEnum.LOADING)?.containerStatusCount || 0)}</span>}
              >
                <Table
                  key={defaultTab}
                  rowKey={record => record.containerId}
                  columns={tableColumns("3")}
                  dataSource={(JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN || JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_EXECUTIVE) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.PLANT_SALES_MANAGER)  || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.SUPER_ADMIN) ? containerData.filter(rec => rec.containerStatus == ContainerStatusEnum.LOADING) : containerData.filter(rec => rec.containerStatus == ContainerStatusEnum.LOADING && rec.plantId === Number(localStorage.getItem("unit_id")))}
                  pagination={{
                    onChange(current) {
                      setPage(current);
                    }
                  }}
                  onChange={onChange}
                  scroll={{ y: 500 }}
                  size="small"
                  bordered />
              </TabPane>
            }
            {
              <TabPane
                // tab="Work in Progress"
                key="6"
                tab={<span style={{ color: "#eb2f96" }}>{(JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN || JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_EXECUTIVE) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.PLANT_SALES_MANAGER)  || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.SUPER_ADMIN) ? 'Loaded and Sealed: ' + (containerStatusCount?.find(el => el.containerStatus === ContainerStatusEnum.LOADED_AND_SEALED)?.containerStatusCount || 0) : 'Loaded and Sealed: ' + (containerStatusCount?.find(el => el.containerStatus === ContainerStatusEnum.LOADED_AND_SEALED)?.containerStatusCount || 0)}</span>}
              >
                <Table
                  key={defaultTab}
                  rowKey={record => record.containerId}
                  columns={tableColumns("3")}
                  dataSource={(JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.ADMIN || JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.LOGISTICS_EXECUTIVE) || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.PLANT_SALES_MANAGER)  || (JSON.parse(localStorage.getItem('role')) === EmployeeRolesEnum.SUPER_ADMIN) ? containerData.filter(rec => rec.containerStatus == ContainerStatusEnum.LOADED_AND_SEALED) : containerData.filter(rec => rec.containerStatus == ContainerStatusEnum.LOADED_AND_SEALED && rec.plantId === Number(localStorage.getItem("unit_id")))}
                  pagination={{
                    onChange(current) {
                      setPage(current);
                    }
                  }}
                  onChange={onChange}
                  scroll={{ y: 500 }}
                  size="small"
                  bordered />
              </TabPane>
            }
            {
              <TabPane
                // tab="Work in Progress"
                key="7"
                tab={<span style={{ color: "#08979c" }}>{'Shipped: ' + (containerStatusCount?.find(el => el.containerStatus === ContainerStatusEnum.SHIPPED)?.containerStatusCount || 0)}</span>}
              >
 <Form form={form} layout={'vertical'}  onFinish={getAllContainerStatus}>
            <Row gutter={[24, 24]} style={{rowGap:'0px'}}>
           
              <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
                                                  <Form.Item name="financialYear" label="Financial Year">
                                                    <Select
                                                      showSearch
                                                      placeholder="Select Financial Year"
                                                      optionFilterProp="children"
                                                      filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                      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: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
                                                <Form.Item name="companyId" label="Company" >


                                                  <Select
                                                      placeholder="Select Company"
                                                      showSearch
                                                      optionFilterProp="children"
                                                      filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                      allowClear
                                                      dropdownMatchSelectWidth={false}

                                                  >
                                                      {factoriesData.map(dropData => {
                                                          return <Option value={dropData.companyId}>{dropData.company}</Option>
                                                      })}
                                                  </Select>
                                                </Form.Item>
                                                          </Col>
              <Col style={{ paddingLeft:'10px', marginTop:'30px' }}>
                <Form.Item >
                  <Button type="primary" htmlType="submit">
                    Get Details
                  </Button>
                </Form.Item>
              </Col>
              <Col style={{ paddingLeft:'10px', marginTop:'30px' }}>
                <Form.Item>
                  <Button htmlType="button" onClick={onReset}>
                    Reset
                  </Button>

                </Form.Item>
              </Col>
           
              <Col  style={{ marginTop: '30px', textAlign: 'right' }}>                
              <Form.Item>
                  <Button ><CSVLink filename={"logistics-shipped-data.csv"} data={containerData.filter(rec => rec.containerStatus == ContainerStatusEnum.SHIPPED)} >
                    Get Excel

                  </CSVLink>
                  </Button>
                </Form.Item>
                </Col> </Row>
                </Form>
                <Table
                  key={defaultTab}
                  rowKey={record => record.containerId}
                  columns={tableColumns("3")}
                  dataSource={containerData.filter(rec => rec.containerStatus == ContainerStatusEnum.SHIPPED)}
                  pagination={{
                    onChange(current) {
                      setPage(current);
                    }
                  }}
                  onChange={onChange}
                  scroll={{ y: 500 }}
                  size="small"
                  bordered />
              </TabPane>
            }
          </Tabs>
          {isModalVisible ?
            <>
              <Modal
                className='print-docket-modal'
                key={'modal' + Date.now()}
                width={'80%'}
                style={{ top: 30, alignContent: 'right' }}
                visible={isModalVisible}
                title={<React.Fragment>
                </React.Fragment>}
                onCancel={handleCancel}
                footer={[

                ]}
              >


                {(modelType == 'gross-weight-form') ?
                  <CaptureGrossWeightForm saleOrderId={saleOrderId} setModalVisible={handleCancel} /> : null}

                {(modelType == 'so-info-view') ? <SoInfoViewPages saleOrderId={saleId} screen="logistics" /> : ''}
              </Modal></>
            : ""}
        </div>

        <Modal
          title="Report Details"
          visible={isModalVisible1}
          onOk={handleOk}
          onCancel={handleCancel1}
          footer={[
            <Button key="back" onClick={handleCancel1}>Close</Button>,
          ]}
          closable={false}
        >
          <>
            <p><strong>QC Report:</strong> {check[0]?.qcReport == 1 ? 'Yes' : 'No'}</p>
            <p><strong>Buyer Inspection Report:</strong> {check[0]?.buyerInspectionReport == 1 ? 'Yes' : 'No'}</p>
            <p><strong>Vessel Schedule Approval:</strong> {check[0]?.vesselScheduleApproval == 1 ? 'Yes' : 'No'}</p>
            <p><strong>Temperature:</strong> {check[0]?.temperature == 1 ? 'Yes' : 'No'}</p>
            <p><strong>TemperatureDegree:</strong>{check[0]?.temperaturee}</p>
          </>

        </Modal>
      </Card>
    </>
  );
}

export default ContainerRegisterGrid;