import Taro from "@tarojs/taro"; // 导入 Taro
import { Component } from "react";
import {
  View,
  Image,
  Swiper,
  SwiperItem,
  Text,
  Button,
} from "@tarojs/components";
import { AtTabs } from "taro-ui";
import { getHomeData, getProductList } from "../../service";
import { getShareContent } from "../../common/share";
import "./index.less";
import Skeleton from "../../components/skeleton"; //骨架屏
import SearchBar from "../../components/index/SearchBar"; //搜索框
import CategoryList from "../../components/index/CategoryList"; //分类列表
import OperationArea from "../../components/index/OperationArea"; //运营区域
import RecommendList from "../../components/index/RecommendList"; //邀请人推荐
import ProductList from "../../components/index/ProductList"; //商品列表
import myStoreIcon from "../../images/index/myStore.png";
import backTopIcon from "../../images/index/back-top.png";
export default class Index extends Component {
  state = {
    current: 0, // 添加当前选中的tab索引
    homeData: {}, // 首页数据
    bannerList: [],
    productList: [], // 添加商品列表
    page: 1, // 添加页码
    totalPages: 1, // 添加总页数
    loading: false, // 添加加载状态
  };
  // 获取首页数据
  getHomeData = async () => {
    const res = await getHomeData();
    res.tags = res.tags.map((item, index) => ({
      title: item.name,
    }));
    this.setState({ homeData: res }, () => {
      this.getProductList(true);
    });
  };
  // 修改 tab 切换处理函数
  handleClick(value) {
    this.setState(
      {
        current: value,
        page: 1,
      },
      () => {
        // 跳转到列表顶部
        Taro.createSelectorQuery()
          .select(".product-list-wrap")
          .boundingClientRect()
          .exec((res) => {
            if (res[0]) {
              const top = res[0].top;
              Taro.pageScrollTo({
                scrollTop: top - 40,
                duration: 300,
              });
              this.getProductList(true);
            } else {
              console.warn("未找到 .product-list-wrap 元素");
            }
          });
      }
    );
  }
  componentDidShow() {
    this.getHomeData(); //获取首页数据
  }
  // 添加回到顶部方法
  handleBackTop = () => {
    Taro.pageScrollTo({
      scrollTop: 0,
      duration: 300,
    });
  };

  // 页面上拉触底
  onReachBottom = () => {
    const { page, totalPages, loading } = this.state;
    if (page < totalPages && !loading) {
      this.setState(
        (prevState) => ({ page: prevState.page + 1 }),
        () => this.getProductList()
      );
    }
  };

  // 获取商品列表
  getProductList = async (isRefresh) => {
    const { page } = this.state;
    this.setState({ loading: true });
    const res = await getProductList({
      tag_name: this.state.homeData.tags[this.state.current].title,
      page,
      page_size: 10,
    });

    this.setState((prevState) => ({
      productList: isRefresh
        ? res.goods_list
        : [...prevState.productList, ...res.goods_list],
      totalPages: res.total_pages,
      loading: false,
    }));
  };
  // 配置分享内容
  onShareAppMessage() {
    return getShareContent();
  }
  render() {
    const { homeData, productList, loading } = this.state;
    return (
      <View className="index">
        <View
          className="header"
          style={{ paddingTop: Taro.navigationBarHeight + "px" }}
        >
          <View className="header-content">
            <Image
              mode="heightFix"
              className="header-img"
              src="https://video-img.fyshark.com/1731495433480WechatIMG674.jpg"
            />
          </View>
          {/* 搜索框包裹盒子 */}
          <View
            className="search-bar-container"
            onClick={() => Taro.navigateTo({ url: "/pages/search/index" })}
          >
            <SearchBar value="" disabled={true} placeholder="点击搜索商品" />
          </View>
          {/* tab分类 */}
          <View className="tabs-list">
            {homeData.tags && (
              <AtTabs
                current={this.state.current}
                scroll
                tabList={homeData.tags}
                onClick={this.handleClick.bind(this)}
              />
            )}

            <View className="tab-more">
              <Image className="tab-more-img" />
            </View>
          </View>
          {/* 轮播图 */}
          <View className="banner-wrap">
            <Swiper
              className="banner-swiper"
              circular
              autoplay
              indicatorDots
              indicatorColor="#e8e8e8"
              indicatorActiveColor="#ffffff"
            >
              {homeData.banner &&
                homeData.banner.map((item) => (
                  <SwiperItem className="banner-item" key={item.id}>
                    <Image
                      className="banner-img"
                      src={item.img}
                      mode="aspectFill"
                    />
                  </SwiperItem>
                ))}
            </Swiper>
          </View>
        </View>
        {/* 骨架屏 */}
        <Skeleton
          isSkeletonShow={!homeData.banner && !productList.length > 0}
        />
        {/* 分类列表组件 */}
        {homeData.icon && <CategoryList categoryList={homeData.icon} />}
        {/* 运营区域 */}
        {homeData.recommend && <OperationArea recommend={homeData.recommend} />}
        {/* 邀请人推荐 */}
        {/* <RecommendList /> */}
        {/* 商品列表 */}
        <View className="product-list-wrap">
          <ProductList
            productList={productList}
            loading={loading}
            onShareProduct={this.handleShare}
          />
        </View>
        {/* 添加浮动按钮 */}
        <View className="float-buttons">
          <View
            className="float-btn"
            onClick={() =>
              Taro.navigateTo({
                url: `/pages/memberSub/storeManagement/index?isManager=${true}`,
              })
            }
          >
            <Image className="my-shop-bg" src={myStoreIcon} mode="aspectFit" />
            <Text>我的{"\n"}小店</Text>
          </View>
          <View className="float-btn" onClick={this.handleBackTop}>
            <Image className="back-top" src={backTopIcon} mode="aspectFit" />
          </View>
        </View>
        {/* 分享弹窗 */}
      </View>
    );
  }
}
