import {
  Button,
  Checkbox,
  FormControlLabel,
  IconButton,
  Tab,
  Tabs,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { format } from "date-fns-jalali";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
// import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import { Grid } from "../../../../components/grid/Grid";
// import { vetFarmGetAllocatedService } from "../../services/vet-farm-get-allocated";
import { VetFarmOperationRow } from "../vet-farm-operation-row/VetFarmOperationRow";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment/moment";
import { SPACING } from "../../../../data/spacing";
import { AppContext } from "../../../../contexts/AppContext";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
// import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { VetFarmSubmitContradicts } from "../vet-farm-submit-contradicts/VetFarmSubmitContradicts";
import { VetFarmEditTrafficCode } from "../vet-farm-edit-traffic-code/VetFarmEditTrafficCode";
import { VetFarmEditQuarantineCodeState } from "../vet-farm-edit-quarantine-code-state/VetFarmEditQuarantineCodeState";
import { formatTime } from "../../../../utils/formatTime";
import { parentCompanyGetBarsOverview } from "../../services/vet-farm-get-bars-overview";
import { ChainBarManagement } from "../../../province/components/chain-bar-management/ChainBarManagement";
import ShowImage from "../../../../components/show-image/ShowImage";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import Accordion from "@mui/material/Accordion";
import AccordionSummary from "@mui/material/AccordionSummary";
import AccordionDetails from "@mui/material/AccordionDetails";
import ArrowDownwardIcon from "@mui/icons-material/ArrowDownward";
import { VetFarmAggregateBars } from "../vet-farm-aggregate-bars/VetFarmAggregateBars";
import { vetFarmDeleteAggregateBarService } from "../../services/vet-farm-delete-aggregate-bar";
import RefreshIcon from "@mui/icons-material/Refresh";
import { ParentCompanyOutOfProvince } from "../parent-company-sale-out-of-province/ParentCompanyOutOfProvince";

export const ParentCompanyVetFarmOperation = ({ province }) => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const userInfo = useSelector((state) => state.userSlice);
  const { parentCompanyBarsOverview } = useSelector(
    (state) => state.vetFarmSlice
  );

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);
  // const { vetFarmGetDeletedBars } = useSelector((state) => state.vetFarmSlice);

  const [selectedTab, setSelectedTab] = useState(0);

  const handleTabChange = (event, newValue) => {
    setSelectedTab(newValue);
  };

  const [hasDocumentState, setHasDocumentState] = useState(false);
  const handleChangeDocumentState = () => {
    setHasDocumentState(!hasDocumentState);
  };

  const dispatch = useDispatch();
  // const [dataTable, setDataTable] = useState([]);
  // const [dataDeletedTable, setDataDeletedTable] = useState([]);

  const getItemState = (item) => {
    let state = "";
    if (item.trash === true) {
      state = "حذف شده";
    } else if (item?.wareHouseConfirmation) {
      state = "ورود به انبار";
    } else if (item?.assignmentStateArchive !== "pending") {
      state = "ثبت اطلاعات بار";
    } else {
      if (item.vetState === "accepted") {
        state = "تایید تخلیه";
      } else if (item.vetState === "pending") {
        state = "در انتظار تخلیه";
      }
    }

    return (
      <Typography variant="body2" color={item?.trash ? "error" : "primary"}>
        {state}
      </Typography>
    );
  };

  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `${province}parent_company_kill_house_request_bar_management/?check&search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&without_quarantine_code_state=${hasDocumentState}`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  const [page, setPage] = useState(1);
  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };

  const aggregateStatus = false;

  useEffect(() => {
    // dispatch(vetFarmGetAllocatedService({ selectedDate1, selectedDate2 }));
    fetchApiData(page);
    dispatch(
      parentCompanyGetBarsOverview({
        selectedDate1,
        selectedDate2,
        textValue,
        hasDocumentState,
        province,
      })
    );
  }, [selectedDate1, selectedDate2, hasDocumentState, perPage, province]);

  useEffect(() => {
    fetchApiData(1);
  }, []);

  const [tableData, setTableData] = useState([]);
  const [aggregates, setAggregates] = useState([]);

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        <Grid
          id="merge"
          container
          key={i}
          alignItems="center"
          justifyContent="center"
          style={{
            minWidth:
              getRoleFromUrl() === "VetFarm" ||
              getRoleFromUrl() === "AdminX" ||
              getRoleFromUrl() === "SuperAdmin"
                ? "100px"
                : "50px",
          }}
        >
          {aggregateStatus?.allow &&
            (getRoleFromUrl() === "VetFarm" ||
              getRoleFromUrl() === "AdminX" ||
              getRoleFromUrl() === "SuperAdmin") && (
              <Grid item>
                {item?.clearanceCode && item?.aggregateCode ? (
                  <FormControlLabel
                    control={
                      <Tooltip title="حذف از ادغام" placement="top">
                        <IconButton
                          color="error"
                          disabled={
                            data?.filter(
                              (option) =>
                                option.aggregateCode === item?.aggregateCode
                            ).length < 3
                          }
                          key={i}
                          onClick={() => {
                            dispatch(
                              vetFarmDeleteAggregateBarService({
                                kill_house_request_key: item?.key,
                              })
                            ).then((r) => {
                              if (r.payload.error) {
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: r.payload.error,
                                  severity: "error",
                                });
                              } else {
                                setAggregates([]);
                                updateTable();
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "عملیات با موفقیت انجام شد.",
                                  severity: "success",
                                });
                              }
                            });
                          }}
                        >
                          <RefreshIcon />
                        </IconButton>
                      </Tooltip>
                    }
                  />
                ) : (
                  <FormControlLabel
                    control={
                      <Checkbox
                        disabled={
                          (aggregates.length &&
                            !(
                              aggregates[0]?.poultryRequest?.poultry
                                ?.unitName ===
                                item?.poultryRequest?.poultry?.unitName &&
                              aggregates[0]?.killhouseUser?.name ===
                                item?.killhouseUser?.name
                            )) ||
                          (item?.clearanceCode && item?.aggregateCode)
                        }
                        checked={
                          aggregates.filter(
                            (option) => option?.barCode === item?.barCode
                          ).length > 0
                        }
                        onChange={() => {
                          if (
                            aggregates.some(
                              (option) => option?.barCode === item?.barCode
                            )
                          ) {
                            setAggregates(
                              aggregates.filter(
                                (option) => option?.barCode !== item?.barCode
                              )
                            );
                          } else {
                            if (item?.aggregateCode) {
                              setAggregates(
                                data?.filter(
                                  (option) =>
                                    option?.aggregateCode ===
                                    item?.aggregateCode
                                )
                              );
                            } else {
                              setAggregates([...aggregates, item]);
                            }
                          }
                        }}
                        color="primary"
                      />
                    }
                  />
                )}
              </Grid>
            )}
          <Grid item>{page === 1 ? i + 1 : i + (perPage * page) / 2 + 1}</Grid>
        </Grid>,
        item?.aggregateCode ? (
          <Tooltip title="مشاهده بارها" placement="top">
            {" "}
            <Typography
              variant="body2"
              color="primary"
              style={{ cursor: "pointer" }}
              onClick={() => {
                if (aggregateValidationHasError()) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: `فقط بارهای با خریدار و مرغدار یکسان و با مجموع تعداد حداکثر ${aggregateStatus?.limitation} میتوانید ادغام کنید!`,
                    severity: "error",
                  });
                } else {
                  dispatch(
                    OPEN_MODAL({
                      title: "مشاهده بارهای ادغام شده",
                      content: (
                        <VetFarmAggregateBars
                          toShow
                          setAggregates={setAggregates}
                          bars={data?.filter(
                            (option) =>
                              option?.aggregateCode === item?.aggregateCode
                          )}
                        />
                      ),
                    })
                  );
                }
              }}
            >
              دارد
            </Typography>
          </Tooltip>
        ) : (
          <Typography variant="body2">ندارد</Typography>
        ),
        getItemState(item),
        <Typography
          key={i}
          style={{ fontSize: "13px", color: item?.trash ? "red" : "black" }}
        >
          {item.barCode}
        </Typography>,
        formatTime(item.createDate),
        item?.poultryRequest?.freezing
          ? "انجماد"
          : item?.poultryRequest?.export
          ? "صادرات"
          : "عادی",
        `${item.killhouseUser?.name} (${item.killhouseUser?.killHouseOperator?.user?.mobile})`,
        item?.killer
          ? `${item?.killer?.name} (${item?.killer?.killHouseOperator?.user?.mobile})`
          : "-",
        `${item.poultryRequest?.poultry?.user?.fullname} (${item.poultryRequest.poultry?.user?.mobile})`,
        `${item.poultryRequest?.poultry?.unitName}`,
        item.quantity?.toLocaleString(),
        item?.weightInfo?.weight?.toLocaleString(),
        <VetFarmEditTrafficCode
          key={i}
          updateTable={updateTable}
          killHouseRequestKey={item.key}
          trafficCode={item?.trafficCode}
          isEditable={
            (getRoleFromUrl() === "ProvinceOperator" ||
              getRoleFromUrl() === "SuperAdmin" ||
              getRoleFromUrl() === "VetFarm" ||
              getRoleFromUrl() === "VetSupervisor" ||
              getRoleFromUrl() === "AdminX" ||
              getRoleFromUrl() === "CityVet" ||
              getRoleFromUrl() === "Supporter") &&
            item.trash !== true &&
            item.assignmentStateArchive === "pending" &&
            !item?.clearanceCode
          }
        />,
        <VetFarmOperationRow
          key={i}
          item={item}
          updateTable={updateTable}
          isEditable={
            getRoleFromUrl() === "VetFarm" ||
            getRoleFromUrl() === "ProvinceOperator" ||
            getRoleFromUrl() === "SuperAdmin" ||
            getRoleFromUrl() === "CityVet" ||
            getRoleFromUrl() === "VetSupervisor" ||
            getRoleFromUrl() === "AdminX" ||
            getRoleFromUrl() === "Supporter"
          }
        />,
        <>
          {item?.quarantineQuantity ? (
            <VetFarmEditQuarantineCodeState
              code={item?.quarantineQuantity}
              updateTable={updateTable}
              item={item}
            />
          ) : (
            <>
              {item?.quarantineCodeState &&
                (item?.quarantineCodeState === "contradiction"
                  ? "مغایرت کد رهگیری"
                  : item?.quarantineCodeState === "noclearance"
                  ? "فاقد کد رهگیری"
                  : item?.quarantineCodeState === "merge"
                  ? "ادغام"
                  : "عدم تایید راهداری")}

              {(getRoleFromUrl() === "ProvinceOperator" ||
                getRoleFromUrl() === "SuperAdmin" ||
                getRoleFromUrl() === "AdminX" ||
                getRoleFromUrl() === "Supporter") && (
                <Button
                  onClick={() => {
                    dispatch(
                      OPEN_MODAL({
                        title: "تعداد ثبت شده در قرنطینه",
                        content: (
                          <VetFarmSubmitContradicts
                            item={item}
                            updateTable={updateTable}
                          />
                        ),
                      })
                    );
                  }}
                >
                  {item?.quarantineCodeState ? "ویرایش" : "ثبت"}
                </Button>
              )}
            </>
          )}
        </>,
        // item?.realAddCar?.driver
        //   ? `${item?.realAddCar?.driver?.typeCar} (${
        //       item?.realAddCar?.driver?.pelak
        //         ? item?.realAddCar?.driver?.pelak
        //         : "نامشخص"
        //     })`
        //   : "-",
        `${item.addCar.driver.typeCar} ${item.addCar.driver.pelak}`,
        `${item.addCar.driver.driverName} (${item.addCar.driver.driverMobile})`,
        item.poultryRequest.chickenBreed,
        item?.weightInfo?.indexWeight?.toLocaleString(),
        item?.poultryRequest?.amount?.toLocaleString() + " ﷼",
        item?.weightInfo?.killHousePrice?.toLocaleString() + " ﷼",
        item?.vetFarm?.vet?.user?.fullname
          ? item?.vetFarm?.vet?.user?.fullname +
            `(${item?.vetFarm?.vet?.user?.mobile})`
          : "فاقد دامپزشک",
        `${item.killPlace}`,
        item.poultryRequest.poultry.address.city.name,
        item?.poultryRequest.sendDate
          ? format(new Date(item?.poultryRequest.sendDate), "yyyy/MM/dd")
          : "-",
        item?.poultryRequest.orderCode,
        <Typography
          key={i}
          variant="body2"
          color={item?.barDocumentStatus?.isError ? "error" : "primary"}
        >
          {item?.barDocumentStatus?.title
            ? item?.barDocumentStatus?.title
            : "-"}
        </Typography>,

        <ShowImage key={i} src={item?.assignmentInfo?.imageWithBar} />,
        item.acceptedRealQuantity?.toLocaleString(),
        item?.acceptedRealWeight?.toLocaleString(),
        item?.weightInfo?.finalIndexWeight?.toLocaleString(),
        item?.wareHouseAcceptedRealQuantity?.toLocaleString(),
        item?.wareHouseAcceptedRealWeight?.toLocaleString(),
        item?.weightLoss?.toLocaleString(),
      ];
    });

    setTableData(d);
  }, [data, aggregates]);

  const [openNotif] = useContext(AppContext);

  const handleDateChange1 = (date) => {
    setSelectedDate1(date);
  };

  const handleDateChange2 = (date) => {
    setSelectedDate2(date);
  };

  const [textValue, setTextValue] = useState("");

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `${province}parent_company_kill_house_request_bar_management/?check&role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}&without_quarantine_code_state=${hasDocumentState}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
    dispatch(
      parentCompanyGetBarsOverview({ selectedDate1, selectedDate2, textValue })
    );
  };

  useEffect(() => {
    if (selectedTab === 0) {
      fetchApiData(1);
    }
  }, [selectedDate1, selectedDate2, hasDocumentState, selectedTab]);

  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  const tableTitle = (
    <Grid
      container
      alignItems="start"
      justifyContent="space-between"
      gap={2}
      paddingTop={2}
      mb={1}
    >
      <Grid container alignItems="center" gap={SPACING.SMALL} xs={12}>
        <Typography>مدیریت بارها</Typography>
        <Grid style={{ width: "150px" }}>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => <TextField {...params} />}
            value={selectedDate1}
            onChange={(e) => {
              handleDateChange1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid style={{ width: "150px" }}>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => <TextField {...params} />}
            value={selectedDate2}
            onChange={(e) => {
              handleDateChange2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <form onSubmit={handleSubmit}>
          <TextField
            autoComplete="off"
            size="small"
            label="جستجو"
            variant="outlined"
            style={{ width: 250 }}
            onChange={handleTextChange}
          />
          <Button
            // disabled={!textValue}
            type="submit"
            onClick={handleSubmit}
            endIcon={<RiSearchLine />}
          >
            جستجو
          </Button>
        </form>

        {(getRoleFromUrl() === "SuperAdmin" ||
          getRoleFromUrl() === "Supporter" ||
          getRoleFromUrl() === "AdminX") && (
          <FormControlLabel
            control={
              <Checkbox
                checked={hasDocumentState}
                onChange={handleChangeDocumentState}
                name="item4"
              />
            }
            label="بدون وضعیت قرنطینه"
          />
        )}
      </Grid>
      <Grid container alignItems="center" gap={SPACING.SMALL} xs={12}>
        <Accordion style={{ width: "100%" }}>
          <AccordionSummary
            expandIcon={<ArrowDownwardIcon />}
            aria-controls="panel1-content"
            id="panel1-header"
          >
            <Typography>گزارش خروجی ها</Typography>
          </AccordionSummary>

          <AccordionDetails>
            <Grid
              container
              justifyContent="space-between"
              alignItems="center"
              xs={12}
              p={1}
            >
              <Grid display="grid" justifyContent="center">
                <Tooltip placement="top" title="خروجی اکسل">
                  {/* <a
            href={`${province}bar_excel/?start=${selectedDate1}&end=${selectedDate2}`}
            rel="noreferrer"
          > */}
                  <Button
                    color="success"
                    onClick={() => {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                        severity: "success",
                      });
                      const link = `${province}bar_excel/?start=${selectedDate1}&end=${selectedDate2}&key=${
                        userInfo?.userProfile?.key
                      }&role=${getRoleFromUrl()}&search=filter&value=${textValue}`;
                      window.location.href = link;
                    }}
                  >
                    <RiFileExcel2Fill size={32} />
                  </Button>
                  {/* </a> */}
                </Tooltip>

                <Typography variant="body2">خروجی اکسل </Typography>
              </Grid>

              {getRoleFromUrl() !== "VetFarm" &&
                getRoleFromUrl() !== "CityPoultry" && (
                  <Grid display="grid" justifyContent="center">
                    <Tooltip placement="top" title="خروجی اکسل گزارش جامع">
                      {/* <a
            href={`${province}detail_of_killing_excel/?date1=${selectedDate1}&date2=${selectedDate2}`}
            rel="noreferrer"
          > */}
                      <Button
                        color="warning"
                        onClick={() => {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                            severity: "success",
                          });
                          const link = `${province}detail_of_killing_excel/?date1=${selectedDate1}&date2=${selectedDate2}&role=${getRoleFromUrl()}&key=${userKey}`;
                          window.location.href = link;
                        }}
                      >
                        <RiFileExcel2Fill size={32} />
                      </Button>
                      {/* </a> */}
                    </Tooltip>
                    <Typography variant="body2">گزارش جامع </Typography>
                  </Grid>
                )}

              <Grid display="grid" justifyContent="center">
                <Tooltip placement="top" title="خروجی اکسل گزارش پایش کشتارگاه">
                  {/* <a
            href={`${province}detail_of_killing_excel/?date1=${selectedDate1}&date2=${selectedDate2}`}
            rel="noreferrer"
          > */}
                  <Button
                    color="primary"
                    onClick={() => {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                        severity: "success",
                      });
                      const link = `${province}comprehensive_report_of_the_slaughterhouse_excel/?date1=${selectedDate1}&date2=${selectedDate2}`;
                      window.location.href = link;
                    }}
                  >
                    <RiFileExcel2Fill size={32} />
                  </Button>
                  {/* </a> */}
                </Tooltip>

                <Typography variant="body2">پایش کشتارگاه </Typography>
              </Grid>

              <Grid display="grid" justifyContent="center">
                <Tooltip
                  placement="top"
                  title="خروجی اکسل گزارش عملکرد کشتارگاه ها"
                >
                  <Button
                    style={{ color: "gray" }}
                    onClick={() => {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                        severity: "success",
                      });
                      const link = `${province}from_allocation_to_distribution_excel/?date1=${selectedDate1}&date2=${selectedDate2}`;
                      window.location.href = link;
                    }}
                  >
                    <RiFileExcel2Fill size={32} />
                  </Button>
                  {/* </a> */}
                </Tooltip>

                <Typography variant="body2">
                  گزارش عملکرد کشتارگاه ها
                </Typography>
              </Grid>

              <Grid display="grid" justifyContent="center">
                <Tooltip placement="top" title="خروجی اکسل پایش بارها">
                  <Button
                    color="error"
                    onClick={() => {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                        severity: "success",
                      });
                      const link = `${province}monitor_loads_excel/?role=${getRoleFromUrl()}&key=${userKey}&date1=${selectedDate1}&date2=${selectedDate2}`;
                      window.location.href = link;
                    }}
                  >
                    <RiFileExcel2Fill size={32} />
                  </Button>
                  {/* </a> */}
                </Tooltip>
                <Typography variant="body2">پایش بارها </Typography>
              </Grid>
            </Grid>
          </AccordionDetails>
        </Accordion>
      </Grid>
    </Grid>
  );

  let tabs = (
    <Tabs
      scrollButtons="auto"
      variant="scrollable"
      allowScrollButtonsMobile
      value={selectedTab}
      onChange={handleTabChange}
    >
      <Tab label="اطلاعات بارها" value={0} />
      <Tab label="فروش خارج استان" value={4} />
      <Tab label="بارهای زنجیره" value={5} />
    </Tabs>
  );

  const aggregateValidationHasError = () => {
    return (
      aggregates?.reduce((total, obj) => total + obj?.quantity, 0) >
        aggregateStatus?.limitation ||
      !aggregates.every(
        (obj) =>
          obj.poultryRequest?.poultry?.unitName ===
            aggregates[0]?.poultryRequest?.poultry?.unitName &&
          obj.killhouseUser?.name === aggregates[0]?.killhouseUser?.name
      )
    );
  };

  return (
    <Grid
      container
      direction="column"
      flexWrap="nowrap"
      mt={SPACING.SMALL}
      xs={12}
    >
      <Grid container justifyContent="center" mb={SPACING.MEDIUM}>
        {tabs}
      </Grid>
      {selectedTab === 0 && (
        <Grid
          container
          mt={SPACING.MEDIUM}
          alignItems="center"
          justifyContent="center"
          xs={12}
        >
          {tableTitle}
          <Grid container mt={2} mb={4} isDashboard xs={12}>
            <ResponsiveTable
              title="اطلاعات کلی"
              noPagination
              isDashboard
              columns={[
                "تعداد بارها",
                "حجم بارها",
                "وزن بارها",
                "میانگین وزن",
                "کمترین سن ",
                "بیشترین سن ",
                "میانگین سنی",
                "بارهای دارای کد قرنطینه",
                "حجم بارهای دارای کد قرنطینه",
                "بارهای احراز شده از قرنطینه",
                "حجم بارهای احراز شده از قرنطینه",
                "بارهای فاقد کد قرنطینه",
                "حجم بارهای فاقد کد قرنطینه",
                "بارهایی که در قرنطینه و رصدیار اختلاف دارند",
                "بارهای تکمیل شده کشتارگاه",
                "حجم نهایی در کشتارگاه	",
                "وزن نهایی در کشتارگاه",
                "تعداد بار ورودی به انبار",
                "حجم لاشه های انبار",
                "وزن لاشه های انبار",
                "درصد افت بار انبار",
              ]}
              data={[
                [
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {parentCompanyBarsOverview?.lenKillRequest?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {parentCompanyBarsOverview?.killRequestQuantity?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {parentCompanyBarsOverview?.killRequestWeight?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {parentCompanyBarsOverview?.avgWeight}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {parentCompanyBarsOverview?.minAge}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {parentCompanyBarsOverview?.maxAge}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {parentCompanyBarsOverview?.avgAge}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {parentCompanyBarsOverview?.lenKillRequestHasCode?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {parentCompanyBarsOverview?.quantityOfKillRequestHasCode?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {parentCompanyBarsOverview?.lenKillRequestHasQuarantine?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {parentCompanyBarsOverview?.quantityOfKillRequestHasQuarantine?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {parentCompanyBarsOverview?.lenKillRequestHasNotCode?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {parentCompanyBarsOverview?.quantityOfKillRequestHasNotCode?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {parentCompanyBarsOverview?.differenceBar?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {parentCompanyBarsOverview?.lenCompleteWithKillHouse?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {parentCompanyBarsOverview?.quantityFinalKillHouse?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {parentCompanyBarsOverview?.weightFinalKillHouse?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {parentCompanyBarsOverview?.wareHouseBars?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {parentCompanyBarsOverview?.wareHouseBarsQuantity?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {parentCompanyBarsOverview?.wareHouseBarsWeight?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {parentCompanyBarsOverview?.wareHouseBarsWeightLose
                      ?.toFixed(2)
                      ?.toLocaleString()}
                  </Typography>,
                ],
              ]}
            />
          </Grid>

          {aggregateStatus?.allow &&
            (getRoleFromUrl() === "VetFarm" ||
              getRoleFromUrl() === "AdminX" ||
              getRoleFromUrl() === "SuperAdmin") && (
              <Grid id="merge" container xs={12} justifyContent="end">
                <Button
                  color={aggregateValidationHasError() ? "error" : "primary"}
                  variant="outlined"
                  disabled={
                    aggregates.some((item) => item?.clearanceCode)
                      ? true
                      : aggregates.some((item) => item?.aggregateCode)
                      ? false
                      : aggregates?.length < 2
                  }
                  onClick={() => {
                    if (aggregateValidationHasError()) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: `فقط بارهای با خریدار و مرغدار یکسان و با مجموع تعداد حداکثر ${aggregateStatus?.limitation} میتوانید ادغام کنید!`,
                        severity: "error",
                      });
                    } else {
                      dispatch(
                        OPEN_MODAL({
                          title:
                            aggregates.some((item) => item?.aggregateCode) &&
                            !aggregates.some((item) => item?.clearanceCode)
                              ? "ورود اطلاعات / لغو ادغام"
                              : "ادغام بارها",
                          content: (
                            <VetFarmAggregateBars
                              setAggregates={setAggregates}
                              bars={
                                aggregates.some((item) => item?.aggregateCode)
                                  ? data?.filter(
                                      (item) =>
                                        item?.aggregateCode ===
                                        aggregates[0]?.aggregateCode
                                    )
                                  : aggregates
                              }
                              updateTable={updateTable}
                              canReturn={
                                aggregates.some(
                                  (item) => item?.aggregateCode
                                ) &&
                                !aggregates.some((item) => item?.clearanceCode)
                              }
                            />
                          ),
                        })
                      );
                    }
                  }}
                >
                  {aggregates.some((item) => item?.aggregateCode) &&
                  !aggregates.some((item) => item?.clearanceCode)
                    ? "ورود اطلاعات / لغو ادغام"
                    : "ادغام بارها"}
                </Button>
              </Grid>
            )}

          <ResponsiveTable
            data={tableData}
            columns={[
              "ردیف",
              "ادغام",
              "وضعیت",
              "کدبار",
              "تاریخ ثبت خودرو",
              "نوع کشتار",
              "خریدار",
              "کشتارکن اختصاصی",
              "مشخصات مرغدار",
              "نام فارم",
              "تعداد اولیه",
              "وزن اولیه بار (کیلوگرم)",
              "کد بهداشتی حمل و نقل",
              "کدرهگیری سامانه قرنطینه",
              "تعداد در قرنطینه",
              // "ماشین واقعی حمل",
              "ماشین",
              "راننده",
              "نژاد",
              "میانگین وزن اولیه (کیلوگرم)",
              "قیمت مرغدار",
              "قیمت کشتارگاه",
              "دامپزشک فارم",
              "محل کشتار",
              "شهر",
              "تاریخ کشتار",
              "کدسفارش کشتار",
              "وضعیت سند",
              "سند (بارنامه)",
              "تعداد نهایی",
              "وزن نهایی بار (کیلوگرم)",
              "میانگین وزن نهایی (کیلوگرم)",
              "حجم لاشه",
              "وزن لاشه",
              "درصد افت",
            ]}
            handlePageChange={handlePageChange}
            totalRows={totalRows}
            page={page}
            perPage={perPage}
            handlePerRowsChange={handlePerRowsChange}
            title="مدیریت بارها"
          />
        </Grid>
      )}

      {selectedTab === 4 && (
        <Grid mt={SPACING.MEDIUM}>
          <ParentCompanyOutOfProvince
            readOnly={
              getRoleFromUrl() === "VetSupervisor" ||
              getRoleFromUrl() === "CityOperator" ||
              getRoleFromUrl() === "ProvinceSupervisor" ||
              getRoleFromUrl() === "ParentCompany"
            }
            province={province}
          />
        </Grid>
      )}

      {selectedTab === 5 && <ChainBarManagement province={province} />}
    </Grid>
  );
};

// const DisabledWrap = ({ children, checked }) => {
//   return <Grid style={{ opacity: !checked ? 0.5 : 1 }}>{children}</Grid>;
// };
