import { Component } from "react";
import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import "./index.less";
import ProductList from "../../../components/index/ProductList";
import { getSearchProductList } from "../../../service";
export default class Index extends Component {
  state = {
    productList: [],
    page: 1,
    totalPages: 1,
    loading: false,
    keyword: "",
  };
  componentDidMount() {
    const { keyword }  = Taro.getCurrentInstance().router.params||"";
    this.setState({ keyword }, () => {
      this.getSearchProductList(true);
    });
  }
  // 获取商品列表
  getSearchProductList = async (isAdd = false) => {
    const { page } = this.state;
    this.setState({ loading: true });

    const res = await getSearchProductList({
      search_name: this.state.keyword,
      page,
      page_size: 10,
    });

    this.setState((prevState) => ({
      productList: isAdd
        ? res.goods_list
        : [...prevState.productList, ...res.goods_list],
      totalPages: res.total_pages,
      loading: false,
    }));
  };
  // 页面上拉触底
  onReachBottom = () => {
    const { page, totalPages, loading } = this.state;
    if (page < totalPages && !loading) {
      this.setState(
        (prevState) => ({ page: prevState.page + 1 }),
        () => this.getSearchProductList()
      );
    }
  };
  render() {
    return (
      <View className="index">
        {/* 搜索列表 */}
        <ProductList
          productList={this.state.productList}
          loading={this.state.loading}
        ></ProductList>
      </View>
    );
  }
}
