import {
  Autocomplete,
  Button,
  Checkbox,
  Divider,
  FormControl,
  FormControlLabel,
  // FormGroup,
  // FormControlLabel,
  FormHelperText,
  FormLabel,
  IconButton,
  InputAdornment,
  InputLabel,
  ListItem,
  ListItemIcon,
  ListItemText,
  MenuItem,
  Radio,
  // Radio,
  RadioGroup,
  Select,
  TextField,
  Typography,
} from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { useEffect } from "react";
import { DatePicker } from "@mui/x-date-pickers";
import { useDispatch, useSelector } from "react-redux";
import { avicultureNewRequest } from "../../services/aviculture-new-request";
import { LabelField } from "../../../../components/label-field/LabelField";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import moment from "moment";
import { useState } from "react";
import { avicultureGetHatchingData } from "../../services/aviculture-get-hatching-data";
import { avicultureGetChickenPrice } from "../../services/aviculture-get-chicken-price";
import DeleteIcon from "@mui/icons-material/Delete";
import { avicultureGetRequests } from "../../services/aviculture-requests";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import AddIcon from "@mui/icons-material/Add";
// import { NumericFormat } from "react-number-format";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { DialogAlert } from "../../../../components/dialog-alert/DialogAlert";
// import useUserProfile from "../../../authentication/hooks/useUserProfile";
// import { NumberFormatCustom } from "../../../../components/number-format-custom/NumberFormatCustom";
import DoneIcon from "@mui/icons-material/Done";
// import { SelectCheck } from "../../../../components/select-check/SelectCheck";
import { avicultureGetSlaughters } from "../../services/aviculture-get-slaughters";
import { avicultureGetUnions } from "../../services/aviculture-get-unions";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceGetPoultry } from "../../services/province-get-poultry";
import { CarPelak } from "../../../../components/car-pelak/CarPelak";
import { avicultureGetWageType } from "../../services/aviculture-get-wage-type";
import { provinceFreeSaleBuyers } from "../../../province/services/province-free-sales-get-buyers";
import RemoveIcon from "@mui/icons-material/Remove";
import { provincePolicyGetWeightRange } from "../../../province/services/province-policy-get-weight-range";
import { isValidIndexWeight } from "../../../../utils/isValidIndexWeight";

export const ProvinceFreeSaleNewRequest = ({ fetchApiData }) => {
  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 [poultry, setPoultry] = useState();
  const [buyersData, setBuyersData] = useState([]);
  const [buyerSelected, setBuyerSelected] = useState();
  const [buyerItem, setBuyerItem] = useState();
  const [selectedHatchingLabel, setSelectedHatchingLabel] = useState();
  const [payerValue, setPayerValue] = useState("poultry");
  const [submitDriver, setSubmitDriver] = useState(false);
  const [transportHealthCodes, setTransportHealthCodes] = useState([]);
  const [showHealthCodeForm, setShowHealthCodeForm] = useState(false);

  const handleChangePayer = (event) => {
    setPayerValue(event.target.value);
    if (event.target.value === "poultry") {
      formikPayer.setFieldValue("mobile", poultry?.user?.mobile);
    } else {
      if (buyerItem) {
        formikPayer.setFieldValue("mobile", buyerItem.mobile);
      } else {
        formikPayer.setFieldValue("mobile", "");
      }
    }
  };

  // const [, userProfile] = useUserProfile();

  const [driverPelak, setDriverPelak] = useState([]);

  const carPelakHandleChange = (pelak1, pelak2, pelak3, pelak4) => {
    setDriverPelak([pelak1, pelak2, pelak3, pelak4]);
  };

  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 [wageType, setWageType] = useState();
  const { weightRange } = useSelector((state) => state.provinceSlice);

  const dispatch = useDispatch();

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

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(avicultureGetChickenPrice());
    dispatch(avicultureGetSlaughters());
    dispatch(avicultureGetWageType()).then((r) => {
      setWageType(r.payload.data.status);
    });
    dispatch(provinceFreeSaleBuyers()).then((r) => {
      setBuyersData(r.payload.data);
    });
    dispatch(LOADING_END());
  }, []);

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

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(provincePolicyGetWeightRange());
    dispatch(avicultureGetUnions()).then((r) => {
      if (r?.payload?.data?.length > 0) {
        setUnions(r?.payload?.data[0]?.key);
      } else {
        setUnions([]);
      }
    });
    dispatch(LOADING_END());
  }, []);

  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: false,
      selectedSlaughters: [],
      killer_kill_house_city: "",
      killer_kill_house_province: "",
      killer_kill_house_unit_name: "",
      kill_house_unique_id: "",
      interface_number: "",
    },
    validationSchema: Yup.object({
      noChicken: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!")
        .min(0, "تعداد وارد شده از حداقل ممکن کمتر است")
        .max(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("لطفا تعداد تلفات را وارد کنید!"),
      sellType: Yup.object()
        .test("sellType", "نحوه فروش را انتخاب کنید!", (val, context) => {
          return (
            context.originalValue &&
            Object.values(context.originalValue).some((item) => item === true)
          );
        })
        .required("این فیلد اجباری است!"),
      interface_number: Yup.string()
        .min(11, "شماره موبایل باید 11 رقم باشد")
        .max(11, "شماره موبایل باید 11 رقم باشد")
        .matches(/^09\d{9}$/, "شماره موبایل باید با 09 شروع شود و 11 رقم باشد"),
    }),
  });

  const formikDriver = useFormik({
    initialValues: {
      driverName: "",
      driverMobile: "",
      driverCar: "",
      driverhealthCode: "",
    },
    validationSchema: Yup.object({
      driverName: Yup.string().required("این فیلد اجباری است!"),
      driverMobile: Yup.string()
        .required("این فیلد اجباری است!")
        .min(11, "شماره موبایل باید 11 رقم باشد")
        .max(11, "شماره موبایل باید 11 رقم باشد")
        .matches(/^09\d{9}$/, "شماره موبایل باید با 09 شروع شود و 11 رقم باشد"),
      driverCar: Yup.string().required("این فیلد اجباری است!"),
      driverhealthCode: Yup.string()
        .required("این فیلد اجباری است!")
        .matches(
          /^[^*&^%$#@!()|.]*$/,
          "این فیلد نباید شامل کاراکترهای ویژه باشد!"
        ),
    }),
  });

  const formikPayer = useFormik({
    initialValues: {
      mobile: "",
      weight: "",
      quantity: "",
    },
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required("شماره موبایل الزامی است")
        .min(11, "شماره موبایل باید 11 رقم باشد")
        .max(11, "شماره موبایل باید 11 رقم باشد")
        .matches(/^09\d{9}$/, "شماره موبایل باید با 09 شروع شود و 11 رقم باشد"),
      weight: Yup.number(),
      quantity: Yup.number(),
    }),
  });

  const formikTransportHealthCode = useFormik({
    initialValues: {
      healthCode: "",
    },
    validationSchema: Yup.object({
      healthCode: Yup.string()
        .required("این فیلد اجباری است!")
        .matches(
          /^[^*&^%$#@!()|.]*$/,
          "این فیلد نباید شامل کاراکترهای ویژه باشد!"
        ),
    }),
  });

  const handleAddTransportHealthCode = () => {
    if (formikTransportHealthCode.values.healthCode.trim()) {
      setTransportHealthCodes([
        ...transportHealthCodes,
        formikTransportHealthCode.values.healthCode,
      ]);
      formikTransportHealthCode.resetForm();
      setShowHealthCodeForm(false);
    }
  };

  const handleRemoveTransportHealthCode = (indexToRemove) => {
    setTransportHealthCodes(
      transportHealthCodes.filter((_, index) => index !== indexToRemove)
    );
  };

  useEffect(() => {
    formikPayer.setFieldValue("mobile", poultry?.user?.mobile);
  }, [poultry]);

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

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

  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 }));
        } else {
          dispatch(LOADING_END());
        }
      });
    }
  }, [isStockMarket]);

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

  useEffect(() => {
    if (poultryKey) {
      dispatch(LOADING_START());
      dispatch(avicultureGetHatchingData({ key: poultryKey })).then((r) => {
        if (r.payload.data) {
          setHatchingData(r.payload.data);

          dispatch(LOADING_END());
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "اطلاعات جوجه ریزی یافت نشد!",
            severity: "error",
          });
        }
        dispatch(LOADING_END());
      });
    }
  }, [poultryKey, poultry]);

  useEffect(() => {
    setChickenCanRequest(hatchingSelected?.leftOver);
  }, [
    formik.values.losses,
    leftOvers,
    formik.values.noChicken,
    hatchingSelected,
  ]);

  useEffect(() => {
    setQuantity(hatchingSelected?.quantity);
    setlosses(hatchingSelected?.losses);
    setLeftOvers(hatchingSelected?.leftOver);
  }, [hatchingSelected]);

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

  const killerFieldsValidation = () => {
    if (buyerItem?.type === "killer") {
      return (
        formik.values.killer_kill_house_city &&
        formik.values.killer_kill_house_province &&
        formik.values.killer_kill_house_unit_name
      );
    } else {
      return true;
    }
  };

  const wageValidation = () => {
    if (wageType) {
      return formikPayer.isValid;
    } else {
      return true;
    }
  };

  const isFormValid = () => {
    if (payerValue === "poultry") {
      if (submitDriver) {
        return (
          formik.isValid &&
          wageValidation() &&
          buyerSelected &&
          formikDriver &&
          driverPelak[0] &&
          killerFieldsValidation()
        );
      } else {
        return (
          formik.isValid &&
          wageValidation() &&
          buyerSelected &&
          killerFieldsValidation()
        );
      }
    } else {
      if (submitDriver) {
        return (
          formik.isValid &&
          buyerSelected &&
          formikDriver &&
          driverPelak[0] &&
          killerFieldsValidation() &&
          wageValidation()
        );
      } else {
        return (
          formik.isValid &&
          buyerSelected &&
          killerFieldsValidation() &&
          wageValidation()
        );
      }
    }
  };

  return (
    <Grid container gap={SPACING.SMALL} direction="column" display={"flex"}>
      <Grid container gap={SPACING.SMALL} direction={"column"}>
        <Grid minWidth={210}>
          <Autocomplete
            disablePortal
            id="combo-box-demo"
            getOptionDisabled={(option) => option.disabled}
            options={
              poultryData
                ? poultryData.map((i) => ({
                    id: i.key,
                    label: `${i.unitName} / ${
                      i.user.mobile
                    } / ${i.lastHatchingRemainQuantity.toLocaleString()} `,
                    item: i,
                    disabled: !i.lastHatchingRemainQuantity,
                  }))
                : []
            }
            onChange={(event, value) => {
              setHatchingSelected(null);
              sethatchingKey(null);
              setSelectedHatchingLabel(null);
              setPolutryKey(value.id);
              setPoultry(value.item);
            }}
            renderInput={(params) => (
              <TextField {...params} label="محل پرورش/تلفن/مانده جوجه ریزی" />
            )}
          />
        </Grid>
        {/* 
        {!poultry?.provinceAllowSellFree && (
          <Typography>اجازه فروش بصورت خارج از استان ندارید!</Typography>
        )} */}

        {poultry?.provinceAllowSellFree ? (
          <Grid container direction="column" gap={SPACING.SMALL} width="100%">
            <Grid minWidth={210}>
              <Autocomplete
                disablePortal
                id="hatching"
                value={selectedHatchingLabel}
                options={
                  hatchingData
                    ? hatchingData.map((i) => {
                        return {
                          id: i.key,
                          race: i.chickenBreed,
                          selected: i,
                          label: `دوره ${i.period} سالن ${i.hall} نژاد ${
                            i.chickenBreed
                          } باقیمانده ${
                            i?.lastHatchingDiffrentRequestQuantity?.leftOver
                              ? i?.lastHatchingDiffrentRequestQuantity?.leftOver
                              : i.leftOver
                          } قطعه`,
                        };
                      })
                    : []
                }
                onChange={(event, value) => {
                  setSelectedHatchingLabel(value.label);
                  sethatchingKey(value.id);
                  setHatchingSelected(value.selected);
                  let race = value.race;
                  if (race.includes("-")) {
                    race = "ترکیبی";
                  }
                  setChickenBreed(race);
                }}
                renderInput={(params) => (
                  <TextField {...params} label="دوره جوجه ریزی" />
                )}
              />
            </Grid>
            <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={chickenCanRequest ? chickenCanRequest : "نامشخص"}
                InputProps={{
                  readOnly: true,
                }}
              />
            </Grid>
          </Grid>
        ) : (
          poultry && (
            <Typography color="error" variant="body">
              مرغدار اجازه فروش مستقیم ندارد!
            </Typography>
          )
        )}
      </Grid>

      {hatchingSelected && (
        <Grid container gap={SPACING.SMALL} direction={"column"}>
          <Typography>اطلاعات کشتار</Typography>
          {/* {getRoleFromUrl() !== "Poultry" && (
            <Grid>
              <Grid>
                <NumberInput
                  allowLeadingZeros
                  thousandSeparator=","
                  fullWidth
                  id="losses"
                  disabled
                  label="تلفات"
                  variant="outlined"
                  value={formik.values.losses}
                  error={
                    formik.touched.losses ? Boolean(formik.errors.losses) : null
                  }
                  InputProps={{
                    readOnly: true,
                  }}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  helperText={
                    formik.touched.losses && Boolean(formik.errors.losses)
                      ? formik.errors.losses
                      : null
                  }
                />
              </Grid>
            </Grid>
          )} */}
          <Grid container gap={SPACING.TINY}>
            {/* <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
              }
            /> */}

            <Grid container gap={SPACING.TINY}>
              <Typography
                color={(prop) => prop.palette.grey["A700"]}
                variant={"caption"}
              >
                باقیمانده:
              </Typography>
              <Typography variant={"button"}>{chickenCanRequest}</Typography>

              <Typography variant={"button"}>قطعه</Typography>
            </Grid>
            <Grid container>
              <Grid container gap={SPACING.TINY} alignItems={"center"}>
                <Typography
                  color={(prop) => prop.palette.grey["A700"]}
                  variant={"caption"}
                >
                  سن مرغ:
                </Typography>
                <Typography variant={"button"}>
                  {hatchingSelected.age}
                </Typography>
                <Typography variant={"button"}>روزه</Typography>
              </Grid>
            </Grid>

            <Grid container xs={12}>
              <DatePicker
                label="تاریخ کشتار"
                id="slaughterDate"
                renderInput={(params) => <TextField fullWidth {...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 container xs={12}>
              <NumberInput
                allowLeadingZeros
                thousandSeparator=","
                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
                }
              />
            </Grid>

            <Grid container xs={12}>
              <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>

          {formik.values.weight && (
            <Typography variant="body2" style={{ color: "green" }}>
              وزن کل:{" "}
              {parseInt(
                parseInt(formik.values.noChicken) *
                  parseFloat(formik.values.weight)
              ).toLocaleString()}{" "}
              کیلوگرم
            </Typography>
          )}

          {/* <Grid>
            <Typography>نحوه فروش</Typography>
          </Grid> */}
          <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={item?.id}
                          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>
          <Grid
            container
            gap={SPACING.SMALL}
            direction={"column"}
            // style={{
            //   borderStyle: "afcceb",
            //   borderColor: "#4545f3",
            //   borderRadius: "15px",
            //   borderWidth: "1px",
            //   padding: "10px",
            // }}
          >
            <Typography variant="body1">اطلاعات خریدار</Typography>
            <Autocomplete
              disablePortal
              id="combo-box-demo"
              getOptionDisabled={(option) => option.disabled}
              options={
                buyersData
                  ? buyersData?.map((i) => ({
                      id: i.key,
                      label:
                        i.type === "killhouse"
                          ? `کشتارگاه ${i?.unitName} / ${i.mobile} / استان ${i?.province}/ ${i?.city}`
                          : `کشتارکن ${i?.fullname} / ${i.mobile} / استان ${i?.province}/ ${i?.city}`,
                      item: i,
                      mobile: i.mobile,
                    }))
                  : []
              }
              onChange={(event, value) => {
                setBuyerSelected(value.id);
                setBuyerItem(value.item);
                if (payerValue === "buyer") {
                  formikPayer.setFieldValue("mobile", value.mobile);
                }
              }}
              renderInput={(params) => (
                <TextField {...params} label="انتخاب خریدار" />
              )}
            />

            {buyerItem?.type === "killer" && (
              <Grid container direction="column" gap={SPACING.SMALL}>
                <TextField
                  id="killer_kill_house_unit_name"
                  label="نام کشتارگاه"
                  variant="outlined"
                  sx={{ width: "100%", height: "100%" }}
                  value={formik.values.killer_kill_house_unit_name}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  error={
                    formik.touched.killer_kill_house_unit_name
                      ? Boolean(formik.errors.killer_kill_house_unit_name)
                      : null
                  }
                  helperText={
                    formik.touched.killer_kill_house_unit_name &&
                    Boolean(formik.errors.killer_kill_house_unit_name)
                      ? formik.errors.killer_kill_house_unit_name
                      : null
                  }
                />
                <TextField
                  id="kill_house_unique_id"
                  label="شناسه یکتا کشتارگاه"
                  variant="outlined"
                  sx={{ width: "100%", height: "100%" }}
                  value={formik.values.kill_house_unique_id}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  error={
                    formik.touched.kill_house_unique_id
                      ? Boolean(formik.errors.kill_house_unique_id)
                      : null
                  }
                  helperText={
                    formik.touched.kill_house_unique_id &&
                    Boolean(formik.errors.kill_house_unique_id)
                      ? formik.errors.kill_house_unique_id
                      : null
                  }
                />

                <TextField
                  id="killer_kill_house_province"
                  label="استان کشتارگاه"
                  variant="outlined"
                  sx={{ width: "100%", height: "100%" }}
                  value={formik.values.killer_kill_house_province}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  error={
                    formik.touched.killer_kill_house_province
                      ? Boolean(formik.errors.killer_kill_house_province)
                      : null
                  }
                  helperText={
                    formik.touched.killer_kill_house_province &&
                    Boolean(formik.errors.killer_kill_house_province)
                      ? formik.errors.killer_kill_house_province
                      : null
                  }
                />
                <TextField
                  id="killer_kill_house_city"
                  label="شهر کشتارگاه"
                  variant="outlined"
                  sx={{ width: "100%", height: "100%" }}
                  value={formik.values.killer_kill_house_city}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  error={
                    formik.touched.killer_kill_house_city
                      ? Boolean(formik.errors.killer_kill_house_city)
                      : null
                  }
                  helperText={
                    formik.touched.killer_kill_house_city &&
                    Boolean(formik.errors.killer_kill_house_city)
                      ? formik.errors.killer_kill_house_city
                      : null
                  }
                />
              </Grid>
            )}
          </Grid>

          {buyerItem?.key && (
            <>
              <Grid
                container
                xs={12}
                alignItems="center"
                justifyContent="center"
                gap={SPACING.SMALL}
              >
                <IconButton
                  color={submitDriver ? "error" : "primary"}
                  onClick={() => {
                    setSubmitDriver(!submitDriver);
                  }}
                >
                  <Typography
                    variant="body1"
                    color={submitDriver ? "error" : "primary"}
                  >
                    {" "}
                    افزودن خودرو
                  </Typography>

                  {submitDriver ? <RemoveIcon /> : <AddIcon />}
                </IconButton>
                {submitDriver && (
                  <Grid
                    container
                    xs={12}
                    alignItems="center"
                    justifyContent="center"
                    gap={SPACING.SMALL}
                  >
                    <Typography variant="body1">اطلاعات خودرو حمل</Typography>
                    <TextField
                      label="نام و نام خانوادگی راننده"
                      name="driverName"
                      value={formikDriver.values.driverName}
                      onChange={formikDriver.handleChange}
                      error={
                        formikDriver.touched.driverName &&
                        Boolean(formikDriver.errors.driverName)
                      }
                      helperText={
                        formikDriver.touched.driverName &&
                        formikDriver.errors.driverName
                      }
                      required
                      fullWidth
                    />
                    <TextField
                      label="تلفن راننده"
                      name="driverMobile"
                      value={formikDriver.values.driverMobile}
                      onChange={formikDriver.handleChange}
                      onBlur={formik.handleBlur}
                      error={
                        formikDriver.touched.driverMobile &&
                        Boolean(formikDriver.errors.driverMobile)
                      }
                      helperText={
                        formikDriver.touched.driverMobile &&
                        formikDriver.errors.driverMobile
                      }
                      required
                      fullWidth
                    />
                    <TextField
                      label="مدل خودرو"
                      name="driverCar"
                      value={formikDriver.values.driverCar}
                      onChange={formikDriver.handleChange}
                      error={
                        formikDriver.touched.driverCar &&
                        Boolean(formikDriver.errors.driverCar)
                      }
                      helperText={
                        formikDriver.touched.driverCar &&
                        formikDriver.errors.driverCar
                      }
                      type="tel"
                      required
                      fullWidth
                    />
                    <CarPelak
                      width="100%"
                      handleChange={carPelakHandleChange}
                    />

                    <TextField
                      id="driverhealthCode"
                      label="کد بهداشتی حمل"
                      variant="outlined"
                      sx={{ width: "100%", height: "100%" }}
                      value={formikDriver.values.driverhealthCode}
                      onChange={formikDriver.handleChange}
                      onBlur={formikDriver.handleBlur}
                      error={
                        formikDriver.touched.driverhealthCode
                          ? Boolean(formikDriver.errors.driverhealthCode)
                          : null
                      }
                      helperText={
                        formikDriver.touched.driverhealthCode &&
                        Boolean(formikDriver.errors.driverhealthCode)
                          ? formikDriver.errors.driverhealthCode
                          : null
                      }
                    />
                  </Grid>
                )}
              </Grid>
              {/* افزودن کد بهداشتی حمل و نقل */}
              <Grid
                container
                xs={12}
                spacing={SPACING}
                alignItems="center"
                justifyContent="center"
                mt={2}
              >
                <Grid item xs={12} mb={SPACING.SMALL}>
                  <Typography variant="body1" sx={{ mb: 1 }}>
                    کدهای بهداشتی حمل و نقل
                  </Typography>
                </Grid>

                {/* Display added health codes */}
                {transportHealthCodes.length > 0 && (
                  <Grid item xs={12} mb={2}>
                    {transportHealthCodes.map((code, index) => (
                      <Grid
                        container
                        key={index}
                        spacing={1}
                        alignItems="center"
                        sx={{ mb: 1 }}
                      >
                        <Grid item xs={10}>
                          <TextField
                            value={code}
                            disabled
                            fullWidth
                            variant="outlined"
                            label={`کد بهداشتی ${index + 1}`}
                          />
                        </Grid>
                        <Grid item xs={2}>
                          <IconButton
                            color="error"
                            onClick={() =>
                              handleRemoveTransportHealthCode(index)
                            }
                            aria-label="حذف"
                          >
                            <DeleteIcon />
                          </IconButton>
                        </Grid>
                      </Grid>
                    ))}
                  </Grid>
                )}

                {/* Form to add new health code */}
                {showHealthCodeForm && (
                  <Grid item xs={12}>
                    <Grid container spacing={2} alignItems="center">
                      <Grid item xs={9}>
                        <TextField
                          label="کد بهداشتی حمل و نقل جدید"
                          name="healthCode"
                          value={formikTransportHealthCode.values.healthCode}
                          onChange={formikTransportHealthCode.handleChange}
                          onBlur={formikTransportHealthCode.handleBlur}
                          error={
                            formikTransportHealthCode.touched.healthCode &&
                            Boolean(formikTransportHealthCode.errors.healthCode)
                          }
                          helperText={
                            formikTransportHealthCode.touched.healthCode &&
                            formikTransportHealthCode.errors.healthCode
                          }
                          variant="outlined"
                        />
                      </Grid>
                      <Grid item xs={3}>
                        <Button
                          variant="contained"
                          color="success"
                          onClick={handleAddTransportHealthCode}
                          startIcon={<AddIcon />}
                          fullWidth
                          sx={{
                            fontSize: "12px",
                          }}
                        >
                          افزودن
                        </Button>
                      </Grid>
                    </Grid>
                  </Grid>
                )}

                {/* Button to show form */}
                <Grid item xs={12} mt={showHealthCodeForm ? 2 : 0} mb={2}>
                  <Button
                    variant="outlined"
                    color="primary"
                    onClick={() => setShowHealthCodeForm(!showHealthCodeForm)}
                    startIcon={
                      showHealthCodeForm ? <RemoveIcon /> : <AddIcon />
                    }
                    fullWidth
                  >
                    {showHealthCodeForm ? "لغو" : "افزودن کد بهداشتی حمل"}
                  </Button>
                </Grid>
              </Grid>
            </>
          )}

          {wageType && (
            <>
              <LabelField label="پرداخت کننده">
                <FormControl fullWidth>
                  <RadioGroup
                    row
                    aria-labelledby="demo-controlled-radio-buttons-group"
                    name="controlled-radio-buttons-group"
                    value={payerValue}
                    onChange={handleChangePayer}
                    justifyContent="space-between"
                  >
                    <FormControlLabel
                      value="poultry"
                      control={<Radio />}
                      label="مرغدار"
                      sx={{
                        marginRight: "auto",
                      }}
                    />
                    <FormControlLabel
                      value="buyer"
                      control={<Radio />}
                      label="خریدار"
                    />
                  </RadioGroup>
                </FormControl>
              </LabelField>

              <Grid
                container
                xs={12}
                alignItems="center"
                justifyContent="center"
                mt={1}
                p={1}
                gap={1}
                style={{
                  borderStyle: "solid",
                  borderWidth: "2px",
                  borderColor: "gray",
                  borderRadius: "5px",
                }}
              >
                <Typography variant="body2" color="error">
                  از این قسمت میتوانید تلفن{" "}
                  {payerValue === "poultry" ? "مرغدار" : "خریدار"} را ویرایش
                  کنید.
                </Typography>
                <TextField
                  fullWidth
                  disabled
                  id="mobile"
                  value={formikPayer.values.mobile}
                  error={
                    formikPayer.touched.mobile
                      ? Boolean(formikPayer.errors.mobile)
                      : null
                  }
                  onChange={formikPayer.handleChange}
                  onBlur={formikPayer.handleBlur}
                  helperText={
                    formikPayer.touched.mobile &&
                    Boolean(formikPayer.errors.mobile)
                      ? formikPayer.errors.mobile
                      : null
                  }
                  label="موبایل"
                  autoComplete="current-password"
                  variant="outlined"
                />
              </Grid>
            </>
          )}

          <Grid container xs={12}>
            <TextField
              id="interface_number"
              label="شماره واسطه (اختیاری)"
              variant="outlined"
              value={formik.values.interface_number}
              error={
                formik.touched.interface_number
                  ? Boolean(formik.errors.interface_number)
                  : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.interface_number &&
                Boolean(formik.errors.interface_number)
                  ? formik.errors.interface_number
                  : null
              }
            />
          </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 && (
            <>
              <Divider />
              <Grid>
                <FormControl>
                  <FormLabel id="demo-radio-buttons-group-label">
                    انتخاب اتحادیه
                  </FormLabel>
                  <RadioGroup
                    aria-labelledby="demo-radio-buttons-group-label"
                    defaultValue={unions[0]?.key}
                    name="radio-buttons-group"
                    onChange={(event) => {
                      setUnionSelected(event.currentTarget.value);
                    }}
                  >
                    {unions.map((item) => {
                      return (
                        <>
                          <FormControlLabel
                            value={item.key}
                            control={<Radio />}
                            label={item.unitName}
                          />
                        </>
                      );
                    })}
                  </RadioGroup>
                </FormControl>
              </Grid>
            </>
          )}

          <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>
          <Grid mb={SPACING.SMALL}>
            <Button
              fullWidth
              disabled={!isFormValid()}
              onClick={() => {
                if (
                  getRoleFromUrl() !== "SuperAdmin" &&
                  getRoleFromUrl() !== "AdminX" &&
                  !isValidIndexWeight(
                    weightRange,
                    hatchingSelected?.age,
                    formik.values.weight
                  )
                ) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "میانگین وزنی با احراز سنی مطابقت ندارد. لطفا با اتحادیه تماس بگیرید.",
                    severity: "error",
                  });
                }
                //  else if (!isValidIndexWeight()) {
                //   openNotif({
                //     vertical: "top",
                //     horizontal: "center",
                //     msg: `میانگین وزنی با سن مرغ تطابق ندارد. برای سن مرغ ${
                //       hatchingSelected?.age
                //     } حداقل میانگین وزنی ${getValidIndexWeight()} وارد کنید!`,
                //     severity: "error",
                //   });
                // }
                else {
                  dispatch(LOADING_START());
                  if (isStockMarket === "فروش مزایده ای") {
                    dispatch(
                      avicultureNewRequest({
                        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,
                        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) => {
                      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 {
                        dispatch(avicultureGetRequests());
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                        dispatch(
                          DRAWER({ right: false, bottom: false, content: null })
                        );
                      }
                    });
                  } else {
                    dispatch(
                      avicultureNewRequest({
                        operator_key: unions?.length > 1 ? unionSelected : "",
                        poultry_hatching_key: hatchingKey,
                        poultry_key: poultry.key,
                        role: getRoleFromUrl(),
                        quantity: formik.values.noChicken,
                        send_date: formik.values.slaughterDate,
                        interface_number: formik.values.interface_number
                          ? formik.values.interface_number
                          : null,
                        chicken_breed: chickenBreed,
                        Index_weight: formik.values.weight,
                        hatching_left_over: parseInt(leftOvers),
                        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,
                        killer_kill_house_unit_name:
                          buyerItem?.type === "killer"
                            ? formik.values.killer_kill_house_unit_name
                            : null,
                        killer_kill_house_city:
                          buyerItem?.type === "killer"
                            ? formik.values.killer_kill_house_city
                            : null,
                        killer_kill_house_province:
                          buyerItem?.type === "killer"
                            ? formik.values.killer_kill_house_province
                            : null,
                        kill_house_unique_id:
                          buyerItem?.type === "killer"
                            ? formik.values.kill_house_unique_id
                            : null,
                        out_province_driver_info: {
                          driverName: !submitDriver
                            ? null
                            : formikDriver.values.driverName,
                          driverMobile: !submitDriver
                            ? null
                            : formikDriver.values.driverMobile,
                          driverCar: !submitDriver
                            ? null
                            : formikDriver.values.driverCar,
                          driverPelak: !submitDriver
                            ? null
                            : driverPelak[0] +
                              " " +
                              driverPelak[1] +
                              " " +
                              driverPelak[2] +
                              " " +
                              driverPelak[3],
                          driverhealthCode: !submitDriver
                            ? null
                            : formikDriver.values.driverhealthCode,
                        },
                        traffic_codes:
                          transportHealthCodes.length > 0
                            ? transportHealthCodes
                            : null,
                        out_province_poultry_request_buyer_key: buyerSelected,
                        payer_type: payerValue,
                        poultry_mobile:
                          payerValue === "poultry"
                            ? formikPayer.values.mobile
                            : null,
                        buyer_mobile:
                          payerValue === "buyer"
                            ? formikPayer.values.mobile
                            : null,
                      })
                    )
                      .then((r) => {
                        dispatch(LOADING_END());
                        if (r.payload?.error) {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: r.payload.error,
                            severity: "error",
                          });
                          return;
                        } else if (r.error) {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: r.error.message || "خطا در ثبت درخواست",
                            severity: "error",
                          });
                          return;
                        } else {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "عملیات با موفقیت انجام شد.",
                            severity: "success",
                          });
                          fetchApiData(1);
                          dispatch(
                            DRAWER({
                              right: false,
                              bottom: false,
                              content: null,
                            })
                          );
                        }
                      })
                      .catch((e) => {
                        dispatch(LOADING_END());
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: e.message || "خطا در ثبت درخواست",
                          severity: "error",
                        });
                      });
                  }
                }
              }}
              size="large"
              variant="contained"
            >
              ثبت درخواست
            </Button>
          </Grid>
        </Grid>
      )}
    </Grid>
  );
};
