import {
  Autocomplete,
  Button,
  Checkbox,
  CircularProgress,
  Divider,
  FormControl,
  FormControlLabel,
  FormHelperText,
  FormLabel,
  IconButton,
  InputAdornment,
  InputLabel,
  ListItem,
  ListItemIcon,
  ListItemText,
  MenuItem,
  Radio,
  RadioGroup,
  Select,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import SearchIcon from "@mui/icons-material/Search";
import { useEffect } from "react";
import { DatePicker } from "@mui/x-date-pickers";
import { useDispatch, useSelector } from "react-redux";
import { useFormik } from "formik";
import moment from "moment";
import { useState } from "react";
import DeleteIcon from "@mui/icons-material/Delete";
import { useContext } from "react";
import AddIcon from "@mui/icons-material/Add";
import DoneIcon from "@mui/icons-material/Done";

import {
  CLOSE_MODAL,
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { avicultureGetChickenPrice } from "../../../aviculture/services/aviculture-get-chicken-price";
import { avicultureGetSlaughters } from "../../../aviculture/services/aviculture-get-slaughters";
import { avicultureGetUnions } from "../../../aviculture/services/aviculture-get-unions";
import { SPACING } from "../../../../data/spacing";
import { Grid } from "../../../../components/grid/Grid";
import { Yup } from "../../../../lib/yup/yup";
import { AppContext } from "../../../../contexts/AppContext";
import { avicultureGetHatchingData } from "../../../aviculture/services/aviculture-get-hatching-data";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import useUserProfile from "../../../authentication/hooks/useUserProfile";
import { avicultureNewRequest } from "../../../aviculture/services/aviculture-new-request";
import { DialogAlert } from "../../../../components/dialog-alert/DialogAlert";
import { cityGetPoultryData } from "../../services/city-get-poultry-data";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { cityGetBuyer } from "../../services/ciry-get-buyer";
import { avicultureGetRequests } from "../../../aviculture/services/aviculture-requests";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { avicultureHatchingRequestsService } from "../../../aviculture/services/aviculture-hatching-requests";
import { cityGetHatchingsByAge } from "../../services/city-get-hatchings-by-age";
import { avicultureGetPoultry } from "../../../aviculture/services/aviculture-get-poultry";
import { cityGetPoultriesService } from "../../services/city-get-poultries";
import { avicultureGetDirectBuys } from "../../../aviculture/services/aviculture-get-direct-buys";
import { formatJustDate } from "../../../../utils/formatTime";
import { provinceGetSellForFreezingStatus } from "../../../province/services/province-get-sell-for-freezing-status";
import { getApprovedPriceState } from "../../../province/services/get-approved-price-state";
import { provincePolicyGetExportAllowStatus } from "../../../province/services/province-policy-get-export-allow-state";
import { provincePolicyValidatePoultryWithSmsStatusService } from "../../../province/services/province-policy-validate-poultry-wth-sms-service";
import { isValidIndexWeight } from "../../../../utils/isValidIndexWeight";
import { provincePolicyGetWeightRange } from "../../../province/services/province-policy-get-weight-range";
import { provincePolicyGetMarketDailyLimitation } from "../../../province/services/province-policy-market-daily-limitation";
import { LabelField } from "../../../../components/label-field/LabelField";
// import { SelectCheck } from "../../../../components/select-check/SelectCheck";

export const CityNewKillRequest = ({
  userCheck,
  selectedAge1,
  selectedAge2,
  isAviculture,
  updateTable,
}) => {
  const [openNotif] = useContext(AppContext);
  const [hatchingKey, sethatchingKey] = useState("");
  const [hatchingData, setHatchingData] = useState("");
  const [hatchingSelected, setHatchingSelected] = useState("");
  const [poultryData, setPoultryData] = useState("");
  const [poultryKey, setPolutryKey] = useState("");
  const [quantity, setQuantity] = useState("");
  const [losses, setlosses] = useState("");
  const [leftOvers, setLeftOvers] = useState("");
  const [isUnion] = useState(false);
  const [isStockMarket, setIsStockMarket] = useState(false);
  const [pricingKey, setPriceKey] = useState();
  const [chickenBreed, setChickenBreed] = useState("");
  const [chickenCanRequest, setChickenCanRequest] = useState("");
  const [freezing, setFreezing] = useState(false);
  const [tradePanel, setTradePanel] = useState(false);
  const [toExport, setToExport] = useState(false);
  const [marketLimitationData, setMarketLimitationData] = useState(null);
  // const [slaughterHousesListForSelect, setSlaughterHousesListForSelect] =
  //   useState([]);
  const [buyerInfo, setBuyerInfo] = useState();
  const [, , selectedDate1, , selectedDate2] = useContext(AppContext);
  const [loading, setLoading] = useState(false);
  const [, userProfile] = useUserProfile();
  const [autoLoading, setAutoLoading] = useState(false);
  const { weightRange } = useSelector((state) => state.provinceSlice);

  const [slaughterHousesListForSelect, setSlaughterHousesListForSelect] =
    useState([]);

  const { avicultureSlaughters } = useSelector(
    (state) => state.avicultureSlice
  );
  const { cityGetPoultries } = useSelector((state) => state.citySlice);

  const [submitStatus, SetSubmitStatus] = useState(false);
  const fetchData = () => {
    dispatch(provincePolicyValidatePoultryWithSmsStatusService()).then((r) => {
      SetSubmitStatus(r.payload.data.poultryStatus);
    });
  };

  useEffect(() => {
    setSlaughterHousesListForSelect(
      avicultureSlaughters?.map((item) => {
        let name = "";
        if (item.killer) {
          name = `کشتارکن ${item?.name}`;
        } else {
          name = `کشتارگاه ${item?.name}`;
        }
        return {
          label: `${name} / ${item?.quantitySum?.toLocaleString()} قطعه`,
          value: `${item?.name} (${item?.fullname})`,
          quantity: item?.quantitySum,
          killhouseKey: item?.killReqKey,
          item: item,
        };
      })
    );
  }, [avicultureSlaughters]);

  const [data, setData] = useState();
  const [approvedPrice, setApprovedPrice] = useState();

  useEffect(() => {
    dispatch(getApprovedPriceState()).then((r) => {
      setData(r.payload.data);
      if (r.payload.data?.approved === false) {
        formik.setFieldValue("avicultureSellType", "freePrice");
      }
      // Check if approved is true but all price/weight fields are zero
      if (
        r.payload.data?.approved === true &&
        r.payload.data?.lowestPrice === 0 &&
        r.payload.data?.highestPrice === 0 &&
        r.payload.data?.lowestWeight === 0 &&
        r.payload.data?.highestWeight === 0
      ) {
        formik.setFieldValue("avicultureSellType", "goverment");
      }
    });
    dispatch(provincePolicyGetWeightRange());
  }, []);

  useEffect(() => {
    if (userCheck) {
      setAutoLoading(true);
      dispatch(cityGetPoultryData(userCheck)).then((r) => {
        setPoultryData(r.payload.data);
        setAutoLoading(false);
      });
    }
  }, [userCheck]);

  useEffect(() => {
    if (isAviculture) {
      dispatch(LOADING_START());
      dispatch(avicultureGetPoultry()).then((r) => {
        setPoultryData(r.payload.data);
        dispatch(LOADING_END());
      });
    }
    fetchData();
  }, []);

  const inputArr = [
    {
      type: "text",
      id: 1,
      value: "",
    },
  ];

  const inputArrPrices = [
    {
      type: "text",
      id: 1,
      value: "",
    },
  ];
  const [arr, setArr] = useState(inputArr);
  const [arrPrices, setArrPrices] = useState(inputArrPrices);

  const dispatch = useDispatch();

  const { avicultureChickenPrice } = useSelector(
    (state) => state.avicultureSlice
  );

  const [value] = useState("insideProvince");

  // const handleChangeRadioButton = (event) => {
  //   setValue(event.target.value);
  // };

  // useEffect(() => {
  //   setSlaughterHousesListForSelect(
  //     avicultureSlaughters?.map((item) => {
  //       return {
  //         label: `${item.name} (${item.killHouseOperator?.user?.fullname})`,
  //         value: `${item.name} (${item.killHouseOperator?.user?.fullname})`,
  //       };
  //     })
  //   );
  // }, [avicultureSlaughters]);

  useEffect(() => {
    dispatch(avicultureGetChickenPrice());
  }, []);

  const [unions, setUnions] = useState();
  const [unionSelected, setUnionSelected] = useState();

  const [selectedKillhouse, setSelectedKillhouse] = useState(null);

  useEffect(() => {
    if (poultryData) {
      dispatch(
        avicultureGetUnions({
          breeding_uniq_id: poultryData[0]?.breedingUniqueId,
        })
      ).then((r) => {
        setUnionSelected(r.payload.data[0]?.key);
        setUnions(r.payload.data);
      });
    }
  }, [poultryData]);

  useEffect(() => {
    setLoading(true);
    dispatch(cityGetPoultriesService()).then(() => {
      setLoading(false);
    });
  }, []);

  const addInput = () => {
    if (arr.length < 3) {
      setArr((prevState) => {
        return [
          ...prevState,
          {
            type: "text",
            value: "",
          },
        ];
      });

      setArrPrices((prevState) => {
        return [
          ...prevState,
          {
            type: "text",
            value: "",
          },
        ];
      });
    }
  };

  const removeInput = () => {
    const number = arr.length - 1;

    if (number !== 0) {
      const filteredArrayPrice = arr?.filter((object, i) => i !== number);
      const filteredArrayTime = arrPrices?.filter((object, i) => i !== number);

      setArr(filteredArrayPrice);
      setArrPrices(filteredArrayTime);
    }

    // setArr((s) => {
    //   return s.splice(arr.findIndex((item) => item.id === number, 1));
    // });

    // setArrPrices((s) => {
    //   return s.splice(arr.findIndex((item) => item.id === number, 1));
    // });
  };

  const handleChange = (e) => {
    e.preventDefault();

    const index = e.target.id;
    setArr((s) => {
      const newArr = s.slice();
      newArr[index].value = e.target.value;

      return newArr;
    });
  };

  const handleChangeTime = (e) => {
    e.preventDefault();

    const index = e.target.id;

    setArrPrices((s) => {
      const newArrPrice = s.slice();
      newArrPrice[index].value = e.target.dataset.value;

      return newArrPrice;
    });
  };

  useEffect(() => {
    if (avicultureChickenPrice) {
      setPriceKey(avicultureChickenPrice?.key);
    }
  }, [avicultureChickenPrice]);

  const formik = useFormik({
    initialValues: {
      noChicken: "",
      sellType: {
        cash: true,
        haveTime: false,
      },
      price1: "",
      price2: "",
      price3: "",
      slaughterDate: moment(Date()).format("YYYY-MM-DD"),
      period1: "4",
      period2: "4",
      period3: "4",
      weight: "",
      losses: "0",
      isUnion,
      isStockMarket,
      isAccepted: getRoleFromUrl() === "Poultry" ? false : true,
      selectedSlaughters: [],
      financialOperation: "outside-system",
      avicultureSellType: "goverment",
      poultryPrice: "",
    },
    validationSchema: Yup.object({
      noChicken: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!")
        .min(0, "تعداد وارد شده از حداقل ممکن کمتر است")
        .max(Number(chickenCanRequest), "تعداد وارد شده قابل تخصیص نیست"),
      isAccepted: Yup.boolean()
        .test("req", "باید تعهد نامه را بپذیرید!", (val, context) => {
          return context.originalValue && context.originalValue === true;
        })
        .required("این فیلد اجباری است!"),
      price1: Yup.number()
        .typeError("لطفا عدد وارد کنید!")
        .min(
          avicultureChickenPrice?.floorPrice,
          "قیمت وارد شده از کف قیمت امروز کمتر است"
        )
        .max(
          avicultureChickenPrice?.ceilingPrice,
          "قیمت وارد شده از سقف قیمت امروز بیشتر است"
        ),
      price2: Yup.number()
        .typeError("لطفا عدد وارد کنید!")
        .min(
          avicultureChickenPrice?.floorPrice,
          "قیمت وارد شده از کف قیمت امروز کمتر است"
        )
        .max(
          avicultureChickenPrice?.ceilingPrice,
          "قیمت وارد شده از سقف قیمت امروز بیشتر است"
        ),
      price3: Yup.number()
        .typeError("لطفا عدد وارد کنید!")
        .min(
          avicultureChickenPrice?.floorPrice,
          "قیمت وارد شده از کف قیمت امروز کمتر است"
        )
        .max(
          avicultureChickenPrice?.ceilingPrice,
          "قیمت وارد شده از سقف قیمت امروز بیشتر است"
        ),
      weight: Yup.number()
        .test("weight", "وزن را تا دو رقم اعشار وارد کنید", (val, context) => {
          return (
            context.originalValue &&
            context.originalValue.toString().length <= 4
          );
        })
        .required("این فیلد اجباری است!")
        .typeError("لطفا وزن را وارد کنید!"),
      losses: Yup.number()
        .required("این فیلد اجباری است!")
        .max(quantity, "تلفات وارد شده از باقیمانده بیشتر است!")
        .typeError("لطفا تعداد تلفات را وارد کنید!"),
      poultryPrice: Yup.number().typeError("لطفا فیلد را به درستی وارد کنید!"),
      sellType: Yup.object()
        .test("sellType", "نحوه فروش را انتخاب کنید!", (val, context) => {
          return (
            context.originalValue &&
            Object.values(context.originalValue).some((item) => item === true)
          );
        })
        .required("این فیلد اجباری است!"),
      selectedSlaughters: poultryData[0]?.provinceAllowChooseKillHouse
        ?.mandatory
        ? Yup.array()
            .of(Yup.string().required("At least one item is required."))
            .min(1, "At least one item is required.")
        : Yup.array(),
    }),
  });

  useEffect(() => {
    if (
      data?.approved &&
      !(
        data?.lowestPrice === 0 &&
        data?.highestPrice === 0 &&
        data?.lowestWeight === 0 &&
        data?.highestWeight === 0
      )
    ) {
      if (formik.values.weight * 1000 <= data?.lowestWeight) {
        setApprovedPrice(data?.lowestPrice);
      } else if (formik.values.weight * 1000 >= data?.highestWeight) {
        setApprovedPrice(data?.highestPrice);
      } else {
        const diffWeight = data?.highestWeight - data?.lowestWeight;
        const diffPrice = data?.highestPrice - data?.lowestPrice;
        const fraction = diffPrice / diffWeight;
        const diffFromMinWeight =
          formik.values.weight * 1000 - data?.lowestWeight;
        setApprovedPrice(diffFromMinWeight * fraction + data?.lowestPrice);
        formik.setFieldValue(
          "poultryPrice",
          diffFromMinWeight * fraction + data?.lowestPrice
        );
      }
    }
  }, [formik.values.weight]);

  const formik2 = useFormik({
    initialValues: {
      userInfoCheck: "",
    },
    validationSchema: Yup.object({
      userInfoCheck: Yup.string()
        .min(11, "شماره موبایل باید 11 رقم باشد")
        .max(11, "شماره موبایل باید 11 رقم باشد")
        .matches(/^09\d{9}$/, "شماره موبایل باید با 09 شروع شود و 11 رقم باشد"),
    }),
  });

  const formik3 = useFormik({
    initialValues: {
      userInfoCheck: "",
    },
    validationSchema: Yup.object({
      userInfoCheck: Yup.number().typeError("لطفا فیلد را به درستی وارد کنید!"),
    }),
  });

  const formikBuyer = useFormik({
    initialValues: {
      mobile: "",
      fname: "",
      lname: "",
      nationalCode: "",
      province: "",
      city: "",
    },
    validationSchema: Yup.object({
      mobile: Yup.string()
        .test("len", "شماره تلفن باید با 0 شروع شود", (val, context) => {
          return context.originalValue && context.originalValue.startsWith("0");
        })
        .test("len", "شماره تماس 11 رقم باید باشد", (val, context) => {
          if (context.originalValue) {
            return context.originalValue.length === 11;
          }
        })
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      fname: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
      lname: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
      nationalCode: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
      province: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
      city: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
    }),
  });
  useEffect(() => {
    formik.validateForm();
    formik2.validateForm();
    formik3.validateForm();
    formikBuyer.validateForm();
  }, []);

  useEffect(() => {
    dispatch(avicultureGetSlaughters({ date: formik.values.slaughterDate }));
  }, [formik.values.slaughterDate]);

  const penaltyPrice = formik.values.noChicken * 1000;
  const dialogContent = (
    <>
      <Typography variant="body1">
        اینجانب {userProfile?.fullname} به وکالت از{" "}
        {poultryData[0]?.userprofile?.fullName} موافقت خود را نسبت به موارد ذکر
        شده اعلام می نمایم.
      </Typography>
      <ListItem>
        <ListItemIcon>
          <DoneIcon />
        </ListItemIcon>
        <ListItemText
          primary={`        بر اساس این توافق نامه در صورت لغو فروش ${formik.values.noChicken} قطعه
          مرغ ${penaltyPrice} ریال جریمه خواهم شد.`}
        />
      </ListItem>
      <Typography></Typography>
    </>
  );

  useEffect(() => {
    let newVal = formik.values.weight;
    const mystring = formik.values.weight.toString().split(".").join("");
    if (formik.values.weight) {
      if (mystring.length <= 3) {
        if (mystring.length === 2) {
          newVal = mystring[0] + "." + mystring[1];
        }
        if (mystring.length === 3) {
          newVal = mystring[0] + "." + mystring[1] + mystring[2];
        }
      }
    }
    if (isNaN(Number.parseFloat(newVal))) {
      formik.setFieldValue("weight", "");
    } else {
      formik.setFieldValue("weight", Number.parseFloat(newVal));
    }
  }, [formik.values.weight]);

  useEffect(() => {
    if (isStockMarket) {
      dispatch(avicultureGetChickenPrice()).then((r) => {
        if (Array.isArray(r.payload.data)) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "قیمت روز مرغ در سامانه ثبت نشده است.",
            severity: "error",
          });

          dispatch(DRAWER({ right: false, bottom: false, content: null }));
        }
      });
    }
  }, [isStockMarket]);

  useEffect(() => {
    formik.validateForm();
    formik2.validateForm();
  }, []);

  useEffect(() => {
    formik.setFieldValue("selectedSlaughters", []);
    setSelectedKillhouse(null);
  }, [formik.values.noChicken]);

  useEffect(() => {
    if (poultryKey) {
      dispatch(avicultureGetDirectBuys(poultryKey)).then((r) => {
        const data = r?.payload?.data;
        if (data?.length) {
          const dataTable = data?.map((item) => {
            let state = "";
            if (item.directBuyingState === "pending") {
              state = "در انتظار تایید استان";
            } else if (item.directBuyingState === "rejected") {
              state = "رد شده";
            } else if (item.directBuyingState === "accepted") {
              state = "تایید شده";
            } else if (item.directBuyingState === "deleted") {
              state = "حذف شده";
            }
            return [
              item?.killHouse?.killer ? "کشتارکن" : "کشتارگاه",
              `${item?.killHouse?.name} (${item?.killHouse?.killHouseOperator?.user?.fullname}) ${item?.killHouse?.killHouseOperator?.user?.mobile}`,
              item?.killCapacity?.toLocaleString(),
              formatJustDate(item?.reciveDate),
              item.inputDirectBuyingCode ? "دارد" : "ندارد",
              state,
            ];
          });
          dispatch(
            OPEN_MODAL({
              title: "هشدار!",
              content: (
                <>
                  <Typography>
                    مرغدار انتخاب شده برای تاریخ امروز درخواست فعال خرید مستقیم
                    دارد.
                  </Typography>
                  <SimpleTable
                    columns={[
                      "ماهیت خریدار",
                      "خریدار",
                      "تعداد (قطعه)",
                      "تاریخ کشتار",
                      "تاییدیه مرغدار",
                      "وضعیت",
                    ]}
                    data={dataTable}
                  />
                  <Grid container gap={SPACING.SMALL}>
                    <Button
                      variant="contained"
                      color="error"
                      onClick={() => {
                        dispatch(CLOSE_MODAL());
                        dispatch(
                          DRAWER({ right: false, bottom: false, content: null })
                        );
                      }}
                    >
                      انصراف از عملیات
                    </Button>
                    <Button
                      variant="contained"
                      onClick={() => {
                        dispatch(CLOSE_MODAL());
                      }}
                    >
                      ادامه عملیات
                    </Button>
                  </Grid>
                </>
              ),
            })
          );
        }
      });
      dispatch(avicultureGetHatchingData({ key: poultryKey })).then((r) => {
        if (r.payload.data) {
          setHatchingData(r.payload.data);
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "اطلاعات جوجه ریزی یافت نشد!",
            severity: "error",
          });
        }
      });
    }
  }, [poultryKey]);

  useEffect(() => {
    let baseCanRequest =
      formik.values.noChicken <= Number(leftOvers) &&
      Number(formik.values.losses) <= Number(leftOvers)
        ? formik.values.avicultureSellType === "freePrice"
          ? parseInt(
              hatchingSelected?.freeGovernmentalInfo
                ?.leftTotalFreeCommitmentQuantity
            )
          : Number(leftOvers) - Number(formik.values.losses)
        : 0;

    // Apply market limitation if tradePanel is checked and active
    if (
      tradePanel &&
      marketLimitationData?.active &&
      marketLimitationData?.market?.remainQuantity !== undefined &&
      marketLimitationData?.market?.maxLimitationQuantity !== undefined
    ) {
      const marketRemain = marketLimitationData.market.remainQuantity;
      baseCanRequest = Math.min(baseCanRequest, marketRemain);
    }

    setChickenCanRequest(baseCanRequest);
    formik.validateForm();
  }, [
    formik.values.losses,
    leftOvers,
    formik.values.noChicken,
    formik.values.avicultureSellType,
    tradePanel,
    marketLimitationData,
  ]);

  const [sellForFreezing, setSellForFreezing] = useState(false);
  const [sellForExport, setSellForExport] = useState(false);

  useEffect(() => {
    setQuantity(hatchingSelected.quantity);
    setlosses(hatchingSelected.losses);
    setLeftOvers(hatchingSelected.leftOver);
    dispatch(provinceGetSellForFreezingStatus()).then((r) => {
      setSellForFreezing(r.payload.data.permission);
    });
    dispatch(provincePolicyGetExportAllowStatus()).then((r) => {
      setSellForExport(r.payload.data.allow);
    });
  }, [hatchingSelected]);

  useEffect(() => {
    if (tradePanel) {
      dispatch(provincePolicyGetMarketDailyLimitation()).then((r) => {
        if (r.payload?.data) {
          setMarketLimitationData(r.payload.data);
        }
      });
    }
  }, [tradePanel]);

  // const handleSellTypeChange = (event) => {
  //   formik.setFieldValue("sellType", {
  //     ...formik.values.sellType,
  //     [event.target.name]: event.target.checked,
  //   });
  // };

  // const [policyAvicultureCommit, setPolicyAvicultureCommit] = useState();

  // useEffect(() => {
  //   dispatch(provinceGetPolicyAvicultureCommitService()).then((r) => {
  //     setPolicyAvicultureCommit(r.payload.data);
  //   });
  // }, []);

  return (
    <>
      {!poultryData && !isAviculture ? (
        <>
          <Grid container alignItems="center" justifyContent="center">
            {autoLoading && <CircularProgress />}
          </Grid>
          {!autoLoading && (
            <Grid>
              <Typography>جستجو کاربر</Typography>
              <Grid mt={SPACING.SMALL} display="flex" width={1}>
                {/* <TextField
                  fullWidth
                  id="userInfoCheck"
                  label="شماره موبایل یا کد ملی یا شناسه یکتا"
                  variant="outlined"
                  value={formik2.values.userInfoCheck}
                  error={
                    formik2.touched.userInfoCheck
                      ? Boolean(formik2.errors.userInfoCheck)
                      : null
                  }
                  onChange={formik2.handleChange}
                  onBlur={formik2.handleBlur}
                  helperText={
                    formik2.touched.userInfoCheck &&
                    Boolean(formik2.errors.userInfoCheck)
                      ? formik2.errors.userInfoCheck
                      : null
                  }
                /> */}
                <Autocomplete
                  fullWidth
                  id="userInfoCheck"
                  getOptionDisabled={(option) => {
                    return option.disabled <= 0;
                  }}
                  loading={loading}
                  options={cityGetPoultries || []}
                  getOptionLabel={(option) => option.label}
                  onChange={(event, newValue) => {
                    formik2.setFieldValue("userInfoCheck", newValue.value);
                  }}
                  onBlur={formik2.handleBlur}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="مرغداری/مانده جوجه ریزی"
                      variant="outlined"
                      slotProps={{
                        input: {
                          ...params.InputProps,
                          endAdornment: (
                            <>
                              {loading ? (
                                <CircularProgress color="inherit" size={20} />
                              ) : null}
                              {params.InputProps.endAdornment}
                            </>
                          ),
                        },
                      }}
                    />
                  )}
                />

                <IconButton
                  disabled={!formik2.isValid}
                  aria-label="delete"
                  color="primary"
                  onClick={() => {
                    dispatch(
                      cityGetPoultryData(formik2.values.userInfoCheck)
                    ).then((r) => {
                      if (r.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "کاربر یافت نشد",
                          severity: "error",
                        });
                      }
                      setPoultryData(r.payload.data);
                    });
                  }}
                >
                  <SearchIcon />
                </IconButton>
              </Grid>
              <FormHelperText>شماره موبایل با صفر شروع می‌شود!</FormHelperText>
              <Typography mt={SPACING.SMALL} variant="body2" color="secondary">
                پس از ثبت درخواست، میتوانید آن را در بخش درخواست ها مدیریت کنید.
              </Typography>
            </Grid>
          )}
        </>
      ) : (
        <Grid container gap={SPACING.SMALL} direction="column" display={"flex"}>
          <Grid container gap={SPACING.SMALL} direction={"column"}>
            {/* <Grid container>
              <SimpleTable
                name={
                  <Typography variant="caption">
                    وکالت مرغدار جهت ثبت درخواست کشتار
                  </Typography>
                }
                columns={["استان", "شهرستان"]}
                data={[
                  [
                    poultryData[0]?.allow?.province ? (
                      <Typography color="green">دارد</Typography>
                    ) : (
                      <Typography color="red">ندارد</Typography>
                    ),
                    poultryData[0]?.allow?.city ? (
                      <Typography color="green">دارد</Typography>
                    ) : (
                      <Typography color="red">ندارد</Typography>
                    ),
                  ],
                ]}
              />
            </Grid> */}
            <Grid minWidth={210}>
              <Autocomplete
                disablePortal
                id="combo-box-demo"
                options={
                  Array.isArray(poultryData)
                    ? poultryData.map((i) => ({
                        id: i.key,
                        label: i.unitName,
                      }))
                    : []
                }
                onChange={(event, value) => {
                  setPolutryKey(value.id);
                }}
                renderInput={(params) => (
                  <TextField {...params} label="محل پرورش" />
                )}
              />
            </Grid>

            {poultryKey && (
              <Grid minWidth={210}>
                <Autocomplete
                  disablePortal
                  id="hatching"
                  options={
                    hatchingData
                      ? hatchingData.map((i) => {
                          return {
                            id: i.key,
                            race: i.chickenBreed,
                            selected: i,
                            label: `دوره ${i.period} سالن ${i.hall} نژاد ${i.chickenBreed} باقیمانده ${i.leftOver} قطعه`,
                          };
                        })
                      : []
                  }
                  onChange={(event, value) => {
                    sethatchingKey(value.id);
                    setHatchingSelected(value.selected);
                    setChickenBreed(value.race);
                  }}
                  renderInput={(params) => (
                    <TextField {...params} label="دوره جوجه ریزی" />
                  )}
                />
              </Grid>
            )}

            {hatchingKey && (
              <>
                <Grid>
                  <TextField
                    disabled
                    fullWidth
                    id="outlined-read-only-input"
                    label="تعداد جوجه ریزی"
                    value={quantity ? quantity : "نامشخص"}
                    InputProps={{
                      readOnly: true,
                    }}
                  />
                </Grid>
                <Grid>
                  <TextField
                    disabled
                    fullWidth
                    id="outlined-read-only-input"
                    label="جمع تلفات ثبت شده دامپزشک و مرغدار"
                    value={losses ? losses : "نامشخص"}
                    InputProps={{
                      readOnly: true,
                    }}
                  />
                </Grid>
                <Grid>
                  <TextField
                    disabled
                    fullWidth
                    id="outlined-read-only-input"
                    label="باقیمانده"
                    value={leftOvers ? leftOvers : "نامشخص"}
                    InputProps={{
                      readOnly: true,
                    }}
                  />
                </Grid>
              </>
            )}
          </Grid>
          {hatchingSelected && (
            <Grid container gap={SPACING.SMALL} direction={"column"}>
              <Grid>
                <Typography>اطلاعات کشتار</Typography>
              </Grid>

              {/* <Grid>
                <NumberInput
                  allowLeadingZeros
                  thousandSeparator=","
                  fullWidth
                  id="losses"
                  label="تلفات"
                  disabled={getRoleFromUrl() === "Poultry"}
                  variant="outlined"
                  value={formik.values.losses}
                  error={
                    formik.touched.losses ? Boolean(formik.errors.losses) : null
                  }
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  helperText={
                    formik.touched.losses && Boolean(formik.errors.losses)
                      ? formik.errors.losses
                      : null
                  }
                />
              </Grid> */}
              <Grid>
                {/* <NumericFormat
                customInput={TextField}
                allowLeadingZeros
                thousandSeparator=","
                fullWidth
                id="noChicken"
                label="تعداد مرغ برای کشتار"
                // InputProps={{
                //   inputComponent: NumberFormatCustom,
                // }}
                variant="outlined"
                value={formik.values.noChicken}
                error={
                  formik.touched.noChicken
                    ? Boolean(formik.errors.noChicken)
                    : null
                }
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                helperText={
                  formik.touched.noChicken && Boolean(formik.errors.noChicken)
                    ? formik.errors.noChicken
                    : null
                }
              /> */}
                <NumberInput
                  allowLeadingZeros
                  thousandSeparator=","
                  fullWidth
                  id="noChicken"
                  label="تعداد مرغ برای کشتار"
                  // InputProps={{
                  //   inputComponent: NumberFormatCustom,
                  // }}
                  variant="outlined"
                  value={formik.values.noChicken}
                  error={
                    formik.values.noChicken > chickenCanRequest
                      ? (() => {
                          if (
                            tradePanel &&
                            marketLimitationData?.active &&
                            formik.values.noChicken >
                              marketLimitationData?.market?.remainQuantity
                          ) {
                            return `حداکثر ظرفیت پنل معاملات ${marketLimitationData?.market?.remainQuantity?.toLocaleString()} قطعه است!`;
                          }
                          return "این حجم قابل تخصیص نیست!";
                        })()
                      : formik.touched.noChicken
                      ? Boolean(formik.errors.noChicken)
                      : null
                  }
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  helperText={
                    formik.values.noChicken > chickenCanRequest
                      ? (() => {
                          if (
                            tradePanel &&
                            marketLimitationData?.active &&
                            formik.values.noChicken >
                              marketLimitationData?.market?.remainQuantity
                          ) {
                            return `حداکثر ظرفیت پنل معاملات ${marketLimitationData?.market?.remainQuantity?.toLocaleString()} قطعه است!`;
                          }
                          return "این حجم قابل تخصیص نیست!";
                        })()
                      : formik.touched.noChicken &&
                        Boolean(formik.errors.noChicken)
                      ? formik.errors.noChicken
                      : null
                  }
                />
              </Grid>

              {data?.approved && (
                <Grid
                  container
                  gap={SPACING.TINY}
                  justifyContent="start"
                  alignItems={"start"}
                >
                  <Grid container gap={SPACING.TINY}>
                    <Typography
                      color={(prop) => prop.palette.grey["A700"]}
                      variant={"caption"}
                    >
                      مجوز فروش آزاد:
                    </Typography>
                    <Typography variant={"button"}>
                      {parseInt(
                        hatchingSelected?.freeGovernmentalInfo
                          ?.totalFreeCommitmentQuantity
                      )?.toLocaleString()}
                    </Typography>

                    <Typography variant={"button"}>قطعه</Typography>
                  </Grid>

                  <Grid container gap={SPACING.TINY}>
                    <Typography color={"error"} variant={"caption"}>
                      مانده فروش آزاد:
                    </Typography>
                    <Typography variant={"button"} color={"error"}>
                      {parseInt(
                        hatchingSelected?.freeGovernmentalInfo
                          ?.leftTotalFreeCommitmentQuantity
                      ).toLocaleString()}
                      {"‌‌"}
                      قطعه
                    </Typography>
                  </Grid>
                </Grid>
              )}

              <Grid>
                <DatePicker
                  label="تاریخ کشتار"
                  id="slaughterDate"
                  renderInput={(params) => <TextField {...params} />}
                  value={formik.values.slaughterDate}
                  error={
                    formik.touched.slaughterDate
                      ? Boolean(formik.errors.slaughterDate)
                      : null
                  }
                  onChange={(e) => {
                    formik.setFieldValue(
                      "slaughterDate",
                      moment(e).format("YYYY-MM-DD")
                    );
                  }}
                  onBlur={formik.handleBlur}
                  helperText={
                    formik.touched.slaughterDate &&
                    Boolean(formik.errors.slaughterDate)
                      ? formik.errors.slaughterDate
                      : null
                  }
                />
              </Grid>

              <Grid>
                <TextField
                  id="weight"
                  label="وزن تقریبی مرغ"
                  variant="outlined"
                  InputProps={{
                    endAdornment: (
                      <InputAdornment position="end">کیلوگرم</InputAdornment>
                    ),
                  }}
                  value={formik.values.weight}
                  error={
                    formik.touched.weight ? Boolean(formik.errors.weight) : null
                  }
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  helperText={
                    formik.touched.weight && Boolean(formik.errors.weight)
                      ? formik.errors.weight
                      : null
                  }
                />
              </Grid>

              {/* <Grid>
                <FormControl>
                  <RadioGroup
                    aria-labelledby="demo-controlled-radio-buttons-group"
                    name="controlled-radio-buttons-group"
                    value={value}
                    onChange={handleChangeRadioButton}
                  >
                    <FormControlLabel
                      value="insideProvince"
                      control={<Radio />}
                      label="فروش داخل استان"
                    />
                    <FormControlLabel
                      value="outOfProvince"
                      control={<Radio />}
                      label="فروش خارج استان"
                    />
                  </RadioGroup>
                </FormControl>
              </Grid> */}

              {/* <Grid>
              <Typography>نحوه فروش</Typography>
            </Grid> */}

              {value === "insideProvince" ? (
                <>
                  <Grid display="none">
                    <FormControl>
                      <RadioGroup
                        aria-labelledby="demo-radio-buttons-group-label"
                        defaultValue="فروش اتحادیه"
                        name="radio-buttons-group"
                        onChange={(event) => {
                          setIsStockMarket(event.currentTarget.value);
                        }}
                      >
                        {/* <FormControlLabel
                    value="فروش اتحادیه"
                    control={<Radio />}
                    label="فروش اتحادیه"
                  /> */}
                        {/* <FormControlLabel
                    value="فروش مزایده ای"
                    control={
                      <Radio id="isStockMarket" onChange={formik.handleChange} />
                    }
                    label="فروش مزایده ای"
                  /> */}
                        {isStockMarket === "فروش مزایده ای" && (
                          <Grid container gap={SPACING.SMALL}>
                            <Grid
                              container
                              gap={SPACING.SMALL}
                              alignItems={"center"}
                            >
                              <Typography
                                color={(prop) => prop.palette.grey["A700"]}
                                variant={"caption"}
                              >
                                کف قیمت امروز:
                              </Typography>
                              <Typography color="secondary" variant={"button"}>
                                {avicultureChickenPrice?.floorPrice
                                  ? avicultureChickenPrice?.floorPrice.toLocaleString()
                                  : "نامشخص"}{" "}
                                {"  "}
                                ریال
                              </Typography>
                            </Grid>
                            <Grid
                              container
                              gap={SPACING.SMALL}
                              alignItems={"center"}
                            >
                              <Typography
                                color={(prop) => prop.palette.grey["A700"]}
                                variant={"caption"}
                              >
                                سقف قیمت امروز:
                              </Typography>
                              <Typography color="secondary" variant={"button"}>
                                {avicultureChickenPrice?.ceilingPrice
                                  ? avicultureChickenPrice?.ceilingPrice.toLocaleString()
                                  : "نامشخص"}
                                ریال
                              </Typography>
                            </Grid>

                            <Divider style={{ width: "100%" }} />

                            {arr.map((item, i) => {
                              return (
                                <Grid
                                  gap={SPACING.SMALL}
                                  container
                                  key={i}
                                  sx={{ minWidth: 210 }}
                                >
                                  <Typography mb={SPACING.SMALL} display="flex">
                                    پیشنهاد {i + 1}
                                  </Typography>

                                  <NumberInput
                                    allowLeadingZeros
                                    thousandSeparator=","
                                    error={false}
                                    fullWidth
                                    label="قیمت پیشنهادی"
                                    variant="outlined"
                                    onChange={handleChange}
                                    id={i}
                                  />

                                  <FormControl fullWidth>
                                    <InputLabel id="demo-simple-select-label">
                                      بازه زمانی (ساعت)
                                    </InputLabel>
                                    <Select
                                      id={i}
                                      labelId="demo-simple-select-label"
                                      label="بازه زمانی (ساعت)"
                                    >
                                      <MenuItem
                                        onClick={handleChangeTime}
                                        id={i}
                                        value={"1"}
                                      >
                                        1
                                      </MenuItem>
                                      <MenuItem
                                        onClick={handleChangeTime}
                                        id={i}
                                        value={"2"}
                                      >
                                        2
                                      </MenuItem>
                                      <MenuItem
                                        onClick={handleChangeTime}
                                        id={i}
                                        value={"3"}
                                      >
                                        3
                                      </MenuItem>
                                      <MenuItem
                                        onClick={handleChangeTime}
                                        id={i}
                                        value={"4"}
                                      >
                                        4
                                      </MenuItem>
                                      <MenuItem
                                        onClick={handleChangeTime}
                                        id={i}
                                        value={"5"}
                                      >
                                        5
                                      </MenuItem>
                                      <MenuItem
                                        onClick={handleChangeTime}
                                        id={i}
                                        value={"6"}
                                      >
                                        6
                                      </MenuItem>
                                      <MenuItem
                                        onClick={handleChangeTime}
                                        id={i}
                                        value={"7"}
                                      >
                                        7
                                      </MenuItem>
                                      <MenuItem
                                        onClick={handleChangeTime}
                                        id={i}
                                        value={"8"}
                                      >
                                        8
                                      </MenuItem>
                                      <MenuItem
                                        onClick={handleChangeTime}
                                        id={i}
                                        value={"9"}
                                      >
                                        9
                                      </MenuItem>
                                      <MenuItem
                                        onClick={handleChangeTime}
                                        id={i}
                                        value={"10"}
                                      >
                                        10
                                      </MenuItem>
                                    </Select>
                                    <FormHelperText>
                                      {formik.touched.period1 &&
                                      Boolean(formik.errors.period1)
                                        ? formik.errors.period1
                                        : null}
                                    </FormHelperText>
                                  </FormControl>
                                  {/* <input
                          key={i}
                          onChange={handleChange}
                          value={item.value}
                          id={i}
                          type={item.type}
                        /> */}
                                </Grid>
                              );
                            })}

                            <Grid container>
                              {arr.length > 1 && (
                                <IconButton
                                  onClick={removeInput}
                                  aria-label="delete"
                                  color="secondary"
                                >
                                  <DeleteIcon />
                                </IconButton>
                              )}
                              {arr.length < 3 && (
                                <IconButton
                                  xs={12}
                                  onClick={addInput}
                                  aria-label="add"
                                  color="primary"
                                >
                                  <AddIcon />
                                  <Typography>افزودن پیشنهاد جدید</Typography>
                                </IconButton>
                              )}
                            </Grid>

                            <Grid container sx={{ width: "100%" }}>
                              <Typography variant="body2">
                                در صورت عدم فروش در بورس، از طریق اتحادیه فروش
                                برود
                                <Checkbox
                                  id="isUnion"
                                  onChange={formik.handleChange}
                                />
                              </Typography>
                            </Grid>
                          </Grid>
                        )}
                      </RadioGroup>
                    </FormControl>
                  </Grid>
                  {/* <SelectCheck
                    label={"انتخاب کشتارگاه پیشنهادی"}
                    onChange={(e) =>
                      formik.setFieldValue("selectedSlaughters", e)
                    }
                    options={slaughterHousesListForSelect}
                  /> */}
                  {/* <Grid container gap={SPACING.SMALL}>
                    {formik.values.selectedSlaughters && (
                      <Typography variant="body1">
                        کشتارگاهای انتخابی
                      </Typography>
                    )}
                    <Grid container direction="column">
                      {formik.values.selectedSlaughters.map((item, i) => {
                        return (
                          <Typography variant="body2" key={i}>
                            {i + 1}- {item}
                          </Typography>
                        );
                      })}
                    </Grid>
                  </Grid> */}
                  {/* <Grid>
                    <Grid mb={SPACING.TINY}>
                      <Typography varaint="body1">نحوه فروش</Typography>
                    </Grid>
                    <FormGroup>
                      <FormControlLabel
                        control={
                          <Checkbox
                            onChange={handleSellTypeChange}
                            name="cash"
                            value="نقدی"
                          />
                        }
                        label="نقدی"
                      />
                      <FormControlLabel
                        control={
                          <Checkbox
                            onChange={handleSellTypeChange}
                            name="haveTime"
                            value="زمان دار"
                          />
                        }
                        label="زمان دار (تا یک ماه)"
                      />
                    </FormGroup>
                    <FormHelperText>
                      {formik.touched.sellType &&
                      Boolean(formik.errors.sellType)
                        ? formik.errors.sellType
                        : null}
                    </FormHelperText>
                  </Grid> */}

                  {/* {unions?.length > 1 && ( */}
                  {/* <> */}

                  {data?.approved &&
                    !(
                      data?.lowestPrice === 0 &&
                      data?.highestPrice === 0 &&
                      data?.lowestWeight === 0 &&
                      data?.highestWeight === 0
                    ) && (
                      <Grid>
                        <Typography>نوع فروش</Typography>
                        <RadioGroup
                          aria-label="avicultureSellType"
                          name="avicultureSellType"
                          value={formik.values.avicultureSellType}
                          onChange={formik.handleChange}
                        >
                          <FormControlLabel
                            value="goverment"
                            control={<Radio />}
                            label="دولتی"
                          />
                          <FormControlLabel
                            value="freePrice"
                            control={<Radio />}
                            label="آزاد"
                          />
                        </RadioGroup>
                      </Grid>
                    )}

                  {data?.approved &&
                    formik.values.avicultureSellType === "goverment" &&
                    !(
                      data?.lowestPrice === 0 &&
                      data?.highestPrice === 0 &&
                      data?.lowestWeight === 0 &&
                      data?.highestWeight === 0
                    ) && (
                      <Grid
                        gap={1}
                        container
                        p={1}
                        style={{
                          borderStyle: "solid",
                          borderWidth: "1px",
                          borderColor: "red",
                          borderRadius: "5px",
                        }}
                      >
                        <Tooltip
                          title={`قیمت مصوب بر اساس قیمت مصوب کف ${data?.lowestPrice.toLocaleString()} هزار ریال و سقف ${data?.highestPrice?.toLocaleString()} هزار ریال محاسبه شده است.`}
                        >
                          <Typography variant="body1" color="secondary">
                            قیمت مصوب:
                          </Typography>
                        </Tooltip>
                        <Typography variant="body1" color="primary">
                          {approvedPrice
                            ? Math.round(approvedPrice)?.toLocaleString()
                            : 0}
                          ریال
                        </Typography>
                      </Grid>
                    )}

                  <Divider />

                  <Grid style={{ display: "none" }}>
                    <Typography>نحوه تسویه حساب</Typography>
                    <RadioGroup
                      name="financialOperation"
                      value={formik.values.financialOperation}
                      onChange={formik.handleChange}
                    >
                      <Tooltip
                        title="تسویه با مرغدار توسط خریدار بصورت مستقیم صورت میگیرد"
                        arrow
                      >
                        <FormControlLabel
                          value="outside-system"
                          control={<Radio />}
                          label="خارج از سامانه"
                        />
                      </Tooltip>
                      <FormControlLabel
                        value="inside-system"
                        control={<Radio />}
                        label="درون سامانه"
                        disabled={true}
                      />
                    </RadioGroup>
                  </Grid>

                  {poultryData?.length &&
                    poultryData[0]?.provinceAllowChooseKillHouse
                      ?.allowState && (
                      <Grid container direction="column" gap={SPACING.SMALL}>
                        <Autocomplete
                          disablePortal
                          value={
                            formik.values.selectedSlaughters?.length
                              ? formik.values.selectedSlaughters[0]
                              : null
                          }
                          onChange={(e, v) => {
                            formik.setFieldValue("selectedSlaughters", [
                              v.value,
                            ]);
                            setSelectedKillhouse(v.killhouseKey);
                          }}
                          id="combo-box-demo"
                          options={slaughterHousesListForSelect}
                          sx={{ width: "100%" }}
                          getOptionDisabled={(option) => {
                            const limit = Number(formik.values.noChicken);
                            return option.item.quantitySum < limit;
                          }}
                          renderInput={(params) => (
                            <TextField
                              {...params}
                              label={"خریدار/ظرفیت باقیمانده"}
                            />
                          )}
                        />
                        {/* <SelectCheck
                          label={"کشتارگاه/ظرفیت"}
                          onChange={(e) => {
                            formik.setFieldValue("selectedSlaughters", e);
                          }}
                          options={slaughterHousesListForSelect}
                        /> */}
                        <Grid container gap={SPACING.SMALL}>
                          {formik.values.selectedSlaughters && (
                            <Typography variant="body1">
                              کشتارگاهای انتخابی
                            </Typography>
                          )}
                          <Grid container direction="column">
                            {formik.values.selectedSlaughters.map((item, i) => {
                              return (
                                <Typography variant="body2" key={i}>
                                  {i + 1}- {item}
                                </Typography>
                              );
                            })}
                          </Grid>
                        </Grid>
                      </Grid>
                    )}
                  <Grid style={{ display: "none" }}>
                    <FormControl>
                      <FormLabel id="demo-radio-buttons-group-label">
                        اطلاعات تعاونی
                      </FormLabel>
                      <RadioGroup
                        defaultValue={unions?.length ? unions[0]?.key : ""}
                        name="radio-buttons-group"
                        onChange={(event) => {
                          setUnionSelected(event.currentTarget.value);
                        }}
                      >
                        {unions?.map((item) => {
                          return (
                            <>
                              <FormControlLabel
                                disabled={true}
                                value={item.key}
                                control={<Radio />}
                                label={item.unitName}
                              />
                            </>
                          );
                        })}
                      </RadioGroup>
                    </FormControl>
                  </Grid>
                  {/* </>
                  )} */}
                </>
              ) : (
                <>
                  <Grid>
                    <Typography variant="body2">
                      اطلاعات کاربر را وارد یا جستجو کنید.
                    </Typography>
                    <Grid mt={SPACING.SMALL} display="flex" width={1}>
                      <TextField
                        fullWidth
                        id="userInfoCheck"
                        label="شماره موبایل یا کد ملی "
                        variant="outlined"
                        value={formik3.values.userInfoCheck}
                        error={
                          formik3.touched.userInfoCheck
                            ? Boolean(formik3.errors.userInfoCheck)
                            : null
                        }
                        onChange={formik3.handleChange}
                        onBlur={formik3.handleBlur}
                        helperText={
                          formik3.touched.userInfoCheck &&
                          Boolean(formik3.errors.userInfoCheck)
                            ? formik3.errors.userInfoCheck
                            : null
                        }
                      />

                      <IconButton
                        disabled={!formik3.isValid}
                        aria-label="delete"
                        color="primary"
                        onClick={() => {
                          dispatch(
                            cityGetBuyer(formik3.values.userInfoCheck)
                          ).then((r) => {
                            if (r.error) {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "کاربر یافت نشد",
                                severity: "error",
                              });
                              setBuyerInfo("");
                            } else {
                              setBuyerInfo(r.payload.data);
                            }
                          });
                        }}
                      >
                        <SearchIcon />
                      </IconButton>
                    </Grid>
                    <FormHelperText>
                      شماره موبایل با صفر شروع می‌شود!
                    </FormHelperText>
                  </Grid>

                  {buyerInfo ? (
                    <Grid>
                      <Grid display="flex">
                        <Typography
                          variant="body1"
                          mr={SPACING.TINY}
                          color={(prop) => prop.palette.grey["A700"]}
                        >
                          نام کامل:
                        </Typography>
                        <Typography mr={SPACING.TINY} fontWeight="bold">
                          {(buyerInfo?.firstname ? buyerInfo?.firstname : "") +
                            " " +
                            (buyerInfo?.lastname ? buyerInfo?.lastname : "")}
                        </Typography>
                      </Grid>

                      <Grid display="flex">
                        <Typography
                          variant="body1"
                          mr={SPACING.TINY}
                          color={(prop) => prop.palette.grey["A700"]}
                        >
                          نقش:
                        </Typography>
                        <Typography mr={SPACING.TINY} fontWeight="bold">
                          اپراتور استان
                        </Typography>
                      </Grid>

                      <Grid display="flex">
                        <Typography
                          variant="body1"
                          mr={SPACING.TINY}
                          color={(prop) => prop.palette.grey["A700"]}
                        >
                          استان:
                        </Typography>
                        <Typography mr={SPACING.TINY} fontWeight="bold">
                          {buyerInfo?.province}
                        </Typography>
                      </Grid>

                      <Grid display="flex">
                        <Typography
                          variant="body1"
                          mr={SPACING.TINY}
                          color={(prop) => prop.palette.grey["A700"]}
                        >
                          شهر:
                        </Typography>
                        <Typography mr={SPACING.TINY} fontWeight="bold">
                          {buyerInfo?.city}
                        </Typography>
                      </Grid>
                    </Grid>
                  ) : (
                    <Grid container gap={SPACING.SMALL}>
                      <Typography variant="body2">
                        اطلاعات کاربر را وارد کنید
                      </Typography>
                      <TextField
                        fullWidth
                        id="mobile"
                        label="شماره موبایل "
                        variant="outlined"
                        value={formikBuyer.values.mobile}
                        error={
                          formikBuyer.touched.mobile
                            ? Boolean(formikBuyer.errors.mobile)
                            : null
                        }
                        onChange={formikBuyer.handleChange}
                        onBlur={formikBuyer.handleBlur}
                        helperText={
                          formikBuyer.touched.mobile &&
                          Boolean(formikBuyer.errors.mobile)
                            ? formikBuyer.errors.mobile
                            : null
                        }
                      />

                      <TextField
                        fullWidth
                        id="fname"
                        label="نام"
                        variant="outlined"
                        value={formikBuyer.values.fname}
                        error={
                          formikBuyer.touched.fname
                            ? Boolean(formikBuyer.errors.fname)
                            : null
                        }
                        onChange={formikBuyer.handleChange}
                        onBlur={formikBuyer.handleBlur}
                        helperText={
                          formikBuyer.touched.fname &&
                          Boolean(formikBuyer.errors.fname)
                            ? formikBuyer.errors.fname
                            : null
                        }
                      />

                      <TextField
                        fullWidth
                        id="lname"
                        label="نام خانوادگی"
                        variant="outlined"
                        value={formikBuyer.values.lname}
                        error={
                          formikBuyer.touched.lname
                            ? Boolean(formikBuyer.errors.lname)
                            : null
                        }
                        onChange={formikBuyer.handleChange}
                        onBlur={formikBuyer.handleBlur}
                        helperText={
                          formikBuyer.touched.lname &&
                          Boolean(formikBuyer.errors.lname)
                            ? formikBuyer.errors.lname
                            : null
                        }
                      />

                      <TextField
                        fullWidth
                        id="nationalCode"
                        label="کد ملی"
                        variant="outlined"
                        value={formikBuyer.values.nationalCode}
                        error={
                          formikBuyer.touched.nationalCode
                            ? Boolean(formikBuyer.errors.nationalCode)
                            : null
                        }
                        onChange={formikBuyer.handleChange}
                        onBlur={formikBuyer.handleBlur}
                        helperText={
                          formikBuyer.touched.nationalCode &&
                          Boolean(formikBuyer.errors.nationalCode)
                            ? formikBuyer.errors.nationalCode
                            : null
                        }
                      />

                      <TextField
                        fullWidth
                        id="province"
                        label="استان"
                        variant="outlined"
                        value={formikBuyer.values.province}
                        error={
                          formikBuyer.touched.province
                            ? Boolean(formikBuyer.errors.province)
                            : null
                        }
                        onChange={formikBuyer.handleChange}
                        onBlur={formikBuyer.handleBlur}
                        helperText={
                          formikBuyer.touched.province &&
                          Boolean(formikBuyer.errors.province)
                            ? formikBuyer.errors.province
                            : null
                        }
                      />

                      <TextField
                        fullWidth
                        id="city"
                        label="شهر"
                        variant="outlined"
                        value={formikBuyer.values.city}
                        error={
                          formikBuyer.touched.city
                            ? Boolean(formikBuyer.errors.city)
                            : null
                        }
                        onChange={formikBuyer.handleChange}
                        onBlur={formikBuyer.handleBlur}
                        helperText={
                          formikBuyer.touched.city &&
                          Boolean(formikBuyer.errors.city)
                            ? formikBuyer.errors.city
                            : null
                        }
                      />
                    </Grid>
                  )}
                </>
              )}

              <Grid container xs={12} gap={1} justifyContent="start">
                {sellForFreezing && (
                  <Grid xs={12}>
                    <Grid container alignItems="center">
                      <Checkbox
                        checked={freezing}
                        onChange={() => {
                          setFreezing(!freezing);
                        }}
                        inputProps={{ "aria-label": "controlled" }}
                      />
                      <Typography variant="body1">کشتار برای انجماد</Typography>
                    </Grid>
                  </Grid>
                )}

                {marketLimitationData?.active ? (
                  <LabelField label="جزییات پنل">
                    <Grid container direction="column" gap={1}>
                      <Grid container alignItems="center">
                        <Checkbox
                          checked={tradePanel}
                          onChange={() => {
                            setTradePanel(!tradePanel);
                          }}
                          inputProps={{ "aria-label": "controlled" }}
                        />
                        <Typography variant="body1">
                          نمایش در پنل معاملات
                        </Typography>
                      </Grid>
                      {tradePanel && (
                        <Grid container direction="column" gap={1} pr={2}>
                          <Grid
                            container
                            gap={SPACING.TINY}
                            justifyContent="space-between"
                            alignItems={"start"}
                          ></Grid>
                          <Grid container gap={1} alignItems="center">
                            <Typography
                              variant="caption"
                              color={(prop) => prop.palette.grey["A700"]}
                            >
                              باقیمانده مجاز:
                            </Typography>
                            <Typography variant="button" color="primary">
                              {marketLimitationData?.market?.remainQuantity?.toLocaleString()}{" "}
                              قطعه
                            </Typography>
                          </Grid>
                          <Grid container gap={1} alignItems="center">
                            <Typography
                              variant="caption"
                              color={(prop) => prop.palette.grey["A700"]}
                            >
                              حداکثر قطعه مجاز:
                            </Typography>
                            <Typography variant="button">
                              {marketLimitationData?.market?.maxLimitationQuantity?.toLocaleString()}{" "}
                              قطعه
                            </Typography>
                          </Grid>
                        </Grid>
                      )}
                    </Grid>
                  </LabelField>
                ) : (
                  <Grid container alignItems="center">
                    <Checkbox
                      checked={tradePanel}
                      onChange={() => {
                        setTradePanel(!tradePanel);
                      }}
                      inputProps={{ "aria-label": "controlled" }}
                    />
                    <Typography variant="body1">
                      نمایش در پنل معاملات
                    </Typography>
                  </Grid>
                )}
              </Grid>

              {(formik.values.avicultureSellType !== "goverment" ||
                (data?.approved &&
                  data?.lowestPrice === 0 &&
                  data?.highestPrice === 0 &&
                  data?.lowestWeight === 0 &&
                  data?.highestWeight === 0)) && (
                <Grid>
                  <TextField
                    id="poultryPrice"
                    label="قیمت پیشنهادی مرغدار"
                    variant="outlined"
                    InputProps={{
                      endAdornment: (
                        <InputAdornment position="end">ریال</InputAdornment>
                      ),
                    }}
                    value={formik.values.poultryPrice}
                    error={
                      formik.touched.poultryPrice
                        ? Boolean(formik.errors.poultryPrice)
                        : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.poultryPrice &&
                      Boolean(formik.errors.poultryPrice)
                        ? formik.errors.poultryPrice
                        : null
                    }
                    sx={{
                      "& .Mui-disabled": {
                        backgroundColor: "#f0f0f0",
                        color: "#666",
                        "& .MuiOutlinedInput-notchedOutline": {
                          borderColor: "#ccc",
                        },
                      },
                    }}
                    disabled={freezing}
                  />
                  {!data?.approved &&
                    formik.values.avicultureSellType !== "goverment" && (
                      <Typography variant="caption" color="error">
                        نوع فروش: آزاد
                      </Typography>
                    )}
                </Grid>
              )}
              {sellForExport && (
                <Grid container alignItems="center">
                  <Checkbox
                    checked={toExport}
                    onChange={() => {
                      setToExport(!toExport);
                    }}
                    inputProps={{ "aria-label": "controlled" }}
                  />
                  <Typography variant="body1">کشتار برای صادرات</Typography>
                </Grid>
              )}

              {getRoleFromUrl() === "Poultry" && (
                <Grid>
                  <DialogAlert
                    title="تعهد نامه"
                    content={dialogContent}
                    actions={
                      <Grid container gap={SPACING.TINY}>
                        <Button
                          variant="outlined"
                          color="error"
                          onClick={() => {
                            formik.setFieldValue("isAccepted", false);
                          }}
                        >
                          رد
                        </Button>
                        <Button
                          variant="contained"
                          color="success"
                          onClick={() => {
                            formik.setFieldValue("isAccepted", true);
                          }}
                        >
                          موافقم
                        </Button>
                      </Grid>
                    }
                    btnTitle={"متن تعهد نامه تایید شد!"}
                    isAccepted={formik.values.isAccepted}
                  />
                </Grid>
              )}

              {submitStatus && (
                <TextField
                  fullWidth
                  id="userInfoCheck"
                  label="ویرایش تلفن مرغدار"
                  variant="outlined"
                  value={formik2.values.userInfoCheck}
                  error={
                    formik2.touched.city
                      ? Boolean(formik2.errors.userInfoCheck)
                      : null
                  }
                  onChange={formik2.handleChange}
                  onBlur={formik2.handleBlur}
                  helperText={
                    formik2.touched.userInfoCheck &&
                    Boolean(formik2.errors.userInfoCheck)
                      ? formik2.errors.userInfoCheck
                      : null
                  }
                />
              )}

              {submitStatus && (
                <Typography variant="caption" color="error">
                  احراز پیامکی قیمت مرغدار در استان فعال است. در صورت ویرایش،
                  تلفن مرغدار در سراسر سامانه با تلفن جدید جایگزین میگردد!
                </Typography>
              )}
              <Grid mb={SPACING.SMALL}>
                <Button
                  fullWidth
                  disabled={
                    !formik.isValid ||
                    !formik2.isValid ||
                    (formik.values.avicultureSellType === "freePrice" &&
                      (freezing ? false : !formik.values.poultryPrice)) ||
                    (tradePanel &&
                      marketLimitationData?.active &&
                      (formik.values.noChicken >
                        marketLimitationData?.market?.remainQuantity ||
                        formik.values.noChicken >
                          marketLimitationData?.market?.maxLimitationQuantity))
                  }
                  onClick={() => {
                    if (
                      getRoleFromUrl() !== "SuperAdmin" &&
                      getRoleFromUrl() !== "AdminX" &&
                      !isValidIndexWeight(
                        weightRange,
                        hatchingSelected?.age,
                        formik.values.weight
                      )
                    ) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "میانگین وزنی با احراز سنی مطابقت ندارد. لطفا با اتحادیه تماس بگیرید.",
                        severity: "error",
                      });
                    } else if (formik.values.noChicken > chickenCanRequest) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "تعداد وارد شده از حجم قابل تخصیص بزرگتر است!",
                        severity: "error",
                      });
                    } else {
                      dispatch(LOADING_START());
                      if (value === "insideProvince") {
                        if (isStockMarket === "فروش مزایده ای") {
                          dispatch(
                            avicultureNewRequest({
                              role: getRoleFromUrl(),
                              poultry_key: poultryData?.key,
                              operator_key:
                                unions?.length > 1 ? unionSelected : "",
                              poultry_hatching_key: hatchingKey,
                              quantity: formik.values.noChicken,
                              send_date: formik.values.slaughterDate,
                              chicken_breed: chickenBreed,
                              Index_weight: formik.values.weight,
                              freezing: freezing,
                              union: formik.values.isUnion,
                              losses:
                                formik.values.losses !== ""
                                  ? formik.values.losses
                                  : 0,
                              auction: true,
                              auction_list: arr.map((item, i) => {
                                return {
                                  pricing_key: pricingKey,
                                  fee: item.value
                                    ? item.value
                                    : avicultureChickenPrice?.floorPrice,
                                  hour: arrPrices[i].value
                                    ? arrPrices[i].value
                                    : "4",
                                };
                              }),
                            })
                          ).then((r) => {
                            if (r.error) {
                              if (r.error.message.includes("403")) {
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "قیمت پیشنهادی نباید از حداکثر قیمت روز بیشتر باشد.",
                                  severity: "error",
                                });
                              } else {
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "مشکلی پیش آمده است!",
                                  severity: "error",
                                });
                              }
                            } else {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "عملیات با موفقیت انجام شد.",
                                severity: "success",
                              });
                              dispatch(
                                DRAWER({
                                  right: false,
                                  bottom: false,
                                  content: null,
                                })
                              );
                            }
                          });
                        } else {
                          dispatch(
                            avicultureNewRequest({
                              approved_price: data?.approved,
                              market: tradePanel,
                              kill_req_key: selectedKillhouse,
                              operator_key:
                                unions?.length > 1 ? unionSelected : "",
                              poultry_hatching_key: hatchingKey,
                              quantity: formik.values.noChicken,
                              send_date: formik.values.slaughterDate,
                              chicken_breed: chickenBreed,
                              Index_weight: formik.values.weight,
                              losses:
                                formik.values.losses !== ""
                                  ? formik.values.losses
                                  : 0,
                              auction_list: [],
                              freezing: freezing,
                              export: toExport,
                              cash: formik.values.sellType.cash,
                              credit: formik.values.sellType.haveTime,
                              kill_house_list: formik.values.selectedSlaughters,
                              role: getRoleFromUrl(),
                              poultry_key: poultryKey,
                              amount:
                                data?.approved &&
                                !(
                                  data?.lowestPrice === 0 &&
                                  data?.highestPrice === 0 &&
                                  data?.lowestWeight === 0 &&
                                  data?.highestWeight === 0
                                )
                                  ? Math.round(approvedPrice)
                                  : Number(formik.values.poultryPrice),
                              financial_operation:
                                formik.values.financialOperation,
                              free_sale_in_province:
                                formik.values.avicultureSellType === "goverment"
                                  ? false
                                  : true,
                              confirm_poultry_mobile:
                                formik2.values.userInfoCheck,
                            })
                          ).then((r) => {
                            dispatch(LOADING_END());
                            if (r.payload.error) {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: r.payload.error,
                                severity: "error",
                              });
                            } else {
                              if (updateTable) {
                                updateTable();
                              }
                              dispatch(
                                avicultureHatchingRequestsService({
                                  selectedDate1,
                                  selectedDate2,
                                })
                              );
                              dispatch(
                                avicultureGetRequests({
                                  selectedDate1,
                                  selectedDate2,
                                })
                              );
                              dispatch(
                                cityGetHatchingsByAge({
                                  selectedAge1,
                                  selectedAge2,
                                })
                              );
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "عملیات با موفقیت انجام شد.",
                                severity: "success",
                              });
                              dispatch(
                                DRAWER({
                                  right: false,
                                  bottom: false,
                                  content: null,
                                })
                              );
                            }
                          });
                        }
                      } else {
                        dispatch(
                          avicultureNewRequest({
                            approved_price: data?.approved,
                            kill_req_key: selectedKillhouse,
                            buyer: {
                              firstname: buyerInfo?.firstname
                                ? buyerInfo?.firstname
                                : formikBuyer.values.fname,
                              lastname: buyerInfo?.lastname
                                ? buyerInfo?.lastname
                                : formikBuyer.values.lname,
                              mobile: buyerInfo?.mobile
                                ? buyerInfo?.mobile
                                : formikBuyer.values.mobile,
                              national_id: buyerInfo?.national_id
                                ? buyerInfo?.national_id
                                : formikBuyer.values.nationalCode,
                              province: buyerInfo?.province
                                ? buyerInfo?.province
                                : formikBuyer.values.province,
                              city: buyerInfo?.city
                                ? buyerInfo?.city
                                : formikBuyer.values.city,
                            },
                            freezing: freezing,
                            operator_key:
                              unions?.length > 1 ? unionSelected : "",
                            poultry_hatching_key: hatchingKey,
                            quantity: formik.values.noChicken,
                            send_date: formik.values.slaughterDate,
                            chicken_breed: chickenBreed,
                            Index_weight: formik.values.weight,
                            losses:
                              formik.values.losses !== ""
                                ? formik.values.losses
                                : 0,
                            auction_list: [],
                            cash: formik.values.sellType.cash,
                            credit: formik.values.sellType.haveTime,
                            kill_house_list: formik.values.selectedSlaughters,
                            confirm_poultry_mobile:
                              formik2.values.userInfoCheck,
                          })
                        ).then((r) => {
                          dispatch(LOADING_END());
                          if (r.error) {
                            if (r.error.message.includes("403")) {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "تعداد مرغ برای کشتار از باقیمانده بیشتر است!",
                                severity: "error",
                              });
                            } else {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "مشکلی پیش آمده است!",
                                severity: "error",
                              });
                            }
                          } else {
                            if (updateTable) {
                              updateTable();
                            }
                            dispatch(
                              avicultureHatchingRequestsService({
                                selectedDate1,
                                selectedDate2,
                              })
                            );
                            dispatch(avicultureGetRequests());
                            dispatch(
                              cityGetHatchingsByAge({
                                selectedAge1,
                                selectedAge2,
                              })
                            );
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "عملیات با موفقیت انجام شد.",
                              severity: "success",
                            });
                            dispatch(
                              DRAWER({
                                right: false,
                                bottom: false,
                                content: null,
                              })
                            );
                          }
                        });
                      }
                    }
                  }}
                  size="large"
                  variant="contained"
                >
                  ثبت درخواست
                </Button>
              </Grid>
            </Grid>
          )}
        </Grid>
      )}
    </>
  );
};
