import React, {
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
} from "react";
import { View, Text, Image, Button } from "@tarojs/components";
import { AtCheckbox, AtActivityIndicator } from "taro-ui";
import { setShareContent } from "../../../common/share";
import Taro from "@tarojs/taro";
import "./index.less";
import joinStoreBg from "../../../images/index/jionStore.png";
import joinStoreAc from "../../../images/index/joinStoreAc.png";
import saveMoneyBg from "../../../images/index/save-money.png";
import shareEarnBg from "../../../images/index/share-earn.png";
import seckillIcon from "../../../images/seckill/seckillIcon.png";
const ProductList = forwardRef((props, ref) => {
  const {
    productList, // 商品列表数据
    loading, // 加载状态
    isSeckill, // 是否秒杀页面使用
    isManagement, // 是否管理页面使用
    isManagementStatus, // 是否管理状态
    isProductClassify, // 是否分类页面使用
    isSelectAll, // 是否全选
    onAddProduct, // 添加商品方法
    onDeleteProductSelect, // 删除商品选中id数组
    isNoMore, // 是否没有更多
    onShareProduct, // 分享商品方法
    } = props;

  const [selectedProducts, setSelectedProducts] = useState([]); // 商品选择状态
  // 监听选中状态变化
  useEffect(() => {
    // 每当 selectedProducts 变化时，调用父组件的回调
    onDeleteProductSelect && onDeleteProductSelect(selectedProducts);
  }, [selectedProducts]);
  // 监听 isSelectAll 的变化
  useEffect(() => {
    if (isSelectAll) {
      // 如果 isSelectAll 为 true，选中所有商品
      setSelectedProducts(productList.map((product) => product.id));
    } else {
      // 如果 isSelectAll 为 false，取消所有选中
      setSelectedProducts([]);
    }
  }, [isSelectAll]);
  // 定义 clearSelectedItems 方法
  useImperativeHandle(ref, () => ({
    clearSelectedItems: () => {
      setSelectedProducts([]);
    },
  }));

  // 跳转产品详情
  const toDetail = (id) => {
    if (isManagementStatus) {
      selectProduct(id);
    } else {
      Taro.navigateTo({
        url: `/pages/indexSub/productDetail/index?id=${id}`,
      });
    }
  };

  // 单选
  const selectProduct = (productId) => {
    setSelectedProducts((prevSelected) => {
      const isSelected = prevSelected.includes(productId);
      if (isSelected) {
        // 如果已经选中，则取消选择
        return prevSelected.filter((id) => id !== productId);
      } else {
        // 如果未选中，则添加到选中列
        return [...prevSelected, productId];
      }
    });
  };
  // 添加商品
  const addProduct = (productId, is_collected, index) => {
    // 是否添加到我的商店（is_collected:为true已添加）
    if (is_collected) {
      return;
    } else {
      // 调用父组件的方法
      onAddProduct && onAddProduct(productId, index);
    }
  };
  // 分享商品 
  const shareProduct = (product, e) => {
    e.stopPropagation(); // 防止事件穿透
    props.onShareProduct && props.onShareProduct();
    setShareContent({
      title: product.item_title,
      path: `/pages/indexSub/productDetail/index?id=${product.id}&&isShare=${true}`,
      imageUrl: product.image_url,
    });
  };
  return (
    <View className="product-list-wrap">
      {isSeckill && (
        <View className="seckill-icon">
          <Image src={seckillIcon} mode="aspectFit" />
          <Text>每日疯抢 限时秒杀</Text>
        </View>
      )}
      {productList.map((product, index) => (
        <View key={product.id}>
          <View onClick={() => toDetail(product.id)} className="product-item">
            {isManagement && isManagementStatus && (
              <AtCheckbox
                options={[{ value: product.id.toString(), label: "" }]} // 确保每个复选框的 options 是独立的
                selectedList={selectedProducts.map((id) => id.toString())}
                onChange={(selectedList) => selectProduct(product.id)} // 传递当前 product.id
              />
            )}
            <View className="right">
              <Image
                className="product-img"
                src={product.image_url}
                mode="aspectFill"
              />
              <View className="product-info">
                <View
                  className="product-name"
                  style={{ WebkitBoxOrient: "vertical" }}
                >
                  <Text className="self-tag">
                    {!isSeckill ? "自营" : "鱼市��杀"}
                  </Text>
                  {product.item_title}
                </View>
                <View className="price-line">
                  <View className="price-info">
                    <Text className="symbol">¥</Text>
                    <Text className="price">{product.reserve_price}</Text>
                    {product.original_price != "0.00" && (
                      <Text className="original-price">
                        ¥{product.original_price}
                      </Text>
                    )}
                  </View>
                  {isProductClassify && (
                    <View
                      onClick={(e) => {
                        e.stopPropagation();
                        addProduct(product.id, product.is_collected, index);
                      }}
                      className="add-btn"
                    >
                      {product.is_collected ? (
                        <Image
                          className="join-store-bg"
                          src={joinStoreBg}
                          mode="aspectFit"
                        />
                      ) : (
                        <Image
                          className="join-store-bg"
                          src={joinStoreAc}
                          mode="aspectFit"
                        />
                      )}
                      <Text className="btn-text">加入小店</Text>
                    </View>
                  )}
                </View>
                <View className="profit-line">
                  <View className="save-money">
                    <Image className="bg" src={saveMoneyBg} mode="aspectFit" />
                    <View className="content">
                      <Text className="label">自购省</Text>
                      <Text className="money">
                        ¥{product.estimated_commission}
                      </Text>
                    </View>
                  </View>
                  <View className="share-earn">
                    <Image className="bg" src={shareEarnBg} mode="aspectFit" />
                    <View className="content">
                      <Button
                        openType="share"
                        onClick={(e) => shareProduct(product, e)} // 传递事件对象
                      >
                        <Text className="label">分享赚</Text>
                        <Text className="money">
                          ¥{product.estimated_commission}
                        </Text>
                      </Button>
                    </View>
                  </View>
                </View>
              </View>
            </View>
          </View>
          {index !== productList.length - 1 && (
            <View className="divider"></View>
          )}
        </View>
      ))}
      {loading && (
        <View className="loading">
          <AtActivityIndicator
            content="加载中..."
            isOpened={loading}
            mode="center"
            color="#fdf764"
          />
        </View>
      )}
      {isNoMore && <View className="no-more">没有更多了~</View>}
    </View>
  );
});

ProductList.defaultProps = {
  isSeckill: false,
  productList: [],
  loading: false,
  isManagement: false,
  isManagementStatus: false,
  isProductClassify: false,
  isSelectAll: false,
  isNoMore: false,
  onAddProduct: () => {}, // 添加商品方法
  onDeleteProductSelect: () => {}, // 删除商品选中id数组
  onShareProduct: () => {}, // 分享商品方法
};

export default ProductList;
