// import React from 'react';
// import Createstaff from 'pages/createstaff'
import { enqueueSnackbar } from "notistack";
import { DeleteFilled, NotificationOutlined } from "@ant-design/icons";

import { useState, useEffect, Fragment } from "react";
import { Empty } from "antd";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import dayjs from "dayjs";
var utc = require("dayjs/plugin/utc");
dayjs.extend(utc);
import axios from "axios";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
// import { DataGrid } from '@mui/x-data-grid'
// material-ui
import HoverSocialCard from "components/cards/statistics/HoverSocialCard";
// import {FacebookOutlined}  from '@ant-design/icons';
import { useTheme } from "@mui/material/styles";
// import { edittabstatus1 } from 'store/reducers/dashboard1';
import {
  Avatar,
  // AvatarGroup,
  // Button as Button1,
  Box,
  // DateRangePicker,
  Button,
  Grid,
  Tabs,
  Tab,
  IconButton,
  Stack,
  TextField,
  Chip,
  // TableSortLabel,
  Typography,
  // Divider,
  Table,
  TableCell,
  TableBody,
  TableHead,
  // TableSortLabel,
  Collapse,
  Dialog,
  TableRow,
  DialogContent,
  DialogTitle,
  Tooltip,
  FormControl,
  OutlinedInput,
  InputAdornment,
  Skeleton,
  CircularProgress,
  DialogActions,
  Switch,
  Autocomplete,
  Popper,
  ClickAwayListener,
  Checkbox,
} from "@mui/material";
import MainCard from "components/MainCard";

// import {  useSelector } from 'store';
// import { useDispatch } from 'react-redux';

import {
  SearchOutlined,
  EnvironmentOutlined,
  UserOutlined,
  MoreOutlined,
  CloseOutlined,
} from "@ant-design/icons";
import { PopupTransition } from "components/@extended/Transitions";

// import FilterList from '@mui/icons-material/FilterList';
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";

import {
  addDays,
  addMonths,
  addWeeks,
  // addYears,
  endOfMonth,
  endOfWeek,
  // endOfYear,
  startOfMonth,
  startOfWeek,
  // startOfYear,
} from "date-fns";

// import { DateRangePicker } from '@mui/x-date-pickers-pro/DateRangePicker';
// import { DesktopDateRangePicker } from '@mui/x-date-pickers-pro/DesktopDateRangePicker';
// import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
// import { DateRangePicker } from "mui-daterange-picker-orient";
import { DateRangePicker } from "mui-daterange-picker";

// import EnhancedTable from 'components/tablemuiedit'
import {
  // CloseOutlined,
  //  PlusOutlined,
  EyeTwoTone,
  // EditTwoTone,
  // DeleteTwoTone
} from "@ant-design/icons";

import { useNavigate } from "react-router";

import * as React from "react";
import PropTypes from "prop-types";
// import { alpha } from '@mui/material/styles';
// import Box from '@mui/material/Box';
// import Table from '@mui/material/Table';
// import TableBody from '@mui/material/TableBody';
// import TableCell from '@mui/material/TableCell';
import TableContainer from "@mui/material/TableContainer";
// import TableHead from '@mui/material/TableHead';
import TablePagination from "@mui/material/TablePagination";
// import TableRow from '@mui/material/TableRow';
// import TablePagination from '@mui/material/TablePagination';
import TableSortLabel from "@mui/material/TableSortLabel";
// import Toolbar from '@mui/material/Toolbar';
// import Typography from '@mui/material/Typography';
// import Paper from '@mui/material/Paper';
// import Checkbox from '@mui/material/Checkbox';
// import IconButton from '@mui/material/IconButton';
// import Tooltip from '@mui/material/Tooltip';
// import FormControlLabel from '@mui/material/FormControlLabel';
// // import Switch from '@mui/material/Switch';
// import DeleteIcon from '@mui/icons-material/Delete';
// import FilterListIcon from '@mui/icons-material/FilterList';
import { visuallyHidden } from "@mui/utils";
import Loader from "components/Loader";
import { FilterList } from "@mui/icons-material";
// import MainCard from 'components/MainCard';
// import DialogTitle from 'themes/overrides/DialogTitle';
// import MainCard from 'components/MainCard';

const Orders = () => {
  const [deliverylist, setDeliverylist] = useState([]);
  const [dialogopen, setDialogopen] = useState(false);
  const [paymentmode, setPaymentmode] = useState([]);
  const [riderslist, setRiderslist] = useState([]);
  const [rider, setRider] = useState({});
  const [payment, setPayment] = useState({});

  const createdeliveryobj = async () => {
    let arr = [];

    deliverylist.map((val) => {
      arr.push({
        deliveryid: 0,
        Partnerid: val.partnerid,
        Tenantid: val.tenantid,
        Locationid: val.locationid,
        configid: val.configid,
        moduleid: val.moduleid,
        userid: rider.userid,
        orderheaderid: val.orderheaderid,
        categoryid: val.categoryid,
        subcategoryid: val.subcategoryid,
        orderid: val.orderid,
        deliverydate: dayjs(val.deliverytime)
          .utc()
          .format("YYYY-MM-DD HH:mm:ss"),
        orderstatus: "pending",
        orderamount: 0.0, //
        itemcount: val.itemcount,
        customerid: val.customerid,
        customername: val.customername,
        contactno: val.contactno,
        deliveryaddress: val.deliveryaddress,
        deliverylocationid: val.deliverylocationid,
        droplat: val.deliverylat, //
        droplon: val.deliverylong, //
        pickupaddress: val.pickupaddress,
        pickuplat: val.pickuplat,
        pickuplon: val.pickuplong,
        ordernotes: val.ordernotes,
        paymenttype: payment ? payment.apptypeid : "",
        applocationid: parseInt(localStorage.getItem("applocationid")),
        kms: "0",
        deliverycharges: 0,
        // "pickuplocationid": val.pickuplocationid,
        pickupcustomer: val.pickupcustomer,
        pickupcontactno: val.pickupcontactno,
        deliverycustomerid: val.deliveryid,
        deliverycontactno: val.deliverycontactno,
        pickuplocationid: val.pickuplocationid,
        pickuplocation: val.pickupsuburb,
        deliverylocation: val.deliverysuburb,
        deliverycustomer: val.deliverycustomer,
      });
    });

    console.log(arr);
    if (!rider.userid) {
      enqueueSnackbar("Choose Rider", {
        variant: "error",
        anchorOrigin: { vertical: "top", horizontal: "right" },
        autoHideDuration: 2000,
      });
    } else if (!payment.typename) {
      enqueueSnackbar("Choose Payment Mode", {
        variant: "error",
        anchorOrigin: { vertical: "top", horizontal: "right" },
        autoHideDuration: 2000,
      });
    } else {
      await axios
        .post(`${process.env.REACT_APP_URL}/deliveries/createdeliveries`, arr)
        .then((res) => {
          console.log(res);
          if (res.data.status) {
            enqueueSnackbar("Delivery Created Successfully", {
              variant: "success",
              anchorOrigin: { vertical: "top", horizontal: "right" },
              autoHideDuration: 2000,
            });
            notifyrider(rider.userfcmtoken);

            if (localStorage.getItem("partnerid")) {
              let val = localStorage.getItem("partnerid");

              fetchpercentage(val);
              fetchtableuncovered(val);
              fetchtablecovered(val);
              fetchtablecancelled(val);

              fetchtablecreated(val);
            }
            setDeliverylist([]);
          }

          dialogclose();
          setLoading(false);
        })
        .catch((err) => {
          console.log(err);
          enqueueSnackbar(err.message, {
            variant: "error",
            anchorOrigin: { vertical: "top", horizontal: "right" },
            autoHideDuration: 2000,
          });
          setLoading(false);
        });
    }
  };

  const notifyrider = async (id1) => {
    await axios
      .post(`${process.env.REACT_APP_URL}/utils/notifyuser`, {
        sender: localStorage.getItem("firstname"),
        accessid: process.env.REACT_APP_RIDER_ACCESS_ID,
        notification: {
          priority: "high",
          to: id1,
          notification: {
            title: "Nearle Admin",
            body: "Orders has been placed for delivery.Kindly accept and process deliveries",
            sound: "ring",
          },
        },
      })
      .then((res) => {
        console.log(res);
        if (res.data.message == "Success") {
          enqueueSnackbar("Notification sent Successfully", {
            variant: "success",
            anchorOrigin: { vertical: "top", horizontal: "right" },
            autoHideDuration: 2000,
          });
        }
      })
      .catch((err) => {
        console.log(err);
        enqueueSnackbar(err.message, {
          variant: "error",
          anchorOrigin: { vertical: "top", horizontal: "right" },
          autoHideDuration: 2000,
        });
        setLoading(false);
      });
  };

  const dialogclose = () => {
    setDialogopen(false);
    setRider({});
    setPayment({});
  };

  function descendingComparator(a, b, orderBy) {
    if (b[orderBy] < a[orderBy]) {
      return -1;
    }
    if (b[orderBy] > a[orderBy]) {
      return 1;
    }
    return 0;
  }

  function getComparator(order, orderBy) {
    return order === "desc"
      ? (a, b) => descendingComparator(a, b, orderBy)
      : (a, b) => -descendingComparator(a, b, orderBy);
  }

  // Since 2020 all major browsers ensure sort stability with Array.prototype.sort().
  // stableSort() brings sort stability to non-modern browsers (notably IE11). If you
  // only support modern browsers you can replace stableSort(exampleArray, exampleComparator)
  // with exampleArray.slice().sort(exampleComparator)
  function stableSort(array, comparator) {
    const stabilizedThis = array.map((el, index) => [el, index]);
    stabilizedThis.sort((a, b) => {
      const order = comparator(a[0], b[0]);
      if (order !== 0) {
        return order;
      }
      return a[1] - b[1];
    });
    return stabilizedThis.map((el) => el[0]);
  }

  const headCells = [
    {
      id: "sno",
      disablePadding: true,
      label: "S NO",
    },
    // {
    //   id: 'tenantname3',
    //   numeric: false,
    //   disablePadding: false,
    //   label: 'CLIENT',
    // },
    // {
    //   id: 'tenantname',
    //   numeric: false,
    //   disablePadding: false,
    //   label: 'CUSTOMER',
    // },
    {
      id: "orderid",
      numeric: false,
      disablePadding: false,
      label: "ORDER ID",
    },
    {
      id: "eventname",
      disablePadding: false,
      label: "Pickup",
    },
    {
      id: "eventname4",
      disablePadding: false,
      label: "Delivery",
    },
    //   {
    //     id: 'ordervalue',
    //     disablePadding: false,
    //     label: 'VALUE $',
    //   },
    {
      id: "itemcount",
      disablePadding: false,
      label: "NOTES",
    },
    {
      id: "orderstatus",
      disablePadding: false,
      label: "STATUS",
    },
    {
      id: "action",
      disablePadding: false,
      label: "ACTION",
    },
  ];

  function EnhancedTableHead(props) {
    const { order, orderBy, onRequestSort } = props;
    const createSortHandler = (property) => (event) => {
      onRequestSort(event, property);
    };

    return (
      <TableHead>
        <TableRow>
          {tabstatus == "Created" && (
            <TableCell>
              <Checkbox
                indeterminate={
                  deliverylist.length > 0 && deliverylist.length != rows.length
                }
                onChange={(e) => {
                  if (e.target.checked) {
                    setDeliverylist([...rows]);
                  } else {
                    setDeliverylist([]);
                  }
                }}
                checked={deliverylist.length == rows.length}
              />
            </TableCell>
          )}

          {headCells.map((headCell) => (
            <TableCell
              key={headCell.id}
              align={headCell.numeric ? "right" : "left"}
              padding={headCell.disablePadding ? "none" : "normal"}
              sortDirection={orderBy === headCell.id ? order : false}
            >
              <TableSortLabel
                active={orderBy === headCell.id}
                direction={orderBy === headCell.id ? order : "asc"}
                onClick={createSortHandler(headCell.id)}
              >
                {headCell.label}
                {orderBy === headCell.id ? (
                  <Box component="span" sx={visuallyHidden}>
                    {order === "desc"
                      ? "sorted descending"
                      : "sorted ascending"}
                  </Box>
                ) : null}
              </TableSortLabel>
            </TableCell>
          ))}
        </TableRow>
      </TableHead>
    );
  }

  EnhancedTableHead.propTypes = {
    numSelected: PropTypes.number.isRequired,
    onRequestSort: PropTypes.func.isRequired,
    onSelectAllClick: PropTypes.func.isRequired,
    order: PropTypes.oneOf(["asc", "desc"]).isRequired,
    orderBy: PropTypes.string.isRequired,
    rowCount: PropTypes.number.isRequired,
  };

  function EnhancedTable() {
    const [order, setOrder] = React.useState("asc");
    const [orderBy, setOrderBy] = React.useState("calories");
    const [selected, setSelected] = React.useState([]);
    const [page, setPage] = React.useState(0);
    const [rowsPerPage, setRowsPerPage] = React.useState(10);
    const [expandopen, setExpandopen] = React.useState("");

    // const [dialogopen, setDialogopen] = useState(false);
    const [stafflist, setStafflist] = useState([]);
    const [loading1, setLoading1] = useState(false);
    const [open, setOpen] = useState(false);
    const [orderheaderid, setOrderheaderid] = useState("");
    const [open1, setOpen1] = useState(false);
    const [anchorEl, setAnchorEl] = React.useState(null);
    const [open2, setOpen2] = useState("");

    const handleClickAway = () => {
      setOpen2("");
    };

    const cancelorder = async () => {
      await axios
        .put(`${process.env.REACT_APP_URL}/orders/updateorder`, {
          orderheaderid: orderheaderid,
          orderstatus: "cancelled",
          cancelled: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        })
        .then((res) => {
          console.log(res);
          if (res.data.status) {
            // if (orderheaderid && tenantid) {
            //   fetchorderdetails();
            //   fetchorderaddons();
            //   fetchorderattires();
            // }
            enqueueSnackbar("Order Cancelled Successfully", {
              variant: "success",
              anchorOrigin: { vertical: "top", horizontal: "right" },
              autoHideDuration: 2000,
            });
            handleClose(true);

            if (localStorage.getItem("partnerid")) {
              setTenantid(localStorage.getItem("tenantid"));
              let val = localStorage.getItem("partnerid");

              // fetchtable(val);
              fetchpercentage(val);
              fetchtableuncovered(val);
              fetchtablecovered(val);
              fetchtablecancelled(val);
              // fetchtableassigned(val);
              // fetchtablepicked(val);
              fetchtablecreated(val);
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };

    const fetchstafflist = async (odid) => {
      setLoading1(true);
      try {
        await axios
          .get(
            `${process.env.REACT_APP_URL2}/orders/getassignedinfo?orderdetailid=${odid}`
          )

          .then((res) => {
            console.log(res);
            if (res.data.status) {
              setStafflist(res.data.Details);
            }

            setLoading1(false);
          })
          .catch((err) => {
            console.log(err);
            setLoading1(false);
          });
      } catch (err) {
        console.log(err);
        setLoading1(false);
      }
    };

    const dialogclose = () => {
      setDialogopen(false);
      setPayment({});
      setRider({});
    };

    const handleRequestSort = (event, property) => {
      const isAsc = orderBy === property && order === "asc";
      setOrder(isAsc ? "desc" : "asc");
      setOrderBy(property);
    };

    const handleSelectAllClick = (event) => {
      if (event.target.checked) {
        const newSelected = rows.map((n) => n.name);
        setSelected(newSelected);
        return;
      }
      setSelected([]);
    };

    const handleChangePage = (event, newPage) => {
      setPage(newPage);
    };

    const handleChangeRowsPerPage = (event) => {
      setRowsPerPage(parseInt(event.target.value, 10));
      setPage(0);
    };

    const isSelected = (name) => selected.indexOf(name) !== -1;

    // Avoid a layout jump when reaching the last page with empty rows.
    const emptyRows =
      page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0;

    const visibleRows = React.useMemo(
      () =>
        stableSort(rows, getComparator(order, orderBy)).slice(
          page * rowsPerPage,
          page * rowsPerPage + rowsPerPage
        ),
      [order, orderBy, page, rowsPerPage]
    );

    const handleClose = () => {
      setOpen(false);
      setOrderheaderid("");
    };

    function AlertCustomerDelete({
      // title,
      open,
      handleClose,
    }) {
      // const [deletepassword, setDeletepassword] = useState('');

      return (
        <Dialog
          open={open}
          onClose={() => handleClose(false)}
          // keepMounted
          // TransitionComponent={PopupTransition}
          maxWidth="xs"
          // aria-labelledby="column-delete-title"
          // aria-describedby="column-delete-description"
        >
          <DialogContent sx={{ mt: 2, my: 1 }}>
            <Stack alignItems="center" spacing={3.5}>
              <Avatar
                color="error"
                sx={{ width: 72, height: 72, fontSize: "1.75rem" }}
              >
                <DeleteFilled />
              </Avatar>
              {/* <Grid >
                  <Chip label={orderid.slice(4)} variant="combined" color='warning' size='small' />
                </Grid> */}
              <Stack spacing={2}>
                <Typography variant="h4" align="center">
                  Are you sure you want to cancel this order?
                </Typography>

                {/* <Typography variant="h4" align="center">
                    Please type in the order number to confirm.
                  </Typography> */}
              </Stack>

              <Stack direction="row" spacing={2} sx={{ width: 1 }}>
                <Button
                  fullWidth
                  color="error"
                  variant="contained"
                  onClick={() => {
                    // if (deletepassword === orderid.slice(4)) {
                    cancelorder();
                    // }
                  }}
                  autoFocus
                >
                  Yes, Cancel
                </Button>
                <Button
                  fullWidth
                  onClick={() => {
                    handleClose(false);
                  }}
                  color="secondary"
                  variant="outlined"
                >
                  No
                </Button>
              </Stack>
            </Stack>
          </DialogContent>
        </Dialog>
      );
    }

    return (
      <Box sx={{ width: "100%" }}>
        <AlertCustomerDelete open={open} handleClose={handleClose} />

        <TableContainer
          sx={{ width: "100%", borderBottom: 1, borderColor: "divider" }}
        >
          <Table
            sx={{ minWidth: 750 }}
            aria-label="collapsible table"
            size={"medium"}
          >
            <EnhancedTableHead
              numSelected={selected.length}
              order={order}
              orderBy={orderBy}
              onSelectAllClick={handleSelectAllClick}
              onRequestSort={handleRequestSort}
              rowCount={rows.length}
            />
            {loading && (
              <>
                <TableBody>
                  {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((item) => (
                    <TableRow key={item}>
                      <TableCell>
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                      </TableCell>
                      <TableCell>
                        <Skeleton animation="wave" />
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </>
            )}
            <TableBody>
              {visibleRows.length == 0 && !loading && (
                <>
                  <TableCell colSpan={7}>
                    <Stack
                      width={"100%"}
                      direction={"row"}
                      justifyContent={"center"}
                    >
                      <Empty />
                    </Stack>
                  </TableCell>
                  {/* <div>empty</div> */}
                </>
              )}

              {visibleRows.map((row, index) => {
                const isItemSelected = isSelected(row.sno);
                const labelId = `enhanced-table-checkbox-${index}`;

                return (
                  <>
                    <TableRow
                      role="checkbox"
                      aria-checked={isItemSelected}
                      tabIndex={-1}
                      key={row.sno}
                      sx={{
                        cursor: "pointer",

                        // backgroundColor: (expandopen === row.sno) ? '#f5f5f5' : ''
                        backgroundColor: deliverylist.find(
                          (res1) => res1.orderheaderid == row.orderheaderid
                        )
                          ? "#e1bee7"
                          : "",
                        "&:hover": {
                          backgroundColor: deliverylist.find(
                            (res1) => res1.orderheaderid == row.orderheaderid
                          )
                            ? "#e1bee7 !important"
                            : "",
                        },
                      }}
                    >
                      {tabstatus == "Created" && (
                        <TableCell
                        // component="th"
                        // id={labelId}
                        // scope="row"
                        // padding="none"
                        >
                          <Checkbox
                            sx={{
                              backgroundColor: deliverylist.find(
                                (res1) =>
                                  res1.orderheaderid == row.orderheaderid
                              )
                                ? "#e1bee7"
                                : "",
                              "&:hover": {
                                backgroundColor: deliverylist.find(
                                  (res1) =>
                                    res1.orderheaderid == row.orderheaderid
                                )
                                  ? "#e1bee7 !important"
                                  : "",
                              },
                            }}
                            onChange={(e) => {
                              if (e.target.checked) {
                                let arr = deliverylist;
                                arr.push({
                                  ...row,
                                  sno: deliverylist.length + 1,
                                });

                                setDeliverylist([...arr]);
                              } else {
                                let res = deliverylist.find(
                                  (res1) =>
                                    res1.orderheaderid == row.orderheaderid
                                );
                                if (res) {
                                  let arr = deliverylist;
                                  let res = deliverylist.find(
                                    (res1) =>
                                      res1.orderheaderid == row.orderheaderid
                                  );
                                  arr.splice(res.sno - 1, 1);
                                  arr.map((val, i) => {
                                    val.sno = i + 1;
                                  });
                                  setDeliverylist([...arr]);
                                }
                              }
                              console.log("list", deliverylist);
                            }}
                            checked={deliverylist.find(
                              (res1) => res1.orderheaderid == row.orderheaderid
                            )}
                          />
                        </TableCell>
                      )}

                      <TableCell
                      // component="th"
                      // id={labelId}
                      // scope="row"
                      // padding="none"
                      >
                        <Typography> {row.sno}</Typography>
                      </TableCell>
                      <TableCell align="left">
                        <Typography variant="body2" noWrap>
                          {row.orderid}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: "11px" }}>
                          {dayjs(row.deliverytime).utc().format("DD/MM/YYYY")}
                        </Typography>
                        <Typography
                          noWrap
                          sx={{ fontSize: "11px" }}
                          variant="h5"
                        >
                          {dayjs(row.deliverytime).utc().format("hh:mm A")}
                        </Typography>
                      </TableCell>

                      {/* <TableCell align="left" sx={{ paddingLeft: '12px !important' }}>

                        <Stack direction="row" alignItems="center" spacing={1} justifyContent="flex-start">
                          <Avatar
                            alt=""
                            size="sm"
                            sx={{
                              width: '25px',
                              height: '25px'
                            }}
                          >

                          </Avatar>
                          <Stack direction="column">
                            <Typography variant="caption">{row.customername}</Typography>
                            <Typography variant="caption" color="textSecondary">

                              {row.contactno}
                            </Typography>
                          </Stack>
                        </Stack>
                      </TableCell> */}
                      <TableCell align="left">
                        <Stack direction={"row"} spacing={1}>
                          <Avatar
                            alt=""
                            size="sm"
                            sx={{
                              width: "25px",
                              height: "25px",
                            }}
                          ></Avatar>
                          <Stack direction="column">
                            <Typography variant="caption">
                              {row.pickupcustomer}
                            </Typography>
                            <Typography variant="caption" color="textSecondary">
                              {row.pickupcontactno}
                            </Typography>
                            <Tooltip title={row.pickupaddress}>
                              <Typography
                                variant="caption"
                                color="textSecondary"
                              >
                                {/* {row.pickupaddress.slice(0, 20)} */}
                                {row.pickupsuburb ||
                                  row.pickupaddress.slice(0, 20)}
                              </Typography>
                            </Tooltip>
                          </Stack>
                        </Stack>
                        {/* <Stack direction='column'>

                        </Stack> */}
                      </TableCell>
                      <TableCell align="left">
                        {/* <Stack direction='column'>
                          <Tooltip title={row.deliveryaddress}>
                            <Typography variant="caption" color="textSecondary"
                            >
                              {row.customersuburb || row.deliveryaddress.slice(0, 20)}

                            </Typography>
                          </Tooltip>
                        </Stack> */}
                        <Stack direction={"row"} spacing={1}>
                          <Avatar
                            alt=""
                            size="sm"
                            sx={{
                              width: "25px",
                              height: "25px",
                            }}
                          ></Avatar>
                          <Stack direction="column">
                            <Typography variant="caption">
                              {row.deliverycustomer}
                            </Typography>
                            <Typography variant="caption" color="textSecondary">
                              {row.deliverycontactno}
                            </Typography>
                            <Tooltip title={row.deliveryaddress}>
                              <Typography
                                variant="caption"
                                color="textSecondary"
                              >
                                {/* {row.pickupaddress.slice(0, 20)} */}
                                {row.deliverysuburb ||
                                  row.deliveryaddress.slice(0, 20)}
                              </Typography>
                            </Tooltip>
                          </Stack>
                        </Stack>
                      </TableCell>
                      <TableCell align="left">{row.ordernotes}</TableCell>
                      {/* <TableCell align="left"><Chip label={row.itemcount} color="primary" variant="light" size="small" /></TableCell> */}
                      <TableCell align="left">
                        <Stack direction="row">
                          {row.orderstatus === "pending" && (
                            <Chip
                              label="Pending"
                              color="warning"
                              size="small"
                            />
                          )}
                          {row.orderstatus === "modified" && (
                            <Chip
                              label="Confirmed"
                              color="success"
                              size="small"
                            />
                          )}
                          {row.orderstatus === "cancelled" && (
                            <Chip
                              label="Cancelled"
                              color="error"
                              size="small"
                            />
                          )}
                          {row.orderstatus === "delivered" && (
                            <Chip
                              label="Completed"
                              color="primary"
                              size="small"
                            />
                          )}
                          {row.orderstatus === "processing" && (
                            <Chip
                              label="Processing"
                              color="primary"
                              size="small"
                            />
                          )}
                          {row.orderstatus === "ready" && (
                            <Chip label="Accepted" color="info" size="small" />
                          )}
                          {row.orderstatus === "confirmed" && (
                            <Chip
                              label="Confirmed"
                              color="success"
                              size="small"
                            />
                          )}

                          {row.orderstatus === "active" && (
                            <Chip label="Picked" color="info" size="small" />
                          )}
                          {row.orderstatus === "closed" && (
                            <Chip label="Closed" color="info" size="small" />
                          )}
                          {row.orderstatus === "created" && (
                            <Chip
                              label="Created"
                              color="secondary"
                              size="small"
                            />
                          )}
                          {row.orderstatus === "accepted" && (
                            <Chip
                              label="Accepted"
                              color="success"
                              size="small"
                            />
                          )}

                          {/* {(row.clientstatus === 'pending') &&
  
                              <Chip label="Pending" color="error" size="small" />
                            }
                            {(row.clientstatus === 'cancelled') &&
  
  
                              <Chip label="Cancelled" color="secondary" size="small" />
                            }
                            {(row.clientstatus === 'completed') &&
  
                              <Chip label="Completed" color="primary" size="small" />
                            }
                            {(row.clientstatus === 'processing') &&
                              <Chip label="Processing" color="primary" size="small" />
                            }
                            {(row.clientstatus === 'assigned') &&
                              <Chip label="Assigned" color="warning" size="small" />
                            }
                            {(row.clientstatus === 'confirmed') &&
                              <Chip label="Confirmed" color="success" size="small" />
                            }
  
                            {(row.clientstatus === 'active') &&
                              <Chip label="Active" color="info" size="small" />
                            }
                            {(row.clientstatus === 'closed') &&
                              <Chip label="Closed" color="info" size="small" />
                            }
  
                            {(row.clientstatus === 'modified') &&
                              <Chip label="Modified"
                                color='secondary'
  
                                size="small" variant='contained' />
                            } */}
                        </Stack>
                      </TableCell>
                      <TableCell>
                        {row.orderstatus == "created" &&
                          deliverylist.find(
                            (res1) => res1.orderheaderid == row.orderheaderid
                          ) && (
                            <>
                              {/* <Tooltip title='Accept'> */}
                              <IconButton
                                // disabled
                                aria-describedby={`aria-${row.sno}`}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  setAnchorEl(e.currentTarget);
                                  setOpen2(row.sno);
                                  // setOrderheaderid(row.orderheaderid)
                                  //           setOpen(true)
                                }}
                              >
                                <MoreOutlined />
                              </IconButton>
                              <Popper
                                id={`aria-${row.sno}`}
                                open={open2 == index + 1}
                                anchorEl={anchorEl}
                                placement="bottom-end"
                                sx={{
                                  zIndex: 5000,
                                  p: 0,
                                }}
                              >
                                <Box
                                  sx={{
                                    backgroundColor: "#fff",
                                    px: 2,
                                    py: 1,
                                    cursor: "pointer",
                                    boxShadow: theme.customShadows.z1,
                                  }}
                                  onClick={() => {
                                    setDialogopen(true);
                                    // setOpen1(true)
                                    handleClickAway();
                                  }}
                                >
                                  <ClickAwayListener
                                    onClickAway={handleClickAway}
                                  >
                                    <Typography>Assign</Typography>
                                  </ClickAwayListener>
                                </Box>
                              </Popper>
                              {/* </Tooltip> */}
                            </>
                          )}
                      </TableCell>
                      {/* <TableCell> */}

                      {/* <Tooltip title='Expand'>
  
                            <IconButton
                              aria-label="expand row"
                              style={{ color: theme.palette.primary.main }}
                              onClick={() => {
                                setExpandopen((expandopen === row.sno) ? '' : row.sno)
  
                              }
                              }
                            >
                              {(expandopen === row.sno) ?
                                <KeyboardArrowUpIcon />
                                :
                                <KeyboardArrowDownIcon />}
                            </IconButton>
                          </Tooltip> */}

                      {/* <TableCell> */}

                      {/* {(row.orderstatus == 'created')&&

    <>
    
                                
                          <Tooltip title='Cancel'>
                            <IconButton
                            disabled
                              onClick={(e) => {
                                e.stopPropagation();
                      setOrderheaderid(row.orderheaderid)
                                setOpen(true)
                              
                              }}>
                              <CloseOutlined
                              style={{
                                color:theme.palette.error.main,
                           
                              }}
                                />
                            </IconButton>
                          </Tooltip>
                          </>

} */}
                      {/* </TableCell> */}
                    </TableRow>
                    <TableRow>
                      <TableCell
                        style={{
                          paddingBottom: 0,
                          paddingTop: 0,
                          paddingLeft: 0,
                          paddingRight: 0,
                        }}
                        colSpan={8}
                        sx={{ width: "100%" }}
                      >
                        <Collapse
                          in={expandopen === row.sno}
                          timeout="auto"
                          unmountOnExit
                        >
                          {/* <Grid container sx={{ width: '100%' }}>
                              {(row.ordershifts).map((val5, k) => {
                                return <>
                                  <Grid item sx={{ width: '100%', m: 1 }}>
                                    <MainCard sx={{
                                      opacity: ((val5.shiftstatus == 1) || (val5.status == 1)) ? '0.6' : ''
  
                                    }}>
  
                                      <Stack direction={{ xs: 'column', md: 'row' }} spacing={2} sx={{ p: 2 }} alignItems={{ md: 'center' }}>
                                        <Typography>Shift {k + 1}</Typography>
  
                                        <Typography color="secondary"  >
                                          <EnvironmentOutlined /> {''}{val5.locationaddress}
                                        </Typography>
                                        <Grid item>
                                          {((val5.shiftstatus == 1) || (val5.status == 1)) &&
                                            <Chip label="Cancelled" color='secondary' />
                                          }
                                        </Grid>
                                      </Stack>
  
  
                                      <TableContainer  >
                                        <Table sx={{ width: '100%' }} >
                                          <TableHead >
                                            <TableRow
  
                                            >
                                              <TableCell></TableCell>
                                              <TableCell>#</TableCell>
                                              <TableCell>Role</TableCell>
                                              <TableCell>Start Date</TableCell>
                                              <TableCell>End Date</TableCell>
                                              <TableCell>Unpaid break</TableCell>
                                              <TableCell align="center">Count</TableCell>
                                              <TableCell align="center">Assigned</TableCell>
                                              <TableCell align="right">Price</TableCell>
                                              <TableCell align="right">Amount</TableCell>
                                              <TableCell align="left">Assigned Roles</TableCell>
  
  
                                            </TableRow>
                                          </TableHead>
                                          <TableBody>
  
                                            {((val5.orderdetails) ? val5.orderdetails : []).map((val, i) => {
  
                                              return <>
  
                                                <TableRow key={i}
  
                                                  sx={{
                                                    opacity: (val.status == 0) ? '' : '0.6'
                                                  }}
                                                >
                                                  <TableCell></TableCell>
                                                  <TableCell>{i + 1}</TableCell>
                                                  <TableCell>
                                                    {val.productname}
                                                  </TableCell>
  
                                                  <TableCell>
                                                    <Stack direction="column">
                                                      <Typography variant="body1">
                                                        {dayjs(val.starttime).format('MM/DD/YYYY')}
                                                      </Typography>
                                                      <Typography variant="body2">
                                                        {dayjs(val.starttime).format('hh:mm A')}
                                                      </Typography>
                                                    </Stack>
                                                  </TableCell>
                                                  <TableCell>
                                                    {' '}
                                                    <Stack direction="column">
                                                      <Typography variant="body1">
                                                        {dayjs(val.endtime).format('MM/DD/YYYY')}
                                                      </Typography>
                                                      <Typography variant="body2">
                                                        {dayjs(val.endtime).format('hh:mm A')}
                                                      </Typography>
                                                    </Stack>
                                                  </TableCell>
                                                  <TableCell>
                                                    {val.unpaidbreak || 0}
                                                  </TableCell>
                                                  <TableCell align="center">
                                                    <Chip label={val.orderqty} color="primary" variant="light" size="small" />
  
                                                  </TableCell>
                                                  <TableCell align="center">
                                                    <Chip label={val.supplyqty} color={(val.supplyqty > 0) ? "warning" : "error"} variant="light" size="small" />
                                                  </TableCell>
                                                  <TableCell align="right">${val.price}</TableCell>
                                                  <TableCell align="right">${val.landingamount}</TableCell>
                                                  <TableCell >
  
                                                    <Tooltip title='Assigned staffs'>
                                                      <Button sx={{ minWidth: '10px !important' }}
                                                        onClick={(e) => {
                                                          e.stopPropagation();
                                                          setStafflist([])
                                                          fetchstafflist(val.orderdetailid)
                                                          setDialogopen(true)
                                                        }}
                                                      >
                                                        <UserOutlined />
                                                      </Button>
                                                    </Tooltip>
                                                  </TableCell>
  
                                                </TableRow>
                                              </>
  
                                            })}
  
                                          </TableBody>
                                        </Table>
                                      </TableContainer >
                                    </MainCard>
                                  </Grid>
  
  
  
  
  
                                  <Dialog maxWidth={false} fullWidth={true}
                                    open={dialogopen} onClose={dialogclose}
  
                                    scroll={'paper'}
                                    TransitionComponent={PopupTransition}>
  
                                    <DialogTitle>
                                      <Stack direction={'row'} justifyContent={'space-between'}>
                                        <Stack direction={{
                                          xs: 'column'
                                        }} spacing={2} alignItems={'flex-start'}>
                                          <Typography variant='h3'>Assigned Roles</Typography>
                                          {(stafflist[0]) &&
  
                                            <Chip icon={<EnvironmentOutlined />} label={stafflist[0].locationaddress} variant="light" color="primary" />
                                          }
                                        </Stack>
                                        {(stafflist[0]) &&
                                          <Chip label={stafflist[0].orderid} variant="combined" color='warning' size={'large'} />
  
                                        }
  
                                      </Stack>
                                      <Grid container sx={{ p: 1 }} spacing={2}>
  
                                        <Grid item sm={6} xs={12}>
  
  
                                        </Grid>
                                        <Grid item sm={6} xs={12}>
  
  
                                        </Grid>
                                      </Grid>
                                    </DialogTitle>
                                    <DialogContent dividers={true}>
  
                                      {(stafflist.length === 0) ?
                                        <>
                                          {(loading1) ?
                                            <>
  
  
                                              <Stack alignItems={'center'}>
                                                <CircularProgress />
                                              </Stack>
  
                                            </>
                                            :
                                            <Typography>No Staffs has been Assigned</Typography>
  
                                          }
                                        </>
                                        :
  
                                        <TableContainer>
                                          <Table>
                                            <TableHead>
                                              <TableRow>
                                                <TableCell>#</TableCell>
                                                <TableCell>Staff</TableCell>
                                                <TableCell>Start Time</TableCell>
                                                <TableCell>End Time</TableCell>
                                                <TableCell>Pay Rate</TableCell>
  
                                                <TableCell align='center'>Clockin</TableCell>
                                                <TableCell align='center'>Clockout</TableCell>
  
                                                <TableCell>Hours Worked</TableCell>
  
  
                                                <TableCell>Status</TableCell>
  
                                              </TableRow>
                                            </TableHead>
                                            <TableBody>
                                              {stafflist.map((val, i) => {
  
                                                return <Fragment key={i}>
  
  
                                                  <TableRow sx={{
  
                                                  }}>
                                                    <TableCell component="th"
                                                      scope="row" padding="none">
                                                      {i + 1}
                                                    </TableCell>
  
                                                    <TableCell align="left">
                                                      <Stack direction="column">
                                                        <Typography variant="caption">
                                                          {val.staffname}
                                                        </Typography>
                                                        <Grid>
                                                          <Chip label={val.productname} color="info" variant="light" size="small" />
                                                        </Grid>
                                                      </Stack>
                                                    </TableCell>
                                                    <TableCell>
                                                      <Stack direction="column">
                                                        <Typography variant="body2">{dayjs(val.Starttime).format('MM/DD/YYYY')}</Typography>
                                                        <Typography variant="caption">{dayjs(val.Starttime).format('hh:mm A')}</Typography>
                                                      </Stack>
                                                    </TableCell>
                                                    <TableCell>
                                                      <Stack direction="column">
                                                        <Typography variant="body2">{dayjs(val.Endtime).format('MM/DD/YYYY')}</Typography>
                                                        <Typography variant="caption">{dayjs(val.Endtime).format('hh:mm A')}</Typography>
                                                      </Stack>
                                                    </TableCell>
                                                    <TableCell>{val.rolecost}</TableCell>
  
  
                                                    <TableCell>
                                                      <Stack spacing={0.5}
                                                        alignItems="center"
                                                      >
  
                                                        <Chip label={(val.clockin) ? dayjs(val.clockin).format('MM/DD/YYYY') : ''} color="primary" variant="light" size="small" />
                                                        <Chip label={(val.clockin) ? dayjs(val.clockin).format('hh:mm A') : ''} color="info" variant="light" size="small" />
  
                                                      </Stack>
                                                    </TableCell>
                                                    <TableCell>
                                                      <Stack spacing={0.5}
                                                        alignItems="center"
                                                      >
  
                                                        <Chip label={(val.clockout) ? dayjs(val.clockout).format('MM/DD/YYYY') : ''} color="primary" variant="light" size="small" />
                                                        <Chip label={(val.clockout) ? dayjs(val.clockout).format('hh:mm A') : ''} color="info" variant="light" size="small" />
  
                                                      </Stack>
                                                    </TableCell>
                                                    <TableCell>
                                                      {val.hoursworked}
                                                    </TableCell>
  
  
  
                                                    <TableCell align="left">
                                                      <Stack direction="row">
  
                                                        {(val.orderstatus === 'pending') &&
  
                                                          <Chip label="Pending" color="error" size="small" />
                                                        }
                                                        {(val.orderstatus === 'cancelled') &&
  
  
                                                          <Chip label="Cancelled" color="secondary" size="small" />
                                                        }
                                                        {(val.orderstatus === 'completed') &&
  
                                                          <Chip label="Completed" color="primary" size="small" />
                                                        }
                                                        {(val.orderstatus === 'processing') &&
                                                          <Chip label="Processing" color="primary" size="small" />
                                                        }
                                                        {(val.orderstatus === 'assigned') &&
                                                          <Chip label="Assigned" color="warning" size="small" />
                                                        }
                                                        {(val.orderstatus === 'confirmed') &&
                                                          <Chip label="Confirmed" color="success" size="small" />
                                                        }
  
                                                        {(val.orderstatus === 'active') &&
                                                          <Chip label="Active" color="info" size="small" />
                                                        }
                                                        {(val.orderstatus === 'closed') &&
                                                          <Chip label="Closed" color="info" size="small" />
                                                        }
                                                      </Stack>
  
                                                    </TableCell>
                                                  </TableRow>
                                                </Fragment>
  
                                              })
                                              }
                                            </TableBody>
                                          </Table>
                                        </TableContainer>
                                      }
                                    </DialogContent>
                                    <DialogActions>
                                      <Stack sx={{ mt: 2 }} direction='row' justifyContent='flex-end' spacing={5}>
  
                                        <Button sx={{ width: '130px' }} color='error' variant='contained' onClick={() => { dialogclose() }}>Close</Button>
                                      </Stack>
                                    </DialogActions>
                                  </Dialog >
                                </>
                              })
  
  
                              }
  
  
                            </Grid> */}
                        </Collapse>
                      </TableCell>
                    </TableRow>
                  </>
                );
              })}
              {emptyRows > 0 && (
                <TableRow
                  style={{
                    height: 53 * emptyRows,
                  }}
                >
                  <TableCell colSpan={8} />
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        <TablePagination
          rowsPerPageOptions={[10, 25, 50, 100]}
          component="div"
          count={rows.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        />
      </Box>
    );
  }

  const [startdate, setStartdate] = useState(
    ""
    // dayjs().format('YYYY-MM-DD')
  );
  const [enddate, setEnddate] = useState(
    ""
    // dayjs().format('YYYY-MM-DD')
  );

  const [tenantid, setTenantid] = useState("");

  const [percentage1, setPercentage1] = useState("0");
  const [percentage2, setPercentage2] = useState("0");
  const [percentage3, setPercentage3] = useState("0");
  const [percentage4, setPercentage4] = useState("0");
  let [orderarr, setArr] = useState([]);
  let [orderarrcovered, setArrcovered] = useState([]);
  let [orderarractive, setArractive] = useState([]);
  let [orderarruncovered, setArruncovered] = useState([]);
  let [orderarrcancelled, setArrcancelled] = useState([]);
  let [orderarrassigned, setArrassigned] = useState([]);
  let [orderarrconfirmed, setArrconfirmed] = useState([]);
  let [orderarrmodified, setArrmodified] = useState([]);
  let [orderarrclosed, setArrclosed] = useState([]);
  let [orderarrpicked, setArrpicked] = useState([]);
  let [orderarrcreated, setArrcreated] = useState([]);

  const [allorders, setAllorders] = useState("");
  const [activeorders, setActiveorders] = useState("");
  const [coveredorders, setCoveredorders] = useState("");
  const [uncoveredorders, setUncoveredorders] = useState("");
  const [cancelled, setCancelled] = useState("");

  const [assigned, setAssigned] = useState("");
  const [confirmed, setConfirmed] = useState("");
  const [modified, setModified] = useState("");
  const [completed, setCompleted] = useState("");
  const [closed, setClosed] = useState("");
  const [picked, setPicked] = useState("");
  const [created, setCreated] = useState("");

  const [tabstatus, setTabstatus] = useState("Created");
  const [loading, setLoading] = useState(false);
  const theme = useTheme();
  let [rows, setRows] = useState([]);
  const [tabvalue, setTabvalue] = useState(0);
  let navigate = useNavigate();
  const [open, setOpen] = useState(false);
  const [dateselect, setDateselect] = useState("select");

  // const [tabstatus1, setTabstatus1] = useState('All');
  const [tabstatus1, setTabstatus1] = useState("Today");

  // const [datestatus, setDatestatus] = useState('All');
  const [datestatus, setDatestatus] = useState("Today");

  const [searchword, setSearchword] = useState("");

  const handleChangetab = (e, i) => {
    setTabvalue(i);

    // if (i === 0) setTabstatus('All orders')
    if (i === 0) setTabstatus("Created");
    // if (i === 2) setTabstatus('Modified')
    if (i === 1) setTabstatus("Pending");

    // if (i === 2) setTabstatus('Assigned')
    // if (i === 3) setTabstatus('Picked')
    if (i === 2) setTabstatus("Delivered");
    if (i === 3) setTabstatus("Cancelled");

    // if (i === 0) setTabstatus('All orders')
    // if (i === 1) setTabstatus('Pending')
    // if (i === 1) setTabstatus('Modified')

    // if (i === 3) setTabstatus('Assigned')
    // if (i === 0) setTabstatus('Confirmed')
    //   if (i === 2) setTabstatus('Completed')
    //   if (i === 3) setTabstatus('Closed')

    console.log(i);
  };

  useEffect(() => {
    console.log(localStorage.getItem("appuserid"));

    if (localStorage.getItem("partnerid")) {
      setTenantid(localStorage.getItem("tenantid"));
      let val = localStorage.getItem("partnerid");

      // fetchtable(val);
      fetchpercentage(val);
      // fetchtableactive();
      fetchtableuncovered(val);
      fetchtablecovered(val);
      fetchtablecancelled(val);
      // fetchtableassigned(val);
      // fetchtablepicked(val);
      fetchtablecreated(val);
      // fetchtableconfirmed(val);
      // fetchtablemodified(val);
      // fetchtableclosed(val)
      // fetchtable(val)
      // console.log(activeorders);
      fetchpaymenttype();
      fetchriderslist(val);
    }
  }, []);

  useEffect(() => {
    if (localStorage.getItem("partnerid")) {
      let val = localStorage.getItem("partnerid");

      // fetchtable();
      fetchpercentage(val);
      // fetchtableactive();
      fetchtableuncovered(val);
      fetchtablecovered(val);
      fetchtablecancelled(val);
      // fetchtableassigned(val);
      // fetchtablepicked(val);
      // fetchtableconfirmed(val);
      // fetchtablemodified(val);
      // fetchtableclosed(val)
      // fetchtable(val)
      fetchtablecreated(val);

      // console.log(activeorders);
    }
  }, [
    startdate,
    enddate,
    // tabvalue
  ]);

  useEffect(() => {
    // if (tabstatus === 'All orders') setRows(orderarr)
    // if (tabstatus === 'Completed') setRows(orderarrcovered)
    // if (tabstatus === 'Active') setRows(orderarractive)
    // if (tabstatus === 'Pending') setRows(orderarruncovered)
    // if (tabstatus === 'Cancelled') setRows(orderarrcancelled)
    // if (tabstatus === 'Assigned') setRows(orderarrassigned)
    // if (tabstatus === 'Confirmed') setRows(orderarrconfirmed)
    if (tabstatus === "Created") setRows(orderarrcreated);

    if (tabstatus === "All orders") setRows(orderarr);
    if (tabstatus === "Delivered") setRows(orderarrcovered);
    if (tabstatus === "Pending") setRows(orderarruncovered);

    // if (tabstatus === 'Active') setRows(orderarractive)
    // if (tabstatus === 'Pending') setRows(orderarruncovered)
    if (tabstatus === "Cancelled") setRows(orderarrcancelled);
    if (tabstatus === "Assigned") setRows(orderarrassigned);
    //   if (tabstatus === 'Confirmed') setRows(orderarrconfirmed)
    //   if (tabstatus === 'Modified') setRows(orderarrmodified)
    //   if (tabstatus === 'Closed') setRows(orderarrclosed)
    if (tabstatus === "Picked") setRows(orderarrpicked);
  }, [tabstatus]);

  const okclicked = () => {
    setOpen(false);
  };

  useEffect(() => {
    var day = 60 * 60 * 24 * 1000;
    var startDate = new Date();
    if (tabstatus1 === "Tomorrow") {
      setEnddate(
        new Date(startDate.getTime() + day).toISOString().substring(0, 10)
      );
      setStartdate(
        new Date(startDate.getTime() + day).toISOString().substring(0, 10)
      );
      setDateselect("select");
    } else if (tabstatus1 === "Today") {
      setEnddate(new Date().toISOString().substring(0, 10));
      setStartdate(new Date().toISOString().substring(0, 10));
      setDateselect("select");
    } else if (tabstatus1 === "Week") {
      setStartdate(
        new Date(startDate.getTime() - day * 7).toISOString().substring(0, 10)
      );
      setEnddate(new Date().toISOString().substring(0, 10));
      setDateselect("select");
    } else if (tabstatus1 === "All") {
      setEnddate("");
      setStartdate("");

      setDateselect("all");
    }
  }, [tabstatus1]);

  const choosedate = (date) => {
    setStartdate(date.$d.toISOString().substring(0, 10));
    setEnddate(date.$d.toISOString().substring(0, 10));
    setTabstatus1("");
  };
  useEffect(() => {
    if (tabstatus === "All Orders") {
      if (searchword) {
        let arr = orderarr.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.deliveryaddress
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            val.pickupaddress
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.ordernotes
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarr]);
      }
    } else if (tabstatus === "Delivered") {
      if (searchword) {
        let arr = orderarrcovered.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.ordernotes
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrcovered]);
      }
    } else if (tabstatus === "Active") {
      if (searchword) {
        let arr = orderarractive.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.eventname.toLowerCase().includes(searchword.toLowerCase()) ||
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            val.ordervalue
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarractive]);
      }
    } else if (tabstatus === "Pending") {
      if (searchword) {
        let arr = orderarruncovered.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.ordernotes
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarruncovered]);
      }
    } else if (tabstatus === "Cancelled") {
      if (searchword) {
        let arr = orderarrcancelled.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.ordernotes
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrcancelled]);
      }
    } else if (tabstatus === "Assigned") {
      if (searchword) {
        let arr = orderarrassigned.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.ordernotes
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrassigned]);
      }
    } else if (tabstatus === "Confirmed") {
      if (searchword) {
        let arr = orderarrconfirmed.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.ordernotes
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrconfirmed]);
      }
    } else if (tabstatus === "Modified") {
      if (searchword) {
        let arr = orderarrmodified.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.eventname.toLowerCase().includes(searchword.toLowerCase()) ||
            val.tenantname.toLowerCase().includes(searchword.toLowerCase()) ||
            val.ordervalue
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.deliveryaddress
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.contactno
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrmodified]);
      }
    } else if (tabstatus === "Closed") {
      if (searchword) {
        let arr = orderarrclosed.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.eventname.toLowerCase().includes(searchword.toLowerCase()) ||
            val.tenantname.toLowerCase().includes(searchword.toLowerCase()) ||
            val.ordervalue
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.deliveryaddress
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.contactno
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      }
    } else if (tabstatus === "Picked") {
      if (searchword) {
        let arr = orderarrpicked.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.ordernotes
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.deliveryaddress
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.customername.toLowerCase().includes(searchword.toLowerCase()) ||
            val.contactno
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrpicked]);
      }
    } else if (tabstatus === "Created") {
      if (searchword) {
        let arr = orderarrcreated.filter((val) => {
          return (
            val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
            val.pickupaddress
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.ordernotes
              .toString()
              .toLowerCase()
              .includes(searchword.toLowerCase()) ||
            val.deliveryaddress.toLowerCase().includes(searchword.toLowerCase())
            // || val.customername.toLowerCase().includes(searchword.toLowerCase())
            // || val.contactno.toString().toLowerCase().includes(searchword.toLowerCase())
          );
        });
        console.log(arr);
        setRows([...arr]);
      } else {
        setRows([...orderarrcreated]);
      }
    }
  }, [orderarr, searchword]);

  const handleChange1 = (e) => {
    setTabstatus1(e.target.innerText);
    setDatestatus(e.target.innerText);
  };

  const fetchtable = async (tid) => {
    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/partner/getorders/?partnerid=${tid}`
        )
        .then((res) => {
          if (res.data.status) {
            let arr = [];
            res.data.details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            setArr(arr);
            console.log(res.data.Details);
            if (tabstatus == "All Orders") {
              setRows(arr);
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtablecovered = async (tid) => {
    setLoading(true);
    try {
      // await axios.get(`${process.env.REACT_APP_URL}/orders/getorders/?tenantid=${tid}&status=completed`)
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/partner/getorders/?partnerid=${tid}&status=delivered&fromdate=${startdate}&todate=${enddate}`
        )
        .then((res) => {
          // if (res.data.message === "Success") {
          let arr = [];
          res.data.details.map((val, i) => {
            arr = [...arr, { ...val, sno: i + 1 }];
          });
          setArrcovered(arr);
          if (tabstatus == "Delivered") {
            setRows([...arr]);
          }
          // }
          setLoading(false);
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
        });
    } catch (err) {
      console.log(err);
      setLoading(false);
    }
  };

  const fetchtablecreated = async (tid) => {
    setLoading(true);
    try {
      // await axios.get(`${process.env.REACT_APP_URL}/orders/getorders/?tenantid=${tid}&status=completed`)
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/partner/getorders/?partnerid=${tid}&status=created&fromdate=${startdate}&todate=${enddate}`
        )
        .then((res) => {
          // if (res.data.message === "Success") {
          let arr = [];
          res.data.details.map((val, i) => {
            arr = [...arr, { ...val, sno: i + 1 }];
          });
          setArrcreated(arr);
          if (tabvalue == 0) {
            setRows(arr);
          }
          setLoading(false);

          // }
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
        });
    } catch (err) {
      console.log(err);
      setLoading(false);
    }
  };

  const fetchtableactive = async () => {
    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL2}/orders/orderliststatus?fromdate=${startdate}&todate=${enddate}&type=${dateselect}&status=processing&sort=desc`
        )
        .then((res) => {
          if (res.data.message === "Success") {
            let arr = [];
            res.data.Details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            setArractive(arr);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtableuncovered = async (tid) => {
    setLoading(true);

    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/partner/getorders/?partnerid=${tid}&status=pending&fromdate=${startdate}&todate=${enddate}`
        )
        .then((res) => {
          if (res.data.message === "Success") {
            let arr = [];
            res.data.details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            setArruncovered(arr);
            if (tabstatus == "Pending") {
              setRows([...arr]);
            }
          }
          setLoading(false);
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
        });
    } catch (err) {
      console.log(err);
      setLoading(false);
    }
  };

  const fetchtablecancelled = async (tid) => {
    setLoading(true);

    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/partner/getorders/?partnerid=${tid}&status=cancelled&fromdate=${startdate}&todate=${enddate}`
        )
        // await axios.get(`${process.env.REACT_APP_URL2}/client/orders/getordersbystatus?tenantid=${tid}&status=cancelled`)

        .then((res) => {
          // if (res.data.message === "Success") {
          let arr = [];
          console.log(res.data.details);
          res.data.details.map((val, i) => {
            arr = [...arr, { ...val, sno: i + 1 }];
          });
          setArrcancelled([...arr]);
          if (tabstatus == "Cancelled") {
            setRows([...arr]);
          }
          setLoading(false);
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
        });
    } catch (err) {
      console.log(err);
      setLoading(false);
    }
  };

  const fetchtableassigned = async (tid) => {
    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/partner/getorders/?partnerid=${tid}&status=accepted`
        )
        .then((res) => {
          // if (res.data.message === "Success") {
          let arr = [];
          console.log(res.data.details);
          res.data.details.map((val, i) => {
            arr = [...arr, { ...val, sno: i + 1 }];
          });
          setArrassigned(arr);
          // }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtablepicked = async (tid) => {
    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/partner/getorders/?partnerid=${tid}&status=picked`
        )
        .then((res) => {
          // if (res.data.message === "Success") {
          let arr = [];
          console.log(res.data.details);
          res.data.details.map((val, i) => {
            arr = [...arr, { ...val, sno: i + 1 }];
          });
          setArrpicked(arr);
          // }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtableconfirmed = async (tid) => {
    try {
      // await axios.get(`${process.env.REACT_APP_URL2}/orders/orderliststatus?fromdate=${startdate}&todate=${enddate}&type=${dateselect}&status=confirmed&sort=desc`)
      await axios
        .get(
          `${process.env.REACT_APP_URL2}/orders/partner/getorders/?partnerid=${tid}&status=confirmed&fromdate=${startdate}&todate=${enddate}`
        )

        .then((res) => {
          if (res.data.message === "Success") {
            let arr = [];
            console.log(res.data.Details);
            res.data.Details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            setArrconfirmed(arr);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtablemodified = async (tid) => {
    try {
      // await axios.get(`${process.env.REACT_APP_URL2}/orders/orderliststatus?fromdate=${startdate}&todate=${enddate}&type=${dateselect}&status=modified&sort=desc`)
      await axios
        .get(
          `${process.env.REACT_APP_URL2}/orders/partner/gettenantorders/?partnerid=${tid}&status=modified&fromdate=${startdate}&todate=${enddate}`
        )

        .then((res) => {
          if (res.data.message === "Success") {
            let arr = [];
            console.log(res.data.Details);
            res.data.Details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            setArrmodified(arr);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchtableclosed = async (tid) => {
    try {
      // await axios.get(`${process.env.REACT_APP_URL2}/orders/orderliststatus?fromdate=${startdate}&todate=${enddate}&type=${dateselect}&status=modified&sort=desc`)
      await axios
        .get(
          `${process.env.REACT_APP_URL2}/orders/partner/gettenantorders/?partnerid=${tid}&status=closed&fromdate=${startdate}&todate=${enddate}`
        )
        .then((res) => {
          if (res.data.message === "Success") {
            let arr = [];
            console.log(res.data.Details);
            res.data.Details.map((val, i) => {
              arr = [...arr, { ...val, sno: i + 1 }];
            });
            setArrclosed(arr);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchpercentage = async (tid) => {
    setLoading(true);
    try {
      // await axios.get(`${process.env.REACT_APP_URL}/orders/getordersummary/?partnerid=${tid}&fromdate=${startdate}&todate=${enddate}`)
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/getordersummary/?partnerid=${tid}`
        )
        .then((res) => {
          console.log(res);
          // setConfirmed(res.data.details.confirmed.toString());
          // setModified(res.data.details.modified.toString());
          setAllorders(res.data.details.total.toString());
          setCoveredorders(res.data.details.delivered.toString());

          setCancelled(res.data.details.cancelled.toString());
          setUncoveredorders(res.data.details.pending.toString());
          // setActiveorders(res.data.details.assigned.toString());
          // setAssigned(res.data.details.accepted.toString());
          setCreated(res.data.details.created.toString());
          setClosed(res.data.details.delivered.toString());
          // setPicked(res.data.details.picked.toString())
          setPercentage1(
            (
              Math.round(
                (res.data.details.created / res.data.details.total) * 100
              ) || 0
            ).toString()
          );
          setPercentage3(
            (
              Math.round(
                (res.data.details.delivered / res.data.details.total) * 100
              ) || 0
            ).toString()
          );

          setPercentage4(
            (
              Math.round(
                (res.data.details.cancelled / res.data.details.total) * 100
              ) || 0
            ).toString()
          );

          setPercentage2(
            (
              Math.round(
                (res.data.details.pending / res.data.details.total) * 100
              ) || 0
            ).toString()
          );

          setLoading(false);
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
          enqueueSnackbar(err.message, {
            variant: "error",
            anchorOrigin: { vertical: "top", horizontal: "right" },
            autoHideDuration: 2000,
          });
        });
    } catch (err) {
      console.log(err);
      setLoading(false);
    }
  };

  const fetchpaymenttype = async (tid) => {
    try {
      await axios
        .get(`${process.env.REACT_APP_URL}/utils/getapptypes/?tag=paymentmode`)
        .then((res) => {
          let arr = [];
          res.data.map((val) => {
            arr.push({
              ...val,
              label: val.typename,
            });
          });

          setPaymentmode(arr);
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  const fetchriderslist = async (tid) => {
    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL}/partners/getriders/?partnerid=${tid}`
        )
        .then((res) => {
          let arr = [];
          res.data.details.map((val) => {
            arr.push({
              ...val,
              label: `${val.firstname} ${val.lastname} | ${val.contactno}`,
            });
          });
          setRiderslist([...arr]);
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <>
      {loading && <Loader />}
      <Grid container rowSpacing={4.5} columnSpacing={2.75}>
        <Grid item xs={12} sx={{ mb: -2.25 }}>
          <Stack
            direction={{ xs: "column", md: "row" }}
            justifyContent="space-between"
            alignItems="center"
            spacing={2}
          >
            <Stack direction="column" alignItems="flex-start" spacing={1}>
              <Typography variant="h3">Orders</Typography>
              {/* {(startdate && enddate) &&
              <Stack direction='row' spacing={2}>
                <Chip label={`Orders-${datestatus}`} color="primary" variant="light" size="small" />
                <Chip label={<Typography noWrap color="secondary">{dayjs(startdate).format('DD/MM/YYYY')} - {dayjs(enddate).format('DD/MM/YYYY')}</Typography>} variant="combined" color='warning' size='small' />


              </Stack>
            }
            {(!startdate || !enddate) &&
              <>
                <Stack direction='row' spacing={2}>
                  <Chip label='Orders-All' color="primary" variant="light" size="small" />
                </Stack>
              </>
            } */}

              {/* </Stack> */}
              {/* 
              <Stack direction='row' spacing={2}>
                <Chip label='Orders-All' color="primary" variant="light" size="small" />
              </Stack> */}
            </Stack>

            {/* <Stack direction='row' spacing={1}
              sx={{ mt: { md: 0, xs: 2 }, p: 1, display: { xs: 'block', md: 'none' } }}
            >
              <Button
                variant={(tabstatus1 === 'Today') ? 'contained' : 'outlined'} onClick={handleChange1}
  
  
                sx={{ borderRadius: '40px' }} size="small">Today</Button>
              <Button
                variant={(tabstatus1 === 'Tomorrow') ? 'contained' : 'outlined'} onClick={handleChange1}
  
                sx={{ borderRadius: '40px' }} size="small" >Tomorrow</Button>
              <Button
                variant={(tabstatus1 === 'Week') ? 'contained' : 'outlined'} onClick={handleChange1}
  
                sx={{ borderRadius: '40px' }} size="small">Week</Button>
              <Button
                variant={(tabstatus1 === 'All') ? 'contained' : 'outlined'} onClick={handleChange1}
  
                sx={{ borderRadius: '40px' }} size="small">All</Button>
            </Stack>
  
  
  
            <Box
              sx={{ backgroundColor: 'white', display: { xs: 'block', md: 'none' } }}
  
            >
  
  
  
              <LocalizationProvider dateAdapter={AdapterDayjs} >
                <DatePicker
                  label="Date"
                  value={dayjs(startdate)}
                  onChange={choosedate}
  
                />
              </LocalizationProvider>
  
  
  
            </Box>*/}
            {/* <Button onClick={()=>{
            notifyrider('id3')
          }}>notify</Button> */}
            {/* <Tooltip title='Order Filter'>
            <IconButton





              color="secondary"
              variant="light"
              sx={{ color: 'text.primary', bgcolor: 'grey.200', display: { xs: 'none', md: 'flex' } }}

              aria-haspopup="true"




              onClick={() => setOpen(true)} >
              <FilterList />
            </IconButton>
          </Tooltip> */}
          </Stack>
        </Grid>
        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: "pointer" }}
          onClick={() => {
            setTabvalue(0);
            handleChangetab(1, 0);
            setStartdate("");
            setEnddate("");
          }}
        >
          <HoverSocialCard
            primary="Created orders"
            secondary={
              created === "" ? (
                <Skeleton sx={{ width: "30px" }} animation="wave" />
              ) : (
                created
              )
            }
            percentage={percentage1.toString()}
            color={theme.palette.primary.main}
          />
        </Grid>
        {/* <Grid item xs={12} lg={3} sm={6}>
          <HoverSocialCard primary="Confirmed orders" secondary={(confirmed === '') ?
  
            <Skeleton sx={{ width: '30px' }} animation="wave" />
  
            : confirmed} percentage={percentage1.toString()} color={theme.palette.success.main} />
        </Grid> */}

        {/* <Grid item xs={12} lg={3} sm={6}>
          <HoverSocialCard primary="Modified Orders" secondary={(cancelled === '') ?
            <Skeleton sx={{ width: '30px' }} animation="wave" />
  
            : modified} percentage={percentage2.toString()} color={theme.palette.secondary[600]} />
        </Grid> */}
        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: "pointer" }}
          onClick={() => {
            setTabvalue(1);
            handleChangetab(1, 1);

            setStartdate("");
            setEnddate("");
          }}
        >
          <HoverSocialCard
            primary="Pending orders"
            secondary={
              uncoveredorders == "" ? (
                <Skeleton sx={{ width: "30px" }} animation="wave" />
              ) : (
                uncoveredorders
              )
            }
            percentage={percentage2.toString()}
            color={theme.palette.warning.main}
          />
        </Grid>
        {/*
        <Grid item xs={12} lg={3} sm={6}>
          <HoverSocialCard primary="Accepted orders" secondary={(assigned === '') ?
            <Skeleton sx={{ width: '30px' }} animation="wave" />
  
            : assigned} percentage={percentage2.toString()} color={theme.palette.info.main} />
        </Grid>
        <Grid item xs={12} lg={3} sm={6}>
          <HoverSocialCard primary="Picked orders" secondary={(picked === '') ?
            <Skeleton sx={{ width: '30px' }} animation="wave" />
  
            : picked} percentage={percentage3.toString()} color={theme.palette.primary.main} />
        </Grid>*/}
        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: "pointer" }}
          onClick={() => {
            setTabvalue(2);
            handleChangetab(1, 2);

            setStartdate("");
            setEnddate("");
          }}
        >
          <HoverSocialCard
            primary="Delivered orders"
            secondary={
              coveredorders === "" ? (
                <Skeleton sx={{ width: "30px" }} animation="wave" />
              ) : (
                coveredorders
              )
            }
            percentage={percentage3.toString()}
            color={theme.palette.success.main}
          />
        </Grid>
        {/*   
        <Grid item xs={12} lg={3} sm={6}>
          <HoverSocialCard primary="Closed orders" secondary={(closed === '') ?
            <Skeleton sx={{ width: '30px' }} animation="wave" />
  
            : closed} percentage={percentage4.toString()} color={theme.palette.warning.main} />
        </Grid>*/}

        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: "pointer" }}
          onClick={() => {
            setTabvalue(3);
            handleChangetab(1, 3);

            setStartdate("");
            setEnddate("");
          }}
        >
          <HoverSocialCard
            primary="Cancelled Orders"
            secondary={
              cancelled === "" ? (
                <Skeleton sx={{ width: "30px" }} animation="wave" />
              ) : (
                cancelled
              )
            }
            percentage={percentage4.toString()}
            color={theme.palette.secondary[600]}
          />
        </Grid>

        <Grid item xs={12} sx={{ mb: -3 }}>
          <Stack direction={"row"} justifyContent={"space-between"}>
            {startdate && enddate && (
              <Stack direction="row" spacing={2}>
                <Chip
                  label={`Orders-${datestatus}`}
                  color="primary"
                  variant="light"
                  size="small"
                />
                <Chip
                  label={
                    <Typography noWrap color="secondary">
                      {dayjs(startdate).format("DD/MM/YYYY")} -{" "}
                      {dayjs(enddate).format("DD/MM/YYYY")}
                    </Typography>
                  }
                  variant="combined"
                  color="warning"
                  size="small"
                />
              </Stack>
            )}
            {(!startdate || !enddate) && (
              <>
                <Stack direction="row" spacing={2}>
                  <Chip
                    label="Orders-All"
                    color="primary"
                    variant="light"
                    size="small"
                  />
                </Stack>
              </>
            )}

            <Tooltip title="Order Filter">
              <IconButton
                color="secondary"
                variant="light"
                sx={{
                  color: "text.primary",
                  bgcolor: "grey.200",
                  display: { xs: "none", md: "flex" },
                }}
                aria-haspopup="true"
                onClick={() => setOpen(true)}
              >
                <FilterList />
              </IconButton>
            </Tooltip>
          </Stack>
        </Grid>

        <Grid item xs={12}>
          <Box
            sx={{
              overflow: "auto",
              border: 1,
              borderColor: "grey.200",
              borderRadius: 2,
              backgroundColor: "#fff",
              minHeight: 350,
            }}
          >
            <Stack
              alignItems="center"
              justifyContent="space-between"
              direction="row"
              sx={{
                p: 2,
                width: "100%",
              }}
            >
              <Tabs
                value={tabvalue}
                onChange={handleChangetab}
                variant="scrollable"
                scrollButtons="auto"
              >
                {/* <Tab label="All orders"
                  iconPosition="end"
                  icon={<Chip label={allorders} color="primary" variant="light" size="small" />}
                /> */}
                <Tab
                  label="Created"
                  icon={
                    <Chip
                      label={orderarrcreated.length}
                      color="primary"
                      variant="light"
                      size="small"
                    />
                  }
                  iconPosition="end"
                />
                <Tab
                  label="Pending"
                  icon={
                    <Chip
                      label={orderarruncovered.length}
                      color="primary"
                      variant="light"
                      size="small"
                    />
                  }
                  iconPosition="end"
                />

                <Tab
                  label="Delivered"
                  icon={
                    <Chip
                      label={orderarrcovered.length}
                      color="primary"
                      variant="light"
                      size="small"
                    />
                  }
                  iconPosition="end"
                />

                <Tab
                  label="Cancelled"
                  icon={
                    <Chip
                      label={orderarrcancelled.length}
                      color="primary"
                      variant="light"
                      size="small"
                    />
                  }
                  iconPosition="end"
                />
              </Tabs>

              <FormControl
                sx={{ width: 250, display: { xs: "none", md: "flex" } }}
              >
                <OutlinedInput
                  size="small"
                  id="header-search"
                  startAdornment={
                    <InputAdornment position="start" sx={{ mr: -0.5 }}>
                      <SearchOutlined />
                    </InputAdornment>
                  }
                  aria-describedby="header-search-text"
                  inputProps={{
                    "aria-label": "weight",
                  }}
                  placeholder="Search"
                  value={searchword}
                  onChange={(e) => {
                    setSearchword(e.target.value);
                  }}
                  autoComplete="off"
                />
              </FormControl>
            </Stack>

            <Box sx={{ width: "100%", display: "table", tableLayout: "fixed" }}>
              <EnhancedTable />
            </Box>
          </Box>
        </Grid>

        <Dialog open={open}>
          <DialogTitle align="left">
            <Typography variant="h4">Select Filter Options</Typography>
          </DialogTitle>
          <DialogContent sx={{ width: "100%" }} className="datedialog">
            <DateRangePicker
              open={open}
              toggle={() => setOpen(!open)}
              id="daterange1"
              onChange={(range) => {
                if (range.label === "All") {
                  setDateselect("all");
                  setStartdate("");
                  setEnddate("");

                  setOpen(false);
                } else {
                  setDateselect("select");
                  setStartdate(dayjs(range.startDate).format("YYYY-MM-DD"));
                  setEnddate(dayjs(range.endDate).format("YYYY-MM-DD"));
                  if (range.label) {
                    setDatestatus(range.label);
                  } else {
                    setDatestatus("");
                  }
                }
                console.log(range);
              }}
              definedRanges={[
                {
                  label: "Today",
                  startDate: new Date(),
                  endDate: new Date(),
                },
                {
                  label: "Yesterday",
                  startDate: addDays(new Date(), -1),
                  endDate: addDays(new Date(), -1),
                },
                {
                  label: "Tomorrow",
                  startDate: addDays(new Date(), +1),
                  endDate: addDays(new Date(), +1),
                },
                {
                  label: "This Week",
                  startDate: startOfWeek(new Date()),
                  endDate: endOfWeek(new Date()),
                },
                {
                  label: "Last Week",
                  startDate: startOfWeek(addWeeks(new Date(), -1)),
                  endDate: endOfWeek(addWeeks(new Date(), -1)),
                },
                {
                  label: "Last 7 Days",
                  startDate: addWeeks(new Date(), -1),
                  endDate: new Date(),
                },
                {
                  label: "This Month",
                  startDate: startOfMonth(new Date()),
                  endDate: endOfMonth(new Date()),
                },
                {
                  label: "Last Month",
                  startDate: startOfMonth(addMonths(new Date(), -1)),
                  endDate: endOfMonth(addMonths(new Date(), -1)),
                },
                // {
                //   label: 'All',
                //   startDate: new Date(),
                //   endDate: addDays(new Date(), -1),
                // },
              ]}
            />
          </DialogContent>
          <Stack
            direction="row"
            justifyContent="flex-end"
            sx={{ width: "100%", p: 2 }}
          >
            <Button variant="contained" size="small" onClick={okclicked}>
              ok
            </Button>
          </Stack>
        </Dialog>

        <Dialog
          maxWidth={false}
          fullWidth={true}
          open={dialogopen}
          onClose={dialogclose}
          scroll={"paper"}
          TransitionComponent={PopupTransition}
        >
          <DialogTitle>
            {/* <Stack direction={'row'} justifyContent={'space-between'}>
            <Stack direction={{
              xs: 'column'
            }} spacing={2} alignItems={'flex-start'}>
              <Typography variant='h3'>Assigned Roles</Typography>
              {(stafflist[0]) &&

                <Chip icon={<EnvironmentOutlined />} label={stafflist[0].locationaddress} variant="light" color="primary" />
              }
            </Stack>
            {(stafflist[0]) &&
              <Chip label={stafflist[0].orderid} variant="combined" color='warning' size={'large'} />

            }

          </Stack>
          <Grid container sx={{ p: 1 }} spacing={2}>

            <Grid item sm={6} xs={12}>


            </Grid>
            <Grid item sm={6} xs={12}>


            </Grid>
          </Grid> */}
            Assign Orders
          </DialogTitle>
          <DialogContent dividers={true}>
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>#</TableCell>
                    {/* <TableCell>Client</TableCell>
                  <TableCell>Customer</TableCell> */}

                    <TableCell>Order ID</TableCell>
                    <TableCell>Pickup </TableCell>

                    <TableCell>Delivery</TableCell>
                    <TableCell>Notes</TableCell>
                    {/* <TableCell >Clockout</TableCell>

                    <TableCell>Hours Worked</TableCell>


                    <TableCell>Status</TableCell> */}
                  </TableRow>
                </TableHead>
                <TableBody>
                  {deliverylist.map((val, i) => {
                    return (
                      <Fragment key={i}>
                        <TableRow sx={{}}>
                          <TableCell>
                            <Typography> {val.sno}</Typography>
                          </TableCell>
                          <TableCell align="left">
                            <Typography variant="body2" noWrap>
                              {val.orderid}
                            </Typography>
                            <Typography noWrap sx={{ fontSize: "11px" }}>
                              {dayjs(val.deliverytime)
                                .utc()
                                .format("DD/MM/YYYY")}
                            </Typography>
                            <Typography
                              noWrap
                              sx={{ fontSize: "11px" }}
                              variant="h5"
                            >
                              {dayjs(val.deliverytime).utc().format("hh:mm A")}
                            </Typography>
                          </TableCell>

                          {/* <TableCell align="left" sx={{ paddingLeft: '12px !important' }}>

                        <Stack direction="row" alignItems="center" spacing={1} justifyContent="flex-start">
                          <Avatar
                            alt=""
                            size="sm"
                            sx={{
                              width: '25px',
                              height: '25px'
                            }}
                          >

                          </Avatar>
                          <Stack direction="column">
                            <Typography variant="caption">{row.customername}</Typography>
                            <Typography variant="caption" color="textSecondary">

                              {row.contactno}
                            </Typography>
                          </Stack>
                        </Stack>
                      </TableCell> */}
                          <TableCell align="left">
                            <Stack direction={"row"} spacing={1}>
                              <Avatar
                                alt=""
                                size="sm"
                                sx={{
                                  width: "25px",
                                  height: "25px",
                                }}
                              ></Avatar>
                              <Stack direction="column">
                                <Typography variant="caption">
                                  {val.pickupcustomer}
                                </Typography>
                                <Typography
                                  variant="caption"
                                  color="textSecondary"
                                >
                                  {val.pickupcontactno}
                                </Typography>
                                <Tooltip title={val.pickupaddress}>
                                  <Typography
                                    variant="caption"
                                    color="textSecondary"
                                  >
                                    {/* {row.pickupaddress.slice(0, 20)} */}
                                    {val.pickupsuburb ||
                                      val.pickupaddress.slice(0, 20)}
                                  </Typography>
                                </Tooltip>
                              </Stack>
                            </Stack>
                            {/* <Stack direction='column'>

                        </Stack> */}
                          </TableCell>
                          <TableCell align="left">
                            {/* <Stack direction='column'>
                          <Tooltip title={row.deliveryaddress}>
                            <Typography variant="caption" color="textSecondary"
                            >
                              {row.customersuburb || row.deliveryaddress.slice(0, 20)}

                            </Typography>
                          </Tooltip>
                        </Stack> */}
                            <Stack direction={"row"} spacing={1}>
                              <Avatar
                                alt=""
                                size="sm"
                                sx={{
                                  width: "25px",
                                  height: "25px",
                                }}
                              ></Avatar>
                              <Stack direction="column">
                                <Typography variant="caption">
                                  {val.deliverycustomer}
                                </Typography>
                                <Typography
                                  variant="caption"
                                  color="textSecondary"
                                >
                                  {val.deliverycontactno}
                                </Typography>
                                <Tooltip title={val.deliveryaddress}>
                                  <Typography
                                    variant="caption"
                                    color="textSecondary"
                                  >
                                    {/* {row.pickupaddress.slice(0, 20)} */}
                                    {val.deliverysuburb ||
                                      val.deliveryaddress.slice(0, 20)}
                                  </Typography>
                                </Tooltip>
                              </Stack>
                            </Stack>
                          </TableCell>
                          <TableCell align="left">{val.ordernotes}</TableCell>
                        </TableRow>
                      </Fragment>
                    );
                  })}
                </TableBody>
              </Table>
            </TableContainer>
            <Grid container sx={{ mt: 2 }} spacing={2}>
              <Grid item xs={12} sm={6}>
                {/* <Stack direction={'row'} spacing={1}>
                <Typography variant='h5' sx={{ ml: 2 }}>{paymentmode.typename}:</Typography> */}
                {/* <Switch
                  checked={payment}
                  onChange={(e) => {
                    if (e.target.checked) {
                      setPayment(true)
                    } else {
                      setPayment(false)
                    }
                  }}
                /> */}
                {/* </Stack> */}

                <Autocomplete
                  id="free-solo-demo"
                  // freeSolo
                  // options={riderslist.map((option) => option.label)}
                  options={paymentmode}
                  renderInput={(params) => (
                    <TextField {...params} label="Choose Payment" />
                  )}
                  onChange={(e, val) => {
                    if (val) {
                      setPayment(val);
                    }
                  }}
                  // value={payment || null}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <Autocomplete
                  id="free-solo-demo"
                  // freeSolo
                  // options={riderslist.map((option) => option.label)}
                  options={riderslist}
                  renderInput={(params) => (
                    <TextField {...params} label="Choose Rider" />
                  )}
                  onChange={(e, val) => {
                    if (val) {
                      setRider(val);
                    }
                  }}
                  // value={rider}
                />
              </Grid>
            </Grid>
          </DialogContent>
          <DialogActions>
            <Stack
              sx={{ mt: 2 }}
              direction="row"
              justifyContent="flex-end"
              spacing={5}
            >
              <Button
                sx={{ width: "130px" }}
                color="primary"
                variant="contained"
                onClick={() => {
                  createdeliveryobj();
                  // dialogclose()
                }}
              >
                OK
              </Button>

              <Button
                sx={{ width: "130px" }}
                color="error"
                variant="contained"
                onClick={() => {
                  dialogclose();
                }}
              >
                Close
              </Button>
            </Stack>
          </DialogActions>
        </Dialog>
      </Grid>
    </>
  );
};

export default Orders;
