"use client";
import React, { useEffect } from "react";
import { Formik, Field, Form, ErrorMessage } from "formik";
import * as Yup from "yup";
import { LoadingView } from "../common";
import {
useGetProductZoneQuery,
useUpdateProductZoneMutation,
useAddProductZoneMutation,
useGetAllZoneMutation,
useGetAllDeliveryTypesQuery,
useGetAllProductsMutation,
} from "@/services";
import { useRouter } from "next/navigation";
import Swal from "sweetalert2";
import { cloneDeep } from "lodash";
const EditProductZone = ({ id }) => {
const router = useRouter();
const { data: { data = {} } = {}, isFetching: isFetchingProductZone } = useGetProductZoneQuery(id, {
skip: isNaN(id),
refetchOnMountOrArgChange: true,
});
const [getAllZones, { isLoading: isFetchingZones, data: zones }] = useGetAllZoneMutation();
const [getAllProducts, { isLoading: isFetchingProducts, data: products }] = useGetAllProductsMutation();
const { data: deliveryTypes, isFetching: isFetchingDeliveryTypes } =
useGetAllDeliveryTypesQuery();
const [updateProductZone, { isLoading: isUpdatingProductZone }] =
useUpdateProductZoneMutation();
const [addProductZone, { isLoading: isAddingProductZone }] = useAddProductZoneMutation();
useEffect(() => {
const getZones = async () => {
const { data: { items = [] } = {} } = await getAllZones({ body: {} });
};
getZones();
}, []);
useEffect(() => {
const getProducts = async () => {
const { data: { items = [], itemsCount, pageNumber, pageSize } = {} } = await getAllProducts({ body: {} });
let noOfPages = Math.ceil(itemsCount / pageSize);
let currentPage = pageNumber;
let productOptions = cloneDeep(items);
while (currentPage < noOfPages - 1) {
currentPage += 1;
const { data: { items: additionalItems = [] } = {} } = await getAllProducts({
body: { pageNumber: currentPage },
});
productOptions.push(...additionalItems);
}
console.log("All products:", productOptions);
};
getProducts();
}, []);
const validationSchema = Yup.object({
productId: Yup.number().required("product is required"),
zoneId: Yup.number().required("zone is required"),
deliveryMethodId: Yup.number().required("delivery type is required"),
});
const initialValues = {
productId: data?.productId || "",
zoneId: data?.zoneId || "",
deliveryMethodId: data?.deliveryMethodId || "",
};
const onResponse = (response, type) => {
if (!response.error) {
Swal.fire({
icon: "success",
title: "Success.",
text:
type == "add" ? "ProductZone has been created" : "ProductZone has been updated",
showConfirmButton: false,
timer: 1000,
});
router.push("/home/productZones");
}
if (response?.error) {
Swal.fire({
icon: "error",
title: "Oops...",
text: "Something went wrong!",
});
}
};
const onSubmit = async (values, { setSubmitting }) => {
setSubmitting(true);
if (!isNaN(id)) {
const response = await updateProductZone({
id: data?.id,
body: {
id: data?.id,
...values,
productId: Number(values.productId),
zoneId: Number(values.zoneId),
deliveryMethodId: Number(values.deliveryMethodId),
},
});
onResponse(response, "update");
} else if (id === "add") {
const response = await addProductZone({
body: {
...values,
productId: Number(values.productId),
zoneId: Number(values.zoneId),
deliveryMethodId: Number(values.deliveryMethodId),
},
});
onResponse(response, "add");
}
setSubmitting(false);
};
return (
<LoadingView
isLoading={isFetchingProductZone || isUpdatingProductZone || isAddingProductZone || isFetchingZones
|| isFetchingProducts
|| isFetchingDeliveryTypes}
>
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={onSubmit}
>
<Form className="w-full">
<div className="flex flex-wrap -mx-3 mb-6">
<div className="w-full md:w-1/3 px-3 mb-6 md:mb-0">
<label
className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
htmlFor="zoneId"
>
Zone
</label>
<Field
as="select"
id="zoneId"
name="zoneId"
className="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500"
>
<option value="">Select a Zone</option>
{zones &&
zones.items.map((zone) => (
<option key={zone.id} value={zone.id}>
{zone.name}
</option>
))}
</Field>
<ErrorMessage
name="zoneId"
component="div"
className="text-[red]"
/>
</div>
<div className="w-full md:w-1/3 px-3 mb-6 md:mb-0">
<label
className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
htmlFor="productId"
>
Product
</label>
<Field
as="select"
id="productId"
name="productId"
className="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500"
>
<option value="">Select a Product</option>
{products &&
products.items.map((product) => (
<option key={product.id} value={product.id}>
{product.name}
</option>
))}
</Field>
<ErrorMessage
name="productId"
component="div"
className="text-[red]"
/>
</div>
<div className="w-full md:w-1/3 px-3 mb-6 md:mb-0">
<label
className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
htmlFor="deliveryMethodId"
>
Delivery Type
</label>
<Field
as="select"
id="deliveryMethodId"
name="deliveryMethodId"
className="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500"
>
<option value="">Select a Delivery type</option>
{deliveryTypes &&
deliveryTypes.map((dt) => (
<option key={dt.value} value={dt.value}>
{dt.label}
</option>
))}
</Field>
<ErrorMessage
name="deliveryMethodId"
component="div"
className="text-[red]"
/>
</div>
</div>
<div className="flex justify-center items-center mb-[2rem]">
<button
type="submit"
className="bg-[#005CE6] py-[0.5rem] px-[1rem] w-[30%] text-[white] transition-all hover:bg-[green]"
>
Submit
</button>
</div>
</Form>
</Formik>
</LoadingView>
);
};
export default EditProductZone;
المشكلة ان products.items يرجع بها data في اخر page of pagination فقط وانا اريد data في كل الصفحات!!