ListingItems.js 11.8 KB
import { Empty, Skeleton } from "antd";
import Image from "next/image";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import { Button } from "react-bootstrap";
import { Loader } from "react-bootstrap-typeahead";
import { useDispatch, useSelector } from "react-redux";
import { cleanImage } from "../../services/imageHandling";
import WishlistComponent from "../detail/WIshlistComponent";
import Pagination from "react-js-pagination";
import { getActivitiesByFilters } from "../../redux/actions/activityAction";
import Link from "next/link";

const ListingItems = ({ allActivitiesData, loading, gridClass, totalCount }) => {
  // const [gridClass, setGridClass] = useState('col-md-3');
  const { endUser } = useSelector(state => state.endUser);
  const { activityFilters } = useSelector(state => state.activityFilters);
  const router = useRouter();
  const [readMoreText, setreadMoreText] = useState();
  const [showModal, setshowModal] = useState(false);
  const dispatch = useDispatch();
  // useEffect(() => {
  //   dispatch(getActivitiesByFilters({ currentPage: router.query.page }));
  // }, [router]);
  console.log("endUser", endUser);
  // console.log("router", router);
  const [page, setpage] = useState(1);
  // let { page, location = "" } = router.query;
  // page = Number(page);

  let queryParams;

  if (typeof window !== "undefined") {
    queryParams = new URLSearchParams(window.location.search);
  }
  const handlePagination = pageNumber => {
    // This was the old way to do this, by doing this we were getting rid of the other query string parameters.
    // router.push(`?page=${pageNumber}`);

    // We have done this to take care of keeping the search filters in the query params
    // when we end up changing the page number.
    setpage(pageNumber);
    if (queryParams.has("page")) {
      queryParams.set("page", pageNumber);
    } else {
      queryParams.append("page", pageNumber);
    }
    console.log("queryParams", queryParams);
    // router.push(`/listing?page=${pageNumber}`)
    //     router.push({
    //       query: `/listing?page=${pageNumber}`
    //     });
    // dispatch(getActivitiesByFilters({ currentPage: pageNumber }));
    let filters = {};
    // console.log("subcategory here", activityFilters.startDate);
    if (activityFilters.category) {
      filters["category"] = { id: { $eq: activityFilters.category } };
    }
    if (activityFilters.subCategories?.length > 0) {
      filters["category"] = null;
      filters["subCategory"] = activityFilters.subCategories.map(item => {
        return { subCategory: { id: { $eq: item } } };
      });
    }
    if (activityFilters.activityType) {
      filters["activityType"] = activityFilters.activityType;
    }
    if (activityFilters.startDate) {
      filters["fromDate"] = activityFilters.startDate;
    }
    if (activityFilters.endDate) {
      filters["toDate"] = activityFilters.endDate;
    }
    if (activityFilters.minDuration > 0) {
      filters["minimumDuration"] = activityFilters.minDuration;
    }
    if (activityFilters.maxDuration > 0) {
      filters["maximumDuration"] = activityFilters.maxDuration;
    }
    if (activityFilters.minGroupSize > 0) {
      filters["minGroupSize"] = activityFilters.minGroupSize;
    }
    if (activityFilters.maxGroupSize > 0) {
      filters["maxGroupSize"] = activityFilters.maxGroupSize;
    }
    if (activityFilters.minAge > 0) {
      filters["ageLowerLimit"] = activityFilters.minAge;
    }
    if (activityFilters.sorting) {
      filters["sort"] = activityFilters.sorting;
    }
    if (activityFilters.priceUpperLimit) {
      filters["priceUpperLimit"] = activityFilters.priceUpperLimit;
    }
    if (activityFilters.priceLowerLimit) {
      filters["priceLowerLimit"] = activityFilters.priceLowerLimit;
    }
    console.log("router query", filters.category);
    dispatch(
      getActivitiesByFilters({
        subCategory: filters.subCategory,
        category: filters.category,
        activityType: filters.activityType,
        fromDate: filters.fromDate,
        toDate: filters.toDate,
        minimumDuration: filters.minimumDuration,
        maximumDuration: filters.maximumDuration,
        minGroupSize: filters.minGroupSize,
        maxGroupSize: filters.maxGroupSize,
        ageLowerLimit: filters.ageLowerLimit,
        sort: filters.sort,
        priceUpperLimit: filters.priceUpperLimit,
        priceLowerLimit: filters.priceLowerLimit,
        currentPage: pageNumber
      })
    );
  };
  console.log("page", page);
  useEffect(() => {
    dispatch(getActivitiesByFilters({ category: router.query.category }));
  }, []);

  const calculateRating = data => {
    let value = 0;
    data.map(item => {
      // console.log("item", item);
      value = value + item.attributes.rating;
    });
    // console.log("value", value);
    let length = data.length;
    return Math.floor(value / length);
  };
  return (
    <>
      {
        // allActivitiesData && !allActivitiesData.data.length == 0 ?
        !loading ? (
          <div className="listing-items">
            {allActivitiesData && !allActivitiesData.data.length == 0 ? (
              <div className="row">
                {allActivitiesData &&
                  allActivitiesData.data.map((data, i) => {
                    return (
                      <div key={i} className={gridClass}>
                        <div className="item">
                          <div className="browse-experiences-item">
                            <div className="img-wrapper">
                              <span className="image-container">
                                <img layout="fill" alt="" className="image img-fluid" src={cleanImage(data.attributes?.image?.data?.attributes)} />
                              </span>
                              {data.attributes.rating > 100 && <div className="top-rated">Top Rated</div>}
                            </div>
                            <div className="info">
                              <div className="top-name">
                                <Link href={`/activities/${data.id}`}>
                                  <div className="title">{data?.attributes?.name}</div>
                                </Link>
                                <div className="rating-wishlist">
                                  {data?.attributes?.reviews.data.length > 0 && (
                                    <div className="rating">
                                      {/* {console.log(">>", calculateRating(data?.attributes?.reviews.data))} */}
                                      {<span className="number">{calculateRating(data?.attributes?.reviews.data)}</span>}
                                      <span className="image-container">
                                        <Image layout="fill" alt="" className="image img-fluid" src="/images/icons/star.svg" />
                                      </span>
                                    </div>
                                  )}
                                  {endUser && <WishlistComponent activityId={data.id} userId={endUser.id} />}
                                </div>
                              </div>
                              <div className="discription">
                                {data?.attributes.description.slice(0, 52)}...
                                <a className="cursor-pointer"
                                  onClick={() => {
                                    router.push(`/activities/${data.id}`);
                                  }}
                                >
                                  Read More
                                </a>
                              </div>
                              <div className="price">
                                ${data?.attributes?.pricePerPerson}{" "}
                                <span className="off">
                                  {data?.attributes?.off}
                                  {/* % OFF */}
                                </span>
                              </div>
                              <div className="detail">
                                {/* <div className="">For 1 Night</div> */}
                                <div className="">Includes taxes & Fees</div>
                              </div>
                              <div className="explore-now">
                                <Button
                                  onClick={() => {
                                    router.push(`/activities/${data.id}`);
                                  }}
                                  variant="primary me-2"
                                >
                                  Explore Now
                                </Button>
                                {data?.attributes.link && (
                                  <Button
                                    // disabled={loading}
                                    onClick={() => {
                                      window.open(data?.attributes?.link, "_blank", "noopener,noreferrer");
                                    }}
                                    variant="primary"
                                  >
                                    Book Now
                                  </Button>
                                )}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
              </div>
            ) : (
              <div className="container">
                <Empty />
              </div>
              // <div className="container">
              //   <div className="py-5">
              //     <div className="row">
              //       {[1, 2, 3, 5, 5, 5, 5, 5, 5].map((_, index) => (
              //         <div key={index} className="col-lg-3 col-md-3 col-sm-12 my-3">
              //           <div className="d-inline-flex flex-column">
              //             <Skeleton.Button active style={{ height: 250, width: 270 }} />
              //             <Skeleton.Button active style={{ marginTop: 10, width: 120 }} />
              //           </div>
              //         </div>
              //       ))}
              //     </div>
              //   </div>
              // </div>
            )}
          </div>
        ) : (
          <div className="container">
            <div className="py-5">
              <div className="row">
                {[1, 2, 3, 5, 5, 5, 5, 5, 5].map((_, index) => (
                  <div key={index} className="col-lg-3 col-md-3 col-sm-12 my-3">
                    <div className="d-inline-flex flex-column">
                      <Skeleton.Button active style={{ height: 250, width: 270 }} />
                      <Skeleton.Button active style={{ marginTop: 10, width: 120 }} />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
          // <div className="container">
          //   <Empty />
          // </div>
        )
      }
      {totalCount && (
        <div className="row">
          <div className="col-12">
            <div className="load-more">
              {/* {console.log("totalCount", totalCount)} */}
              <Pagination
                activePage={page}
                hideNavigation={true}
                itemsCountPerPage={12}
                totalItemsCount={totalCount}
                pageRangeDisplayed={5}
                onChange={async e => {
                  console.log("log >", e);
                  await handlePagination(e);
                }}
                nextPageText={"›"}
                prevPageText={"‹"}
                firstPageText={"«"}
                lastPageText={"»"}
                itemClass="page-item"
                linkClass="page-link"
              ></Pagination>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default ListingItems;