import { Image, Text, View } from "@tarojs/components";
import Taro, { FC, useReachBottom } from "@tarojs/taro";
import { useEffect, useRef, useState } from "react";
import BuyIcon from "../../../../images/icon_presents@2x-min.png";
import { getProductListApi } from "../../../../../api";
import { getBaseURL } from "@dage/service";
import "./index.scss";

const baseUrl = getBaseURL();

export interface ProductsProps {
  curTab: number;
  /**
   * 用户当前积分
   */
  point: number;
}

export const Products: FC<ProductsProps> = ({ curTab, point }) => {
  const params = useRef({
    pageNum: 1,
    pageSize: 20,
  });
  const hasMore = useRef(true);
  const [list, setList] = useState<any[]>([]);

  const getProductList = async () => {
    if (!hasMore.current) return;

    const data = await getProductListApi(params.current);

    if (params.current.pageNum === 1) {
      setList(data.records);
    } else {
      setList([...list, ...data.records]);
    }

    if (params.current.pageNum + 1 > data.pages) {
      hasMore.current = false;
    }

    params.current.pageNum += 1;
  };

  useEffect(() => {
    getProductList();
  }, []);

  useReachBottom(() => {
    curTab === 0 && getProductList();
  });

  const handleBuy = (item: any) => {
    if (point < item.score) {
      Taro.showToast({
        title: "积分不足，无法兑换",
        icon: "none",
        duration: 3000,
      });
      return;
    }

    Taro.navigateTo({
      url: `/subModule/pages/order/index?id=${item.id}&score=${item.score}&point=${point}`,
    });
  };

  return (
    <View className="products">
      {list.map((item) => (
        <View key={item.id} className="products-item">
          <Image
            className="products-item__img"
            src={`${baseUrl}${item.thumb}`}
            mode="aspectFill"
          />

          <View className="products-item__main">
            <View className="products-item__title limit-line">{item.name}</View>
            <View className="products-item__stock">库存：{item.stock}</View>
            <View className="products-item__ft">
              <Text className="products-item__ft__price">{item.score}</Text>
              <Text>爱心币</Text>
            </View>

            <Image
              className="products-item__buy"
              src={BuyIcon}
              onClick={handleBuy.bind(undefined, item)}
            />
          </View>
        </View>
      ))}
    </View>
  );
};
